echarts.js 2.9 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  3. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  4. (factory((global.echarts = {})));
  5. }(this, (function (exports) { 'use strict';
  6. /*
  7. * Licensed to the Apache Software Foundation (ASF) under one
  8. * or more contributor license agreements. See the NOTICE file
  9. * distributed with this work for additional information
  10. * regarding copyright ownership. The ASF licenses this file
  11. * to you under the Apache License, Version 2.0 (the
  12. * "License"); you may not use this file except in compliance
  13. * with the License. You may obtain a copy of the License at
  14. *
  15. * http://www.apache.org/licenses/LICENSE-2.0
  16. *
  17. * Unless required by applicable law or agreed to in writing,
  18. * software distributed under the License is distributed on an
  19. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20. * KIND, either express or implied. See the License for the
  21. * specific language governing permissions and limitations
  22. * under the License.
  23. */
  24. // (1) The code `if (__DEV__) ...` can be removed by build tool.
  25. // (2) If intend to use `__DEV__`, this module should be imported. Use a global
  26. // variable `__DEV__` may cause that miss the declaration (see #6535), or the
  27. // declaration is behind of the using position (for example in `Model.extent`,
  28. // And tools like rollup can not analysis the dependency if not import).
  29. var dev;
  30. // In browser
  31. if (typeof window !== 'undefined') {
  32. dev = window.__DEV__;
  33. }
  34. // In node
  35. else if (typeof global !== 'undefined') {
  36. dev = global.__DEV__;
  37. }
  38. if (typeof dev === 'undefined') {
  39. dev = true;
  40. }
  41. var __DEV__ = dev;
  42. /**
  43. * zrender: 生成唯一id
  44. *
  45. * @author errorrik (errorrik@gmail.com)
  46. */
  47. var idStart = 0x0907;
  48. var guid = function () {
  49. return idStart++;
  50. };
  51. /**
  52. * echarts设备环境识别
  53. *
  54. * @desc echarts基于Canvas,纯Javascript图表库,提供直观,生动,可交互,可个性化定制的数据统计图表。
  55. * @author firede[firede@firede.us]
  56. * @desc thanks zepto.
  57. */
  58. /* global wx */
  59. var env = {};
  60. if (typeof wx === 'object' && typeof wx.getSystemInfoSync === 'function') {
  61. // In Weixin Application
  62. env = {
  63. browser: {},
  64. os: {},
  65. node: false,
  66. wxa: true, // Weixin Application
  67. canvasSupported: true,
  68. svgSupported: false,
  69. touchEventsSupported: true,
  70. domSupported: false
  71. };
  72. }
  73. else if (typeof document === 'undefined' && typeof self !== 'undefined') {
  74. // In worker
  75. env = {
  76. browser: {},
  77. os: {},
  78. node: false,
  79. worker: true,
  80. canvasSupported: true,
  81. domSupported: false
  82. };
  83. }
  84. else if (typeof navigator === 'undefined') {
  85. // In node
  86. env = {
  87. browser: {},
  88. os: {},
  89. node: true,
  90. worker: false,
  91. // Assume canvas is supported
  92. canvasSupported: true,
  93. svgSupported: true,
  94. domSupported: false
  95. };
  96. }
  97. else {
  98. env = detect(navigator.userAgent);
  99. }
  100. var env$1 = env;
  101. // Zepto.js
  102. // (c) 2010-2013 Thomas Fuchs
  103. // Zepto.js may be freely distributed under the MIT license.
  104. function detect(ua) {
  105. var os = {};
  106. var browser = {};
  107. // var webkit = ua.match(/Web[kK]it[\/]{0,1}([\d.]+)/);
  108. // var android = ua.match(/(Android);?[\s\/]+([\d.]+)?/);
  109. // var ipad = ua.match(/(iPad).*OS\s([\d_]+)/);
  110. // var ipod = ua.match(/(iPod)(.*OS\s([\d_]+))?/);
  111. // var iphone = !ipad && ua.match(/(iPhone\sOS)\s([\d_]+)/);
  112. // var webos = ua.match(/(webOS|hpwOS)[\s\/]([\d.]+)/);
  113. // var touchpad = webos && ua.match(/TouchPad/);
  114. // var kindle = ua.match(/Kindle\/([\d.]+)/);
  115. // var silk = ua.match(/Silk\/([\d._]+)/);
  116. // var blackberry = ua.match(/(BlackBerry).*Version\/([\d.]+)/);
  117. // var bb10 = ua.match(/(BB10).*Version\/([\d.]+)/);
  118. // var rimtabletos = ua.match(/(RIM\sTablet\sOS)\s([\d.]+)/);
  119. // var playbook = ua.match(/PlayBook/);
  120. // var chrome = ua.match(/Chrome\/([\d.]+)/) || ua.match(/CriOS\/([\d.]+)/);
  121. var firefox = ua.match(/Firefox\/([\d.]+)/);
  122. // var safari = webkit && ua.match(/Mobile\//) && !chrome;
  123. // var webview = ua.match(/(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/) && !chrome;
  124. var ie = ua.match(/MSIE\s([\d.]+)/)
  125. // IE 11 Trident/7.0; rv:11.0
  126. || ua.match(/Trident\/.+?rv:(([\d.]+))/);
  127. var edge = ua.match(/Edge\/([\d.]+)/); // IE 12 and 12+
  128. var weChat = (/micromessenger/i).test(ua);
  129. // Todo: clean this up with a better OS/browser seperation:
  130. // - discern (more) between multiple browsers on android
  131. // - decide if kindle fire in silk mode is android or not
  132. // - Firefox on Android doesn't specify the Android version
  133. // - possibly devide in os, device and browser hashes
  134. // if (browser.webkit = !!webkit) browser.version = webkit[1];
  135. // if (android) os.android = true, os.version = android[2];
  136. // if (iphone && !ipod) os.ios = os.iphone = true, os.version = iphone[2].replace(/_/g, '.');
  137. // if (ipad) os.ios = os.ipad = true, os.version = ipad[2].replace(/_/g, '.');
  138. // if (ipod) os.ios = os.ipod = true, os.version = ipod[3] ? ipod[3].replace(/_/g, '.') : null;
  139. // if (webos) os.webos = true, os.version = webos[2];
  140. // if (touchpad) os.touchpad = true;
  141. // if (blackberry) os.blackberry = true, os.version = blackberry[2];
  142. // if (bb10) os.bb10 = true, os.version = bb10[2];
  143. // if (rimtabletos) os.rimtabletos = true, os.version = rimtabletos[2];
  144. // if (playbook) browser.playbook = true;
  145. // if (kindle) os.kindle = true, os.version = kindle[1];
  146. // if (silk) browser.silk = true, browser.version = silk[1];
  147. // if (!silk && os.android && ua.match(/Kindle Fire/)) browser.silk = true;
  148. // if (chrome) browser.chrome = true, browser.version = chrome[1];
  149. if (firefox) {
  150. browser.firefox = true;
  151. browser.version = firefox[1];
  152. }
  153. // if (safari && (ua.match(/Safari/) || !!os.ios)) browser.safari = true;
  154. // if (webview) browser.webview = true;
  155. if (ie) {
  156. browser.ie = true;
  157. browser.version = ie[1];
  158. }
  159. if (edge) {
  160. browser.edge = true;
  161. browser.version = edge[1];
  162. }
  163. // It is difficult to detect WeChat in Win Phone precisely, because ua can
  164. // not be set on win phone. So we do not consider Win Phone.
  165. if (weChat) {
  166. browser.weChat = true;
  167. }
  168. // os.tablet = !!(ipad || playbook || (android && !ua.match(/Mobile/)) ||
  169. // (firefox && ua.match(/Tablet/)) || (ie && !ua.match(/Phone/) && ua.match(/Touch/)));
  170. // os.phone = !!(!os.tablet && !os.ipod && (android || iphone || webos ||
  171. // (chrome && ua.match(/Android/)) || (chrome && ua.match(/CriOS\/([\d.]+)/)) ||
  172. // (firefox && ua.match(/Mobile/)) || (ie && ua.match(/Touch/))));
  173. return {
  174. browser: browser,
  175. os: os,
  176. node: false,
  177. // 原生canvas支持,改极端点了
  178. // canvasSupported : !(browser.ie && parseFloat(browser.version) < 9)
  179. canvasSupported: !!document.createElement('canvas').getContext,
  180. svgSupported: typeof SVGRect !== 'undefined',
  181. // works on most browsers
  182. // IE10/11 does not support touch event, and MS Edge supports them but not by
  183. // default, so we dont check navigator.maxTouchPoints for them here.
  184. touchEventsSupported: 'ontouchstart' in window && !browser.ie && !browser.edge,
  185. // <http://caniuse.com/#search=pointer%20event>.
  186. pointerEventsSupported:
  187. // (1) Firefox supports pointer but not by default, only MS browsers are reliable on pointer
  188. // events currently. So we dont use that on other browsers unless tested sufficiently.
  189. // For example, in iOS 13 Mobile Chromium 78, if the touching behavior starts page
  190. // scroll, the `pointermove` event can not be fired any more. That will break some
  191. // features like "pan horizontally to move something and pan vertically to page scroll".
  192. // The horizontal pan probably be interrupted by the casually triggered page scroll.
  193. // (2) Although IE 10 supports pointer event, it use old style and is different from the
  194. // standard. So we exclude that. (IE 10 is hardly used on touch device)
  195. 'onpointerdown' in window
  196. && (browser.edge || (browser.ie && browser.version >= 11)),
  197. // passiveSupported: detectPassiveSupport()
  198. domSupported: typeof document !== 'undefined'
  199. };
  200. }
  201. // See https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md#feature-detection
  202. // function detectPassiveSupport() {
  203. // // Test via a getter in the options object to see if the passive property is accessed
  204. // var supportsPassive = false;
  205. // try {
  206. // var opts = Object.defineProperty({}, 'passive', {
  207. // get: function() {
  208. // supportsPassive = true;
  209. // }
  210. // });
  211. // window.addEventListener('testPassive', function() {}, opts);
  212. // } catch (e) {
  213. // }
  214. // return supportsPassive;
  215. // }
  216. /**
  217. * @module zrender/core/util
  218. */
  219. // 用于处理merge时无法遍历Date等对象的问题
  220. var BUILTIN_OBJECT = {
  221. '[object Function]': 1,
  222. '[object RegExp]': 1,
  223. '[object Date]': 1,
  224. '[object Error]': 1,
  225. '[object CanvasGradient]': 1,
  226. '[object CanvasPattern]': 1,
  227. // For node-canvas
  228. '[object Image]': 1,
  229. '[object Canvas]': 1
  230. };
  231. var TYPED_ARRAY = {
  232. '[object Int8Array]': 1,
  233. '[object Uint8Array]': 1,
  234. '[object Uint8ClampedArray]': 1,
  235. '[object Int16Array]': 1,
  236. '[object Uint16Array]': 1,
  237. '[object Int32Array]': 1,
  238. '[object Uint32Array]': 1,
  239. '[object Float32Array]': 1,
  240. '[object Float64Array]': 1
  241. };
  242. var objToString = Object.prototype.toString;
  243. var arrayProto = Array.prototype;
  244. var nativeForEach = arrayProto.forEach;
  245. var nativeFilter = arrayProto.filter;
  246. var nativeSlice = arrayProto.slice;
  247. var nativeMap = arrayProto.map;
  248. var nativeReduce = arrayProto.reduce;
  249. // Avoid assign to an exported variable, for transforming to cjs.
  250. var methods = {};
  251. function $override(name, fn) {
  252. // Clear ctx instance for different environment
  253. if (name === 'createCanvas') {
  254. _ctx = null;
  255. }
  256. methods[name] = fn;
  257. }
  258. /**
  259. * Those data types can be cloned:
  260. * Plain object, Array, TypedArray, number, string, null, undefined.
  261. * Those data types will be assgined using the orginal data:
  262. * BUILTIN_OBJECT
  263. * Instance of user defined class will be cloned to a plain object, without
  264. * properties in prototype.
  265. * Other data types is not supported (not sure what will happen).
  266. *
  267. * Caution: do not support clone Date, for performance consideration.
  268. * (There might be a large number of date in `series.data`).
  269. * So date should not be modified in and out of echarts.
  270. *
  271. * @param {*} source
  272. * @return {*} new
  273. */
  274. function clone(source) {
  275. if (source == null || typeof source !== 'object') {
  276. return source;
  277. }
  278. var result = source;
  279. var typeStr = objToString.call(source);
  280. if (typeStr === '[object Array]') {
  281. if (!isPrimitive(source)) {
  282. result = [];
  283. for (var i = 0, len = source.length; i < len; i++) {
  284. result[i] = clone(source[i]);
  285. }
  286. }
  287. }
  288. else if (TYPED_ARRAY[typeStr]) {
  289. if (!isPrimitive(source)) {
  290. var Ctor = source.constructor;
  291. if (source.constructor.from) {
  292. result = Ctor.from(source);
  293. }
  294. else {
  295. result = new Ctor(source.length);
  296. for (var i = 0, len = source.length; i < len; i++) {
  297. result[i] = clone(source[i]);
  298. }
  299. }
  300. }
  301. }
  302. else if (!BUILTIN_OBJECT[typeStr] && !isPrimitive(source) && !isDom(source)) {
  303. result = {};
  304. for (var key in source) {
  305. if (source.hasOwnProperty(key)) {
  306. result[key] = clone(source[key]);
  307. }
  308. }
  309. }
  310. return result;
  311. }
  312. /**
  313. * @memberOf module:zrender/core/util
  314. * @param {*} target
  315. * @param {*} source
  316. * @param {boolean} [overwrite=false]
  317. */
  318. function merge(target, source, overwrite) {
  319. // We should escapse that source is string
  320. // and enter for ... in ...
  321. if (!isObject$1(source) || !isObject$1(target)) {
  322. return overwrite ? clone(source) : target;
  323. }
  324. for (var key in source) {
  325. if (source.hasOwnProperty(key)) {
  326. var targetProp = target[key];
  327. var sourceProp = source[key];
  328. if (isObject$1(sourceProp)
  329. && isObject$1(targetProp)
  330. && !isArray(sourceProp)
  331. && !isArray(targetProp)
  332. && !isDom(sourceProp)
  333. && !isDom(targetProp)
  334. && !isBuiltInObject(sourceProp)
  335. && !isBuiltInObject(targetProp)
  336. && !isPrimitive(sourceProp)
  337. && !isPrimitive(targetProp)
  338. ) {
  339. // 如果需要递归覆盖,就递归调用merge
  340. merge(targetProp, sourceProp, overwrite);
  341. }
  342. else if (overwrite || !(key in target)) {
  343. // 否则只处理overwrite为true,或者在目标对象中没有此属性的情况
  344. // NOTE,在 target[key] 不存在的时候也是直接覆盖
  345. target[key] = clone(source[key], true);
  346. }
  347. }
  348. }
  349. return target;
  350. }
  351. /**
  352. * @param {Array} targetAndSources The first item is target, and the rests are source.
  353. * @param {boolean} [overwrite=false]
  354. * @return {*} target
  355. */
  356. function mergeAll(targetAndSources, overwrite) {
  357. var result = targetAndSources[0];
  358. for (var i = 1, len = targetAndSources.length; i < len; i++) {
  359. result = merge(result, targetAndSources[i], overwrite);
  360. }
  361. return result;
  362. }
  363. /**
  364. * @param {*} target
  365. * @param {*} source
  366. * @memberOf module:zrender/core/util
  367. */
  368. function extend(target, source) {
  369. for (var key in source) {
  370. if (source.hasOwnProperty(key)) {
  371. target[key] = source[key];
  372. }
  373. }
  374. return target;
  375. }
  376. /**
  377. * @param {*} target
  378. * @param {*} source
  379. * @param {boolean} [overlay=false]
  380. * @memberOf module:zrender/core/util
  381. */
  382. function defaults(target, source, overlay) {
  383. for (var key in source) {
  384. if (source.hasOwnProperty(key)
  385. && (overlay ? source[key] != null : target[key] == null)
  386. ) {
  387. target[key] = source[key];
  388. }
  389. }
  390. return target;
  391. }
  392. var createCanvas = function () {
  393. return methods.createCanvas();
  394. };
  395. methods.createCanvas = function () {
  396. return document.createElement('canvas');
  397. };
  398. // FIXME
  399. var _ctx;
  400. function getContext() {
  401. if (!_ctx) {
  402. // Use util.createCanvas instead of createCanvas
  403. // because createCanvas may be overwritten in different environment
  404. _ctx = createCanvas().getContext('2d');
  405. }
  406. return _ctx;
  407. }
  408. /**
  409. * 查询数组中元素的index
  410. * @memberOf module:zrender/core/util
  411. */
  412. function indexOf(array, value) {
  413. if (array) {
  414. if (array.indexOf) {
  415. return array.indexOf(value);
  416. }
  417. for (var i = 0, len = array.length; i < len; i++) {
  418. if (array[i] === value) {
  419. return i;
  420. }
  421. }
  422. }
  423. return -1;
  424. }
  425. /**
  426. * 构造类继承关系
  427. *
  428. * @memberOf module:zrender/core/util
  429. * @param {Function} clazz 源类
  430. * @param {Function} baseClazz 基类
  431. */
  432. function inherits(clazz, baseClazz) {
  433. var clazzPrototype = clazz.prototype;
  434. function F() {}
  435. F.prototype = baseClazz.prototype;
  436. clazz.prototype = new F();
  437. for (var prop in clazzPrototype) {
  438. if (clazzPrototype.hasOwnProperty(prop)) {
  439. clazz.prototype[prop] = clazzPrototype[prop];
  440. }
  441. }
  442. clazz.prototype.constructor = clazz;
  443. clazz.superClass = baseClazz;
  444. }
  445. /**
  446. * @memberOf module:zrender/core/util
  447. * @param {Object|Function} target
  448. * @param {Object|Function} sorce
  449. * @param {boolean} overlay
  450. */
  451. function mixin(target, source, overlay) {
  452. target = 'prototype' in target ? target.prototype : target;
  453. source = 'prototype' in source ? source.prototype : source;
  454. defaults(target, source, overlay);
  455. }
  456. /**
  457. * Consider typed array.
  458. * @param {Array|TypedArray} data
  459. */
  460. function isArrayLike(data) {
  461. if (!data) {
  462. return;
  463. }
  464. if (typeof data === 'string') {
  465. return false;
  466. }
  467. return typeof data.length === 'number';
  468. }
  469. /**
  470. * 数组或对象遍历
  471. * @memberOf module:zrender/core/util
  472. * @param {Object|Array} obj
  473. * @param {Function} cb
  474. * @param {*} [context]
  475. */
  476. function each$1(obj, cb, context) {
  477. if (!(obj && cb)) {
  478. return;
  479. }
  480. if (obj.forEach && obj.forEach === nativeForEach) {
  481. obj.forEach(cb, context);
  482. }
  483. else if (obj.length === +obj.length) {
  484. for (var i = 0, len = obj.length; i < len; i++) {
  485. cb.call(context, obj[i], i, obj);
  486. }
  487. }
  488. else {
  489. for (var key in obj) {
  490. if (obj.hasOwnProperty(key)) {
  491. cb.call(context, obj[key], key, obj);
  492. }
  493. }
  494. }
  495. }
  496. /**
  497. * 数组映射
  498. * @memberOf module:zrender/core/util
  499. * @param {Array} obj
  500. * @param {Function} cb
  501. * @param {*} [context]
  502. * @return {Array}
  503. */
  504. function map(obj, cb, context) {
  505. if (!(obj && cb)) {
  506. return;
  507. }
  508. if (obj.map && obj.map === nativeMap) {
  509. return obj.map(cb, context);
  510. }
  511. else {
  512. var result = [];
  513. for (var i = 0, len = obj.length; i < len; i++) {
  514. result.push(cb.call(context, obj[i], i, obj));
  515. }
  516. return result;
  517. }
  518. }
  519. /**
  520. * @memberOf module:zrender/core/util
  521. * @param {Array} obj
  522. * @param {Function} cb
  523. * @param {Object} [memo]
  524. * @param {*} [context]
  525. * @return {Array}
  526. */
  527. function reduce(obj, cb, memo, context) {
  528. if (!(obj && cb)) {
  529. return;
  530. }
  531. if (obj.reduce && obj.reduce === nativeReduce) {
  532. return obj.reduce(cb, memo, context);
  533. }
  534. else {
  535. for (var i = 0, len = obj.length; i < len; i++) {
  536. memo = cb.call(context, memo, obj[i], i, obj);
  537. }
  538. return memo;
  539. }
  540. }
  541. /**
  542. * 数组过滤
  543. * @memberOf module:zrender/core/util
  544. * @param {Array} obj
  545. * @param {Function} cb
  546. * @param {*} [context]
  547. * @return {Array}
  548. */
  549. function filter(obj, cb, context) {
  550. if (!(obj && cb)) {
  551. return;
  552. }
  553. if (obj.filter && obj.filter === nativeFilter) {
  554. return obj.filter(cb, context);
  555. }
  556. else {
  557. var result = [];
  558. for (var i = 0, len = obj.length; i < len; i++) {
  559. if (cb.call(context, obj[i], i, obj)) {
  560. result.push(obj[i]);
  561. }
  562. }
  563. return result;
  564. }
  565. }
  566. /**
  567. * 数组项查找
  568. * @memberOf module:zrender/core/util
  569. * @param {Array} obj
  570. * @param {Function} cb
  571. * @param {*} [context]
  572. * @return {*}
  573. */
  574. function find(obj, cb, context) {
  575. if (!(obj && cb)) {
  576. return;
  577. }
  578. for (var i = 0, len = obj.length; i < len; i++) {
  579. if (cb.call(context, obj[i], i, obj)) {
  580. return obj[i];
  581. }
  582. }
  583. }
  584. /**
  585. * @memberOf module:zrender/core/util
  586. * @param {Function} func
  587. * @param {*} context
  588. * @return {Function}
  589. */
  590. function bind(func, context) {
  591. var args = nativeSlice.call(arguments, 2);
  592. return function () {
  593. return func.apply(context, args.concat(nativeSlice.call(arguments)));
  594. };
  595. }
  596. /**
  597. * @memberOf module:zrender/core/util
  598. * @param {Function} func
  599. * @return {Function}
  600. */
  601. function curry(func) {
  602. var args = nativeSlice.call(arguments, 1);
  603. return function () {
  604. return func.apply(this, args.concat(nativeSlice.call(arguments)));
  605. };
  606. }
  607. /**
  608. * @memberOf module:zrender/core/util
  609. * @param {*} value
  610. * @return {boolean}
  611. */
  612. function isArray(value) {
  613. return objToString.call(value) === '[object Array]';
  614. }
  615. /**
  616. * @memberOf module:zrender/core/util
  617. * @param {*} value
  618. * @return {boolean}
  619. */
  620. function isFunction$1(value) {
  621. return typeof value === 'function';
  622. }
  623. /**
  624. * @memberOf module:zrender/core/util
  625. * @param {*} value
  626. * @return {boolean}
  627. */
  628. function isString(value) {
  629. return objToString.call(value) === '[object String]';
  630. }
  631. /**
  632. * @memberOf module:zrender/core/util
  633. * @param {*} value
  634. * @return {boolean}
  635. */
  636. function isObject$1(value) {
  637. // Avoid a V8 JIT bug in Chrome 19-20.
  638. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
  639. var type = typeof value;
  640. return type === 'function' || (!!value && type === 'object');
  641. }
  642. /**
  643. * @memberOf module:zrender/core/util
  644. * @param {*} value
  645. * @return {boolean}
  646. */
  647. function isBuiltInObject(value) {
  648. return !!BUILTIN_OBJECT[objToString.call(value)];
  649. }
  650. /**
  651. * @memberOf module:zrender/core/util
  652. * @param {*} value
  653. * @return {boolean}
  654. */
  655. function isTypedArray(value) {
  656. return !!TYPED_ARRAY[objToString.call(value)];
  657. }
  658. /**
  659. * @memberOf module:zrender/core/util
  660. * @param {*} value
  661. * @return {boolean}
  662. */
  663. function isDom(value) {
  664. return typeof value === 'object'
  665. && typeof value.nodeType === 'number'
  666. && typeof value.ownerDocument === 'object';
  667. }
  668. /**
  669. * Whether is exactly NaN. Notice isNaN('a') returns true.
  670. * @param {*} value
  671. * @return {boolean}
  672. */
  673. function eqNaN(value) {
  674. /* eslint-disable-next-line no-self-compare */
  675. return value !== value;
  676. }
  677. /**
  678. * If value1 is not null, then return value1, otherwise judget rest of values.
  679. * Low performance.
  680. * @memberOf module:zrender/core/util
  681. * @return {*} Final value
  682. */
  683. function retrieve(values) {
  684. for (var i = 0, len = arguments.length; i < len; i++) {
  685. if (arguments[i] != null) {
  686. return arguments[i];
  687. }
  688. }
  689. }
  690. function retrieve2(value0, value1) {
  691. return value0 != null
  692. ? value0
  693. : value1;
  694. }
  695. function retrieve3(value0, value1, value2) {
  696. return value0 != null
  697. ? value0
  698. : value1 != null
  699. ? value1
  700. : value2;
  701. }
  702. /**
  703. * @memberOf module:zrender/core/util
  704. * @param {Array} arr
  705. * @param {number} startIndex
  706. * @param {number} endIndex
  707. * @return {Array}
  708. */
  709. function slice() {
  710. return Function.call.apply(nativeSlice, arguments);
  711. }
  712. /**
  713. * Normalize css liked array configuration
  714. * e.g.
  715. * 3 => [3, 3, 3, 3]
  716. * [4, 2] => [4, 2, 4, 2]
  717. * [4, 3, 2] => [4, 3, 2, 3]
  718. * @param {number|Array.<number>} val
  719. * @return {Array.<number>}
  720. */
  721. function normalizeCssArray(val) {
  722. if (typeof (val) === 'number') {
  723. return [val, val, val, val];
  724. }
  725. var len = val.length;
  726. if (len === 2) {
  727. // vertical | horizontal
  728. return [val[0], val[1], val[0], val[1]];
  729. }
  730. else if (len === 3) {
  731. // top | horizontal | bottom
  732. return [val[0], val[1], val[2], val[1]];
  733. }
  734. return val;
  735. }
  736. /**
  737. * @memberOf module:zrender/core/util
  738. * @param {boolean} condition
  739. * @param {string} message
  740. */
  741. function assert$1(condition, message) {
  742. if (!condition) {
  743. throw new Error(message);
  744. }
  745. }
  746. /**
  747. * @memberOf module:zrender/core/util
  748. * @param {string} str string to be trimed
  749. * @return {string} trimed string
  750. */
  751. function trim(str) {
  752. if (str == null) {
  753. return null;
  754. }
  755. else if (typeof str.trim === 'function') {
  756. return str.trim();
  757. }
  758. else {
  759. return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  760. }
  761. }
  762. var primitiveKey = '__ec_primitive__';
  763. /**
  764. * Set an object as primitive to be ignored traversing children in clone or merge
  765. */
  766. function setAsPrimitive(obj) {
  767. obj[primitiveKey] = true;
  768. }
  769. function isPrimitive(obj) {
  770. return obj[primitiveKey];
  771. }
  772. /**
  773. * @constructor
  774. * @param {Object} obj Only apply `ownProperty`.
  775. */
  776. function HashMap(obj) {
  777. var isArr = isArray(obj);
  778. // Key should not be set on this, otherwise
  779. // methods get/set/... may be overrided.
  780. this.data = {};
  781. var thisMap = this;
  782. (obj instanceof HashMap)
  783. ? obj.each(visit)
  784. : (obj && each$1(obj, visit));
  785. function visit(value, key) {
  786. isArr ? thisMap.set(value, key) : thisMap.set(key, value);
  787. }
  788. }
  789. HashMap.prototype = {
  790. constructor: HashMap,
  791. // Do not provide `has` method to avoid defining what is `has`.
  792. // (We usually treat `null` and `undefined` as the same, different
  793. // from ES6 Map).
  794. get: function (key) {
  795. return this.data.hasOwnProperty(key) ? this.data[key] : null;
  796. },
  797. set: function (key, value) {
  798. // Comparing with invocation chaining, `return value` is more commonly
  799. // used in this case: `var someVal = map.set('a', genVal());`
  800. return (this.data[key] = value);
  801. },
  802. // Although util.each can be performed on this hashMap directly, user
  803. // should not use the exposed keys, who are prefixed.
  804. each: function (cb, context) {
  805. context !== void 0 && (cb = bind(cb, context));
  806. /* eslint-disable guard-for-in */
  807. for (var key in this.data) {
  808. this.data.hasOwnProperty(key) && cb(this.data[key], key);
  809. }
  810. /* eslint-enable guard-for-in */
  811. },
  812. // Do not use this method if performance sensitive.
  813. removeKey: function (key) {
  814. delete this.data[key];
  815. }
  816. };
  817. function createHashMap(obj) {
  818. return new HashMap(obj);
  819. }
  820. function concatArray(a, b) {
  821. var newArray = new a.constructor(a.length + b.length);
  822. for (var i = 0; i < a.length; i++) {
  823. newArray[i] = a[i];
  824. }
  825. var offset = a.length;
  826. for (i = 0; i < b.length; i++) {
  827. newArray[i + offset] = b[i];
  828. }
  829. return newArray;
  830. }
  831. function noop() {}
  832. var zrUtil = (Object.freeze || Object)({
  833. $override: $override,
  834. clone: clone,
  835. merge: merge,
  836. mergeAll: mergeAll,
  837. extend: extend,
  838. defaults: defaults,
  839. createCanvas: createCanvas,
  840. getContext: getContext,
  841. indexOf: indexOf,
  842. inherits: inherits,
  843. mixin: mixin,
  844. isArrayLike: isArrayLike,
  845. each: each$1,
  846. map: map,
  847. reduce: reduce,
  848. filter: filter,
  849. find: find,
  850. bind: bind,
  851. curry: curry,
  852. isArray: isArray,
  853. isFunction: isFunction$1,
  854. isString: isString,
  855. isObject: isObject$1,
  856. isBuiltInObject: isBuiltInObject,
  857. isTypedArray: isTypedArray,
  858. isDom: isDom,
  859. eqNaN: eqNaN,
  860. retrieve: retrieve,
  861. retrieve2: retrieve2,
  862. retrieve3: retrieve3,
  863. slice: slice,
  864. normalizeCssArray: normalizeCssArray,
  865. assert: assert$1,
  866. trim: trim,
  867. setAsPrimitive: setAsPrimitive,
  868. isPrimitive: isPrimitive,
  869. createHashMap: createHashMap,
  870. concatArray: concatArray,
  871. noop: noop
  872. });
  873. /* global Float32Array */
  874. var ArrayCtor = typeof Float32Array === 'undefined'
  875. ? Array
  876. : Float32Array;
  877. /**
  878. * 创建一个向量
  879. * @param {number} [x=0]
  880. * @param {number} [y=0]
  881. * @return {Vector2}
  882. */
  883. function create(x, y) {
  884. var out = new ArrayCtor(2);
  885. if (x == null) {
  886. x = 0;
  887. }
  888. if (y == null) {
  889. y = 0;
  890. }
  891. out[0] = x;
  892. out[1] = y;
  893. return out;
  894. }
  895. /**
  896. * 复制向量数据
  897. * @param {Vector2} out
  898. * @param {Vector2} v
  899. * @return {Vector2}
  900. */
  901. function copy(out, v) {
  902. out[0] = v[0];
  903. out[1] = v[1];
  904. return out;
  905. }
  906. /**
  907. * 克隆一个向量
  908. * @param {Vector2} v
  909. * @return {Vector2}
  910. */
  911. function clone$1(v) {
  912. var out = new ArrayCtor(2);
  913. out[0] = v[0];
  914. out[1] = v[1];
  915. return out;
  916. }
  917. /**
  918. * 设置向量的两个项
  919. * @param {Vector2} out
  920. * @param {number} a
  921. * @param {number} b
  922. * @return {Vector2} 结果
  923. */
  924. function set(out, a, b) {
  925. out[0] = a;
  926. out[1] = b;
  927. return out;
  928. }
  929. /**
  930. * 向量相加
  931. * @param {Vector2} out
  932. * @param {Vector2} v1
  933. * @param {Vector2} v2
  934. */
  935. function add(out, v1, v2) {
  936. out[0] = v1[0] + v2[0];
  937. out[1] = v1[1] + v2[1];
  938. return out;
  939. }
  940. /**
  941. * 向量缩放后相加
  942. * @param {Vector2} out
  943. * @param {Vector2} v1
  944. * @param {Vector2} v2
  945. * @param {number} a
  946. */
  947. function scaleAndAdd(out, v1, v2, a) {
  948. out[0] = v1[0] + v2[0] * a;
  949. out[1] = v1[1] + v2[1] * a;
  950. return out;
  951. }
  952. /**
  953. * 向量相减
  954. * @param {Vector2} out
  955. * @param {Vector2} v1
  956. * @param {Vector2} v2
  957. */
  958. function sub(out, v1, v2) {
  959. out[0] = v1[0] - v2[0];
  960. out[1] = v1[1] - v2[1];
  961. return out;
  962. }
  963. /**
  964. * 向量长度
  965. * @param {Vector2} v
  966. * @return {number}
  967. */
  968. function len(v) {
  969. return Math.sqrt(lenSquare(v));
  970. }
  971. var length = len; // jshint ignore:line
  972. /**
  973. * 向量长度平方
  974. * @param {Vector2} v
  975. * @return {number}
  976. */
  977. function lenSquare(v) {
  978. return v[0] * v[0] + v[1] * v[1];
  979. }
  980. var lengthSquare = lenSquare;
  981. /**
  982. * 向量乘法
  983. * @param {Vector2} out
  984. * @param {Vector2} v1
  985. * @param {Vector2} v2
  986. */
  987. function mul(out, v1, v2) {
  988. out[0] = v1[0] * v2[0];
  989. out[1] = v1[1] * v2[1];
  990. return out;
  991. }
  992. /**
  993. * 向量除法
  994. * @param {Vector2} out
  995. * @param {Vector2} v1
  996. * @param {Vector2} v2
  997. */
  998. function div(out, v1, v2) {
  999. out[0] = v1[0] / v2[0];
  1000. out[1] = v1[1] / v2[1];
  1001. return out;
  1002. }
  1003. /**
  1004. * 向量点乘
  1005. * @param {Vector2} v1
  1006. * @param {Vector2} v2
  1007. * @return {number}
  1008. */
  1009. function dot(v1, v2) {
  1010. return v1[0] * v2[0] + v1[1] * v2[1];
  1011. }
  1012. /**
  1013. * 向量缩放
  1014. * @param {Vector2} out
  1015. * @param {Vector2} v
  1016. * @param {number} s
  1017. */
  1018. function scale(out, v, s) {
  1019. out[0] = v[0] * s;
  1020. out[1] = v[1] * s;
  1021. return out;
  1022. }
  1023. /**
  1024. * 向量归一化
  1025. * @param {Vector2} out
  1026. * @param {Vector2} v
  1027. */
  1028. function normalize(out, v) {
  1029. var d = len(v);
  1030. if (d === 0) {
  1031. out[0] = 0;
  1032. out[1] = 0;
  1033. }
  1034. else {
  1035. out[0] = v[0] / d;
  1036. out[1] = v[1] / d;
  1037. }
  1038. return out;
  1039. }
  1040. /**
  1041. * 计算向量间距离
  1042. * @param {Vector2} v1
  1043. * @param {Vector2} v2
  1044. * @return {number}
  1045. */
  1046. function distance(v1, v2) {
  1047. return Math.sqrt(
  1048. (v1[0] - v2[0]) * (v1[0] - v2[0])
  1049. + (v1[1] - v2[1]) * (v1[1] - v2[1])
  1050. );
  1051. }
  1052. var dist = distance;
  1053. /**
  1054. * 向量距离平方
  1055. * @param {Vector2} v1
  1056. * @param {Vector2} v2
  1057. * @return {number}
  1058. */
  1059. function distanceSquare(v1, v2) {
  1060. return (v1[0] - v2[0]) * (v1[0] - v2[0])
  1061. + (v1[1] - v2[1]) * (v1[1] - v2[1]);
  1062. }
  1063. var distSquare = distanceSquare;
  1064. /**
  1065. * 求负向量
  1066. * @param {Vector2} out
  1067. * @param {Vector2} v
  1068. */
  1069. function negate(out, v) {
  1070. out[0] = -v[0];
  1071. out[1] = -v[1];
  1072. return out;
  1073. }
  1074. /**
  1075. * 插值两个点
  1076. * @param {Vector2} out
  1077. * @param {Vector2} v1
  1078. * @param {Vector2} v2
  1079. * @param {number} t
  1080. */
  1081. function lerp(out, v1, v2, t) {
  1082. out[0] = v1[0] + t * (v2[0] - v1[0]);
  1083. out[1] = v1[1] + t * (v2[1] - v1[1]);
  1084. return out;
  1085. }
  1086. /**
  1087. * 矩阵左乘向量
  1088. * @param {Vector2} out
  1089. * @param {Vector2} v
  1090. * @param {Vector2} m
  1091. */
  1092. function applyTransform(out, v, m) {
  1093. var x = v[0];
  1094. var y = v[1];
  1095. out[0] = m[0] * x + m[2] * y + m[4];
  1096. out[1] = m[1] * x + m[3] * y + m[5];
  1097. return out;
  1098. }
  1099. /**
  1100. * 求两个向量最小值
  1101. * @param {Vector2} out
  1102. * @param {Vector2} v1
  1103. * @param {Vector2} v2
  1104. */
  1105. function min(out, v1, v2) {
  1106. out[0] = Math.min(v1[0], v2[0]);
  1107. out[1] = Math.min(v1[1], v2[1]);
  1108. return out;
  1109. }
  1110. /**
  1111. * 求两个向量最大值
  1112. * @param {Vector2} out
  1113. * @param {Vector2} v1
  1114. * @param {Vector2} v2
  1115. */
  1116. function max(out, v1, v2) {
  1117. out[0] = Math.max(v1[0], v2[0]);
  1118. out[1] = Math.max(v1[1], v2[1]);
  1119. return out;
  1120. }
  1121. var vector = (Object.freeze || Object)({
  1122. create: create,
  1123. copy: copy,
  1124. clone: clone$1,
  1125. set: set,
  1126. add: add,
  1127. scaleAndAdd: scaleAndAdd,
  1128. sub: sub,
  1129. len: len,
  1130. length: length,
  1131. lenSquare: lenSquare,
  1132. lengthSquare: lengthSquare,
  1133. mul: mul,
  1134. div: div,
  1135. dot: dot,
  1136. scale: scale,
  1137. normalize: normalize,
  1138. distance: distance,
  1139. dist: dist,
  1140. distanceSquare: distanceSquare,
  1141. distSquare: distSquare,
  1142. negate: negate,
  1143. lerp: lerp,
  1144. applyTransform: applyTransform,
  1145. min: min,
  1146. max: max
  1147. });
  1148. // TODO Draggable for group
  1149. // FIXME Draggable on element which has parent rotation or scale
  1150. function Draggable() {
  1151. this.on('mousedown', this._dragStart, this);
  1152. this.on('mousemove', this._drag, this);
  1153. this.on('mouseup', this._dragEnd, this);
  1154. // `mosuemove` and `mouseup` can be continue to fire when dragging.
  1155. // See [Drag outside] in `Handler.js`. So we do not need to trigger
  1156. // `_dragEnd` when globalout. That would brings better user experience.
  1157. // this.on('globalout', this._dragEnd, this);
  1158. // this._dropTarget = null;
  1159. // this._draggingTarget = null;
  1160. // this._x = 0;
  1161. // this._y = 0;
  1162. }
  1163. Draggable.prototype = {
  1164. constructor: Draggable,
  1165. _dragStart: function (e) {
  1166. var draggingTarget = e.target;
  1167. // Find if there is draggable in the ancestor
  1168. while (draggingTarget && !draggingTarget.draggable) {
  1169. draggingTarget = draggingTarget.parent;
  1170. }
  1171. if (draggingTarget) {
  1172. this._draggingTarget = draggingTarget;
  1173. draggingTarget.dragging = true;
  1174. this._x = e.offsetX;
  1175. this._y = e.offsetY;
  1176. this.dispatchToElement(param(draggingTarget, e), 'dragstart', e.event);
  1177. }
  1178. },
  1179. _drag: function (e) {
  1180. var draggingTarget = this._draggingTarget;
  1181. if (draggingTarget) {
  1182. var x = e.offsetX;
  1183. var y = e.offsetY;
  1184. var dx = x - this._x;
  1185. var dy = y - this._y;
  1186. this._x = x;
  1187. this._y = y;
  1188. draggingTarget.drift(dx, dy, e);
  1189. this.dispatchToElement(param(draggingTarget, e), 'drag', e.event);
  1190. var dropTarget = this.findHover(x, y, draggingTarget).target;
  1191. var lastDropTarget = this._dropTarget;
  1192. this._dropTarget = dropTarget;
  1193. if (draggingTarget !== dropTarget) {
  1194. if (lastDropTarget && dropTarget !== lastDropTarget) {
  1195. this.dispatchToElement(param(lastDropTarget, e), 'dragleave', e.event);
  1196. }
  1197. if (dropTarget && dropTarget !== lastDropTarget) {
  1198. this.dispatchToElement(param(dropTarget, e), 'dragenter', e.event);
  1199. }
  1200. }
  1201. }
  1202. },
  1203. _dragEnd: function (e) {
  1204. var draggingTarget = this._draggingTarget;
  1205. if (draggingTarget) {
  1206. draggingTarget.dragging = false;
  1207. }
  1208. this.dispatchToElement(param(draggingTarget, e), 'dragend', e.event);
  1209. if (this._dropTarget) {
  1210. this.dispatchToElement(param(this._dropTarget, e), 'drop', e.event);
  1211. }
  1212. this._draggingTarget = null;
  1213. this._dropTarget = null;
  1214. }
  1215. };
  1216. function param(target, e) {
  1217. return {target: target, topTarget: e && e.topTarget};
  1218. }
  1219. /**
  1220. * Event Mixin
  1221. * @module zrender/mixin/Eventful
  1222. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  1223. * pissang (https://www.github.com/pissang)
  1224. */
  1225. var arrySlice = Array.prototype.slice;
  1226. /**
  1227. * Event dispatcher.
  1228. *
  1229. * @alias module:zrender/mixin/Eventful
  1230. * @constructor
  1231. * @param {Object} [eventProcessor] The object eventProcessor is the scope when
  1232. * `eventProcessor.xxx` called.
  1233. * @param {Function} [eventProcessor.normalizeQuery]
  1234. * param: {string|Object} Raw query.
  1235. * return: {string|Object} Normalized query.
  1236. * @param {Function} [eventProcessor.filter] Event will be dispatched only
  1237. * if it returns `true`.
  1238. * param: {string} eventType
  1239. * param: {string|Object} query
  1240. * return: {boolean}
  1241. * @param {Function} [eventProcessor.afterTrigger] Called after all handlers called.
  1242. * param: {string} eventType
  1243. */
  1244. var Eventful = function (eventProcessor) {
  1245. this._$handlers = {};
  1246. this._$eventProcessor = eventProcessor;
  1247. };
  1248. Eventful.prototype = {
  1249. constructor: Eventful,
  1250. /**
  1251. * The handler can only be triggered once, then removed.
  1252. *
  1253. * @param {string} event The event name.
  1254. * @param {string|Object} [query] Condition used on event filter.
  1255. * @param {Function} handler The event handler.
  1256. * @param {Object} context
  1257. */
  1258. one: function (event, query, handler, context) {
  1259. return on(this, event, query, handler, context, true);
  1260. },
  1261. /**
  1262. * Bind a handler.
  1263. *
  1264. * @param {string} event The event name.
  1265. * @param {string|Object} [query] Condition used on event filter.
  1266. * @param {Function} handler The event handler.
  1267. * @param {Object} [context]
  1268. */
  1269. on: function (event, query, handler, context) {
  1270. return on(this, event, query, handler, context, false);
  1271. },
  1272. /**
  1273. * Whether any handler has bound.
  1274. *
  1275. * @param {string} event
  1276. * @return {boolean}
  1277. */
  1278. isSilent: function (event) {
  1279. var _h = this._$handlers;
  1280. return !_h[event] || !_h[event].length;
  1281. },
  1282. /**
  1283. * Unbind a event.
  1284. *
  1285. * @param {string} [event] The event name.
  1286. * If no `event` input, "off" all listeners.
  1287. * @param {Function} [handler] The event handler.
  1288. * If no `handler` input, "off" all listeners of the `event`.
  1289. */
  1290. off: function (event, handler) {
  1291. var _h = this._$handlers;
  1292. if (!event) {
  1293. this._$handlers = {};
  1294. return this;
  1295. }
  1296. if (handler) {
  1297. if (_h[event]) {
  1298. var newList = [];
  1299. for (var i = 0, l = _h[event].length; i < l; i++) {
  1300. if (_h[event][i].h !== handler) {
  1301. newList.push(_h[event][i]);
  1302. }
  1303. }
  1304. _h[event] = newList;
  1305. }
  1306. if (_h[event] && _h[event].length === 0) {
  1307. delete _h[event];
  1308. }
  1309. }
  1310. else {
  1311. delete _h[event];
  1312. }
  1313. return this;
  1314. },
  1315. /**
  1316. * Dispatch a event.
  1317. *
  1318. * @param {string} type The event name.
  1319. */
  1320. trigger: function (type) {
  1321. var _h = this._$handlers[type];
  1322. var eventProcessor = this._$eventProcessor;
  1323. if (_h) {
  1324. var args = arguments;
  1325. var argLen = args.length;
  1326. if (argLen > 3) {
  1327. args = arrySlice.call(args, 1);
  1328. }
  1329. var len = _h.length;
  1330. for (var i = 0; i < len;) {
  1331. var hItem = _h[i];
  1332. if (eventProcessor
  1333. && eventProcessor.filter
  1334. && hItem.query != null
  1335. && !eventProcessor.filter(type, hItem.query)
  1336. ) {
  1337. i++;
  1338. continue;
  1339. }
  1340. // Optimize advise from backbone
  1341. switch (argLen) {
  1342. case 1:
  1343. hItem.h.call(hItem.ctx);
  1344. break;
  1345. case 2:
  1346. hItem.h.call(hItem.ctx, args[1]);
  1347. break;
  1348. case 3:
  1349. hItem.h.call(hItem.ctx, args[1], args[2]);
  1350. break;
  1351. default:
  1352. // have more than 2 given arguments
  1353. hItem.h.apply(hItem.ctx, args);
  1354. break;
  1355. }
  1356. if (hItem.one) {
  1357. _h.splice(i, 1);
  1358. len--;
  1359. }
  1360. else {
  1361. i++;
  1362. }
  1363. }
  1364. }
  1365. eventProcessor && eventProcessor.afterTrigger
  1366. && eventProcessor.afterTrigger(type);
  1367. return this;
  1368. },
  1369. /**
  1370. * Dispatch a event with context, which is specified at the last parameter.
  1371. *
  1372. * @param {string} type The event name.
  1373. */
  1374. triggerWithContext: function (type) {
  1375. var _h = this._$handlers[type];
  1376. var eventProcessor = this._$eventProcessor;
  1377. if (_h) {
  1378. var args = arguments;
  1379. var argLen = args.length;
  1380. if (argLen > 4) {
  1381. args = arrySlice.call(args, 1, args.length - 1);
  1382. }
  1383. var ctx = args[args.length - 1];
  1384. var len = _h.length;
  1385. for (var i = 0; i < len;) {
  1386. var hItem = _h[i];
  1387. if (eventProcessor
  1388. && eventProcessor.filter
  1389. && hItem.query != null
  1390. && !eventProcessor.filter(type, hItem.query)
  1391. ) {
  1392. i++;
  1393. continue;
  1394. }
  1395. // Optimize advise from backbone
  1396. switch (argLen) {
  1397. case 1:
  1398. hItem.h.call(ctx);
  1399. break;
  1400. case 2:
  1401. hItem.h.call(ctx, args[1]);
  1402. break;
  1403. case 3:
  1404. hItem.h.call(ctx, args[1], args[2]);
  1405. break;
  1406. default:
  1407. // have more than 2 given arguments
  1408. hItem.h.apply(ctx, args);
  1409. break;
  1410. }
  1411. if (hItem.one) {
  1412. _h.splice(i, 1);
  1413. len--;
  1414. }
  1415. else {
  1416. i++;
  1417. }
  1418. }
  1419. }
  1420. eventProcessor && eventProcessor.afterTrigger
  1421. && eventProcessor.afterTrigger(type);
  1422. return this;
  1423. }
  1424. };
  1425. function normalizeQuery(host, query) {
  1426. var eventProcessor = host._$eventProcessor;
  1427. if (query != null && eventProcessor && eventProcessor.normalizeQuery) {
  1428. query = eventProcessor.normalizeQuery(query);
  1429. }
  1430. return query;
  1431. }
  1432. function on(eventful, event, query, handler, context, isOnce) {
  1433. var _h = eventful._$handlers;
  1434. if (typeof query === 'function') {
  1435. context = handler;
  1436. handler = query;
  1437. query = null;
  1438. }
  1439. if (!handler || !event) {
  1440. return eventful;
  1441. }
  1442. query = normalizeQuery(eventful, query);
  1443. if (!_h[event]) {
  1444. _h[event] = [];
  1445. }
  1446. for (var i = 0; i < _h[event].length; i++) {
  1447. if (_h[event][i].h === handler) {
  1448. return eventful;
  1449. }
  1450. }
  1451. var wrap = {
  1452. h: handler,
  1453. one: isOnce,
  1454. query: query,
  1455. ctx: context || eventful,
  1456. // FIXME
  1457. // Do not publish this feature util it is proved that it makes sense.
  1458. callAtLast: handler.zrEventfulCallAtLast
  1459. };
  1460. var lastIndex = _h[event].length - 1;
  1461. var lastWrap = _h[event][lastIndex];
  1462. (lastWrap && lastWrap.callAtLast)
  1463. ? _h[event].splice(lastIndex, 0, wrap)
  1464. : _h[event].push(wrap);
  1465. return eventful;
  1466. }
  1467. /**
  1468. * The algoritm is learnt from
  1469. * https://franklinta.com/2014/09/08/computing-css-matrix3d-transforms/
  1470. * And we made some optimization for matrix inversion.
  1471. * Other similar approaches:
  1472. * "cv::getPerspectiveTransform", "Direct Linear Transformation".
  1473. */
  1474. var LN2 = Math.log(2);
  1475. function determinant(rows, rank, rowStart, rowMask, colMask, detCache) {
  1476. var cacheKey = rowMask + '-' + colMask;
  1477. var fullRank = rows.length;
  1478. if (detCache.hasOwnProperty(cacheKey)) {
  1479. return detCache[cacheKey];
  1480. }
  1481. if (rank === 1) {
  1482. // In this case the colMask must be like: `11101111`. We can find the place of `0`.
  1483. var colStart = Math.round(Math.log(((1 << fullRank) - 1) & ~colMask) / LN2);
  1484. return rows[rowStart][colStart];
  1485. }
  1486. var subRowMask = rowMask | (1 << rowStart);
  1487. var subRowStart = rowStart + 1;
  1488. while (rowMask & (1 << subRowStart)) {
  1489. subRowStart++;
  1490. }
  1491. var sum = 0;
  1492. for (var j = 0, colLocalIdx = 0; j < fullRank; j++) {
  1493. var colTag = 1 << j;
  1494. if (!(colTag & colMask)) {
  1495. sum += (colLocalIdx % 2 ? -1 : 1) * rows[rowStart][j]
  1496. // det(subMatrix(0, j))
  1497. * determinant(rows, rank - 1, subRowStart, subRowMask, colMask | colTag, detCache);
  1498. colLocalIdx++;
  1499. }
  1500. }
  1501. detCache[cacheKey] = sum;
  1502. return sum;
  1503. }
  1504. /**
  1505. * Usage:
  1506. * ```js
  1507. * var transformer = buildTransformer(
  1508. * [10, 44, 100, 44, 100, 300, 10, 300],
  1509. * [50, 54, 130, 14, 140, 330, 14, 220]
  1510. * );
  1511. * var out = [];
  1512. * transformer && transformer([11, 33], out);
  1513. * ```
  1514. *
  1515. * Notice: `buildTransformer` may take more than 10ms in some Android device.
  1516. *
  1517. * @param {Array.<number>} src source four points, [x0, y0, x1, y1, x2, y2, x3, y3]
  1518. * @param {Array.<number>} dest destination four points, [x0, y0, x1, y1, x2, y2, x3, y3]
  1519. * @return {Function} transformer If fail, return null/undefined.
  1520. */
  1521. function buildTransformer(src, dest) {
  1522. var mA = [
  1523. [src[0], src[1], 1, 0, 0, 0, -dest[0] * src[0], -dest[0] * src[1]],
  1524. [0, 0, 0, src[0], src[1], 1, -dest[1] * src[0], -dest[1] * src[1]],
  1525. [src[2], src[3], 1, 0, 0, 0, -dest[2] * src[2], -dest[2] * src[3]],
  1526. [0, 0, 0, src[2], src[3], 1, -dest[3] * src[2], -dest[3] * src[3]],
  1527. [src[4], src[5], 1, 0, 0, 0, -dest[4] * src[4], -dest[4] * src[5]],
  1528. [0, 0, 0, src[4], src[5], 1, -dest[5] * src[4], -dest[5] * src[5]],
  1529. [src[6], src[7], 1, 0, 0, 0, -dest[6] * src[6], -dest[6] * src[7]],
  1530. [0, 0, 0, src[6], src[7], 1, -dest[7] * src[6], -dest[7] * src[7]]
  1531. ];
  1532. var detCache = {};
  1533. var det = determinant(mA, 8, 0, 0, 0, detCache);
  1534. if (det === 0) {
  1535. // can not make transformer when and only when
  1536. // any three of the markers are collinear.
  1537. return;
  1538. }
  1539. // `invert(mA) * dest`, that is, `adj(mA) / det * dest`.
  1540. var vh = [];
  1541. for (var i = 0; i < 8; i++) {
  1542. for (var j = 0; j < 8; j++) {
  1543. vh[j] == null && (vh[j] = 0);
  1544. vh[j] += ((i + j) % 2 ? -1 : 1)
  1545. // det(subMatrix(i, j))
  1546. * determinant(mA, 7, i === 0 ? 1 : 0, 1 << i, 1 << j, detCache)
  1547. / det * dest[i];
  1548. }
  1549. }
  1550. return function (out, srcPointX, srcPointY) {
  1551. var pk = srcPointX * vh[6] + srcPointY * vh[7] + 1;
  1552. out[0] = (srcPointX * vh[0] + srcPointY * vh[1] + vh[2]) / pk;
  1553. out[1] = (srcPointX * vh[3] + srcPointY * vh[4] + vh[5]) / pk;
  1554. };
  1555. }
  1556. var EVENT_SAVED_PROP = '___zrEVENTSAVED';
  1557. var _calcOut$1 = [];
  1558. /**
  1559. * Transform "local coord" from `elFrom` to `elTarget`.
  1560. * "local coord": the coord based on the input `el`. The origin point is at
  1561. * the position of "left: 0; top: 0;" in the `el`.
  1562. *
  1563. * Support when CSS transform is used.
  1564. *
  1565. * Having the `out` (that is, `[outX, outY]`), we can create an DOM element
  1566. * and set the CSS style as "left: outX; top: outY;" and append it to `elTarge`
  1567. * to locate the element.
  1568. *
  1569. * For example, this code below positions a child of `document.body` on the event
  1570. * point, no matter whether `body` has `margin`/`paddin`/`transfrom`/... :
  1571. * ```js
  1572. * transformLocalCoord(out, container, document.body, event.offsetX, event.offsetY);
  1573. * if (!eqNaN(out[0])) {
  1574. * // Then locate the tip element on the event point.
  1575. * var tipEl = document.createElement('div');
  1576. * tipEl.style.cssText = 'position: absolute; left:' + out[0] + ';top:' + out[1] + ';';
  1577. * document.body.appendChild(tipEl);
  1578. * }
  1579. * ```
  1580. *
  1581. * Notice: In some env this method is not supported. If called, `out` will be `[NaN, NaN]`.
  1582. *
  1583. * @param {Array.<number>} out [inX: number, inY: number] The output..
  1584. * If can not transform, `out` will not be modified but return `false`.
  1585. * @param {HTMLElement} elFrom The `[inX, inY]` is based on elFrom.
  1586. * @param {HTMLElement} elTarget The `out` is based on elTarget.
  1587. * @param {number} inX
  1588. * @param {number} inY
  1589. * @return {boolean} Whether transform successfully.
  1590. */
  1591. function transformLocalCoord(out, elFrom, elTarget, inX, inY) {
  1592. return transformCoordWithViewport(_calcOut$1, elFrom, inX, inY, true)
  1593. && transformCoordWithViewport(out, elTarget, _calcOut$1[0], _calcOut$1[1]);
  1594. }
  1595. /**
  1596. * Transform between a "viewport coord" and a "local coord".
  1597. * "viewport coord": the coord based on the left-top corner of the viewport
  1598. * of the browser.
  1599. * "local coord": the coord based on the input `el`. The origin point is at
  1600. * the position of "left: 0; top: 0;" in the `el`.
  1601. *
  1602. * Support the case when CSS transform is used on el.
  1603. *
  1604. * @param {Array.<number>} out [inX: number, inY: number] The output. If `inverse: false`,
  1605. * it represents "local coord", otherwise "vireport coord".
  1606. * If can not transform, `out` will not be modified but return `false`.
  1607. * @param {HTMLElement} el The "local coord" is based on the `el`, see comment above.
  1608. * @param {number} inX If `inverse: false`,
  1609. * it represents "vireport coord", otherwise "local coord".
  1610. * @param {number} inY If `inverse: false`,
  1611. * it represents "vireport coord", otherwise "local coord".
  1612. * @param {boolean} [inverse=false]
  1613. * `true`: from "viewport coord" to "local coord".
  1614. * `false`: from "local coord" to "viewport coord".
  1615. * @return {boolean} Whether transform successfully.
  1616. */
  1617. function transformCoordWithViewport(out, el, inX, inY, inverse) {
  1618. if (el.getBoundingClientRect && env$1.domSupported && !isCanvasEl(el)) {
  1619. var saved = el[EVENT_SAVED_PROP] || (el[EVENT_SAVED_PROP] = {});
  1620. var markers = prepareCoordMarkers(el, saved);
  1621. var transformer = preparePointerTransformer(markers, saved, inverse);
  1622. if (transformer) {
  1623. transformer(out, inX, inY);
  1624. return true;
  1625. }
  1626. }
  1627. return false;
  1628. }
  1629. function prepareCoordMarkers(el, saved) {
  1630. var markers = saved.markers;
  1631. if (markers) {
  1632. return markers;
  1633. }
  1634. markers = saved.markers = [];
  1635. var propLR = ['left', 'right'];
  1636. var propTB = ['top', 'bottom'];
  1637. for (var i = 0; i < 4; i++) {
  1638. var marker = document.createElement('div');
  1639. var stl = marker.style;
  1640. var idxLR = i % 2;
  1641. var idxTB = (i >> 1) % 2;
  1642. stl.cssText = [
  1643. 'position: absolute',
  1644. 'visibility: hidden',
  1645. 'padding: 0',
  1646. 'margin: 0',
  1647. 'border-width: 0',
  1648. 'user-select: none',
  1649. 'width:0',
  1650. 'height:0',
  1651. // 'width: 5px',
  1652. // 'height: 5px',
  1653. propLR[idxLR] + ':0',
  1654. propTB[idxTB] + ':0',
  1655. propLR[1 - idxLR] + ':auto',
  1656. propTB[1 - idxTB] + ':auto',
  1657. ''
  1658. ].join('!important;');
  1659. el.appendChild(marker);
  1660. markers.push(marker);
  1661. }
  1662. return markers;
  1663. }
  1664. function preparePointerTransformer(markers, saved, inverse) {
  1665. var transformerName = inverse ? 'invTrans' : 'trans';
  1666. var transformer = saved[transformerName];
  1667. var oldSrcCoords = saved.srcCoords;
  1668. var oldCoordTheSame = true;
  1669. var srcCoords = [];
  1670. var destCoords = [];
  1671. for (var i = 0; i < 4; i++) {
  1672. var rect = markers[i].getBoundingClientRect();
  1673. var ii = 2 * i;
  1674. var x = rect.left;
  1675. var y = rect.top;
  1676. srcCoords.push(x, y);
  1677. oldCoordTheSame = oldCoordTheSame && oldSrcCoords && x === oldSrcCoords[ii] && y === oldSrcCoords[ii + 1];
  1678. destCoords.push(markers[i].offsetLeft, markers[i].offsetTop);
  1679. }
  1680. // Cache to avoid time consuming of `buildTransformer`.
  1681. return (oldCoordTheSame && transformer)
  1682. ? transformer
  1683. : (
  1684. saved.srcCoords = srcCoords,
  1685. saved[transformerName] = inverse
  1686. ? buildTransformer(destCoords, srcCoords)
  1687. : buildTransformer(srcCoords, destCoords)
  1688. );
  1689. }
  1690. function isCanvasEl(el) {
  1691. return el.nodeName.toUpperCase() === 'CANVAS';
  1692. }
  1693. /**
  1694. * Utilities for mouse or touch events.
  1695. */
  1696. var isDomLevel2 = (typeof window !== 'undefined') && !!window.addEventListener;
  1697. var MOUSE_EVENT_REG = /^(?:mouse|pointer|contextmenu|drag|drop)|click/;
  1698. var _calcOut = [];
  1699. /**
  1700. * Get the `zrX` and `zrY`, which are relative to the top-left of
  1701. * the input `el`.
  1702. * CSS transform (2D & 3D) is supported.
  1703. *
  1704. * The strategy to fetch the coords:
  1705. * + If `calculate` is not set as `true`, users of this method should
  1706. * ensure that `el` is the same or the same size & location as `e.target`.
  1707. * Otherwise the result coords are probably not expected. Because we
  1708. * firstly try to get coords from e.offsetX/e.offsetY.
  1709. * + If `calculate` is set as `true`, the input `el` can be any element
  1710. * and we force to calculate the coords based on `el`.
  1711. * + The input `el` should be positionable (not position:static).
  1712. *
  1713. * The force `calculate` can be used in case like:
  1714. * When mousemove event triggered on ec tooltip, `e.target` is not `el`(zr painter.dom).
  1715. *
  1716. * @param {HTMLElement} el DOM element.
  1717. * @param {Event} e Mouse event or touch event.
  1718. * @param {Object} out Get `out.zrX` and `out.zrY` as the result.
  1719. * @param {boolean} [calculate=false] Whether to force calculate
  1720. * the coordinates but not use ones provided by browser.
  1721. */
  1722. function clientToLocal(el, e, out, calculate) {
  1723. out = out || {};
  1724. // According to the W3C Working Draft, offsetX and offsetY should be relative
  1725. // to the padding edge of the target element. The only browser using this convention
  1726. // is IE. Webkit uses the border edge, Opera uses the content edge, and FireFox does
  1727. // not support the properties.
  1728. // (see http://www.jacklmoore.com/notes/mouse-position/)
  1729. // In zr painter.dom, padding edge equals to border edge.
  1730. if (calculate || !env$1.canvasSupported) {
  1731. calculateZrXY(el, e, out);
  1732. }
  1733. // Caution: In FireFox, layerX/layerY Mouse position relative to the closest positioned
  1734. // ancestor element, so we should make sure el is positioned (e.g., not position:static).
  1735. // BTW1, Webkit don't return the same results as FF in non-simple cases (like add
  1736. // zoom-factor, overflow / opacity layers, transforms ...)
  1737. // BTW2, (ev.offsetY || ev.pageY - $(ev.target).offset().top) is not correct in preserve-3d.
  1738. // <https://bugs.jquery.com/ticket/8523#comment:14>
  1739. // BTW3, In ff, offsetX/offsetY is always 0.
  1740. else if (env$1.browser.firefox && e.layerX != null && e.layerX !== e.offsetX) {
  1741. out.zrX = e.layerX;
  1742. out.zrY = e.layerY;
  1743. }
  1744. // For IE6+, chrome, safari, opera. (When will ff support offsetX?)
  1745. else if (e.offsetX != null) {
  1746. out.zrX = e.offsetX;
  1747. out.zrY = e.offsetY;
  1748. }
  1749. // For some other device, e.g., IOS safari.
  1750. else {
  1751. calculateZrXY(el, e, out);
  1752. }
  1753. return out;
  1754. }
  1755. function calculateZrXY(el, e, out) {
  1756. // BlackBerry 5, iOS 3 (original iPhone) don't have getBoundingRect.
  1757. if (env$1.domSupported && el.getBoundingClientRect) {
  1758. var ex = e.clientX;
  1759. var ey = e.clientY;
  1760. if (isCanvasEl(el)) {
  1761. // Original approach, which do not support CSS transform.
  1762. // marker can not be locationed in a canvas container
  1763. // (getBoundingClientRect is always 0). We do not support
  1764. // that input a pre-created canvas to zr while using css
  1765. // transform in iOS.
  1766. var box = el.getBoundingClientRect();
  1767. out.zrX = ex - box.left;
  1768. out.zrY = ey - box.top;
  1769. return;
  1770. }
  1771. else {
  1772. if (transformCoordWithViewport(_calcOut, el, ex, ey)) {
  1773. out.zrX = _calcOut[0];
  1774. out.zrY = _calcOut[1];
  1775. return;
  1776. }
  1777. }
  1778. }
  1779. out.zrX = out.zrY = 0;
  1780. }
  1781. /**
  1782. * Find native event compat for legency IE.
  1783. * Should be called at the begining of a native event listener.
  1784. *
  1785. * @param {Event} [e] Mouse event or touch event or pointer event.
  1786. * For lagency IE, we use `window.event` is used.
  1787. * @return {Event} The native event.
  1788. */
  1789. function getNativeEvent(e) {
  1790. return e || window.event;
  1791. }
  1792. /**
  1793. * Normalize the coordinates of the input event.
  1794. *
  1795. * Get the `e.zrX` and `e.zrY`, which are relative to the top-left of
  1796. * the input `el`.
  1797. * Get `e.zrDelta` if using mouse wheel.
  1798. * Get `e.which`, see the comment inside this function.
  1799. *
  1800. * Do not calculate repeatly if `zrX` and `zrY` already exist.
  1801. *
  1802. * Notice: see comments in `clientToLocal`. check the relationship
  1803. * between the result coords and the parameters `el` and `calculate`.
  1804. *
  1805. * @param {HTMLElement} el DOM element.
  1806. * @param {Event} [e] See `getNativeEvent`.
  1807. * @param {boolean} [calculate=false] Whether to force calculate
  1808. * the coordinates but not use ones provided by browser.
  1809. * @return {UIEvent} The normalized native UIEvent.
  1810. */
  1811. function normalizeEvent(el, e, calculate) {
  1812. e = getNativeEvent(e);
  1813. if (e.zrX != null) {
  1814. return e;
  1815. }
  1816. var eventType = e.type;
  1817. var isTouch = eventType && eventType.indexOf('touch') >= 0;
  1818. if (!isTouch) {
  1819. clientToLocal(el, e, e, calculate);
  1820. e.zrDelta = (e.wheelDelta) ? e.wheelDelta / 120 : -(e.detail || 0) / 3;
  1821. }
  1822. else {
  1823. var touch = eventType !== 'touchend'
  1824. ? e.targetTouches[0]
  1825. : e.changedTouches[0];
  1826. touch && clientToLocal(el, touch, e, calculate);
  1827. }
  1828. // Add which for click: 1 === left; 2 === middle; 3 === right; otherwise: 0;
  1829. // See jQuery: https://github.com/jquery/jquery/blob/master/src/event.js
  1830. // If e.which has been defined, it may be readonly,
  1831. // see: https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/which
  1832. var button = e.button;
  1833. if (e.which == null && button !== undefined && MOUSE_EVENT_REG.test(e.type)) {
  1834. e.which = (button & 1 ? 1 : (button & 2 ? 3 : (button & 4 ? 2 : 0)));
  1835. }
  1836. // [Caution]: `e.which` from browser is not always reliable. For example,
  1837. // when press left button and `mousemove (pointermove)` in Edge, the `e.which`
  1838. // is 65536 and the `e.button` is -1. But the `mouseup (pointerup)` and
  1839. // `mousedown (pointerdown)` is the same as Chrome does.
  1840. return e;
  1841. }
  1842. /**
  1843. * @param {HTMLElement} el
  1844. * @param {string} name
  1845. * @param {Function} handler
  1846. * @param {Object|boolean} opt If boolean, means `opt.capture`
  1847. * @param {boolean} [opt.capture=false]
  1848. * @param {boolean} [opt.passive=false]
  1849. */
  1850. function addEventListener(el, name, handler, opt) {
  1851. if (isDomLevel2) {
  1852. // Reproduct the console warning:
  1853. // [Violation] Added non-passive event listener to a scroll-blocking <some> event.
  1854. // Consider marking event handler as 'passive' to make the page more responsive.
  1855. // Just set console log level: verbose in chrome dev tool.
  1856. // then the warning log will be printed when addEventListener called.
  1857. // See https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md
  1858. // We have not yet found a neat way to using passive. Because in zrender the dom event
  1859. // listener delegate all of the upper events of element. Some of those events need
  1860. // to prevent default. For example, the feature `preventDefaultMouseMove` of echarts.
  1861. // Before passive can be adopted, these issues should be considered:
  1862. // (1) Whether and how a zrender user specifies an event listener passive. And by default,
  1863. // passive or not.
  1864. // (2) How to tread that some zrender event listener is passive, and some is not. If
  1865. // we use other way but not preventDefault of mousewheel and touchmove, browser
  1866. // compatibility should be handled.
  1867. // var opts = (env.passiveSupported && name === 'mousewheel')
  1868. // ? {passive: true}
  1869. // // By default, the third param of el.addEventListener is `capture: false`.
  1870. // : void 0;
  1871. // el.addEventListener(name, handler /* , opts */);
  1872. el.addEventListener(name, handler, opt);
  1873. }
  1874. else {
  1875. // For simplicity, do not implement `setCapture` for IE9-.
  1876. el.attachEvent('on' + name, handler);
  1877. }
  1878. }
  1879. /**
  1880. * Parameter are the same as `addEventListener`.
  1881. *
  1882. * Notice that if a listener is registered twice, one with capture and one without,
  1883. * remove each one separately. Removal of a capturing listener does not affect a
  1884. * non-capturing version of the same listener, and vice versa.
  1885. */
  1886. function removeEventListener(el, name, handler, opt) {
  1887. if (isDomLevel2) {
  1888. el.removeEventListener(name, handler, opt);
  1889. }
  1890. else {
  1891. el.detachEvent('on' + name, handler);
  1892. }
  1893. }
  1894. /**
  1895. * preventDefault and stopPropagation.
  1896. * Notice: do not use this method in zrender. It can only be
  1897. * used by upper applications if necessary.
  1898. *
  1899. * @param {Event} e A mouse or touch event.
  1900. */
  1901. var stop = isDomLevel2
  1902. ? function (e) {
  1903. e.preventDefault();
  1904. e.stopPropagation();
  1905. e.cancelBubble = true;
  1906. }
  1907. : function (e) {
  1908. e.returnValue = false;
  1909. e.cancelBubble = true;
  1910. };
  1911. /**
  1912. * This method only works for mouseup and mousedown. The functionality is restricted
  1913. * for fault tolerance, See the `e.which` compatibility above.
  1914. *
  1915. * @param {MouseEvent} e
  1916. * @return {boolean}
  1917. */
  1918. function isMiddleOrRightButtonOnMouseUpDown(e) {
  1919. return e.which === 2 || e.which === 3;
  1920. }
  1921. /**
  1922. * To be removed.
  1923. * @deprecated
  1924. */
  1925. /**
  1926. * Only implements needed gestures for mobile.
  1927. */
  1928. var GestureMgr = function () {
  1929. /**
  1930. * @private
  1931. * @type {Array.<Object>}
  1932. */
  1933. this._track = [];
  1934. };
  1935. GestureMgr.prototype = {
  1936. constructor: GestureMgr,
  1937. recognize: function (event, target, root) {
  1938. this._doTrack(event, target, root);
  1939. return this._recognize(event);
  1940. },
  1941. clear: function () {
  1942. this._track.length = 0;
  1943. return this;
  1944. },
  1945. _doTrack: function (event, target, root) {
  1946. var touches = event.touches;
  1947. if (!touches) {
  1948. return;
  1949. }
  1950. var trackItem = {
  1951. points: [],
  1952. touches: [],
  1953. target: target,
  1954. event: event
  1955. };
  1956. for (var i = 0, len = touches.length; i < len; i++) {
  1957. var touch = touches[i];
  1958. var pos = clientToLocal(root, touch, {});
  1959. trackItem.points.push([pos.zrX, pos.zrY]);
  1960. trackItem.touches.push(touch);
  1961. }
  1962. this._track.push(trackItem);
  1963. },
  1964. _recognize: function (event) {
  1965. for (var eventName in recognizers) {
  1966. if (recognizers.hasOwnProperty(eventName)) {
  1967. var gestureInfo = recognizers[eventName](this._track, event);
  1968. if (gestureInfo) {
  1969. return gestureInfo;
  1970. }
  1971. }
  1972. }
  1973. }
  1974. };
  1975. function dist$1(pointPair) {
  1976. var dx = pointPair[1][0] - pointPair[0][0];
  1977. var dy = pointPair[1][1] - pointPair[0][1];
  1978. return Math.sqrt(dx * dx + dy * dy);
  1979. }
  1980. function center(pointPair) {
  1981. return [
  1982. (pointPair[0][0] + pointPair[1][0]) / 2,
  1983. (pointPair[0][1] + pointPair[1][1]) / 2
  1984. ];
  1985. }
  1986. var recognizers = {
  1987. pinch: function (track, event) {
  1988. var trackLen = track.length;
  1989. if (!trackLen) {
  1990. return;
  1991. }
  1992. var pinchEnd = (track[trackLen - 1] || {}).points;
  1993. var pinchPre = (track[trackLen - 2] || {}).points || pinchEnd;
  1994. if (pinchPre
  1995. && pinchPre.length > 1
  1996. && pinchEnd
  1997. && pinchEnd.length > 1
  1998. ) {
  1999. var pinchScale = dist$1(pinchEnd) / dist$1(pinchPre);
  2000. !isFinite(pinchScale) && (pinchScale = 1);
  2001. event.pinchScale = pinchScale;
  2002. var pinchCenter = center(pinchEnd);
  2003. event.pinchX = pinchCenter[0];
  2004. event.pinchY = pinchCenter[1];
  2005. return {
  2006. type: 'pinch',
  2007. target: track[0].target,
  2008. event: event
  2009. };
  2010. }
  2011. }
  2012. // Only pinch currently.
  2013. };
  2014. /**
  2015. * [The interface between `Handler` and `HandlerProxy`]:
  2016. *
  2017. * The default `HandlerProxy` only support the common standard web environment
  2018. * (e.g., standalone browser, headless browser, embed browser in mobild APP, ...).
  2019. * But `HandlerProxy` can be replaced to support more non-standard environment
  2020. * (e.g., mini app), or to support more feature that the default `HandlerProxy`
  2021. * not provided (like echarts-gl did).
  2022. * So the interface between `Handler` and `HandlerProxy` should be stable. Do not
  2023. * make break changes util inevitable. The interface include the public methods
  2024. * of `Handler` and the events listed in `handlerNames` below, by which `HandlerProxy`
  2025. * drives `Handler`.
  2026. */
  2027. /**
  2028. * [Drag outside]:
  2029. *
  2030. * That is, triggering `mousemove` and `mouseup` event when the pointer is out of the
  2031. * zrender area when dragging. That is important for the improvement of the user experience
  2032. * when dragging something near the boundary without being terminated unexpectedly.
  2033. *
  2034. * We originally consider to introduce new events like `pagemovemove` and `pagemouseup`
  2035. * to resolve this issue. But some drawbacks of it is described in
  2036. * https://github.com/ecomfe/zrender/pull/536#issuecomment-560286899
  2037. *
  2038. * Instead, we referenced the specifications:
  2039. * https://www.w3.org/TR/touch-events/#the-touchmove-event
  2040. * https://www.w3.org/TR/2014/WD-DOM-Level-3-Events-20140925/#event-type-mousemove
  2041. * where the the mousemove/touchmove can be continue to fire if the user began a drag
  2042. * operation and the pointer has left the boundary. (for the mouse event, browsers
  2043. * only do it on `document` and when the pointer has left the boundary of the browser.)
  2044. *
  2045. * So the default `HandlerProxy` supports this feature similarly: if it is in the dragging
  2046. * state (see `pointerCapture` in `HandlerProxy`), the `mousemove` and `mouseup` continue
  2047. * to fire until release the pointer. That is implemented by listen to those event on
  2048. * `document`.
  2049. * If we implement some other `HandlerProxy` only for touch device, that would be easier.
  2050. * The touch event support this feature by default.
  2051. *
  2052. * Note:
  2053. * There might be some cases that the mouse event can not be
  2054. * received on `document`. For example,
  2055. * (A) `useCapture` is not supported and some user defined event listeners on the ancestor
  2056. * of zr dom throw Error .
  2057. * (B) `useCapture` is not supported Some user defined event listeners on the ancestor of
  2058. * zr dom call `stopPropagation`.
  2059. * In these cases, the `mousemove` event might be keep triggered event
  2060. * if the mouse is released. We try to reduce the side-effect in those cases.
  2061. * That is, do nothing (especially, `findHover`) in those cases. See `isOutsideBoundary`.
  2062. *
  2063. * Note:
  2064. * If `HandlerProxy` listens to `document` with `useCapture`, `HandlerProxy` needs to
  2065. * make sure `stopPropagation` and `preventDefault` doing nothing if and only if the event
  2066. * target is not zrender dom. Becuase it is dangerous to enable users to call them in
  2067. * `document` capture phase to prevent the propagation to any listener of the webpage.
  2068. * But they are needed to work when the pointer inside the zrender dom.
  2069. */
  2070. var SILENT = 'silent';
  2071. function makeEventPacket(eveType, targetInfo, event) {
  2072. return {
  2073. type: eveType,
  2074. event: event,
  2075. // target can only be an element that is not silent.
  2076. target: targetInfo.target,
  2077. // topTarget can be a silent element.
  2078. topTarget: targetInfo.topTarget,
  2079. cancelBubble: false,
  2080. offsetX: event.zrX,
  2081. offsetY: event.zrY,
  2082. gestureEvent: event.gestureEvent,
  2083. pinchX: event.pinchX,
  2084. pinchY: event.pinchY,
  2085. pinchScale: event.pinchScale,
  2086. wheelDelta: event.zrDelta,
  2087. zrByTouch: event.zrByTouch,
  2088. which: event.which,
  2089. stop: stopEvent
  2090. };
  2091. }
  2092. function stopEvent() {
  2093. stop(this.event);
  2094. }
  2095. function EmptyProxy() {}
  2096. EmptyProxy.prototype.dispose = function () {};
  2097. var handlerNames = [
  2098. 'click', 'dblclick', 'mousewheel', 'mouseout',
  2099. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  2100. ];
  2101. /**
  2102. * @alias module:zrender/Handler
  2103. * @constructor
  2104. * @extends module:zrender/mixin/Eventful
  2105. * @param {module:zrender/Storage} storage Storage instance.
  2106. * @param {module:zrender/Painter} painter Painter instance.
  2107. * @param {module:zrender/dom/HandlerProxy} proxy HandlerProxy instance.
  2108. * @param {HTMLElement} painterRoot painter.root (not painter.getViewportRoot()).
  2109. */
  2110. var Handler = function (storage, painter, proxy, painterRoot) {
  2111. Eventful.call(this);
  2112. this.storage = storage;
  2113. this.painter = painter;
  2114. this.painterRoot = painterRoot;
  2115. proxy = proxy || new EmptyProxy();
  2116. /**
  2117. * Proxy of event. can be Dom, WebGLSurface, etc.
  2118. */
  2119. this.proxy = null;
  2120. /**
  2121. * {target, topTarget, x, y}
  2122. * @private
  2123. * @type {Object}
  2124. */
  2125. this._hovered = {};
  2126. /**
  2127. * @private
  2128. * @type {Date}
  2129. */
  2130. this._lastTouchMoment;
  2131. /**
  2132. * @private
  2133. * @type {number}
  2134. */
  2135. this._lastX;
  2136. /**
  2137. * @private
  2138. * @type {number}
  2139. */
  2140. this._lastY;
  2141. /**
  2142. * @private
  2143. * @type {module:zrender/core/GestureMgr}
  2144. */
  2145. this._gestureMgr;
  2146. Draggable.call(this);
  2147. this.setHandlerProxy(proxy);
  2148. };
  2149. Handler.prototype = {
  2150. constructor: Handler,
  2151. setHandlerProxy: function (proxy) {
  2152. if (this.proxy) {
  2153. this.proxy.dispose();
  2154. }
  2155. if (proxy) {
  2156. each$1(handlerNames, function (name) {
  2157. proxy.on && proxy.on(name, this[name], this);
  2158. }, this);
  2159. // Attach handler
  2160. proxy.handler = this;
  2161. }
  2162. this.proxy = proxy;
  2163. },
  2164. mousemove: function (event) {
  2165. var x = event.zrX;
  2166. var y = event.zrY;
  2167. var isOutside = isOutsideBoundary(this, x, y);
  2168. var lastHovered = this._hovered;
  2169. var lastHoveredTarget = lastHovered.target;
  2170. // If lastHoveredTarget is removed from zr (detected by '__zr') by some API call
  2171. // (like 'setOption' or 'dispatchAction') in event handlers, we should find
  2172. // lastHovered again here. Otherwise 'mouseout' can not be triggered normally.
  2173. // See #6198.
  2174. if (lastHoveredTarget && !lastHoveredTarget.__zr) {
  2175. lastHovered = this.findHover(lastHovered.x, lastHovered.y);
  2176. lastHoveredTarget = lastHovered.target;
  2177. }
  2178. var hovered = this._hovered = isOutside ? {x: x, y: y} : this.findHover(x, y);
  2179. var hoveredTarget = hovered.target;
  2180. var proxy = this.proxy;
  2181. proxy.setCursor && proxy.setCursor(hoveredTarget ? hoveredTarget.cursor : 'default');
  2182. // Mouse out on previous hovered element
  2183. if (lastHoveredTarget && hoveredTarget !== lastHoveredTarget) {
  2184. this.dispatchToElement(lastHovered, 'mouseout', event);
  2185. }
  2186. // Mouse moving on one element
  2187. this.dispatchToElement(hovered, 'mousemove', event);
  2188. // Mouse over on a new element
  2189. if (hoveredTarget && hoveredTarget !== lastHoveredTarget) {
  2190. this.dispatchToElement(hovered, 'mouseover', event);
  2191. }
  2192. },
  2193. mouseout: function (event) {
  2194. var eventControl = event.zrEventControl;
  2195. var zrIsToLocalDOM = event.zrIsToLocalDOM;
  2196. if (eventControl !== 'only_globalout') {
  2197. this.dispatchToElement(this._hovered, 'mouseout', event);
  2198. }
  2199. if (eventControl !== 'no_globalout') {
  2200. // FIXME: if the pointer moving from the extra doms to realy "outside",
  2201. // the `globalout` should have been triggered. But currently not.
  2202. !zrIsToLocalDOM && this.trigger('globalout', {type: 'globalout', event: event});
  2203. }
  2204. },
  2205. /**
  2206. * Resize
  2207. */
  2208. resize: function (event) {
  2209. this._hovered = {};
  2210. },
  2211. /**
  2212. * Dispatch event
  2213. * @param {string} eventName
  2214. * @param {event=} eventArgs
  2215. */
  2216. dispatch: function (eventName, eventArgs) {
  2217. var handler = this[eventName];
  2218. handler && handler.call(this, eventArgs);
  2219. },
  2220. /**
  2221. * Dispose
  2222. */
  2223. dispose: function () {
  2224. this.proxy.dispose();
  2225. this.storage =
  2226. this.proxy =
  2227. this.painter = null;
  2228. },
  2229. /**
  2230. * 设置默认的cursor style
  2231. * @param {string} [cursorStyle='default'] 例如 crosshair
  2232. */
  2233. setCursorStyle: function (cursorStyle) {
  2234. var proxy = this.proxy;
  2235. proxy.setCursor && proxy.setCursor(cursorStyle);
  2236. },
  2237. /**
  2238. * 事件分发代理
  2239. *
  2240. * @private
  2241. * @param {Object} targetInfo {target, topTarget} 目标图形元素
  2242. * @param {string} eventName 事件名称
  2243. * @param {Object} event 事件对象
  2244. */
  2245. dispatchToElement: function (targetInfo, eventName, event) {
  2246. targetInfo = targetInfo || {};
  2247. var el = targetInfo.target;
  2248. if (el && el.silent) {
  2249. return;
  2250. }
  2251. var eventHandler = 'on' + eventName;
  2252. var eventPacket = makeEventPacket(eventName, targetInfo, event);
  2253. while (el) {
  2254. el[eventHandler]
  2255. && (eventPacket.cancelBubble = el[eventHandler].call(el, eventPacket));
  2256. el.trigger(eventName, eventPacket);
  2257. el = el.parent;
  2258. if (eventPacket.cancelBubble) {
  2259. break;
  2260. }
  2261. }
  2262. if (!eventPacket.cancelBubble) {
  2263. // 冒泡到顶级 zrender 对象
  2264. this.trigger(eventName, eventPacket);
  2265. // 分发事件到用户自定义层
  2266. // 用户有可能在全局 click 事件中 dispose,所以需要判断下 painter 是否存在
  2267. this.painter && this.painter.eachOtherLayer(function (layer) {
  2268. if (typeof (layer[eventHandler]) === 'function') {
  2269. layer[eventHandler].call(layer, eventPacket);
  2270. }
  2271. if (layer.trigger) {
  2272. layer.trigger(eventName, eventPacket);
  2273. }
  2274. });
  2275. }
  2276. },
  2277. /**
  2278. * @private
  2279. * @param {number} x
  2280. * @param {number} y
  2281. * @param {module:zrender/graphic/Displayable} exclude
  2282. * @return {model:zrender/Element}
  2283. * @method
  2284. */
  2285. findHover: function (x, y, exclude) {
  2286. var list = this.storage.getDisplayList();
  2287. var out = {x: x, y: y};
  2288. for (var i = list.length - 1; i >= 0; i--) {
  2289. var hoverCheckResult;
  2290. if (list[i] !== exclude
  2291. // getDisplayList may include ignored item in VML mode
  2292. && !list[i].ignore
  2293. && (hoverCheckResult = isHover(list[i], x, y))
  2294. ) {
  2295. !out.topTarget && (out.topTarget = list[i]);
  2296. if (hoverCheckResult !== SILENT) {
  2297. out.target = list[i];
  2298. break;
  2299. }
  2300. }
  2301. }
  2302. return out;
  2303. },
  2304. processGesture: function (event, stage) {
  2305. if (!this._gestureMgr) {
  2306. this._gestureMgr = new GestureMgr();
  2307. }
  2308. var gestureMgr = this._gestureMgr;
  2309. stage === 'start' && gestureMgr.clear();
  2310. var gestureInfo = gestureMgr.recognize(
  2311. event,
  2312. this.findHover(event.zrX, event.zrY, null).target,
  2313. this.proxy.dom
  2314. );
  2315. stage === 'end' && gestureMgr.clear();
  2316. // Do not do any preventDefault here. Upper application do that if necessary.
  2317. if (gestureInfo) {
  2318. var type = gestureInfo.type;
  2319. event.gestureEvent = type;
  2320. this.dispatchToElement({target: gestureInfo.target}, type, gestureInfo.event);
  2321. }
  2322. }
  2323. };
  2324. // Common handlers
  2325. each$1(['click', 'mousedown', 'mouseup', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  2326. Handler.prototype[name] = function (event) {
  2327. var x = event.zrX;
  2328. var y = event.zrY;
  2329. var isOutside = isOutsideBoundary(this, x, y);
  2330. var hovered;
  2331. var hoveredTarget;
  2332. if (name !== 'mouseup' || !isOutside) {
  2333. // Find hover again to avoid click event is dispatched manually. Or click is triggered without mouseover
  2334. hovered = this.findHover(x, y);
  2335. hoveredTarget = hovered.target;
  2336. }
  2337. if (name === 'mousedown') {
  2338. this._downEl = hoveredTarget;
  2339. this._downPoint = [event.zrX, event.zrY];
  2340. // In case click triggered before mouseup
  2341. this._upEl = hoveredTarget;
  2342. }
  2343. else if (name === 'mouseup') {
  2344. this._upEl = hoveredTarget;
  2345. }
  2346. else if (name === 'click') {
  2347. if (this._downEl !== this._upEl
  2348. // Original click event is triggered on the whole canvas element,
  2349. // including the case that `mousedown` - `mousemove` - `mouseup`,
  2350. // which should be filtered, otherwise it will bring trouble to
  2351. // pan and zoom.
  2352. || !this._downPoint
  2353. // Arbitrary value
  2354. || dist(this._downPoint, [event.zrX, event.zrY]) > 4
  2355. ) {
  2356. return;
  2357. }
  2358. this._downPoint = null;
  2359. }
  2360. this.dispatchToElement(hovered, name, event);
  2361. };
  2362. });
  2363. function isHover(displayable, x, y) {
  2364. if (displayable[displayable.rectHover ? 'rectContain' : 'contain'](x, y)) {
  2365. var el = displayable;
  2366. var isSilent;
  2367. while (el) {
  2368. // If clipped by ancestor.
  2369. // FIXME: If clipPath has neither stroke nor fill,
  2370. // el.clipPath.contain(x, y) will always return false.
  2371. if (el.clipPath && !el.clipPath.contain(x, y)) {
  2372. return false;
  2373. }
  2374. if (el.silent) {
  2375. isSilent = true;
  2376. }
  2377. el = el.parent;
  2378. }
  2379. return isSilent ? SILENT : true;
  2380. }
  2381. return false;
  2382. }
  2383. /**
  2384. * See [Drag outside].
  2385. */
  2386. function isOutsideBoundary(handlerInstance, x, y) {
  2387. var painter = handlerInstance.painter;
  2388. return x < 0 || x > painter.getWidth() || y < 0 || y > painter.getHeight();
  2389. }
  2390. mixin(Handler, Eventful);
  2391. mixin(Handler, Draggable);
  2392. /**
  2393. * 3x2矩阵操作类
  2394. * @exports zrender/tool/matrix
  2395. */
  2396. /* global Float32Array */
  2397. var ArrayCtor$1 = typeof Float32Array === 'undefined'
  2398. ? Array
  2399. : Float32Array;
  2400. /**
  2401. * Create a identity matrix.
  2402. * @return {Float32Array|Array.<number>}
  2403. */
  2404. function create$1() {
  2405. var out = new ArrayCtor$1(6);
  2406. identity(out);
  2407. return out;
  2408. }
  2409. /**
  2410. * 设置矩阵为单位矩阵
  2411. * @param {Float32Array|Array.<number>} out
  2412. */
  2413. function identity(out) {
  2414. out[0] = 1;
  2415. out[1] = 0;
  2416. out[2] = 0;
  2417. out[3] = 1;
  2418. out[4] = 0;
  2419. out[5] = 0;
  2420. return out;
  2421. }
  2422. /**
  2423. * 复制矩阵
  2424. * @param {Float32Array|Array.<number>} out
  2425. * @param {Float32Array|Array.<number>} m
  2426. */
  2427. function copy$1(out, m) {
  2428. out[0] = m[0];
  2429. out[1] = m[1];
  2430. out[2] = m[2];
  2431. out[3] = m[3];
  2432. out[4] = m[4];
  2433. out[5] = m[5];
  2434. return out;
  2435. }
  2436. /**
  2437. * 矩阵相乘
  2438. * @param {Float32Array|Array.<number>} out
  2439. * @param {Float32Array|Array.<number>} m1
  2440. * @param {Float32Array|Array.<number>} m2
  2441. */
  2442. function mul$1(out, m1, m2) {
  2443. // Consider matrix.mul(m, m2, m);
  2444. // where out is the same as m2.
  2445. // So use temp variable to escape error.
  2446. var out0 = m1[0] * m2[0] + m1[2] * m2[1];
  2447. var out1 = m1[1] * m2[0] + m1[3] * m2[1];
  2448. var out2 = m1[0] * m2[2] + m1[2] * m2[3];
  2449. var out3 = m1[1] * m2[2] + m1[3] * m2[3];
  2450. var out4 = m1[0] * m2[4] + m1[2] * m2[5] + m1[4];
  2451. var out5 = m1[1] * m2[4] + m1[3] * m2[5] + m1[5];
  2452. out[0] = out0;
  2453. out[1] = out1;
  2454. out[2] = out2;
  2455. out[3] = out3;
  2456. out[4] = out4;
  2457. out[5] = out5;
  2458. return out;
  2459. }
  2460. /**
  2461. * 平移变换
  2462. * @param {Float32Array|Array.<number>} out
  2463. * @param {Float32Array|Array.<number>} a
  2464. * @param {Float32Array|Array.<number>} v
  2465. */
  2466. function translate(out, a, v) {
  2467. out[0] = a[0];
  2468. out[1] = a[1];
  2469. out[2] = a[2];
  2470. out[3] = a[3];
  2471. out[4] = a[4] + v[0];
  2472. out[5] = a[5] + v[1];
  2473. return out;
  2474. }
  2475. /**
  2476. * 旋转变换
  2477. * @param {Float32Array|Array.<number>} out
  2478. * @param {Float32Array|Array.<number>} a
  2479. * @param {number} rad
  2480. */
  2481. function rotate(out, a, rad) {
  2482. var aa = a[0];
  2483. var ac = a[2];
  2484. var atx = a[4];
  2485. var ab = a[1];
  2486. var ad = a[3];
  2487. var aty = a[5];
  2488. var st = Math.sin(rad);
  2489. var ct = Math.cos(rad);
  2490. out[0] = aa * ct + ab * st;
  2491. out[1] = -aa * st + ab * ct;
  2492. out[2] = ac * ct + ad * st;
  2493. out[3] = -ac * st + ct * ad;
  2494. out[4] = ct * atx + st * aty;
  2495. out[5] = ct * aty - st * atx;
  2496. return out;
  2497. }
  2498. /**
  2499. * 缩放变换
  2500. * @param {Float32Array|Array.<number>} out
  2501. * @param {Float32Array|Array.<number>} a
  2502. * @param {Float32Array|Array.<number>} v
  2503. */
  2504. function scale$1(out, a, v) {
  2505. var vx = v[0];
  2506. var vy = v[1];
  2507. out[0] = a[0] * vx;
  2508. out[1] = a[1] * vy;
  2509. out[2] = a[2] * vx;
  2510. out[3] = a[3] * vy;
  2511. out[4] = a[4] * vx;
  2512. out[5] = a[5] * vy;
  2513. return out;
  2514. }
  2515. /**
  2516. * 求逆矩阵
  2517. * @param {Float32Array|Array.<number>} out
  2518. * @param {Float32Array|Array.<number>} a
  2519. */
  2520. function invert(out, a) {
  2521. var aa = a[0];
  2522. var ac = a[2];
  2523. var atx = a[4];
  2524. var ab = a[1];
  2525. var ad = a[3];
  2526. var aty = a[5];
  2527. var det = aa * ad - ab * ac;
  2528. if (!det) {
  2529. return null;
  2530. }
  2531. det = 1.0 / det;
  2532. out[0] = ad * det;
  2533. out[1] = -ab * det;
  2534. out[2] = -ac * det;
  2535. out[3] = aa * det;
  2536. out[4] = (ac * aty - ad * atx) * det;
  2537. out[5] = (ab * atx - aa * aty) * det;
  2538. return out;
  2539. }
  2540. /**
  2541. * Clone a new matrix.
  2542. * @param {Float32Array|Array.<number>} a
  2543. */
  2544. function clone$2(a) {
  2545. var b = create$1();
  2546. copy$1(b, a);
  2547. return b;
  2548. }
  2549. var matrix = (Object.freeze || Object)({
  2550. create: create$1,
  2551. identity: identity,
  2552. copy: copy$1,
  2553. mul: mul$1,
  2554. translate: translate,
  2555. rotate: rotate,
  2556. scale: scale$1,
  2557. invert: invert,
  2558. clone: clone$2
  2559. });
  2560. /**
  2561. * 提供变换扩展
  2562. * @module zrender/mixin/Transformable
  2563. * @author pissang (https://www.github.com/pissang)
  2564. */
  2565. var mIdentity = identity;
  2566. var EPSILON = 5e-5;
  2567. function isNotAroundZero(val) {
  2568. return val > EPSILON || val < -EPSILON;
  2569. }
  2570. /**
  2571. * @alias module:zrender/mixin/Transformable
  2572. * @constructor
  2573. */
  2574. var Transformable = function (opts) {
  2575. opts = opts || {};
  2576. // If there are no given position, rotation, scale
  2577. if (!opts.position) {
  2578. /**
  2579. * 平移
  2580. * @type {Array.<number>}
  2581. * @default [0, 0]
  2582. */
  2583. this.position = [0, 0];
  2584. }
  2585. if (opts.rotation == null) {
  2586. /**
  2587. * 旋转
  2588. * @type {Array.<number>}
  2589. * @default 0
  2590. */
  2591. this.rotation = 0;
  2592. }
  2593. if (!opts.scale) {
  2594. /**
  2595. * 缩放
  2596. * @type {Array.<number>}
  2597. * @default [1, 1]
  2598. */
  2599. this.scale = [1, 1];
  2600. }
  2601. /**
  2602. * 旋转和缩放的原点
  2603. * @type {Array.<number>}
  2604. * @default null
  2605. */
  2606. this.origin = this.origin || null;
  2607. };
  2608. var transformableProto = Transformable.prototype;
  2609. transformableProto.transform = null;
  2610. /**
  2611. * 判断是否需要有坐标变换
  2612. * 如果有坐标变换, 则从position, rotation, scale以及父节点的transform计算出自身的transform矩阵
  2613. */
  2614. transformableProto.needLocalTransform = function () {
  2615. return isNotAroundZero(this.rotation)
  2616. || isNotAroundZero(this.position[0])
  2617. || isNotAroundZero(this.position[1])
  2618. || isNotAroundZero(this.scale[0] - 1)
  2619. || isNotAroundZero(this.scale[1] - 1);
  2620. };
  2621. var scaleTmp = [];
  2622. transformableProto.updateTransform = function () {
  2623. var parent = this.parent;
  2624. var parentHasTransform = parent && parent.transform;
  2625. var needLocalTransform = this.needLocalTransform();
  2626. var m = this.transform;
  2627. if (!(needLocalTransform || parentHasTransform)) {
  2628. m && mIdentity(m);
  2629. return;
  2630. }
  2631. m = m || create$1();
  2632. if (needLocalTransform) {
  2633. this.getLocalTransform(m);
  2634. }
  2635. else {
  2636. mIdentity(m);
  2637. }
  2638. // 应用父节点变换
  2639. if (parentHasTransform) {
  2640. if (needLocalTransform) {
  2641. mul$1(m, parent.transform, m);
  2642. }
  2643. else {
  2644. copy$1(m, parent.transform);
  2645. }
  2646. }
  2647. // 保存这个变换矩阵
  2648. this.transform = m;
  2649. var globalScaleRatio = this.globalScaleRatio;
  2650. if (globalScaleRatio != null && globalScaleRatio !== 1) {
  2651. this.getGlobalScale(scaleTmp);
  2652. var relX = scaleTmp[0] < 0 ? -1 : 1;
  2653. var relY = scaleTmp[1] < 0 ? -1 : 1;
  2654. var sx = ((scaleTmp[0] - relX) * globalScaleRatio + relX) / scaleTmp[0] || 0;
  2655. var sy = ((scaleTmp[1] - relY) * globalScaleRatio + relY) / scaleTmp[1] || 0;
  2656. m[0] *= sx;
  2657. m[1] *= sx;
  2658. m[2] *= sy;
  2659. m[3] *= sy;
  2660. }
  2661. this.invTransform = this.invTransform || create$1();
  2662. invert(this.invTransform, m);
  2663. };
  2664. transformableProto.getLocalTransform = function (m) {
  2665. return Transformable.getLocalTransform(this, m);
  2666. };
  2667. /**
  2668. * 将自己的transform应用到context上
  2669. * @param {CanvasRenderingContext2D} ctx
  2670. */
  2671. transformableProto.setTransform = function (ctx) {
  2672. var m = this.transform;
  2673. var dpr = ctx.dpr || 1;
  2674. if (m) {
  2675. ctx.setTransform(dpr * m[0], dpr * m[1], dpr * m[2], dpr * m[3], dpr * m[4], dpr * m[5]);
  2676. }
  2677. else {
  2678. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  2679. }
  2680. };
  2681. transformableProto.restoreTransform = function (ctx) {
  2682. var dpr = ctx.dpr || 1;
  2683. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  2684. };
  2685. var tmpTransform = [];
  2686. var originTransform = create$1();
  2687. transformableProto.setLocalTransform = function (m) {
  2688. if (!m) {
  2689. // TODO return or set identity?
  2690. return;
  2691. }
  2692. var sx = m[0] * m[0] + m[1] * m[1];
  2693. var sy = m[2] * m[2] + m[3] * m[3];
  2694. var position = this.position;
  2695. var scale$$1 = this.scale;
  2696. if (isNotAroundZero(sx - 1)) {
  2697. sx = Math.sqrt(sx);
  2698. }
  2699. if (isNotAroundZero(sy - 1)) {
  2700. sy = Math.sqrt(sy);
  2701. }
  2702. if (m[0] < 0) {
  2703. sx = -sx;
  2704. }
  2705. if (m[3] < 0) {
  2706. sy = -sy;
  2707. }
  2708. position[0] = m[4];
  2709. position[1] = m[5];
  2710. scale$$1[0] = sx;
  2711. scale$$1[1] = sy;
  2712. this.rotation = Math.atan2(-m[1] / sy, m[0] / sx);
  2713. };
  2714. /**
  2715. * 分解`transform`矩阵到`position`, `rotation`, `scale`
  2716. */
  2717. transformableProto.decomposeTransform = function () {
  2718. if (!this.transform) {
  2719. return;
  2720. }
  2721. var parent = this.parent;
  2722. var m = this.transform;
  2723. if (parent && parent.transform) {
  2724. // Get local transform and decompose them to position, scale, rotation
  2725. mul$1(tmpTransform, parent.invTransform, m);
  2726. m = tmpTransform;
  2727. }
  2728. var origin = this.origin;
  2729. if (origin && (origin[0] || origin[1])) {
  2730. originTransform[4] = origin[0];
  2731. originTransform[5] = origin[1];
  2732. mul$1(tmpTransform, m, originTransform);
  2733. tmpTransform[4] -= origin[0];
  2734. tmpTransform[5] -= origin[1];
  2735. m = tmpTransform;
  2736. }
  2737. this.setLocalTransform(m);
  2738. };
  2739. /**
  2740. * Get global scale
  2741. * @return {Array.<number>}
  2742. */
  2743. transformableProto.getGlobalScale = function (out) {
  2744. var m = this.transform;
  2745. out = out || [];
  2746. if (!m) {
  2747. out[0] = 1;
  2748. out[1] = 1;
  2749. return out;
  2750. }
  2751. out[0] = Math.sqrt(m[0] * m[0] + m[1] * m[1]);
  2752. out[1] = Math.sqrt(m[2] * m[2] + m[3] * m[3]);
  2753. if (m[0] < 0) {
  2754. out[0] = -out[0];
  2755. }
  2756. if (m[3] < 0) {
  2757. out[1] = -out[1];
  2758. }
  2759. return out;
  2760. };
  2761. /**
  2762. * 变换坐标位置到 shape 的局部坐标空间
  2763. * @method
  2764. * @param {number} x
  2765. * @param {number} y
  2766. * @return {Array.<number>}
  2767. */
  2768. transformableProto.transformCoordToLocal = function (x, y) {
  2769. var v2 = [x, y];
  2770. var invTransform = this.invTransform;
  2771. if (invTransform) {
  2772. applyTransform(v2, v2, invTransform);
  2773. }
  2774. return v2;
  2775. };
  2776. /**
  2777. * 变换局部坐标位置到全局坐标空间
  2778. * @method
  2779. * @param {number} x
  2780. * @param {number} y
  2781. * @return {Array.<number>}
  2782. */
  2783. transformableProto.transformCoordToGlobal = function (x, y) {
  2784. var v2 = [x, y];
  2785. var transform = this.transform;
  2786. if (transform) {
  2787. applyTransform(v2, v2, transform);
  2788. }
  2789. return v2;
  2790. };
  2791. /**
  2792. * @static
  2793. * @param {Object} target
  2794. * @param {Array.<number>} target.origin
  2795. * @param {number} target.rotation
  2796. * @param {Array.<number>} target.position
  2797. * @param {Array.<number>} [m]
  2798. */
  2799. Transformable.getLocalTransform = function (target, m) {
  2800. m = m || [];
  2801. mIdentity(m);
  2802. var origin = target.origin;
  2803. var scale$$1 = target.scale || [1, 1];
  2804. var rotation = target.rotation || 0;
  2805. var position = target.position || [0, 0];
  2806. if (origin) {
  2807. // Translate to origin
  2808. m[4] -= origin[0];
  2809. m[5] -= origin[1];
  2810. }
  2811. scale$1(m, m, scale$$1);
  2812. if (rotation) {
  2813. rotate(m, m, rotation);
  2814. }
  2815. if (origin) {
  2816. // Translate back from origin
  2817. m[4] += origin[0];
  2818. m[5] += origin[1];
  2819. }
  2820. m[4] += position[0];
  2821. m[5] += position[1];
  2822. return m;
  2823. };
  2824. /**
  2825. * 缓动代码来自 https://github.com/sole/tween.js/blob/master/src/Tween.js
  2826. * @see http://sole.github.io/tween.js/examples/03_graphs.html
  2827. * @exports zrender/animation/easing
  2828. */
  2829. var easing = {
  2830. /**
  2831. * @param {number} k
  2832. * @return {number}
  2833. */
  2834. linear: function (k) {
  2835. return k;
  2836. },
  2837. /**
  2838. * @param {number} k
  2839. * @return {number}
  2840. */
  2841. quadraticIn: function (k) {
  2842. return k * k;
  2843. },
  2844. /**
  2845. * @param {number} k
  2846. * @return {number}
  2847. */
  2848. quadraticOut: function (k) {
  2849. return k * (2 - k);
  2850. },
  2851. /**
  2852. * @param {number} k
  2853. * @return {number}
  2854. */
  2855. quadraticInOut: function (k) {
  2856. if ((k *= 2) < 1) {
  2857. return 0.5 * k * k;
  2858. }
  2859. return -0.5 * (--k * (k - 2) - 1);
  2860. },
  2861. // 三次方的缓动(t^3)
  2862. /**
  2863. * @param {number} k
  2864. * @return {number}
  2865. */
  2866. cubicIn: function (k) {
  2867. return k * k * k;
  2868. },
  2869. /**
  2870. * @param {number} k
  2871. * @return {number}
  2872. */
  2873. cubicOut: function (k) {
  2874. return --k * k * k + 1;
  2875. },
  2876. /**
  2877. * @param {number} k
  2878. * @return {number}
  2879. */
  2880. cubicInOut: function (k) {
  2881. if ((k *= 2) < 1) {
  2882. return 0.5 * k * k * k;
  2883. }
  2884. return 0.5 * ((k -= 2) * k * k + 2);
  2885. },
  2886. // 四次方的缓动(t^4)
  2887. /**
  2888. * @param {number} k
  2889. * @return {number}
  2890. */
  2891. quarticIn: function (k) {
  2892. return k * k * k * k;
  2893. },
  2894. /**
  2895. * @param {number} k
  2896. * @return {number}
  2897. */
  2898. quarticOut: function (k) {
  2899. return 1 - (--k * k * k * k);
  2900. },
  2901. /**
  2902. * @param {number} k
  2903. * @return {number}
  2904. */
  2905. quarticInOut: function (k) {
  2906. if ((k *= 2) < 1) {
  2907. return 0.5 * k * k * k * k;
  2908. }
  2909. return -0.5 * ((k -= 2) * k * k * k - 2);
  2910. },
  2911. // 五次方的缓动(t^5)
  2912. /**
  2913. * @param {number} k
  2914. * @return {number}
  2915. */
  2916. quinticIn: function (k) {
  2917. return k * k * k * k * k;
  2918. },
  2919. /**
  2920. * @param {number} k
  2921. * @return {number}
  2922. */
  2923. quinticOut: function (k) {
  2924. return --k * k * k * k * k + 1;
  2925. },
  2926. /**
  2927. * @param {number} k
  2928. * @return {number}
  2929. */
  2930. quinticInOut: function (k) {
  2931. if ((k *= 2) < 1) {
  2932. return 0.5 * k * k * k * k * k;
  2933. }
  2934. return 0.5 * ((k -= 2) * k * k * k * k + 2);
  2935. },
  2936. // 正弦曲线的缓动(sin(t))
  2937. /**
  2938. * @param {number} k
  2939. * @return {number}
  2940. */
  2941. sinusoidalIn: function (k) {
  2942. return 1 - Math.cos(k * Math.PI / 2);
  2943. },
  2944. /**
  2945. * @param {number} k
  2946. * @return {number}
  2947. */
  2948. sinusoidalOut: function (k) {
  2949. return Math.sin(k * Math.PI / 2);
  2950. },
  2951. /**
  2952. * @param {number} k
  2953. * @return {number}
  2954. */
  2955. sinusoidalInOut: function (k) {
  2956. return 0.5 * (1 - Math.cos(Math.PI * k));
  2957. },
  2958. // 指数曲线的缓动(2^t)
  2959. /**
  2960. * @param {number} k
  2961. * @return {number}
  2962. */
  2963. exponentialIn: function (k) {
  2964. return k === 0 ? 0 : Math.pow(1024, k - 1);
  2965. },
  2966. /**
  2967. * @param {number} k
  2968. * @return {number}
  2969. */
  2970. exponentialOut: function (k) {
  2971. return k === 1 ? 1 : 1 - Math.pow(2, -10 * k);
  2972. },
  2973. /**
  2974. * @param {number} k
  2975. * @return {number}
  2976. */
  2977. exponentialInOut: function (k) {
  2978. if (k === 0) {
  2979. return 0;
  2980. }
  2981. if (k === 1) {
  2982. return 1;
  2983. }
  2984. if ((k *= 2) < 1) {
  2985. return 0.5 * Math.pow(1024, k - 1);
  2986. }
  2987. return 0.5 * (-Math.pow(2, -10 * (k - 1)) + 2);
  2988. },
  2989. // 圆形曲线的缓动(sqrt(1-t^2))
  2990. /**
  2991. * @param {number} k
  2992. * @return {number}
  2993. */
  2994. circularIn: function (k) {
  2995. return 1 - Math.sqrt(1 - k * k);
  2996. },
  2997. /**
  2998. * @param {number} k
  2999. * @return {number}
  3000. */
  3001. circularOut: function (k) {
  3002. return Math.sqrt(1 - (--k * k));
  3003. },
  3004. /**
  3005. * @param {number} k
  3006. * @return {number}
  3007. */
  3008. circularInOut: function (k) {
  3009. if ((k *= 2) < 1) {
  3010. return -0.5 * (Math.sqrt(1 - k * k) - 1);
  3011. }
  3012. return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1);
  3013. },
  3014. // 创建类似于弹簧在停止前来回振荡的动画
  3015. /**
  3016. * @param {number} k
  3017. * @return {number}
  3018. */
  3019. elasticIn: function (k) {
  3020. var s;
  3021. var a = 0.1;
  3022. var p = 0.4;
  3023. if (k === 0) {
  3024. return 0;
  3025. }
  3026. if (k === 1) {
  3027. return 1;
  3028. }
  3029. if (!a || a < 1) {
  3030. a = 1;
  3031. s = p / 4;
  3032. }
  3033. else {
  3034. s = p * Math.asin(1 / a) / (2 * Math.PI);
  3035. }
  3036. return -(a * Math.pow(2, 10 * (k -= 1))
  3037. * Math.sin((k - s) * (2 * Math.PI) / p));
  3038. },
  3039. /**
  3040. * @param {number} k
  3041. * @return {number}
  3042. */
  3043. elasticOut: function (k) {
  3044. var s;
  3045. var a = 0.1;
  3046. var p = 0.4;
  3047. if (k === 0) {
  3048. return 0;
  3049. }
  3050. if (k === 1) {
  3051. return 1;
  3052. }
  3053. if (!a || a < 1) {
  3054. a = 1;
  3055. s = p / 4;
  3056. }
  3057. else {
  3058. s = p * Math.asin(1 / a) / (2 * Math.PI);
  3059. }
  3060. return (a * Math.pow(2, -10 * k)
  3061. * Math.sin((k - s) * (2 * Math.PI) / p) + 1);
  3062. },
  3063. /**
  3064. * @param {number} k
  3065. * @return {number}
  3066. */
  3067. elasticInOut: function (k) {
  3068. var s;
  3069. var a = 0.1;
  3070. var p = 0.4;
  3071. if (k === 0) {
  3072. return 0;
  3073. }
  3074. if (k === 1) {
  3075. return 1;
  3076. }
  3077. if (!a || a < 1) {
  3078. a = 1;
  3079. s = p / 4;
  3080. }
  3081. else {
  3082. s = p * Math.asin(1 / a) / (2 * Math.PI);
  3083. }
  3084. if ((k *= 2) < 1) {
  3085. return -0.5 * (a * Math.pow(2, 10 * (k -= 1))
  3086. * Math.sin((k - s) * (2 * Math.PI) / p));
  3087. }
  3088. return a * Math.pow(2, -10 * (k -= 1))
  3089. * Math.sin((k - s) * (2 * Math.PI) / p) * 0.5 + 1;
  3090. },
  3091. // 在某一动画开始沿指示的路径进行动画处理前稍稍收回该动画的移动
  3092. /**
  3093. * @param {number} k
  3094. * @return {number}
  3095. */
  3096. backIn: function (k) {
  3097. var s = 1.70158;
  3098. return k * k * ((s + 1) * k - s);
  3099. },
  3100. /**
  3101. * @param {number} k
  3102. * @return {number}
  3103. */
  3104. backOut: function (k) {
  3105. var s = 1.70158;
  3106. return --k * k * ((s + 1) * k + s) + 1;
  3107. },
  3108. /**
  3109. * @param {number} k
  3110. * @return {number}
  3111. */
  3112. backInOut: function (k) {
  3113. var s = 1.70158 * 1.525;
  3114. if ((k *= 2) < 1) {
  3115. return 0.5 * (k * k * ((s + 1) * k - s));
  3116. }
  3117. return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2);
  3118. },
  3119. // 创建弹跳效果
  3120. /**
  3121. * @param {number} k
  3122. * @return {number}
  3123. */
  3124. bounceIn: function (k) {
  3125. return 1 - easing.bounceOut(1 - k);
  3126. },
  3127. /**
  3128. * @param {number} k
  3129. * @return {number}
  3130. */
  3131. bounceOut: function (k) {
  3132. if (k < (1 / 2.75)) {
  3133. return 7.5625 * k * k;
  3134. }
  3135. else if (k < (2 / 2.75)) {
  3136. return 7.5625 * (k -= (1.5 / 2.75)) * k + 0.75;
  3137. }
  3138. else if (k < (2.5 / 2.75)) {
  3139. return 7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375;
  3140. }
  3141. else {
  3142. return 7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375;
  3143. }
  3144. },
  3145. /**
  3146. * @param {number} k
  3147. * @return {number}
  3148. */
  3149. bounceInOut: function (k) {
  3150. if (k < 0.5) {
  3151. return easing.bounceIn(k * 2) * 0.5;
  3152. }
  3153. return easing.bounceOut(k * 2 - 1) * 0.5 + 0.5;
  3154. }
  3155. };
  3156. /**
  3157. * 动画主控制器
  3158. * @config target 动画对象,可以是数组,如果是数组的话会批量分发onframe等事件
  3159. * @config life(1000) 动画时长
  3160. * @config delay(0) 动画延迟时间
  3161. * @config loop(true)
  3162. * @config gap(0) 循环的间隔时间
  3163. * @config onframe
  3164. * @config easing(optional)
  3165. * @config ondestroy(optional)
  3166. * @config onrestart(optional)
  3167. *
  3168. * TODO pause
  3169. */
  3170. function Clip(options) {
  3171. this._target = options.target;
  3172. // 生命周期
  3173. this._life = options.life || 1000;
  3174. // 延时
  3175. this._delay = options.delay || 0;
  3176. // 开始时间
  3177. // this._startTime = new Date().getTime() + this._delay;// 单位毫秒
  3178. this._initialized = false;
  3179. // 是否循环
  3180. this.loop = options.loop == null ? false : options.loop;
  3181. this.gap = options.gap || 0;
  3182. this.easing = options.easing || 'Linear';
  3183. this.onframe = options.onframe;
  3184. this.ondestroy = options.ondestroy;
  3185. this.onrestart = options.onrestart;
  3186. this._pausedTime = 0;
  3187. this._paused = false;
  3188. }
  3189. Clip.prototype = {
  3190. constructor: Clip,
  3191. step: function (globalTime, deltaTime) {
  3192. // Set startTime on first step, or _startTime may has milleseconds different between clips
  3193. // PENDING
  3194. if (!this._initialized) {
  3195. this._startTime = globalTime + this._delay;
  3196. this._initialized = true;
  3197. }
  3198. if (this._paused) {
  3199. this._pausedTime += deltaTime;
  3200. return;
  3201. }
  3202. var percent = (globalTime - this._startTime - this._pausedTime) / this._life;
  3203. // 还没开始
  3204. if (percent < 0) {
  3205. return;
  3206. }
  3207. percent = Math.min(percent, 1);
  3208. var easing$$1 = this.easing;
  3209. var easingFunc = typeof easing$$1 === 'string' ? easing[easing$$1] : easing$$1;
  3210. var schedule = typeof easingFunc === 'function'
  3211. ? easingFunc(percent)
  3212. : percent;
  3213. this.fire('frame', schedule);
  3214. // 结束
  3215. if (percent === 1) {
  3216. if (this.loop) {
  3217. this.restart(globalTime);
  3218. // 重新开始周期
  3219. // 抛出而不是直接调用事件直到 stage.update 后再统一调用这些事件
  3220. return 'restart';
  3221. }
  3222. // 动画完成将这个控制器标识为待删除
  3223. // 在Animation.update中进行批量删除
  3224. this._needsRemove = true;
  3225. return 'destroy';
  3226. }
  3227. return null;
  3228. },
  3229. restart: function (globalTime) {
  3230. var remainder = (globalTime - this._startTime - this._pausedTime) % this._life;
  3231. this._startTime = globalTime - remainder + this.gap;
  3232. this._pausedTime = 0;
  3233. this._needsRemove = false;
  3234. },
  3235. fire: function (eventType, arg) {
  3236. eventType = 'on' + eventType;
  3237. if (this[eventType]) {
  3238. this[eventType](this._target, arg);
  3239. }
  3240. },
  3241. pause: function () {
  3242. this._paused = true;
  3243. },
  3244. resume: function () {
  3245. this._paused = false;
  3246. }
  3247. };
  3248. // Simple LRU cache use doubly linked list
  3249. // @module zrender/core/LRU
  3250. /**
  3251. * Simple double linked list. Compared with array, it has O(1) remove operation.
  3252. * @constructor
  3253. */
  3254. var LinkedList = function () {
  3255. /**
  3256. * @type {module:zrender/core/LRU~Entry}
  3257. */
  3258. this.head = null;
  3259. /**
  3260. * @type {module:zrender/core/LRU~Entry}
  3261. */
  3262. this.tail = null;
  3263. this._len = 0;
  3264. };
  3265. var linkedListProto = LinkedList.prototype;
  3266. /**
  3267. * Insert a new value at the tail
  3268. * @param {} val
  3269. * @return {module:zrender/core/LRU~Entry}
  3270. */
  3271. linkedListProto.insert = function (val) {
  3272. var entry = new Entry(val);
  3273. this.insertEntry(entry);
  3274. return entry;
  3275. };
  3276. /**
  3277. * Insert an entry at the tail
  3278. * @param {module:zrender/core/LRU~Entry} entry
  3279. */
  3280. linkedListProto.insertEntry = function (entry) {
  3281. if (!this.head) {
  3282. this.head = this.tail = entry;
  3283. }
  3284. else {
  3285. this.tail.next = entry;
  3286. entry.prev = this.tail;
  3287. entry.next = null;
  3288. this.tail = entry;
  3289. }
  3290. this._len++;
  3291. };
  3292. /**
  3293. * Remove entry.
  3294. * @param {module:zrender/core/LRU~Entry} entry
  3295. */
  3296. linkedListProto.remove = function (entry) {
  3297. var prev = entry.prev;
  3298. var next = entry.next;
  3299. if (prev) {
  3300. prev.next = next;
  3301. }
  3302. else {
  3303. // Is head
  3304. this.head = next;
  3305. }
  3306. if (next) {
  3307. next.prev = prev;
  3308. }
  3309. else {
  3310. // Is tail
  3311. this.tail = prev;
  3312. }
  3313. entry.next = entry.prev = null;
  3314. this._len--;
  3315. };
  3316. /**
  3317. * @return {number}
  3318. */
  3319. linkedListProto.len = function () {
  3320. return this._len;
  3321. };
  3322. /**
  3323. * Clear list
  3324. */
  3325. linkedListProto.clear = function () {
  3326. this.head = this.tail = null;
  3327. this._len = 0;
  3328. };
  3329. /**
  3330. * @constructor
  3331. * @param {} val
  3332. */
  3333. var Entry = function (val) {
  3334. /**
  3335. * @type {}
  3336. */
  3337. this.value = val;
  3338. /**
  3339. * @type {module:zrender/core/LRU~Entry}
  3340. */
  3341. this.next;
  3342. /**
  3343. * @type {module:zrender/core/LRU~Entry}
  3344. */
  3345. this.prev;
  3346. };
  3347. /**
  3348. * LRU Cache
  3349. * @constructor
  3350. * @alias module:zrender/core/LRU
  3351. */
  3352. var LRU = function (maxSize) {
  3353. this._list = new LinkedList();
  3354. this._map = {};
  3355. this._maxSize = maxSize || 10;
  3356. this._lastRemovedEntry = null;
  3357. };
  3358. var LRUProto = LRU.prototype;
  3359. /**
  3360. * @param {string} key
  3361. * @param {} value
  3362. * @return {} Removed value
  3363. */
  3364. LRUProto.put = function (key, value) {
  3365. var list = this._list;
  3366. var map = this._map;
  3367. var removed = null;
  3368. if (map[key] == null) {
  3369. var len = list.len();
  3370. // Reuse last removed entry
  3371. var entry = this._lastRemovedEntry;
  3372. if (len >= this._maxSize && len > 0) {
  3373. // Remove the least recently used
  3374. var leastUsedEntry = list.head;
  3375. list.remove(leastUsedEntry);
  3376. delete map[leastUsedEntry.key];
  3377. removed = leastUsedEntry.value;
  3378. this._lastRemovedEntry = leastUsedEntry;
  3379. }
  3380. if (entry) {
  3381. entry.value = value;
  3382. }
  3383. else {
  3384. entry = new Entry(value);
  3385. }
  3386. entry.key = key;
  3387. list.insertEntry(entry);
  3388. map[key] = entry;
  3389. }
  3390. return removed;
  3391. };
  3392. /**
  3393. * @param {string} key
  3394. * @return {}
  3395. */
  3396. LRUProto.get = function (key) {
  3397. var entry = this._map[key];
  3398. var list = this._list;
  3399. if (entry != null) {
  3400. // Put the latest used entry in the tail
  3401. if (entry !== list.tail) {
  3402. list.remove(entry);
  3403. list.insertEntry(entry);
  3404. }
  3405. return entry.value;
  3406. }
  3407. };
  3408. /**
  3409. * Clear the cache
  3410. */
  3411. LRUProto.clear = function () {
  3412. this._list.clear();
  3413. this._map = {};
  3414. };
  3415. var kCSSColorTable = {
  3416. 'transparent': [0, 0, 0, 0], 'aliceblue': [240, 248, 255, 1],
  3417. 'antiquewhite': [250, 235, 215, 1], 'aqua': [0, 255, 255, 1],
  3418. 'aquamarine': [127, 255, 212, 1], 'azure': [240, 255, 255, 1],
  3419. 'beige': [245, 245, 220, 1], 'bisque': [255, 228, 196, 1],
  3420. 'black': [0, 0, 0, 1], 'blanchedalmond': [255, 235, 205, 1],
  3421. 'blue': [0, 0, 255, 1], 'blueviolet': [138, 43, 226, 1],
  3422. 'brown': [165, 42, 42, 1], 'burlywood': [222, 184, 135, 1],
  3423. 'cadetblue': [95, 158, 160, 1], 'chartreuse': [127, 255, 0, 1],
  3424. 'chocolate': [210, 105, 30, 1], 'coral': [255, 127, 80, 1],
  3425. 'cornflowerblue': [100, 149, 237, 1], 'cornsilk': [255, 248, 220, 1],
  3426. 'crimson': [220, 20, 60, 1], 'cyan': [0, 255, 255, 1],
  3427. 'darkblue': [0, 0, 139, 1], 'darkcyan': [0, 139, 139, 1],
  3428. 'darkgoldenrod': [184, 134, 11, 1], 'darkgray': [169, 169, 169, 1],
  3429. 'darkgreen': [0, 100, 0, 1], 'darkgrey': [169, 169, 169, 1],
  3430. 'darkkhaki': [189, 183, 107, 1], 'darkmagenta': [139, 0, 139, 1],
  3431. 'darkolivegreen': [85, 107, 47, 1], 'darkorange': [255, 140, 0, 1],
  3432. 'darkorchid': [153, 50, 204, 1], 'darkred': [139, 0, 0, 1],
  3433. 'darksalmon': [233, 150, 122, 1], 'darkseagreen': [143, 188, 143, 1],
  3434. 'darkslateblue': [72, 61, 139, 1], 'darkslategray': [47, 79, 79, 1],
  3435. 'darkslategrey': [47, 79, 79, 1], 'darkturquoise': [0, 206, 209, 1],
  3436. 'darkviolet': [148, 0, 211, 1], 'deeppink': [255, 20, 147, 1],
  3437. 'deepskyblue': [0, 191, 255, 1], 'dimgray': [105, 105, 105, 1],
  3438. 'dimgrey': [105, 105, 105, 1], 'dodgerblue': [30, 144, 255, 1],
  3439. 'firebrick': [178, 34, 34, 1], 'floralwhite': [255, 250, 240, 1],
  3440. 'forestgreen': [34, 139, 34, 1], 'fuchsia': [255, 0, 255, 1],
  3441. 'gainsboro': [220, 220, 220, 1], 'ghostwhite': [248, 248, 255, 1],
  3442. 'gold': [255, 215, 0, 1], 'goldenrod': [218, 165, 32, 1],
  3443. 'gray': [128, 128, 128, 1], 'green': [0, 128, 0, 1],
  3444. 'greenyellow': [173, 255, 47, 1], 'grey': [128, 128, 128, 1],
  3445. 'honeydew': [240, 255, 240, 1], 'hotpink': [255, 105, 180, 1],
  3446. 'indianred': [205, 92, 92, 1], 'indigo': [75, 0, 130, 1],
  3447. 'ivory': [255, 255, 240, 1], 'khaki': [240, 230, 140, 1],
  3448. 'lavender': [230, 230, 250, 1], 'lavenderblush': [255, 240, 245, 1],
  3449. 'lawngreen': [124, 252, 0, 1], 'lemonchiffon': [255, 250, 205, 1],
  3450. 'lightblue': [173, 216, 230, 1], 'lightcoral': [240, 128, 128, 1],
  3451. 'lightcyan': [224, 255, 255, 1], 'lightgoldenrodyellow': [250, 250, 210, 1],
  3452. 'lightgray': [211, 211, 211, 1], 'lightgreen': [144, 238, 144, 1],
  3453. 'lightgrey': [211, 211, 211, 1], 'lightpink': [255, 182, 193, 1],
  3454. 'lightsalmon': [255, 160, 122, 1], 'lightseagreen': [32, 178, 170, 1],
  3455. 'lightskyblue': [135, 206, 250, 1], 'lightslategray': [119, 136, 153, 1],
  3456. 'lightslategrey': [119, 136, 153, 1], 'lightsteelblue': [176, 196, 222, 1],
  3457. 'lightyellow': [255, 255, 224, 1], 'lime': [0, 255, 0, 1],
  3458. 'limegreen': [50, 205, 50, 1], 'linen': [250, 240, 230, 1],
  3459. 'magenta': [255, 0, 255, 1], 'maroon': [128, 0, 0, 1],
  3460. 'mediumaquamarine': [102, 205, 170, 1], 'mediumblue': [0, 0, 205, 1],
  3461. 'mediumorchid': [186, 85, 211, 1], 'mediumpurple': [147, 112, 219, 1],
  3462. 'mediumseagreen': [60, 179, 113, 1], 'mediumslateblue': [123, 104, 238, 1],
  3463. 'mediumspringgreen': [0, 250, 154, 1], 'mediumturquoise': [72, 209, 204, 1],
  3464. 'mediumvioletred': [199, 21, 133, 1], 'midnightblue': [25, 25, 112, 1],
  3465. 'mintcream': [245, 255, 250, 1], 'mistyrose': [255, 228, 225, 1],
  3466. 'moccasin': [255, 228, 181, 1], 'navajowhite': [255, 222, 173, 1],
  3467. 'navy': [0, 0, 128, 1], 'oldlace': [253, 245, 230, 1],
  3468. 'olive': [128, 128, 0, 1], 'olivedrab': [107, 142, 35, 1],
  3469. 'orange': [255, 165, 0, 1], 'orangered': [255, 69, 0, 1],
  3470. 'orchid': [218, 112, 214, 1], 'palegoldenrod': [238, 232, 170, 1],
  3471. 'palegreen': [152, 251, 152, 1], 'paleturquoise': [175, 238, 238, 1],
  3472. 'palevioletred': [219, 112, 147, 1], 'papayawhip': [255, 239, 213, 1],
  3473. 'peachpuff': [255, 218, 185, 1], 'peru': [205, 133, 63, 1],
  3474. 'pink': [255, 192, 203, 1], 'plum': [221, 160, 221, 1],
  3475. 'powderblue': [176, 224, 230, 1], 'purple': [128, 0, 128, 1],
  3476. 'red': [255, 0, 0, 1], 'rosybrown': [188, 143, 143, 1],
  3477. 'royalblue': [65, 105, 225, 1], 'saddlebrown': [139, 69, 19, 1],
  3478. 'salmon': [250, 128, 114, 1], 'sandybrown': [244, 164, 96, 1],
  3479. 'seagreen': [46, 139, 87, 1], 'seashell': [255, 245, 238, 1],
  3480. 'sienna': [160, 82, 45, 1], 'silver': [192, 192, 192, 1],
  3481. 'skyblue': [135, 206, 235, 1], 'slateblue': [106, 90, 205, 1],
  3482. 'slategray': [112, 128, 144, 1], 'slategrey': [112, 128, 144, 1],
  3483. 'snow': [255, 250, 250, 1], 'springgreen': [0, 255, 127, 1],
  3484. 'steelblue': [70, 130, 180, 1], 'tan': [210, 180, 140, 1],
  3485. 'teal': [0, 128, 128, 1], 'thistle': [216, 191, 216, 1],
  3486. 'tomato': [255, 99, 71, 1], 'turquoise': [64, 224, 208, 1],
  3487. 'violet': [238, 130, 238, 1], 'wheat': [245, 222, 179, 1],
  3488. 'white': [255, 255, 255, 1], 'whitesmoke': [245, 245, 245, 1],
  3489. 'yellow': [255, 255, 0, 1], 'yellowgreen': [154, 205, 50, 1]
  3490. };
  3491. function clampCssByte(i) { // Clamp to integer 0 .. 255.
  3492. i = Math.round(i); // Seems to be what Chrome does (vs truncation).
  3493. return i < 0 ? 0 : i > 255 ? 255 : i;
  3494. }
  3495. function clampCssAngle(i) { // Clamp to integer 0 .. 360.
  3496. i = Math.round(i); // Seems to be what Chrome does (vs truncation).
  3497. return i < 0 ? 0 : i > 360 ? 360 : i;
  3498. }
  3499. function clampCssFloat(f) { // Clamp to float 0.0 .. 1.0.
  3500. return f < 0 ? 0 : f > 1 ? 1 : f;
  3501. }
  3502. function parseCssInt(str) { // int or percentage.
  3503. if (str.length && str.charAt(str.length - 1) === '%') {
  3504. return clampCssByte(parseFloat(str) / 100 * 255);
  3505. }
  3506. return clampCssByte(parseInt(str, 10));
  3507. }
  3508. function parseCssFloat(str) { // float or percentage.
  3509. if (str.length && str.charAt(str.length - 1) === '%') {
  3510. return clampCssFloat(parseFloat(str) / 100);
  3511. }
  3512. return clampCssFloat(parseFloat(str));
  3513. }
  3514. function cssHueToRgb(m1, m2, h) {
  3515. if (h < 0) {
  3516. h += 1;
  3517. }
  3518. else if (h > 1) {
  3519. h -= 1;
  3520. }
  3521. if (h * 6 < 1) {
  3522. return m1 + (m2 - m1) * h * 6;
  3523. }
  3524. if (h * 2 < 1) {
  3525. return m2;
  3526. }
  3527. if (h * 3 < 2) {
  3528. return m1 + (m2 - m1) * (2 / 3 - h) * 6;
  3529. }
  3530. return m1;
  3531. }
  3532. function lerpNumber(a, b, p) {
  3533. return a + (b - a) * p;
  3534. }
  3535. function setRgba(out, r, g, b, a) {
  3536. out[0] = r;
  3537. out[1] = g;
  3538. out[2] = b;
  3539. out[3] = a;
  3540. return out;
  3541. }
  3542. function copyRgba(out, a) {
  3543. out[0] = a[0];
  3544. out[1] = a[1];
  3545. out[2] = a[2];
  3546. out[3] = a[3];
  3547. return out;
  3548. }
  3549. var colorCache = new LRU(20);
  3550. var lastRemovedArr = null;
  3551. function putToCache(colorStr, rgbaArr) {
  3552. // Reuse removed array
  3553. if (lastRemovedArr) {
  3554. copyRgba(lastRemovedArr, rgbaArr);
  3555. }
  3556. lastRemovedArr = colorCache.put(colorStr, lastRemovedArr || (rgbaArr.slice()));
  3557. }
  3558. /**
  3559. * @param {string} colorStr
  3560. * @param {Array.<number>} out
  3561. * @return {Array.<number>}
  3562. * @memberOf module:zrender/util/color
  3563. */
  3564. function parse(colorStr, rgbaArr) {
  3565. if (!colorStr) {
  3566. return;
  3567. }
  3568. rgbaArr = rgbaArr || [];
  3569. var cached = colorCache.get(colorStr);
  3570. if (cached) {
  3571. return copyRgba(rgbaArr, cached);
  3572. }
  3573. // colorStr may be not string
  3574. colorStr = colorStr + '';
  3575. // Remove all whitespace, not compliant, but should just be more accepting.
  3576. var str = colorStr.replace(/ /g, '').toLowerCase();
  3577. // Color keywords (and transparent) lookup.
  3578. if (str in kCSSColorTable) {
  3579. copyRgba(rgbaArr, kCSSColorTable[str]);
  3580. putToCache(colorStr, rgbaArr);
  3581. return rgbaArr;
  3582. }
  3583. // #abc and #abc123 syntax.
  3584. if (str.charAt(0) === '#') {
  3585. if (str.length === 4) {
  3586. var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
  3587. if (!(iv >= 0 && iv <= 0xfff)) {
  3588. setRgba(rgbaArr, 0, 0, 0, 1);
  3589. return; // Covers NaN.
  3590. }
  3591. setRgba(rgbaArr,
  3592. ((iv & 0xf00) >> 4) | ((iv & 0xf00) >> 8),
  3593. (iv & 0xf0) | ((iv & 0xf0) >> 4),
  3594. (iv & 0xf) | ((iv & 0xf) << 4),
  3595. 1
  3596. );
  3597. putToCache(colorStr, rgbaArr);
  3598. return rgbaArr;
  3599. }
  3600. else if (str.length === 7) {
  3601. var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
  3602. if (!(iv >= 0 && iv <= 0xffffff)) {
  3603. setRgba(rgbaArr, 0, 0, 0, 1);
  3604. return; // Covers NaN.
  3605. }
  3606. setRgba(rgbaArr,
  3607. (iv & 0xff0000) >> 16,
  3608. (iv & 0xff00) >> 8,
  3609. iv & 0xff,
  3610. 1
  3611. );
  3612. putToCache(colorStr, rgbaArr);
  3613. return rgbaArr;
  3614. }
  3615. return;
  3616. }
  3617. var op = str.indexOf('(');
  3618. var ep = str.indexOf(')');
  3619. if (op !== -1 && ep + 1 === str.length) {
  3620. var fname = str.substr(0, op);
  3621. var params = str.substr(op + 1, ep - (op + 1)).split(',');
  3622. var alpha = 1; // To allow case fallthrough.
  3623. switch (fname) {
  3624. case 'rgba':
  3625. if (params.length !== 4) {
  3626. setRgba(rgbaArr, 0, 0, 0, 1);
  3627. return;
  3628. }
  3629. alpha = parseCssFloat(params.pop()); // jshint ignore:line
  3630. // Fall through.
  3631. case 'rgb':
  3632. if (params.length !== 3) {
  3633. setRgba(rgbaArr, 0, 0, 0, 1);
  3634. return;
  3635. }
  3636. setRgba(rgbaArr,
  3637. parseCssInt(params[0]),
  3638. parseCssInt(params[1]),
  3639. parseCssInt(params[2]),
  3640. alpha
  3641. );
  3642. putToCache(colorStr, rgbaArr);
  3643. return rgbaArr;
  3644. case 'hsla':
  3645. if (params.length !== 4) {
  3646. setRgba(rgbaArr, 0, 0, 0, 1);
  3647. return;
  3648. }
  3649. params[3] = parseCssFloat(params[3]);
  3650. hsla2rgba(params, rgbaArr);
  3651. putToCache(colorStr, rgbaArr);
  3652. return rgbaArr;
  3653. case 'hsl':
  3654. if (params.length !== 3) {
  3655. setRgba(rgbaArr, 0, 0, 0, 1);
  3656. return;
  3657. }
  3658. hsla2rgba(params, rgbaArr);
  3659. putToCache(colorStr, rgbaArr);
  3660. return rgbaArr;
  3661. default:
  3662. return;
  3663. }
  3664. }
  3665. setRgba(rgbaArr, 0, 0, 0, 1);
  3666. return;
  3667. }
  3668. /**
  3669. * @param {Array.<number>} hsla
  3670. * @param {Array.<number>} rgba
  3671. * @return {Array.<number>} rgba
  3672. */
  3673. function hsla2rgba(hsla, rgba) {
  3674. var h = (((parseFloat(hsla[0]) % 360) + 360) % 360) / 360; // 0 .. 1
  3675. // NOTE(deanm): According to the CSS spec s/l should only be
  3676. // percentages, but we don't bother and let float or percentage.
  3677. var s = parseCssFloat(hsla[1]);
  3678. var l = parseCssFloat(hsla[2]);
  3679. var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
  3680. var m1 = l * 2 - m2;
  3681. rgba = rgba || [];
  3682. setRgba(rgba,
  3683. clampCssByte(cssHueToRgb(m1, m2, h + 1 / 3) * 255),
  3684. clampCssByte(cssHueToRgb(m1, m2, h) * 255),
  3685. clampCssByte(cssHueToRgb(m1, m2, h - 1 / 3) * 255),
  3686. 1
  3687. );
  3688. if (hsla.length === 4) {
  3689. rgba[3] = hsla[3];
  3690. }
  3691. return rgba;
  3692. }
  3693. /**
  3694. * @param {Array.<number>} rgba
  3695. * @return {Array.<number>} hsla
  3696. */
  3697. function rgba2hsla(rgba) {
  3698. if (!rgba) {
  3699. return;
  3700. }
  3701. // RGB from 0 to 255
  3702. var R = rgba[0] / 255;
  3703. var G = rgba[1] / 255;
  3704. var B = rgba[2] / 255;
  3705. var vMin = Math.min(R, G, B); // Min. value of RGB
  3706. var vMax = Math.max(R, G, B); // Max. value of RGB
  3707. var delta = vMax - vMin; // Delta RGB value
  3708. var L = (vMax + vMin) / 2;
  3709. var H;
  3710. var S;
  3711. // HSL results from 0 to 1
  3712. if (delta === 0) {
  3713. H = 0;
  3714. S = 0;
  3715. }
  3716. else {
  3717. if (L < 0.5) {
  3718. S = delta / (vMax + vMin);
  3719. }
  3720. else {
  3721. S = delta / (2 - vMax - vMin);
  3722. }
  3723. var deltaR = (((vMax - R) / 6) + (delta / 2)) / delta;
  3724. var deltaG = (((vMax - G) / 6) + (delta / 2)) / delta;
  3725. var deltaB = (((vMax - B) / 6) + (delta / 2)) / delta;
  3726. if (R === vMax) {
  3727. H = deltaB - deltaG;
  3728. }
  3729. else if (G === vMax) {
  3730. H = (1 / 3) + deltaR - deltaB;
  3731. }
  3732. else if (B === vMax) {
  3733. H = (2 / 3) + deltaG - deltaR;
  3734. }
  3735. if (H < 0) {
  3736. H += 1;
  3737. }
  3738. if (H > 1) {
  3739. H -= 1;
  3740. }
  3741. }
  3742. var hsla = [H * 360, S, L];
  3743. if (rgba[3] != null) {
  3744. hsla.push(rgba[3]);
  3745. }
  3746. return hsla;
  3747. }
  3748. /**
  3749. * @param {string} color
  3750. * @param {number} level
  3751. * @return {string}
  3752. * @memberOf module:zrender/util/color
  3753. */
  3754. function lift(color, level) {
  3755. var colorArr = parse(color);
  3756. if (colorArr) {
  3757. for (var i = 0; i < 3; i++) {
  3758. if (level < 0) {
  3759. colorArr[i] = colorArr[i] * (1 - level) | 0;
  3760. }
  3761. else {
  3762. colorArr[i] = ((255 - colorArr[i]) * level + colorArr[i]) | 0;
  3763. }
  3764. if (colorArr[i] > 255) {
  3765. colorArr[i] = 255;
  3766. }
  3767. else if (color[i] < 0) {
  3768. colorArr[i] = 0;
  3769. }
  3770. }
  3771. return stringify(colorArr, colorArr.length === 4 ? 'rgba' : 'rgb');
  3772. }
  3773. }
  3774. /**
  3775. * @param {string} color
  3776. * @return {string}
  3777. * @memberOf module:zrender/util/color
  3778. */
  3779. function toHex(color) {
  3780. var colorArr = parse(color);
  3781. if (colorArr) {
  3782. return ((1 << 24) + (colorArr[0] << 16) + (colorArr[1] << 8) + (+colorArr[2])).toString(16).slice(1);
  3783. }
  3784. }
  3785. /**
  3786. * Map value to color. Faster than lerp methods because color is represented by rgba array.
  3787. * @param {number} normalizedValue A float between 0 and 1.
  3788. * @param {Array.<Array.<number>>} colors List of rgba color array
  3789. * @param {Array.<number>} [out] Mapped gba color array
  3790. * @return {Array.<number>} will be null/undefined if input illegal.
  3791. */
  3792. function fastLerp(normalizedValue, colors, out) {
  3793. if (!(colors && colors.length)
  3794. || !(normalizedValue >= 0 && normalizedValue <= 1)
  3795. ) {
  3796. return;
  3797. }
  3798. out = out || [];
  3799. var value = normalizedValue * (colors.length - 1);
  3800. var leftIndex = Math.floor(value);
  3801. var rightIndex = Math.ceil(value);
  3802. var leftColor = colors[leftIndex];
  3803. var rightColor = colors[rightIndex];
  3804. var dv = value - leftIndex;
  3805. out[0] = clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv));
  3806. out[1] = clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv));
  3807. out[2] = clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv));
  3808. out[3] = clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv));
  3809. return out;
  3810. }
  3811. /**
  3812. * @deprecated
  3813. */
  3814. var fastMapToColor = fastLerp;
  3815. /**
  3816. * @param {number} normalizedValue A float between 0 and 1.
  3817. * @param {Array.<string>} colors Color list.
  3818. * @param {boolean=} fullOutput Default false.
  3819. * @return {(string|Object)} Result color. If fullOutput,
  3820. * return {color: ..., leftIndex: ..., rightIndex: ..., value: ...},
  3821. * @memberOf module:zrender/util/color
  3822. */
  3823. function lerp$1(normalizedValue, colors, fullOutput) {
  3824. if (!(colors && colors.length)
  3825. || !(normalizedValue >= 0 && normalizedValue <= 1)
  3826. ) {
  3827. return;
  3828. }
  3829. var value = normalizedValue * (colors.length - 1);
  3830. var leftIndex = Math.floor(value);
  3831. var rightIndex = Math.ceil(value);
  3832. var leftColor = parse(colors[leftIndex]);
  3833. var rightColor = parse(colors[rightIndex]);
  3834. var dv = value - leftIndex;
  3835. var color = stringify(
  3836. [
  3837. clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv)),
  3838. clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv)),
  3839. clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv)),
  3840. clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv))
  3841. ],
  3842. 'rgba'
  3843. );
  3844. return fullOutput
  3845. ? {
  3846. color: color,
  3847. leftIndex: leftIndex,
  3848. rightIndex: rightIndex,
  3849. value: value
  3850. }
  3851. : color;
  3852. }
  3853. /**
  3854. * @deprecated
  3855. */
  3856. var mapToColor = lerp$1;
  3857. /**
  3858. * @param {string} color
  3859. * @param {number=} h 0 ~ 360, ignore when null.
  3860. * @param {number=} s 0 ~ 1, ignore when null.
  3861. * @param {number=} l 0 ~ 1, ignore when null.
  3862. * @return {string} Color string in rgba format.
  3863. * @memberOf module:zrender/util/color
  3864. */
  3865. function modifyHSL(color, h, s, l) {
  3866. color = parse(color);
  3867. if (color) {
  3868. color = rgba2hsla(color);
  3869. h != null && (color[0] = clampCssAngle(h));
  3870. s != null && (color[1] = parseCssFloat(s));
  3871. l != null && (color[2] = parseCssFloat(l));
  3872. return stringify(hsla2rgba(color), 'rgba');
  3873. }
  3874. }
  3875. /**
  3876. * @param {string} color
  3877. * @param {number=} alpha 0 ~ 1
  3878. * @return {string} Color string in rgba format.
  3879. * @memberOf module:zrender/util/color
  3880. */
  3881. function modifyAlpha(color, alpha) {
  3882. color = parse(color);
  3883. if (color && alpha != null) {
  3884. color[3] = clampCssFloat(alpha);
  3885. return stringify(color, 'rgba');
  3886. }
  3887. }
  3888. /**
  3889. * @param {Array.<number>} arrColor like [12,33,44,0.4]
  3890. * @param {string} type 'rgba', 'hsva', ...
  3891. * @return {string} Result color. (If input illegal, return undefined).
  3892. */
  3893. function stringify(arrColor, type) {
  3894. if (!arrColor || !arrColor.length) {
  3895. return;
  3896. }
  3897. var colorStr = arrColor[0] + ',' + arrColor[1] + ',' + arrColor[2];
  3898. if (type === 'rgba' || type === 'hsva' || type === 'hsla') {
  3899. colorStr += ',' + arrColor[3];
  3900. }
  3901. return type + '(' + colorStr + ')';
  3902. }
  3903. var color = (Object.freeze || Object)({
  3904. parse: parse,
  3905. lift: lift,
  3906. toHex: toHex,
  3907. fastLerp: fastLerp,
  3908. fastMapToColor: fastMapToColor,
  3909. lerp: lerp$1,
  3910. mapToColor: mapToColor,
  3911. modifyHSL: modifyHSL,
  3912. modifyAlpha: modifyAlpha,
  3913. stringify: stringify
  3914. });
  3915. /**
  3916. * @module echarts/animation/Animator
  3917. */
  3918. var arraySlice = Array.prototype.slice;
  3919. function defaultGetter(target, key) {
  3920. return target[key];
  3921. }
  3922. function defaultSetter(target, key, value) {
  3923. target[key] = value;
  3924. }
  3925. /**
  3926. * @param {number} p0
  3927. * @param {number} p1
  3928. * @param {number} percent
  3929. * @return {number}
  3930. */
  3931. function interpolateNumber(p0, p1, percent) {
  3932. return (p1 - p0) * percent + p0;
  3933. }
  3934. /**
  3935. * @param {string} p0
  3936. * @param {string} p1
  3937. * @param {number} percent
  3938. * @return {string}
  3939. */
  3940. function interpolateString(p0, p1, percent) {
  3941. return percent > 0.5 ? p1 : p0;
  3942. }
  3943. /**
  3944. * @param {Array} p0
  3945. * @param {Array} p1
  3946. * @param {number} percent
  3947. * @param {Array} out
  3948. * @param {number} arrDim
  3949. */
  3950. function interpolateArray(p0, p1, percent, out, arrDim) {
  3951. var len = p0.length;
  3952. if (arrDim === 1) {
  3953. for (var i = 0; i < len; i++) {
  3954. out[i] = interpolateNumber(p0[i], p1[i], percent);
  3955. }
  3956. }
  3957. else {
  3958. var len2 = len && p0[0].length;
  3959. for (var i = 0; i < len; i++) {
  3960. for (var j = 0; j < len2; j++) {
  3961. out[i][j] = interpolateNumber(
  3962. p0[i][j], p1[i][j], percent
  3963. );
  3964. }
  3965. }
  3966. }
  3967. }
  3968. // arr0 is source array, arr1 is target array.
  3969. // Do some preprocess to avoid error happened when interpolating from arr0 to arr1
  3970. function fillArr(arr0, arr1, arrDim) {
  3971. var arr0Len = arr0.length;
  3972. var arr1Len = arr1.length;
  3973. if (arr0Len !== arr1Len) {
  3974. // FIXME Not work for TypedArray
  3975. var isPreviousLarger = arr0Len > arr1Len;
  3976. if (isPreviousLarger) {
  3977. // Cut the previous
  3978. arr0.length = arr1Len;
  3979. }
  3980. else {
  3981. // Fill the previous
  3982. for (var i = arr0Len; i < arr1Len; i++) {
  3983. arr0.push(
  3984. arrDim === 1 ? arr1[i] : arraySlice.call(arr1[i])
  3985. );
  3986. }
  3987. }
  3988. }
  3989. // Handling NaN value
  3990. var len2 = arr0[0] && arr0[0].length;
  3991. for (var i = 0; i < arr0.length; i++) {
  3992. if (arrDim === 1) {
  3993. if (isNaN(arr0[i])) {
  3994. arr0[i] = arr1[i];
  3995. }
  3996. }
  3997. else {
  3998. for (var j = 0; j < len2; j++) {
  3999. if (isNaN(arr0[i][j])) {
  4000. arr0[i][j] = arr1[i][j];
  4001. }
  4002. }
  4003. }
  4004. }
  4005. }
  4006. /**
  4007. * @param {Array} arr0
  4008. * @param {Array} arr1
  4009. * @param {number} arrDim
  4010. * @return {boolean}
  4011. */
  4012. function isArraySame(arr0, arr1, arrDim) {
  4013. if (arr0 === arr1) {
  4014. return true;
  4015. }
  4016. var len = arr0.length;
  4017. if (len !== arr1.length) {
  4018. return false;
  4019. }
  4020. if (arrDim === 1) {
  4021. for (var i = 0; i < len; i++) {
  4022. if (arr0[i] !== arr1[i]) {
  4023. return false;
  4024. }
  4025. }
  4026. }
  4027. else {
  4028. var len2 = arr0[0].length;
  4029. for (var i = 0; i < len; i++) {
  4030. for (var j = 0; j < len2; j++) {
  4031. if (arr0[i][j] !== arr1[i][j]) {
  4032. return false;
  4033. }
  4034. }
  4035. }
  4036. }
  4037. return true;
  4038. }
  4039. /**
  4040. * Catmull Rom interpolate array
  4041. * @param {Array} p0
  4042. * @param {Array} p1
  4043. * @param {Array} p2
  4044. * @param {Array} p3
  4045. * @param {number} t
  4046. * @param {number} t2
  4047. * @param {number} t3
  4048. * @param {Array} out
  4049. * @param {number} arrDim
  4050. */
  4051. function catmullRomInterpolateArray(
  4052. p0, p1, p2, p3, t, t2, t3, out, arrDim
  4053. ) {
  4054. var len = p0.length;
  4055. if (arrDim === 1) {
  4056. for (var i = 0; i < len; i++) {
  4057. out[i] = catmullRomInterpolate(
  4058. p0[i], p1[i], p2[i], p3[i], t, t2, t3
  4059. );
  4060. }
  4061. }
  4062. else {
  4063. var len2 = p0[0].length;
  4064. for (var i = 0; i < len; i++) {
  4065. for (var j = 0; j < len2; j++) {
  4066. out[i][j] = catmullRomInterpolate(
  4067. p0[i][j], p1[i][j], p2[i][j], p3[i][j],
  4068. t, t2, t3
  4069. );
  4070. }
  4071. }
  4072. }
  4073. }
  4074. /**
  4075. * Catmull Rom interpolate number
  4076. * @param {number} p0
  4077. * @param {number} p1
  4078. * @param {number} p2
  4079. * @param {number} p3
  4080. * @param {number} t
  4081. * @param {number} t2
  4082. * @param {number} t3
  4083. * @return {number}
  4084. */
  4085. function catmullRomInterpolate(p0, p1, p2, p3, t, t2, t3) {
  4086. var v0 = (p2 - p0) * 0.5;
  4087. var v1 = (p3 - p1) * 0.5;
  4088. return (2 * (p1 - p2) + v0 + v1) * t3
  4089. + (-3 * (p1 - p2) - 2 * v0 - v1) * t2
  4090. + v0 * t + p1;
  4091. }
  4092. function cloneValue(value) {
  4093. if (isArrayLike(value)) {
  4094. var len = value.length;
  4095. if (isArrayLike(value[0])) {
  4096. var ret = [];
  4097. for (var i = 0; i < len; i++) {
  4098. ret.push(arraySlice.call(value[i]));
  4099. }
  4100. return ret;
  4101. }
  4102. return arraySlice.call(value);
  4103. }
  4104. return value;
  4105. }
  4106. function rgba2String(rgba) {
  4107. rgba[0] = Math.floor(rgba[0]);
  4108. rgba[1] = Math.floor(rgba[1]);
  4109. rgba[2] = Math.floor(rgba[2]);
  4110. return 'rgba(' + rgba.join(',') + ')';
  4111. }
  4112. function getArrayDim(keyframes) {
  4113. var lastValue = keyframes[keyframes.length - 1].value;
  4114. return isArrayLike(lastValue && lastValue[0]) ? 2 : 1;
  4115. }
  4116. function createTrackClip(animator, easing, oneTrackDone, keyframes, propName, forceAnimate) {
  4117. var getter = animator._getter;
  4118. var setter = animator._setter;
  4119. var useSpline = easing === 'spline';
  4120. var trackLen = keyframes.length;
  4121. if (!trackLen) {
  4122. return;
  4123. }
  4124. // Guess data type
  4125. var firstVal = keyframes[0].value;
  4126. var isValueArray = isArrayLike(firstVal);
  4127. var isValueColor = false;
  4128. var isValueString = false;
  4129. // For vertices morphing
  4130. var arrDim = isValueArray ? getArrayDim(keyframes) : 0;
  4131. var trackMaxTime;
  4132. // Sort keyframe as ascending
  4133. keyframes.sort(function (a, b) {
  4134. return a.time - b.time;
  4135. });
  4136. trackMaxTime = keyframes[trackLen - 1].time;
  4137. // Percents of each keyframe
  4138. var kfPercents = [];
  4139. // Value of each keyframe
  4140. var kfValues = [];
  4141. var prevValue = keyframes[0].value;
  4142. var isAllValueEqual = true;
  4143. for (var i = 0; i < trackLen; i++) {
  4144. kfPercents.push(keyframes[i].time / trackMaxTime);
  4145. // Assume value is a color when it is a string
  4146. var value = keyframes[i].value;
  4147. // Check if value is equal, deep check if value is array
  4148. if (!((isValueArray && isArraySame(value, prevValue, arrDim))
  4149. || (!isValueArray && value === prevValue))) {
  4150. isAllValueEqual = false;
  4151. }
  4152. prevValue = value;
  4153. // Try converting a string to a color array
  4154. if (typeof value === 'string') {
  4155. var colorArray = parse(value);
  4156. if (colorArray) {
  4157. value = colorArray;
  4158. isValueColor = true;
  4159. }
  4160. else {
  4161. isValueString = true;
  4162. }
  4163. }
  4164. kfValues.push(value);
  4165. }
  4166. if (!forceAnimate && isAllValueEqual) {
  4167. return;
  4168. }
  4169. var lastValue = kfValues[trackLen - 1];
  4170. // Polyfill array and NaN value
  4171. for (var i = 0; i < trackLen - 1; i++) {
  4172. if (isValueArray) {
  4173. fillArr(kfValues[i], lastValue, arrDim);
  4174. }
  4175. else {
  4176. if (isNaN(kfValues[i]) && !isNaN(lastValue) && !isValueString && !isValueColor) {
  4177. kfValues[i] = lastValue;
  4178. }
  4179. }
  4180. }
  4181. isValueArray && fillArr(getter(animator._target, propName), lastValue, arrDim);
  4182. // Cache the key of last frame to speed up when
  4183. // animation playback is sequency
  4184. var lastFrame = 0;
  4185. var lastFramePercent = 0;
  4186. var start;
  4187. var w;
  4188. var p0;
  4189. var p1;
  4190. var p2;
  4191. var p3;
  4192. if (isValueColor) {
  4193. var rgba = [0, 0, 0, 0];
  4194. }
  4195. var onframe = function (target, percent) {
  4196. // Find the range keyframes
  4197. // kf1-----kf2---------current--------kf3
  4198. // find kf2 and kf3 and do interpolation
  4199. var frame;
  4200. // In the easing function like elasticOut, percent may less than 0
  4201. if (percent < 0) {
  4202. frame = 0;
  4203. }
  4204. else if (percent < lastFramePercent) {
  4205. // Start from next key
  4206. // PENDING start from lastFrame ?
  4207. start = Math.min(lastFrame + 1, trackLen - 1);
  4208. for (frame = start; frame >= 0; frame--) {
  4209. if (kfPercents[frame] <= percent) {
  4210. break;
  4211. }
  4212. }
  4213. // PENDING really need to do this ?
  4214. frame = Math.min(frame, trackLen - 2);
  4215. }
  4216. else {
  4217. for (frame = lastFrame; frame < trackLen; frame++) {
  4218. if (kfPercents[frame] > percent) {
  4219. break;
  4220. }
  4221. }
  4222. frame = Math.min(frame - 1, trackLen - 2);
  4223. }
  4224. lastFrame = frame;
  4225. lastFramePercent = percent;
  4226. var range = (kfPercents[frame + 1] - kfPercents[frame]);
  4227. if (range === 0) {
  4228. return;
  4229. }
  4230. else {
  4231. w = (percent - kfPercents[frame]) / range;
  4232. }
  4233. if (useSpline) {
  4234. p1 = kfValues[frame];
  4235. p0 = kfValues[frame === 0 ? frame : frame - 1];
  4236. p2 = kfValues[frame > trackLen - 2 ? trackLen - 1 : frame + 1];
  4237. p3 = kfValues[frame > trackLen - 3 ? trackLen - 1 : frame + 2];
  4238. if (isValueArray) {
  4239. catmullRomInterpolateArray(
  4240. p0, p1, p2, p3, w, w * w, w * w * w,
  4241. getter(target, propName),
  4242. arrDim
  4243. );
  4244. }
  4245. else {
  4246. var value;
  4247. if (isValueColor) {
  4248. value = catmullRomInterpolateArray(
  4249. p0, p1, p2, p3, w, w * w, w * w * w,
  4250. rgba, 1
  4251. );
  4252. value = rgba2String(rgba);
  4253. }
  4254. else if (isValueString) {
  4255. // String is step(0.5)
  4256. return interpolateString(p1, p2, w);
  4257. }
  4258. else {
  4259. value = catmullRomInterpolate(
  4260. p0, p1, p2, p3, w, w * w, w * w * w
  4261. );
  4262. }
  4263. setter(
  4264. target,
  4265. propName,
  4266. value
  4267. );
  4268. }
  4269. }
  4270. else {
  4271. if (isValueArray) {
  4272. interpolateArray(
  4273. kfValues[frame], kfValues[frame + 1], w,
  4274. getter(target, propName),
  4275. arrDim
  4276. );
  4277. }
  4278. else {
  4279. var value;
  4280. if (isValueColor) {
  4281. interpolateArray(
  4282. kfValues[frame], kfValues[frame + 1], w,
  4283. rgba, 1
  4284. );
  4285. value = rgba2String(rgba);
  4286. }
  4287. else if (isValueString) {
  4288. // String is step(0.5)
  4289. return interpolateString(kfValues[frame], kfValues[frame + 1], w);
  4290. }
  4291. else {
  4292. value = interpolateNumber(kfValues[frame], kfValues[frame + 1], w);
  4293. }
  4294. setter(
  4295. target,
  4296. propName,
  4297. value
  4298. );
  4299. }
  4300. }
  4301. };
  4302. var clip = new Clip({
  4303. target: animator._target,
  4304. life: trackMaxTime,
  4305. loop: animator._loop,
  4306. delay: animator._delay,
  4307. onframe: onframe,
  4308. ondestroy: oneTrackDone
  4309. });
  4310. if (easing && easing !== 'spline') {
  4311. clip.easing = easing;
  4312. }
  4313. return clip;
  4314. }
  4315. /**
  4316. * @alias module:zrender/animation/Animator
  4317. * @constructor
  4318. * @param {Object} target
  4319. * @param {boolean} loop
  4320. * @param {Function} getter
  4321. * @param {Function} setter
  4322. */
  4323. var Animator = function (target, loop, getter, setter) {
  4324. this._tracks = {};
  4325. this._target = target;
  4326. this._loop = loop || false;
  4327. this._getter = getter || defaultGetter;
  4328. this._setter = setter || defaultSetter;
  4329. this._clipCount = 0;
  4330. this._delay = 0;
  4331. this._doneList = [];
  4332. this._onframeList = [];
  4333. this._clipList = [];
  4334. };
  4335. Animator.prototype = {
  4336. /**
  4337. * Set Animation keyframe
  4338. * @param {number} time 关键帧时间,单位是ms
  4339. * @param {Object} props 关键帧的属性值,key-value表示
  4340. * @return {module:zrender/animation/Animator}
  4341. */
  4342. when: function (time /* ms */, props) {
  4343. var tracks = this._tracks;
  4344. for (var propName in props) {
  4345. if (!props.hasOwnProperty(propName)) {
  4346. continue;
  4347. }
  4348. if (!tracks[propName]) {
  4349. tracks[propName] = [];
  4350. // Invalid value
  4351. var value = this._getter(this._target, propName);
  4352. if (value == null) {
  4353. // zrLog('Invalid property ' + propName);
  4354. continue;
  4355. }
  4356. // If time is 0
  4357. // Then props is given initialize value
  4358. // Else
  4359. // Initialize value from current prop value
  4360. if (time !== 0) {
  4361. tracks[propName].push({
  4362. time: 0,
  4363. value: cloneValue(value)
  4364. });
  4365. }
  4366. }
  4367. tracks[propName].push({
  4368. time: time,
  4369. value: props[propName]
  4370. });
  4371. }
  4372. return this;
  4373. },
  4374. /**
  4375. * 添加动画每一帧的回调函数
  4376. * @param {Function} callback
  4377. * @return {module:zrender/animation/Animator}
  4378. */
  4379. during: function (callback) {
  4380. this._onframeList.push(callback);
  4381. return this;
  4382. },
  4383. pause: function () {
  4384. for (var i = 0; i < this._clipList.length; i++) {
  4385. this._clipList[i].pause();
  4386. }
  4387. this._paused = true;
  4388. },
  4389. resume: function () {
  4390. for (var i = 0; i < this._clipList.length; i++) {
  4391. this._clipList[i].resume();
  4392. }
  4393. this._paused = false;
  4394. },
  4395. isPaused: function () {
  4396. return !!this._paused;
  4397. },
  4398. _doneCallback: function () {
  4399. // Clear all tracks
  4400. this._tracks = {};
  4401. // Clear all clips
  4402. this._clipList.length = 0;
  4403. var doneList = this._doneList;
  4404. var len = doneList.length;
  4405. for (var i = 0; i < len; i++) {
  4406. doneList[i].call(this);
  4407. }
  4408. },
  4409. /**
  4410. * Start the animation
  4411. * @param {string|Function} [easing]
  4412. * 动画缓动函数,详见{@link module:zrender/animation/easing}
  4413. * @param {boolean} forceAnimate
  4414. * @return {module:zrender/animation/Animator}
  4415. */
  4416. start: function (easing, forceAnimate) {
  4417. var self = this;
  4418. var clipCount = 0;
  4419. var oneTrackDone = function () {
  4420. clipCount--;
  4421. if (!clipCount) {
  4422. self._doneCallback();
  4423. }
  4424. };
  4425. var lastClip;
  4426. for (var propName in this._tracks) {
  4427. if (!this._tracks.hasOwnProperty(propName)) {
  4428. continue;
  4429. }
  4430. var clip = createTrackClip(
  4431. this, easing, oneTrackDone,
  4432. this._tracks[propName], propName, forceAnimate
  4433. );
  4434. if (clip) {
  4435. this._clipList.push(clip);
  4436. clipCount++;
  4437. // If start after added to animation
  4438. if (this.animation) {
  4439. this.animation.addClip(clip);
  4440. }
  4441. lastClip = clip;
  4442. }
  4443. }
  4444. // Add during callback on the last clip
  4445. if (lastClip) {
  4446. var oldOnFrame = lastClip.onframe;
  4447. lastClip.onframe = function (target, percent) {
  4448. oldOnFrame(target, percent);
  4449. for (var i = 0; i < self._onframeList.length; i++) {
  4450. self._onframeList[i](target, percent);
  4451. }
  4452. };
  4453. }
  4454. // This optimization will help the case that in the upper application
  4455. // the view may be refreshed frequently, where animation will be
  4456. // called repeatly but nothing changed.
  4457. if (!clipCount) {
  4458. this._doneCallback();
  4459. }
  4460. return this;
  4461. },
  4462. /**
  4463. * Stop animation
  4464. * @param {boolean} forwardToLast If move to last frame before stop
  4465. */
  4466. stop: function (forwardToLast) {
  4467. var clipList = this._clipList;
  4468. var animation = this.animation;
  4469. for (var i = 0; i < clipList.length; i++) {
  4470. var clip = clipList[i];
  4471. if (forwardToLast) {
  4472. // Move to last frame before stop
  4473. clip.onframe(this._target, 1);
  4474. }
  4475. animation && animation.removeClip(clip);
  4476. }
  4477. clipList.length = 0;
  4478. },
  4479. /**
  4480. * Set when animation delay starts
  4481. * @param {number} time 单位ms
  4482. * @return {module:zrender/animation/Animator}
  4483. */
  4484. delay: function (time) {
  4485. this._delay = time;
  4486. return this;
  4487. },
  4488. /**
  4489. * Add callback for animation end
  4490. * @param {Function} cb
  4491. * @return {module:zrender/animation/Animator}
  4492. */
  4493. done: function (cb) {
  4494. if (cb) {
  4495. this._doneList.push(cb);
  4496. }
  4497. return this;
  4498. },
  4499. /**
  4500. * @return {Array.<module:zrender/animation/Clip>}
  4501. */
  4502. getClips: function () {
  4503. return this._clipList;
  4504. }
  4505. };
  4506. var dpr = 1;
  4507. // If in browser environment
  4508. if (typeof window !== 'undefined') {
  4509. dpr = Math.max(window.devicePixelRatio || 1, 1);
  4510. }
  4511. /**
  4512. * config默认配置项
  4513. * @exports zrender/config
  4514. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  4515. */
  4516. /**
  4517. * Debug log mode:
  4518. * 0: Do nothing, for release.
  4519. * 1: console.error, for debug.
  4520. */
  4521. var debugMode = 0;
  4522. // retina 屏幕优化
  4523. var devicePixelRatio = dpr;
  4524. var logError = function () {
  4525. };
  4526. if (debugMode === 1) {
  4527. logError = console.error;
  4528. }
  4529. var logError$1 = logError;
  4530. /**
  4531. * @alias module:zrender/mixin/Animatable
  4532. * @constructor
  4533. */
  4534. var Animatable = function () {
  4535. /**
  4536. * @type {Array.<module:zrender/animation/Animator>}
  4537. * @readOnly
  4538. */
  4539. this.animators = [];
  4540. };
  4541. Animatable.prototype = {
  4542. constructor: Animatable,
  4543. /**
  4544. * 动画
  4545. *
  4546. * @param {string} path The path to fetch value from object, like 'a.b.c'.
  4547. * @param {boolean} [loop] Whether to loop animation.
  4548. * @return {module:zrender/animation/Animator}
  4549. * @example:
  4550. * el.animate('style', false)
  4551. * .when(1000, {x: 10} )
  4552. * .done(function(){ // Animation done })
  4553. * .start()
  4554. */
  4555. animate: function (path, loop) {
  4556. var target;
  4557. var animatingShape = false;
  4558. var el = this;
  4559. var zr = this.__zr;
  4560. if (path) {
  4561. var pathSplitted = path.split('.');
  4562. var prop = el;
  4563. // If animating shape
  4564. animatingShape = pathSplitted[0] === 'shape';
  4565. for (var i = 0, l = pathSplitted.length; i < l; i++) {
  4566. if (!prop) {
  4567. continue;
  4568. }
  4569. prop = prop[pathSplitted[i]];
  4570. }
  4571. if (prop) {
  4572. target = prop;
  4573. }
  4574. }
  4575. else {
  4576. target = el;
  4577. }
  4578. if (!target) {
  4579. logError$1(
  4580. 'Property "'
  4581. + path
  4582. + '" is not existed in element '
  4583. + el.id
  4584. );
  4585. return;
  4586. }
  4587. var animators = el.animators;
  4588. var animator = new Animator(target, loop);
  4589. animator.during(function (target) {
  4590. el.dirty(animatingShape);
  4591. })
  4592. .done(function () {
  4593. // FIXME Animator will not be removed if use `Animator#stop` to stop animation
  4594. animators.splice(indexOf(animators, animator), 1);
  4595. });
  4596. animators.push(animator);
  4597. // If animate after added to the zrender
  4598. if (zr) {
  4599. zr.animation.addAnimator(animator);
  4600. }
  4601. return animator;
  4602. },
  4603. /**
  4604. * 停止动画
  4605. * @param {boolean} forwardToLast If move to last frame before stop
  4606. */
  4607. stopAnimation: function (forwardToLast) {
  4608. var animators = this.animators;
  4609. var len = animators.length;
  4610. for (var i = 0; i < len; i++) {
  4611. animators[i].stop(forwardToLast);
  4612. }
  4613. animators.length = 0;
  4614. return this;
  4615. },
  4616. /**
  4617. * Caution: this method will stop previous animation.
  4618. * So do not use this method to one element twice before
  4619. * animation starts, unless you know what you are doing.
  4620. * @param {Object} target
  4621. * @param {number} [time=500] Time in ms
  4622. * @param {string} [easing='linear']
  4623. * @param {number} [delay=0]
  4624. * @param {Function} [callback]
  4625. * @param {Function} [forceAnimate] Prevent stop animation and callback
  4626. * immediently when target values are the same as current values.
  4627. *
  4628. * @example
  4629. * // Animate position
  4630. * el.animateTo({
  4631. * position: [10, 10]
  4632. * }, function () { // done })
  4633. *
  4634. * // Animate shape, style and position in 100ms, delayed 100ms, with cubicOut easing
  4635. * el.animateTo({
  4636. * shape: {
  4637. * width: 500
  4638. * },
  4639. * style: {
  4640. * fill: 'red'
  4641. * }
  4642. * position: [10, 10]
  4643. * }, 100, 100, 'cubicOut', function () { // done })
  4644. */
  4645. // TODO Return animation key
  4646. animateTo: function (target, time, delay, easing, callback, forceAnimate) {
  4647. animateTo(this, target, time, delay, easing, callback, forceAnimate);
  4648. },
  4649. /**
  4650. * Animate from the target state to current state.
  4651. * The params and the return value are the same as `this.animateTo`.
  4652. */
  4653. animateFrom: function (target, time, delay, easing, callback, forceAnimate) {
  4654. animateTo(this, target, time, delay, easing, callback, forceAnimate, true);
  4655. }
  4656. };
  4657. function animateTo(animatable, target, time, delay, easing, callback, forceAnimate, reverse) {
  4658. // animateTo(target, time, easing, callback);
  4659. if (isString(delay)) {
  4660. callback = easing;
  4661. easing = delay;
  4662. delay = 0;
  4663. }
  4664. // animateTo(target, time, delay, callback);
  4665. else if (isFunction$1(easing)) {
  4666. callback = easing;
  4667. easing = 'linear';
  4668. delay = 0;
  4669. }
  4670. // animateTo(target, time, callback);
  4671. else if (isFunction$1(delay)) {
  4672. callback = delay;
  4673. delay = 0;
  4674. }
  4675. // animateTo(target, callback)
  4676. else if (isFunction$1(time)) {
  4677. callback = time;
  4678. time = 500;
  4679. }
  4680. // animateTo(target)
  4681. else if (!time) {
  4682. time = 500;
  4683. }
  4684. // Stop all previous animations
  4685. animatable.stopAnimation();
  4686. animateToShallow(animatable, '', animatable, target, time, delay, reverse);
  4687. // Animators may be removed immediately after start
  4688. // if there is nothing to animate
  4689. var animators = animatable.animators.slice();
  4690. var count = animators.length;
  4691. function done() {
  4692. count--;
  4693. if (!count) {
  4694. callback && callback();
  4695. }
  4696. }
  4697. // No animators. This should be checked before animators[i].start(),
  4698. // because 'done' may be executed immediately if no need to animate.
  4699. if (!count) {
  4700. callback && callback();
  4701. }
  4702. // Start after all animators created
  4703. // Incase any animator is done immediately when all animation properties are not changed
  4704. for (var i = 0; i < animators.length; i++) {
  4705. animators[i]
  4706. .done(done)
  4707. .start(easing, forceAnimate);
  4708. }
  4709. }
  4710. /**
  4711. * @param {string} path=''
  4712. * @param {Object} source=animatable
  4713. * @param {Object} target
  4714. * @param {number} [time=500]
  4715. * @param {number} [delay=0]
  4716. * @param {boolean} [reverse] If `true`, animate
  4717. * from the `target` to current state.
  4718. *
  4719. * @example
  4720. * // Animate position
  4721. * el._animateToShallow({
  4722. * position: [10, 10]
  4723. * })
  4724. *
  4725. * // Animate shape, style and position in 100ms, delayed 100ms
  4726. * el._animateToShallow({
  4727. * shape: {
  4728. * width: 500
  4729. * },
  4730. * style: {
  4731. * fill: 'red'
  4732. * }
  4733. * position: [10, 10]
  4734. * }, 100, 100)
  4735. */
  4736. function animateToShallow(animatable, path, source, target, time, delay, reverse) {
  4737. var objShallow = {};
  4738. var propertyCount = 0;
  4739. for (var name in target) {
  4740. if (!target.hasOwnProperty(name)) {
  4741. continue;
  4742. }
  4743. if (source[name] != null) {
  4744. if (isObject$1(target[name]) && !isArrayLike(target[name])) {
  4745. animateToShallow(
  4746. animatable,
  4747. path ? path + '.' + name : name,
  4748. source[name],
  4749. target[name],
  4750. time,
  4751. delay,
  4752. reverse
  4753. );
  4754. }
  4755. else {
  4756. if (reverse) {
  4757. objShallow[name] = source[name];
  4758. setAttrByPath(animatable, path, name, target[name]);
  4759. }
  4760. else {
  4761. objShallow[name] = target[name];
  4762. }
  4763. propertyCount++;
  4764. }
  4765. }
  4766. else if (target[name] != null && !reverse) {
  4767. setAttrByPath(animatable, path, name, target[name]);
  4768. }
  4769. }
  4770. if (propertyCount > 0) {
  4771. animatable.animate(path, false)
  4772. .when(time == null ? 500 : time, objShallow)
  4773. .delay(delay || 0);
  4774. }
  4775. }
  4776. function setAttrByPath(el, path, name, value) {
  4777. // Attr directly if not has property
  4778. // FIXME, if some property not needed for element ?
  4779. if (!path) {
  4780. el.attr(name, value);
  4781. }
  4782. else {
  4783. // Only support set shape or style
  4784. var props = {};
  4785. props[path] = {};
  4786. props[path][name] = value;
  4787. el.attr(props);
  4788. }
  4789. }
  4790. /**
  4791. * @alias module:zrender/Element
  4792. * @constructor
  4793. * @extends {module:zrender/mixin/Animatable}
  4794. * @extends {module:zrender/mixin/Transformable}
  4795. * @extends {module:zrender/mixin/Eventful}
  4796. */
  4797. var Element = function (opts) { // jshint ignore:line
  4798. Transformable.call(this, opts);
  4799. Eventful.call(this, opts);
  4800. Animatable.call(this, opts);
  4801. /**
  4802. * 画布元素ID
  4803. * @type {string}
  4804. */
  4805. this.id = opts.id || guid();
  4806. };
  4807. Element.prototype = {
  4808. /**
  4809. * 元素类型
  4810. * Element type
  4811. * @type {string}
  4812. */
  4813. type: 'element',
  4814. /**
  4815. * 元素名字
  4816. * Element name
  4817. * @type {string}
  4818. */
  4819. name: '',
  4820. /**
  4821. * ZRender 实例对象,会在 element 添加到 zrender 实例中后自动赋值
  4822. * ZRender instance will be assigned when element is associated with zrender
  4823. * @name module:/zrender/Element#__zr
  4824. * @type {module:zrender/ZRender}
  4825. */
  4826. __zr: null,
  4827. /**
  4828. * 图形是否忽略,为true时忽略图形的绘制以及事件触发
  4829. * If ignore drawing and events of the element object
  4830. * @name module:/zrender/Element#ignore
  4831. * @type {boolean}
  4832. * @default false
  4833. */
  4834. ignore: false,
  4835. /**
  4836. * 用于裁剪的路径(shape),所有 Group 内的路径在绘制时都会被这个路径裁剪
  4837. * 该路径会继承被裁减对象的变换
  4838. * @type {module:zrender/graphic/Path}
  4839. * @see http://www.w3.org/TR/2dcontext/#clipping-region
  4840. * @readOnly
  4841. */
  4842. clipPath: null,
  4843. /**
  4844. * 是否是 Group
  4845. * @type {boolean}
  4846. */
  4847. isGroup: false,
  4848. /**
  4849. * Drift element
  4850. * @param {number} dx dx on the global space
  4851. * @param {number} dy dy on the global space
  4852. */
  4853. drift: function (dx, dy) {
  4854. switch (this.draggable) {
  4855. case 'horizontal':
  4856. dy = 0;
  4857. break;
  4858. case 'vertical':
  4859. dx = 0;
  4860. break;
  4861. }
  4862. var m = this.transform;
  4863. if (!m) {
  4864. m = this.transform = [1, 0, 0, 1, 0, 0];
  4865. }
  4866. m[4] += dx;
  4867. m[5] += dy;
  4868. this.decomposeTransform();
  4869. this.dirty(false);
  4870. },
  4871. /**
  4872. * Hook before update
  4873. */
  4874. beforeUpdate: function () {},
  4875. /**
  4876. * Hook after update
  4877. */
  4878. afterUpdate: function () {},
  4879. /**
  4880. * Update each frame
  4881. */
  4882. update: function () {
  4883. this.updateTransform();
  4884. },
  4885. /**
  4886. * @param {Function} cb
  4887. * @param {} context
  4888. */
  4889. traverse: function (cb, context) {},
  4890. /**
  4891. * @protected
  4892. */
  4893. attrKV: function (key, value) {
  4894. if (key === 'position' || key === 'scale' || key === 'origin') {
  4895. // Copy the array
  4896. if (value) {
  4897. var target = this[key];
  4898. if (!target) {
  4899. target = this[key] = [];
  4900. }
  4901. target[0] = value[0];
  4902. target[1] = value[1];
  4903. }
  4904. }
  4905. else {
  4906. this[key] = value;
  4907. }
  4908. },
  4909. /**
  4910. * Hide the element
  4911. */
  4912. hide: function () {
  4913. this.ignore = true;
  4914. this.__zr && this.__zr.refresh();
  4915. },
  4916. /**
  4917. * Show the element
  4918. */
  4919. show: function () {
  4920. this.ignore = false;
  4921. this.__zr && this.__zr.refresh();
  4922. },
  4923. /**
  4924. * @param {string|Object} key
  4925. * @param {*} value
  4926. */
  4927. attr: function (key, value) {
  4928. if (typeof key === 'string') {
  4929. this.attrKV(key, value);
  4930. }
  4931. else if (isObject$1(key)) {
  4932. for (var name in key) {
  4933. if (key.hasOwnProperty(name)) {
  4934. this.attrKV(name, key[name]);
  4935. }
  4936. }
  4937. }
  4938. this.dirty(false);
  4939. return this;
  4940. },
  4941. /**
  4942. * @param {module:zrender/graphic/Path} clipPath
  4943. */
  4944. setClipPath: function (clipPath) {
  4945. var zr = this.__zr;
  4946. if (zr) {
  4947. clipPath.addSelfToZr(zr);
  4948. }
  4949. // Remove previous clip path
  4950. if (this.clipPath && this.clipPath !== clipPath) {
  4951. this.removeClipPath();
  4952. }
  4953. this.clipPath = clipPath;
  4954. clipPath.__zr = zr;
  4955. clipPath.__clipTarget = this;
  4956. this.dirty(false);
  4957. },
  4958. /**
  4959. */
  4960. removeClipPath: function () {
  4961. var clipPath = this.clipPath;
  4962. if (clipPath) {
  4963. if (clipPath.__zr) {
  4964. clipPath.removeSelfFromZr(clipPath.__zr);
  4965. }
  4966. clipPath.__zr = null;
  4967. clipPath.__clipTarget = null;
  4968. this.clipPath = null;
  4969. this.dirty(false);
  4970. }
  4971. },
  4972. /**
  4973. * Add self from zrender instance.
  4974. * Not recursively because it will be invoked when element added to storage.
  4975. * @param {module:zrender/ZRender} zr
  4976. */
  4977. addSelfToZr: function (zr) {
  4978. this.__zr = zr;
  4979. // 添加动画
  4980. var animators = this.animators;
  4981. if (animators) {
  4982. for (var i = 0; i < animators.length; i++) {
  4983. zr.animation.addAnimator(animators[i]);
  4984. }
  4985. }
  4986. if (this.clipPath) {
  4987. this.clipPath.addSelfToZr(zr);
  4988. }
  4989. },
  4990. /**
  4991. * Remove self from zrender instance.
  4992. * Not recursively because it will be invoked when element added to storage.
  4993. * @param {module:zrender/ZRender} zr
  4994. */
  4995. removeSelfFromZr: function (zr) {
  4996. this.__zr = null;
  4997. // 移除动画
  4998. var animators = this.animators;
  4999. if (animators) {
  5000. for (var i = 0; i < animators.length; i++) {
  5001. zr.animation.removeAnimator(animators[i]);
  5002. }
  5003. }
  5004. if (this.clipPath) {
  5005. this.clipPath.removeSelfFromZr(zr);
  5006. }
  5007. }
  5008. };
  5009. mixin(Element, Animatable);
  5010. mixin(Element, Transformable);
  5011. mixin(Element, Eventful);
  5012. /**
  5013. * @module echarts/core/BoundingRect
  5014. */
  5015. var v2ApplyTransform = applyTransform;
  5016. var mathMin = Math.min;
  5017. var mathMax = Math.max;
  5018. /**
  5019. * @alias module:echarts/core/BoundingRect
  5020. */
  5021. function BoundingRect(x, y, width, height) {
  5022. if (width < 0) {
  5023. x = x + width;
  5024. width = -width;
  5025. }
  5026. if (height < 0) {
  5027. y = y + height;
  5028. height = -height;
  5029. }
  5030. /**
  5031. * @type {number}
  5032. */
  5033. this.x = x;
  5034. /**
  5035. * @type {number}
  5036. */
  5037. this.y = y;
  5038. /**
  5039. * @type {number}
  5040. */
  5041. this.width = width;
  5042. /**
  5043. * @type {number}
  5044. */
  5045. this.height = height;
  5046. }
  5047. BoundingRect.prototype = {
  5048. constructor: BoundingRect,
  5049. /**
  5050. * @param {module:echarts/core/BoundingRect} other
  5051. */
  5052. union: function (other) {
  5053. var x = mathMin(other.x, this.x);
  5054. var y = mathMin(other.y, this.y);
  5055. this.width = mathMax(
  5056. other.x + other.width,
  5057. this.x + this.width
  5058. ) - x;
  5059. this.height = mathMax(
  5060. other.y + other.height,
  5061. this.y + this.height
  5062. ) - y;
  5063. this.x = x;
  5064. this.y = y;
  5065. },
  5066. /**
  5067. * @param {Array.<number>} m
  5068. * @methods
  5069. */
  5070. applyTransform: (function () {
  5071. var lt = [];
  5072. var rb = [];
  5073. var lb = [];
  5074. var rt = [];
  5075. return function (m) {
  5076. // In case usage like this
  5077. // el.getBoundingRect().applyTransform(el.transform)
  5078. // And element has no transform
  5079. if (!m) {
  5080. return;
  5081. }
  5082. lt[0] = lb[0] = this.x;
  5083. lt[1] = rt[1] = this.y;
  5084. rb[0] = rt[0] = this.x + this.width;
  5085. rb[1] = lb[1] = this.y + this.height;
  5086. v2ApplyTransform(lt, lt, m);
  5087. v2ApplyTransform(rb, rb, m);
  5088. v2ApplyTransform(lb, lb, m);
  5089. v2ApplyTransform(rt, rt, m);
  5090. this.x = mathMin(lt[0], rb[0], lb[0], rt[0]);
  5091. this.y = mathMin(lt[1], rb[1], lb[1], rt[1]);
  5092. var maxX = mathMax(lt[0], rb[0], lb[0], rt[0]);
  5093. var maxY = mathMax(lt[1], rb[1], lb[1], rt[1]);
  5094. this.width = maxX - this.x;
  5095. this.height = maxY - this.y;
  5096. };
  5097. })(),
  5098. /**
  5099. * Calculate matrix of transforming from self to target rect
  5100. * @param {module:zrender/core/BoundingRect} b
  5101. * @return {Array.<number>}
  5102. */
  5103. calculateTransform: function (b) {
  5104. var a = this;
  5105. var sx = b.width / a.width;
  5106. var sy = b.height / a.height;
  5107. var m = create$1();
  5108. // 矩阵右乘
  5109. translate(m, m, [-a.x, -a.y]);
  5110. scale$1(m, m, [sx, sy]);
  5111. translate(m, m, [b.x, b.y]);
  5112. return m;
  5113. },
  5114. /**
  5115. * @param {(module:echarts/core/BoundingRect|Object)} b
  5116. * @return {boolean}
  5117. */
  5118. intersect: function (b) {
  5119. if (!b) {
  5120. return false;
  5121. }
  5122. if (!(b instanceof BoundingRect)) {
  5123. // Normalize negative width/height.
  5124. b = BoundingRect.create(b);
  5125. }
  5126. var a = this;
  5127. var ax0 = a.x;
  5128. var ax1 = a.x + a.width;
  5129. var ay0 = a.y;
  5130. var ay1 = a.y + a.height;
  5131. var bx0 = b.x;
  5132. var bx1 = b.x + b.width;
  5133. var by0 = b.y;
  5134. var by1 = b.y + b.height;
  5135. return !(ax1 < bx0 || bx1 < ax0 || ay1 < by0 || by1 < ay0);
  5136. },
  5137. contain: function (x, y) {
  5138. var rect = this;
  5139. return x >= rect.x
  5140. && x <= (rect.x + rect.width)
  5141. && y >= rect.y
  5142. && y <= (rect.y + rect.height);
  5143. },
  5144. /**
  5145. * @return {module:echarts/core/BoundingRect}
  5146. */
  5147. clone: function () {
  5148. return new BoundingRect(this.x, this.y, this.width, this.height);
  5149. },
  5150. /**
  5151. * Copy from another rect
  5152. */
  5153. copy: function (other) {
  5154. this.x = other.x;
  5155. this.y = other.y;
  5156. this.width = other.width;
  5157. this.height = other.height;
  5158. },
  5159. plain: function () {
  5160. return {
  5161. x: this.x,
  5162. y: this.y,
  5163. width: this.width,
  5164. height: this.height
  5165. };
  5166. }
  5167. };
  5168. /**
  5169. * @param {Object|module:zrender/core/BoundingRect} rect
  5170. * @param {number} rect.x
  5171. * @param {number} rect.y
  5172. * @param {number} rect.width
  5173. * @param {number} rect.height
  5174. * @return {module:zrender/core/BoundingRect}
  5175. */
  5176. BoundingRect.create = function (rect) {
  5177. return new BoundingRect(rect.x, rect.y, rect.width, rect.height);
  5178. };
  5179. /**
  5180. * Group是一个容器,可以插入子节点,Group的变换也会被应用到子节点上
  5181. * @module zrender/graphic/Group
  5182. * @example
  5183. * var Group = require('zrender/container/Group');
  5184. * var Circle = require('zrender/graphic/shape/Circle');
  5185. * var g = new Group();
  5186. * g.position[0] = 100;
  5187. * g.position[1] = 100;
  5188. * g.add(new Circle({
  5189. * style: {
  5190. * x: 100,
  5191. * y: 100,
  5192. * r: 20,
  5193. * }
  5194. * }));
  5195. * zr.add(g);
  5196. */
  5197. /**
  5198. * @alias module:zrender/graphic/Group
  5199. * @constructor
  5200. * @extends module:zrender/mixin/Transformable
  5201. * @extends module:zrender/mixin/Eventful
  5202. */
  5203. var Group = function (opts) {
  5204. opts = opts || {};
  5205. Element.call(this, opts);
  5206. for (var key in opts) {
  5207. if (opts.hasOwnProperty(key)) {
  5208. this[key] = opts[key];
  5209. }
  5210. }
  5211. this._children = [];
  5212. this.__storage = null;
  5213. this.__dirty = true;
  5214. };
  5215. Group.prototype = {
  5216. constructor: Group,
  5217. isGroup: true,
  5218. /**
  5219. * @type {string}
  5220. */
  5221. type: 'group',
  5222. /**
  5223. * 所有子孙元素是否响应鼠标事件
  5224. * @name module:/zrender/container/Group#silent
  5225. * @type {boolean}
  5226. * @default false
  5227. */
  5228. silent: false,
  5229. /**
  5230. * @return {Array.<module:zrender/Element>}
  5231. */
  5232. children: function () {
  5233. return this._children.slice();
  5234. },
  5235. /**
  5236. * 获取指定 index 的儿子节点
  5237. * @param {number} idx
  5238. * @return {module:zrender/Element}
  5239. */
  5240. childAt: function (idx) {
  5241. return this._children[idx];
  5242. },
  5243. /**
  5244. * 获取指定名字的儿子节点
  5245. * @param {string} name
  5246. * @return {module:zrender/Element}
  5247. */
  5248. childOfName: function (name) {
  5249. var children = this._children;
  5250. for (var i = 0; i < children.length; i++) {
  5251. if (children[i].name === name) {
  5252. return children[i];
  5253. }
  5254. }
  5255. },
  5256. /**
  5257. * @return {number}
  5258. */
  5259. childCount: function () {
  5260. return this._children.length;
  5261. },
  5262. /**
  5263. * 添加子节点到最后
  5264. * @param {module:zrender/Element} child
  5265. */
  5266. add: function (child) {
  5267. if (child && child !== this && child.parent !== this) {
  5268. this._children.push(child);
  5269. this._doAdd(child);
  5270. }
  5271. return this;
  5272. },
  5273. /**
  5274. * 添加子节点在 nextSibling 之前
  5275. * @param {module:zrender/Element} child
  5276. * @param {module:zrender/Element} nextSibling
  5277. */
  5278. addBefore: function (child, nextSibling) {
  5279. if (child && child !== this && child.parent !== this
  5280. && nextSibling && nextSibling.parent === this) {
  5281. var children = this._children;
  5282. var idx = children.indexOf(nextSibling);
  5283. if (idx >= 0) {
  5284. children.splice(idx, 0, child);
  5285. this._doAdd(child);
  5286. }
  5287. }
  5288. return this;
  5289. },
  5290. _doAdd: function (child) {
  5291. if (child.parent) {
  5292. child.parent.remove(child);
  5293. }
  5294. child.parent = this;
  5295. var storage = this.__storage;
  5296. var zr = this.__zr;
  5297. if (storage && storage !== child.__storage) {
  5298. storage.addToStorage(child);
  5299. if (child instanceof Group) {
  5300. child.addChildrenToStorage(storage);
  5301. }
  5302. }
  5303. zr && zr.refresh();
  5304. },
  5305. /**
  5306. * 移除子节点
  5307. * @param {module:zrender/Element} child
  5308. */
  5309. remove: function (child) {
  5310. var zr = this.__zr;
  5311. var storage = this.__storage;
  5312. var children = this._children;
  5313. var idx = indexOf(children, child);
  5314. if (idx < 0) {
  5315. return this;
  5316. }
  5317. children.splice(idx, 1);
  5318. child.parent = null;
  5319. if (storage) {
  5320. storage.delFromStorage(child);
  5321. if (child instanceof Group) {
  5322. child.delChildrenFromStorage(storage);
  5323. }
  5324. }
  5325. zr && zr.refresh();
  5326. return this;
  5327. },
  5328. /**
  5329. * 移除所有子节点
  5330. */
  5331. removeAll: function () {
  5332. var children = this._children;
  5333. var storage = this.__storage;
  5334. var child;
  5335. var i;
  5336. for (i = 0; i < children.length; i++) {
  5337. child = children[i];
  5338. if (storage) {
  5339. storage.delFromStorage(child);
  5340. if (child instanceof Group) {
  5341. child.delChildrenFromStorage(storage);
  5342. }
  5343. }
  5344. child.parent = null;
  5345. }
  5346. children.length = 0;
  5347. return this;
  5348. },
  5349. /**
  5350. * 遍历所有子节点
  5351. * @param {Function} cb
  5352. * @param {} context
  5353. */
  5354. eachChild: function (cb, context) {
  5355. var children = this._children;
  5356. for (var i = 0; i < children.length; i++) {
  5357. var child = children[i];
  5358. cb.call(context, child, i);
  5359. }
  5360. return this;
  5361. },
  5362. /**
  5363. * 深度优先遍历所有子孙节点
  5364. * @param {Function} cb
  5365. * @param {} context
  5366. */
  5367. traverse: function (cb, context) {
  5368. for (var i = 0; i < this._children.length; i++) {
  5369. var child = this._children[i];
  5370. cb.call(context, child);
  5371. if (child.type === 'group') {
  5372. child.traverse(cb, context);
  5373. }
  5374. }
  5375. return this;
  5376. },
  5377. addChildrenToStorage: function (storage) {
  5378. for (var i = 0; i < this._children.length; i++) {
  5379. var child = this._children[i];
  5380. storage.addToStorage(child);
  5381. if (child instanceof Group) {
  5382. child.addChildrenToStorage(storage);
  5383. }
  5384. }
  5385. },
  5386. delChildrenFromStorage: function (storage) {
  5387. for (var i = 0; i < this._children.length; i++) {
  5388. var child = this._children[i];
  5389. storage.delFromStorage(child);
  5390. if (child instanceof Group) {
  5391. child.delChildrenFromStorage(storage);
  5392. }
  5393. }
  5394. },
  5395. dirty: function () {
  5396. this.__dirty = true;
  5397. this.__zr && this.__zr.refresh();
  5398. return this;
  5399. },
  5400. /**
  5401. * @return {module:zrender/core/BoundingRect}
  5402. */
  5403. getBoundingRect: function (includeChildren) {
  5404. // TODO Caching
  5405. var rect = null;
  5406. var tmpRect = new BoundingRect(0, 0, 0, 0);
  5407. var children = includeChildren || this._children;
  5408. var tmpMat = [];
  5409. for (var i = 0; i < children.length; i++) {
  5410. var child = children[i];
  5411. if (child.ignore || child.invisible) {
  5412. continue;
  5413. }
  5414. var childRect = child.getBoundingRect();
  5415. var transform = child.getLocalTransform(tmpMat);
  5416. // TODO
  5417. // The boundingRect cacluated by transforming original
  5418. // rect may be bigger than the actual bundingRect when rotation
  5419. // is used. (Consider a circle rotated aginst its center, where
  5420. // the actual boundingRect should be the same as that not be
  5421. // rotated.) But we can not find better approach to calculate
  5422. // actual boundingRect yet, considering performance.
  5423. if (transform) {
  5424. tmpRect.copy(childRect);
  5425. tmpRect.applyTransform(transform);
  5426. rect = rect || tmpRect.clone();
  5427. rect.union(tmpRect);
  5428. }
  5429. else {
  5430. rect = rect || childRect.clone();
  5431. rect.union(childRect);
  5432. }
  5433. }
  5434. return rect || tmpRect;
  5435. }
  5436. };
  5437. inherits(Group, Element);
  5438. // https://github.com/mziccard/node-timsort
  5439. var DEFAULT_MIN_MERGE = 32;
  5440. var DEFAULT_MIN_GALLOPING = 7;
  5441. function minRunLength(n) {
  5442. var r = 0;
  5443. while (n >= DEFAULT_MIN_MERGE) {
  5444. r |= n & 1;
  5445. n >>= 1;
  5446. }
  5447. return n + r;
  5448. }
  5449. function makeAscendingRun(array, lo, hi, compare) {
  5450. var runHi = lo + 1;
  5451. if (runHi === hi) {
  5452. return 1;
  5453. }
  5454. if (compare(array[runHi++], array[lo]) < 0) {
  5455. while (runHi < hi && compare(array[runHi], array[runHi - 1]) < 0) {
  5456. runHi++;
  5457. }
  5458. reverseRun(array, lo, runHi);
  5459. }
  5460. else {
  5461. while (runHi < hi && compare(array[runHi], array[runHi - 1]) >= 0) {
  5462. runHi++;
  5463. }
  5464. }
  5465. return runHi - lo;
  5466. }
  5467. function reverseRun(array, lo, hi) {
  5468. hi--;
  5469. while (lo < hi) {
  5470. var t = array[lo];
  5471. array[lo++] = array[hi];
  5472. array[hi--] = t;
  5473. }
  5474. }
  5475. function binaryInsertionSort(array, lo, hi, start, compare) {
  5476. if (start === lo) {
  5477. start++;
  5478. }
  5479. for (; start < hi; start++) {
  5480. var pivot = array[start];
  5481. var left = lo;
  5482. var right = start;
  5483. var mid;
  5484. while (left < right) {
  5485. mid = left + right >>> 1;
  5486. if (compare(pivot, array[mid]) < 0) {
  5487. right = mid;
  5488. }
  5489. else {
  5490. left = mid + 1;
  5491. }
  5492. }
  5493. var n = start - left;
  5494. switch (n) {
  5495. case 3:
  5496. array[left + 3] = array[left + 2];
  5497. case 2:
  5498. array[left + 2] = array[left + 1];
  5499. case 1:
  5500. array[left + 1] = array[left];
  5501. break;
  5502. default:
  5503. while (n > 0) {
  5504. array[left + n] = array[left + n - 1];
  5505. n--;
  5506. }
  5507. }
  5508. array[left] = pivot;
  5509. }
  5510. }
  5511. function gallopLeft(value, array, start, length, hint, compare) {
  5512. var lastOffset = 0;
  5513. var maxOffset = 0;
  5514. var offset = 1;
  5515. if (compare(value, array[start + hint]) > 0) {
  5516. maxOffset = length - hint;
  5517. while (offset < maxOffset && compare(value, array[start + hint + offset]) > 0) {
  5518. lastOffset = offset;
  5519. offset = (offset << 1) + 1;
  5520. if (offset <= 0) {
  5521. offset = maxOffset;
  5522. }
  5523. }
  5524. if (offset > maxOffset) {
  5525. offset = maxOffset;
  5526. }
  5527. lastOffset += hint;
  5528. offset += hint;
  5529. }
  5530. else {
  5531. maxOffset = hint + 1;
  5532. while (offset < maxOffset && compare(value, array[start + hint - offset]) <= 0) {
  5533. lastOffset = offset;
  5534. offset = (offset << 1) + 1;
  5535. if (offset <= 0) {
  5536. offset = maxOffset;
  5537. }
  5538. }
  5539. if (offset > maxOffset) {
  5540. offset = maxOffset;
  5541. }
  5542. var tmp = lastOffset;
  5543. lastOffset = hint - offset;
  5544. offset = hint - tmp;
  5545. }
  5546. lastOffset++;
  5547. while (lastOffset < offset) {
  5548. var m = lastOffset + (offset - lastOffset >>> 1);
  5549. if (compare(value, array[start + m]) > 0) {
  5550. lastOffset = m + 1;
  5551. }
  5552. else {
  5553. offset = m;
  5554. }
  5555. }
  5556. return offset;
  5557. }
  5558. function gallopRight(value, array, start, length, hint, compare) {
  5559. var lastOffset = 0;
  5560. var maxOffset = 0;
  5561. var offset = 1;
  5562. if (compare(value, array[start + hint]) < 0) {
  5563. maxOffset = hint + 1;
  5564. while (offset < maxOffset && compare(value, array[start + hint - offset]) < 0) {
  5565. lastOffset = offset;
  5566. offset = (offset << 1) + 1;
  5567. if (offset <= 0) {
  5568. offset = maxOffset;
  5569. }
  5570. }
  5571. if (offset > maxOffset) {
  5572. offset = maxOffset;
  5573. }
  5574. var tmp = lastOffset;
  5575. lastOffset = hint - offset;
  5576. offset = hint - tmp;
  5577. }
  5578. else {
  5579. maxOffset = length - hint;
  5580. while (offset < maxOffset && compare(value, array[start + hint + offset]) >= 0) {
  5581. lastOffset = offset;
  5582. offset = (offset << 1) + 1;
  5583. if (offset <= 0) {
  5584. offset = maxOffset;
  5585. }
  5586. }
  5587. if (offset > maxOffset) {
  5588. offset = maxOffset;
  5589. }
  5590. lastOffset += hint;
  5591. offset += hint;
  5592. }
  5593. lastOffset++;
  5594. while (lastOffset < offset) {
  5595. var m = lastOffset + (offset - lastOffset >>> 1);
  5596. if (compare(value, array[start + m]) < 0) {
  5597. offset = m;
  5598. }
  5599. else {
  5600. lastOffset = m + 1;
  5601. }
  5602. }
  5603. return offset;
  5604. }
  5605. function TimSort(array, compare) {
  5606. var minGallop = DEFAULT_MIN_GALLOPING;
  5607. var runStart;
  5608. var runLength;
  5609. var stackSize = 0;
  5610. var tmp = [];
  5611. runStart = [];
  5612. runLength = [];
  5613. function pushRun(_runStart, _runLength) {
  5614. runStart[stackSize] = _runStart;
  5615. runLength[stackSize] = _runLength;
  5616. stackSize += 1;
  5617. }
  5618. function mergeRuns() {
  5619. while (stackSize > 1) {
  5620. var n = stackSize - 2;
  5621. if (
  5622. (n >= 1 && runLength[n - 1] <= runLength[n] + runLength[n + 1])
  5623. || (n >= 2 && runLength[n - 2] <= runLength[n] + runLength[n - 1])
  5624. ) {
  5625. if (runLength[n - 1] < runLength[n + 1]) {
  5626. n--;
  5627. }
  5628. }
  5629. else if (runLength[n] > runLength[n + 1]) {
  5630. break;
  5631. }
  5632. mergeAt(n);
  5633. }
  5634. }
  5635. function forceMergeRuns() {
  5636. while (stackSize > 1) {
  5637. var n = stackSize - 2;
  5638. if (n > 0 && runLength[n - 1] < runLength[n + 1]) {
  5639. n--;
  5640. }
  5641. mergeAt(n);
  5642. }
  5643. }
  5644. function mergeAt(i) {
  5645. var start1 = runStart[i];
  5646. var length1 = runLength[i];
  5647. var start2 = runStart[i + 1];
  5648. var length2 = runLength[i + 1];
  5649. runLength[i] = length1 + length2;
  5650. if (i === stackSize - 3) {
  5651. runStart[i + 1] = runStart[i + 2];
  5652. runLength[i + 1] = runLength[i + 2];
  5653. }
  5654. stackSize--;
  5655. var k = gallopRight(array[start2], array, start1, length1, 0, compare);
  5656. start1 += k;
  5657. length1 -= k;
  5658. if (length1 === 0) {
  5659. return;
  5660. }
  5661. length2 = gallopLeft(array[start1 + length1 - 1], array, start2, length2, length2 - 1, compare);
  5662. if (length2 === 0) {
  5663. return;
  5664. }
  5665. if (length1 <= length2) {
  5666. mergeLow(start1, length1, start2, length2);
  5667. }
  5668. else {
  5669. mergeHigh(start1, length1, start2, length2);
  5670. }
  5671. }
  5672. function mergeLow(start1, length1, start2, length2) {
  5673. var i = 0;
  5674. for (i = 0; i < length1; i++) {
  5675. tmp[i] = array[start1 + i];
  5676. }
  5677. var cursor1 = 0;
  5678. var cursor2 = start2;
  5679. var dest = start1;
  5680. array[dest++] = array[cursor2++];
  5681. if (--length2 === 0) {
  5682. for (i = 0; i < length1; i++) {
  5683. array[dest + i] = tmp[cursor1 + i];
  5684. }
  5685. return;
  5686. }
  5687. if (length1 === 1) {
  5688. for (i = 0; i < length2; i++) {
  5689. array[dest + i] = array[cursor2 + i];
  5690. }
  5691. array[dest + length2] = tmp[cursor1];
  5692. return;
  5693. }
  5694. var _minGallop = minGallop;
  5695. var count1;
  5696. var count2;
  5697. var exit;
  5698. while (1) {
  5699. count1 = 0;
  5700. count2 = 0;
  5701. exit = false;
  5702. do {
  5703. if (compare(array[cursor2], tmp[cursor1]) < 0) {
  5704. array[dest++] = array[cursor2++];
  5705. count2++;
  5706. count1 = 0;
  5707. if (--length2 === 0) {
  5708. exit = true;
  5709. break;
  5710. }
  5711. }
  5712. else {
  5713. array[dest++] = tmp[cursor1++];
  5714. count1++;
  5715. count2 = 0;
  5716. if (--length1 === 1) {
  5717. exit = true;
  5718. break;
  5719. }
  5720. }
  5721. } while ((count1 | count2) < _minGallop);
  5722. if (exit) {
  5723. break;
  5724. }
  5725. do {
  5726. count1 = gallopRight(array[cursor2], tmp, cursor1, length1, 0, compare);
  5727. if (count1 !== 0) {
  5728. for (i = 0; i < count1; i++) {
  5729. array[dest + i] = tmp[cursor1 + i];
  5730. }
  5731. dest += count1;
  5732. cursor1 += count1;
  5733. length1 -= count1;
  5734. if (length1 <= 1) {
  5735. exit = true;
  5736. break;
  5737. }
  5738. }
  5739. array[dest++] = array[cursor2++];
  5740. if (--length2 === 0) {
  5741. exit = true;
  5742. break;
  5743. }
  5744. count2 = gallopLeft(tmp[cursor1], array, cursor2, length2, 0, compare);
  5745. if (count2 !== 0) {
  5746. for (i = 0; i < count2; i++) {
  5747. array[dest + i] = array[cursor2 + i];
  5748. }
  5749. dest += count2;
  5750. cursor2 += count2;
  5751. length2 -= count2;
  5752. if (length2 === 0) {
  5753. exit = true;
  5754. break;
  5755. }
  5756. }
  5757. array[dest++] = tmp[cursor1++];
  5758. if (--length1 === 1) {
  5759. exit = true;
  5760. break;
  5761. }
  5762. _minGallop--;
  5763. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  5764. if (exit) {
  5765. break;
  5766. }
  5767. if (_minGallop < 0) {
  5768. _minGallop = 0;
  5769. }
  5770. _minGallop += 2;
  5771. }
  5772. minGallop = _minGallop;
  5773. minGallop < 1 && (minGallop = 1);
  5774. if (length1 === 1) {
  5775. for (i = 0; i < length2; i++) {
  5776. array[dest + i] = array[cursor2 + i];
  5777. }
  5778. array[dest + length2] = tmp[cursor1];
  5779. }
  5780. else if (length1 === 0) {
  5781. throw new Error();
  5782. // throw new Error('mergeLow preconditions were not respected');
  5783. }
  5784. else {
  5785. for (i = 0; i < length1; i++) {
  5786. array[dest + i] = tmp[cursor1 + i];
  5787. }
  5788. }
  5789. }
  5790. function mergeHigh(start1, length1, start2, length2) {
  5791. var i = 0;
  5792. for (i = 0; i < length2; i++) {
  5793. tmp[i] = array[start2 + i];
  5794. }
  5795. var cursor1 = start1 + length1 - 1;
  5796. var cursor2 = length2 - 1;
  5797. var dest = start2 + length2 - 1;
  5798. var customCursor = 0;
  5799. var customDest = 0;
  5800. array[dest--] = array[cursor1--];
  5801. if (--length1 === 0) {
  5802. customCursor = dest - (length2 - 1);
  5803. for (i = 0; i < length2; i++) {
  5804. array[customCursor + i] = tmp[i];
  5805. }
  5806. return;
  5807. }
  5808. if (length2 === 1) {
  5809. dest -= length1;
  5810. cursor1 -= length1;
  5811. customDest = dest + 1;
  5812. customCursor = cursor1 + 1;
  5813. for (i = length1 - 1; i >= 0; i--) {
  5814. array[customDest + i] = array[customCursor + i];
  5815. }
  5816. array[dest] = tmp[cursor2];
  5817. return;
  5818. }
  5819. var _minGallop = minGallop;
  5820. while (true) {
  5821. var count1 = 0;
  5822. var count2 = 0;
  5823. var exit = false;
  5824. do {
  5825. if (compare(tmp[cursor2], array[cursor1]) < 0) {
  5826. array[dest--] = array[cursor1--];
  5827. count1++;
  5828. count2 = 0;
  5829. if (--length1 === 0) {
  5830. exit = true;
  5831. break;
  5832. }
  5833. }
  5834. else {
  5835. array[dest--] = tmp[cursor2--];
  5836. count2++;
  5837. count1 = 0;
  5838. if (--length2 === 1) {
  5839. exit = true;
  5840. break;
  5841. }
  5842. }
  5843. } while ((count1 | count2) < _minGallop);
  5844. if (exit) {
  5845. break;
  5846. }
  5847. do {
  5848. count1 = length1 - gallopRight(tmp[cursor2], array, start1, length1, length1 - 1, compare);
  5849. if (count1 !== 0) {
  5850. dest -= count1;
  5851. cursor1 -= count1;
  5852. length1 -= count1;
  5853. customDest = dest + 1;
  5854. customCursor = cursor1 + 1;
  5855. for (i = count1 - 1; i >= 0; i--) {
  5856. array[customDest + i] = array[customCursor + i];
  5857. }
  5858. if (length1 === 0) {
  5859. exit = true;
  5860. break;
  5861. }
  5862. }
  5863. array[dest--] = tmp[cursor2--];
  5864. if (--length2 === 1) {
  5865. exit = true;
  5866. break;
  5867. }
  5868. count2 = length2 - gallopLeft(array[cursor1], tmp, 0, length2, length2 - 1, compare);
  5869. if (count2 !== 0) {
  5870. dest -= count2;
  5871. cursor2 -= count2;
  5872. length2 -= count2;
  5873. customDest = dest + 1;
  5874. customCursor = cursor2 + 1;
  5875. for (i = 0; i < count2; i++) {
  5876. array[customDest + i] = tmp[customCursor + i];
  5877. }
  5878. if (length2 <= 1) {
  5879. exit = true;
  5880. break;
  5881. }
  5882. }
  5883. array[dest--] = array[cursor1--];
  5884. if (--length1 === 0) {
  5885. exit = true;
  5886. break;
  5887. }
  5888. _minGallop--;
  5889. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  5890. if (exit) {
  5891. break;
  5892. }
  5893. if (_minGallop < 0) {
  5894. _minGallop = 0;
  5895. }
  5896. _minGallop += 2;
  5897. }
  5898. minGallop = _minGallop;
  5899. if (minGallop < 1) {
  5900. minGallop = 1;
  5901. }
  5902. if (length2 === 1) {
  5903. dest -= length1;
  5904. cursor1 -= length1;
  5905. customDest = dest + 1;
  5906. customCursor = cursor1 + 1;
  5907. for (i = length1 - 1; i >= 0; i--) {
  5908. array[customDest + i] = array[customCursor + i];
  5909. }
  5910. array[dest] = tmp[cursor2];
  5911. }
  5912. else if (length2 === 0) {
  5913. throw new Error();
  5914. // throw new Error('mergeHigh preconditions were not respected');
  5915. }
  5916. else {
  5917. customCursor = dest - (length2 - 1);
  5918. for (i = 0; i < length2; i++) {
  5919. array[customCursor + i] = tmp[i];
  5920. }
  5921. }
  5922. }
  5923. this.mergeRuns = mergeRuns;
  5924. this.forceMergeRuns = forceMergeRuns;
  5925. this.pushRun = pushRun;
  5926. }
  5927. function sort(array, compare, lo, hi) {
  5928. if (!lo) {
  5929. lo = 0;
  5930. }
  5931. if (!hi) {
  5932. hi = array.length;
  5933. }
  5934. var remaining = hi - lo;
  5935. if (remaining < 2) {
  5936. return;
  5937. }
  5938. var runLength = 0;
  5939. if (remaining < DEFAULT_MIN_MERGE) {
  5940. runLength = makeAscendingRun(array, lo, hi, compare);
  5941. binaryInsertionSort(array, lo, hi, lo + runLength, compare);
  5942. return;
  5943. }
  5944. var ts = new TimSort(array, compare);
  5945. var minRun = minRunLength(remaining);
  5946. do {
  5947. runLength = makeAscendingRun(array, lo, hi, compare);
  5948. if (runLength < minRun) {
  5949. var force = remaining;
  5950. if (force > minRun) {
  5951. force = minRun;
  5952. }
  5953. binaryInsertionSort(array, lo, lo + force, lo + runLength, compare);
  5954. runLength = force;
  5955. }
  5956. ts.pushRun(lo, runLength);
  5957. ts.mergeRuns();
  5958. remaining -= runLength;
  5959. lo += runLength;
  5960. } while (remaining !== 0);
  5961. ts.forceMergeRuns();
  5962. }
  5963. // Use timsort because in most case elements are partially sorted
  5964. // https://jsfiddle.net/pissang/jr4x7mdm/8/
  5965. function shapeCompareFunc(a, b) {
  5966. if (a.zlevel === b.zlevel) {
  5967. if (a.z === b.z) {
  5968. // if (a.z2 === b.z2) {
  5969. // // FIXME Slow has renderidx compare
  5970. // // http://stackoverflow.com/questions/20883421/sorting-in-javascript-should-every-compare-function-have-a-return-0-statement
  5971. // // https://github.com/v8/v8/blob/47cce544a31ed5577ffe2963f67acb4144ee0232/src/js/array.js#L1012
  5972. // return a.__renderidx - b.__renderidx;
  5973. // }
  5974. return a.z2 - b.z2;
  5975. }
  5976. return a.z - b.z;
  5977. }
  5978. return a.zlevel - b.zlevel;
  5979. }
  5980. /**
  5981. * 内容仓库 (M)
  5982. * @alias module:zrender/Storage
  5983. * @constructor
  5984. */
  5985. var Storage = function () { // jshint ignore:line
  5986. this._roots = [];
  5987. this._displayList = [];
  5988. this._displayListLen = 0;
  5989. };
  5990. Storage.prototype = {
  5991. constructor: Storage,
  5992. /**
  5993. * @param {Function} cb
  5994. *
  5995. */
  5996. traverse: function (cb, context) {
  5997. for (var i = 0; i < this._roots.length; i++) {
  5998. this._roots[i].traverse(cb, context);
  5999. }
  6000. },
  6001. /**
  6002. * 返回所有图形的绘制队列
  6003. * @param {boolean} [update=false] 是否在返回前更新该数组
  6004. * @param {boolean} [includeIgnore=false] 是否包含 ignore 的数组, 在 update 为 true 的时候有效
  6005. *
  6006. * 详见{@link module:zrender/graphic/Displayable.prototype.updateDisplayList}
  6007. * @return {Array.<module:zrender/graphic/Displayable>}
  6008. */
  6009. getDisplayList: function (update, includeIgnore) {
  6010. includeIgnore = includeIgnore || false;
  6011. if (update) {
  6012. this.updateDisplayList(includeIgnore);
  6013. }
  6014. return this._displayList;
  6015. },
  6016. /**
  6017. * 更新图形的绘制队列。
  6018. * 每次绘制前都会调用,该方法会先深度优先遍历整个树,更新所有Group和Shape的变换并且把所有可见的Shape保存到数组中,
  6019. * 最后根据绘制的优先级(zlevel > z > 插入顺序)排序得到绘制队列
  6020. * @param {boolean} [includeIgnore=false] 是否包含 ignore 的数组
  6021. */
  6022. updateDisplayList: function (includeIgnore) {
  6023. this._displayListLen = 0;
  6024. var roots = this._roots;
  6025. var displayList = this._displayList;
  6026. for (var i = 0, len = roots.length; i < len; i++) {
  6027. this._updateAndAddDisplayable(roots[i], null, includeIgnore);
  6028. }
  6029. displayList.length = this._displayListLen;
  6030. env$1.canvasSupported && sort(displayList, shapeCompareFunc);
  6031. },
  6032. _updateAndAddDisplayable: function (el, clipPaths, includeIgnore) {
  6033. if (el.ignore && !includeIgnore) {
  6034. return;
  6035. }
  6036. el.beforeUpdate();
  6037. if (el.__dirty) {
  6038. el.update();
  6039. }
  6040. el.afterUpdate();
  6041. var userSetClipPath = el.clipPath;
  6042. if (userSetClipPath) {
  6043. // FIXME 效率影响
  6044. if (clipPaths) {
  6045. clipPaths = clipPaths.slice();
  6046. }
  6047. else {
  6048. clipPaths = [];
  6049. }
  6050. var currentClipPath = userSetClipPath;
  6051. var parentClipPath = el;
  6052. // Recursively add clip path
  6053. while (currentClipPath) {
  6054. // clipPath 的变换是基于使用这个 clipPath 的元素
  6055. currentClipPath.parent = parentClipPath;
  6056. currentClipPath.updateTransform();
  6057. clipPaths.push(currentClipPath);
  6058. parentClipPath = currentClipPath;
  6059. currentClipPath = currentClipPath.clipPath;
  6060. }
  6061. }
  6062. if (el.isGroup) {
  6063. var children = el._children;
  6064. for (var i = 0; i < children.length; i++) {
  6065. var child = children[i];
  6066. // Force to mark as dirty if group is dirty
  6067. // FIXME __dirtyPath ?
  6068. if (el.__dirty) {
  6069. child.__dirty = true;
  6070. }
  6071. this._updateAndAddDisplayable(child, clipPaths, includeIgnore);
  6072. }
  6073. // Mark group clean here
  6074. el.__dirty = false;
  6075. }
  6076. else {
  6077. el.__clipPaths = clipPaths;
  6078. this._displayList[this._displayListLen++] = el;
  6079. }
  6080. },
  6081. /**
  6082. * 添加图形(Shape)或者组(Group)到根节点
  6083. * @param {module:zrender/Element} el
  6084. */
  6085. addRoot: function (el) {
  6086. if (el.__storage === this) {
  6087. return;
  6088. }
  6089. if (el instanceof Group) {
  6090. el.addChildrenToStorage(this);
  6091. }
  6092. this.addToStorage(el);
  6093. this._roots.push(el);
  6094. },
  6095. /**
  6096. * 删除指定的图形(Shape)或者组(Group)
  6097. * @param {string|Array.<string>} [el] 如果为空清空整个Storage
  6098. */
  6099. delRoot: function (el) {
  6100. if (el == null) {
  6101. // 不指定el清空
  6102. for (var i = 0; i < this._roots.length; i++) {
  6103. var root = this._roots[i];
  6104. if (root instanceof Group) {
  6105. root.delChildrenFromStorage(this);
  6106. }
  6107. }
  6108. this._roots = [];
  6109. this._displayList = [];
  6110. this._displayListLen = 0;
  6111. return;
  6112. }
  6113. if (el instanceof Array) {
  6114. for (var i = 0, l = el.length; i < l; i++) {
  6115. this.delRoot(el[i]);
  6116. }
  6117. return;
  6118. }
  6119. var idx = indexOf(this._roots, el);
  6120. if (idx >= 0) {
  6121. this.delFromStorage(el);
  6122. this._roots.splice(idx, 1);
  6123. if (el instanceof Group) {
  6124. el.delChildrenFromStorage(this);
  6125. }
  6126. }
  6127. },
  6128. addToStorage: function (el) {
  6129. if (el) {
  6130. el.__storage = this;
  6131. el.dirty(false);
  6132. }
  6133. return this;
  6134. },
  6135. delFromStorage: function (el) {
  6136. if (el) {
  6137. el.__storage = null;
  6138. }
  6139. return this;
  6140. },
  6141. /**
  6142. * 清空并且释放Storage
  6143. */
  6144. dispose: function () {
  6145. this._renderList =
  6146. this._roots = null;
  6147. },
  6148. displayableSortFunc: shapeCompareFunc
  6149. };
  6150. var SHADOW_PROPS = {
  6151. 'shadowBlur': 1,
  6152. 'shadowOffsetX': 1,
  6153. 'shadowOffsetY': 1,
  6154. 'textShadowBlur': 1,
  6155. 'textShadowOffsetX': 1,
  6156. 'textShadowOffsetY': 1,
  6157. 'textBoxShadowBlur': 1,
  6158. 'textBoxShadowOffsetX': 1,
  6159. 'textBoxShadowOffsetY': 1
  6160. };
  6161. var fixShadow = function (ctx, propName, value) {
  6162. if (SHADOW_PROPS.hasOwnProperty(propName)) {
  6163. return value *= ctx.dpr;
  6164. }
  6165. return value;
  6166. };
  6167. var ContextCachedBy = {
  6168. NONE: 0,
  6169. STYLE_BIND: 1,
  6170. PLAIN_TEXT: 2
  6171. };
  6172. // Avoid confused with 0/false.
  6173. var WILL_BE_RESTORED = 9;
  6174. var STYLE_COMMON_PROPS = [
  6175. ['shadowBlur', 0], ['shadowOffsetX', 0], ['shadowOffsetY', 0], ['shadowColor', '#000'],
  6176. ['lineCap', 'butt'], ['lineJoin', 'miter'], ['miterLimit', 10]
  6177. ];
  6178. // var SHADOW_PROPS = STYLE_COMMON_PROPS.slice(0, 4);
  6179. // var LINE_PROPS = STYLE_COMMON_PROPS.slice(4);
  6180. var Style = function (opts) {
  6181. this.extendFrom(opts, false);
  6182. };
  6183. function createLinearGradient(ctx, obj, rect) {
  6184. var x = obj.x == null ? 0 : obj.x;
  6185. var x2 = obj.x2 == null ? 1 : obj.x2;
  6186. var y = obj.y == null ? 0 : obj.y;
  6187. var y2 = obj.y2 == null ? 0 : obj.y2;
  6188. if (!obj.global) {
  6189. x = x * rect.width + rect.x;
  6190. x2 = x2 * rect.width + rect.x;
  6191. y = y * rect.height + rect.y;
  6192. y2 = y2 * rect.height + rect.y;
  6193. }
  6194. // Fix NaN when rect is Infinity
  6195. x = isNaN(x) ? 0 : x;
  6196. x2 = isNaN(x2) ? 1 : x2;
  6197. y = isNaN(y) ? 0 : y;
  6198. y2 = isNaN(y2) ? 0 : y2;
  6199. var canvasGradient = ctx.createLinearGradient(x, y, x2, y2);
  6200. return canvasGradient;
  6201. }
  6202. function createRadialGradient(ctx, obj, rect) {
  6203. var width = rect.width;
  6204. var height = rect.height;
  6205. var min = Math.min(width, height);
  6206. var x = obj.x == null ? 0.5 : obj.x;
  6207. var y = obj.y == null ? 0.5 : obj.y;
  6208. var r = obj.r == null ? 0.5 : obj.r;
  6209. if (!obj.global) {
  6210. x = x * width + rect.x;
  6211. y = y * height + rect.y;
  6212. r = r * min;
  6213. }
  6214. var canvasGradient = ctx.createRadialGradient(x, y, 0, x, y, r);
  6215. return canvasGradient;
  6216. }
  6217. Style.prototype = {
  6218. constructor: Style,
  6219. /**
  6220. * @type {string}
  6221. */
  6222. fill: '#000',
  6223. /**
  6224. * @type {string}
  6225. */
  6226. stroke: null,
  6227. /**
  6228. * @type {number}
  6229. */
  6230. opacity: 1,
  6231. /**
  6232. * @type {number}
  6233. */
  6234. fillOpacity: null,
  6235. /**
  6236. * @type {number}
  6237. */
  6238. strokeOpacity: null,
  6239. /**
  6240. * `true` is not supported.
  6241. * `false`/`null`/`undefined` are the same.
  6242. * `false` is used to remove lineDash in some
  6243. * case that `null`/`undefined` can not be set.
  6244. * (e.g., emphasis.lineStyle in echarts)
  6245. * @type {Array.<number>|boolean}
  6246. */
  6247. lineDash: null,
  6248. /**
  6249. * @type {number}
  6250. */
  6251. lineDashOffset: 0,
  6252. /**
  6253. * @type {number}
  6254. */
  6255. shadowBlur: 0,
  6256. /**
  6257. * @type {number}
  6258. */
  6259. shadowOffsetX: 0,
  6260. /**
  6261. * @type {number}
  6262. */
  6263. shadowOffsetY: 0,
  6264. /**
  6265. * @type {number}
  6266. */
  6267. lineWidth: 1,
  6268. /**
  6269. * If stroke ignore scale
  6270. * @type {Boolean}
  6271. */
  6272. strokeNoScale: false,
  6273. // Bounding rect text configuration
  6274. // Not affected by element transform
  6275. /**
  6276. * @type {string}
  6277. */
  6278. text: null,
  6279. /**
  6280. * If `fontSize` or `fontFamily` exists, `font` will be reset by
  6281. * `fontSize`, `fontStyle`, `fontWeight`, `fontFamily`.
  6282. * So do not visit it directly in upper application (like echarts),
  6283. * but use `contain/text#makeFont` instead.
  6284. * @type {string}
  6285. */
  6286. font: null,
  6287. /**
  6288. * The same as font. Use font please.
  6289. * @deprecated
  6290. * @type {string}
  6291. */
  6292. textFont: null,
  6293. /**
  6294. * It helps merging respectively, rather than parsing an entire font string.
  6295. * @type {string}
  6296. */
  6297. fontStyle: null,
  6298. /**
  6299. * It helps merging respectively, rather than parsing an entire font string.
  6300. * @type {string}
  6301. */
  6302. fontWeight: null,
  6303. /**
  6304. * It helps merging respectively, rather than parsing an entire font string.
  6305. * Should be 12 but not '12px'.
  6306. * @type {number}
  6307. */
  6308. fontSize: null,
  6309. /**
  6310. * It helps merging respectively, rather than parsing an entire font string.
  6311. * @type {string}
  6312. */
  6313. fontFamily: null,
  6314. /**
  6315. * Reserved for special functinality, like 'hr'.
  6316. * @type {string}
  6317. */
  6318. textTag: null,
  6319. /**
  6320. * @type {string}
  6321. */
  6322. textFill: '#000',
  6323. /**
  6324. * @type {string}
  6325. */
  6326. textStroke: null,
  6327. /**
  6328. * @type {number}
  6329. */
  6330. textWidth: null,
  6331. /**
  6332. * Only for textBackground.
  6333. * @type {number}
  6334. */
  6335. textHeight: null,
  6336. /**
  6337. * textStroke may be set as some color as a default
  6338. * value in upper applicaion, where the default value
  6339. * of textStrokeWidth should be 0 to make sure that
  6340. * user can choose to do not use text stroke.
  6341. * @type {number}
  6342. */
  6343. textStrokeWidth: 0,
  6344. /**
  6345. * @type {number}
  6346. */
  6347. textLineHeight: null,
  6348. /**
  6349. * 'inside', 'left', 'right', 'top', 'bottom'
  6350. * [x, y]
  6351. * Based on x, y of rect.
  6352. * @type {string|Array.<number>}
  6353. * @default 'inside'
  6354. */
  6355. textPosition: 'inside',
  6356. /**
  6357. * If not specified, use the boundingRect of a `displayable`.
  6358. * @type {Object}
  6359. */
  6360. textRect: null,
  6361. /**
  6362. * [x, y]
  6363. * @type {Array.<number>}
  6364. */
  6365. textOffset: null,
  6366. /**
  6367. * @type {string}
  6368. */
  6369. textAlign: null,
  6370. /**
  6371. * @type {string}
  6372. */
  6373. textVerticalAlign: null,
  6374. /**
  6375. * @type {number}
  6376. */
  6377. textDistance: 5,
  6378. /**
  6379. * @type {string}
  6380. */
  6381. textShadowColor: 'transparent',
  6382. /**
  6383. * @type {number}
  6384. */
  6385. textShadowBlur: 0,
  6386. /**
  6387. * @type {number}
  6388. */
  6389. textShadowOffsetX: 0,
  6390. /**
  6391. * @type {number}
  6392. */
  6393. textShadowOffsetY: 0,
  6394. /**
  6395. * @type {string}
  6396. */
  6397. textBoxShadowColor: 'transparent',
  6398. /**
  6399. * @type {number}
  6400. */
  6401. textBoxShadowBlur: 0,
  6402. /**
  6403. * @type {number}
  6404. */
  6405. textBoxShadowOffsetX: 0,
  6406. /**
  6407. * @type {number}
  6408. */
  6409. textBoxShadowOffsetY: 0,
  6410. /**
  6411. * Whether transform text.
  6412. * Only available in Path and Image element,
  6413. * where the text is called as `RectText`.
  6414. * @type {boolean}
  6415. */
  6416. transformText: false,
  6417. /**
  6418. * Text rotate around position of Path or Image.
  6419. * The origin of the rotation can be specified by `textOrigin`.
  6420. * Only available in Path and Image element,
  6421. * where the text is called as `RectText`.
  6422. */
  6423. textRotation: 0,
  6424. /**
  6425. * Text origin of text rotation.
  6426. * Useful in the case like label rotation of circular symbol.
  6427. * Only available in Path and Image element, where the text is called
  6428. * as `RectText` and the element is called as "host element".
  6429. * The value can be:
  6430. * + If specified as a coordinate like `[10, 40]`, it is the `[x, y]`
  6431. * base on the left-top corner of the rect of its host element.
  6432. * + If specified as a string `center`, it is the center of the rect of
  6433. * its host element.
  6434. * + By default, this origin is the `textPosition`.
  6435. * @type {string|Array.<number>}
  6436. */
  6437. textOrigin: null,
  6438. /**
  6439. * @type {string}
  6440. */
  6441. textBackgroundColor: null,
  6442. /**
  6443. * @type {string}
  6444. */
  6445. textBorderColor: null,
  6446. /**
  6447. * @type {number}
  6448. */
  6449. textBorderWidth: 0,
  6450. /**
  6451. * @type {number}
  6452. */
  6453. textBorderRadius: 0,
  6454. /**
  6455. * Can be `2` or `[2, 4]` or `[2, 3, 4, 5]`
  6456. * @type {number|Array.<number>}
  6457. */
  6458. textPadding: null,
  6459. /**
  6460. * Text styles for rich text.
  6461. * @type {Object}
  6462. */
  6463. rich: null,
  6464. /**
  6465. * {outerWidth, outerHeight, ellipsis, placeholder}
  6466. * @type {Object}
  6467. */
  6468. truncate: null,
  6469. /**
  6470. * https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  6471. * @type {string}
  6472. */
  6473. blend: null,
  6474. /**
  6475. * @param {CanvasRenderingContext2D} ctx
  6476. */
  6477. bind: function (ctx, el, prevEl) {
  6478. var style = this;
  6479. var prevStyle = prevEl && prevEl.style;
  6480. // If no prevStyle, it means first draw.
  6481. // Only apply cache if the last time cachced by this function.
  6482. var notCheckCache = !prevStyle || ctx.__attrCachedBy !== ContextCachedBy.STYLE_BIND;
  6483. ctx.__attrCachedBy = ContextCachedBy.STYLE_BIND;
  6484. for (var i = 0; i < STYLE_COMMON_PROPS.length; i++) {
  6485. var prop = STYLE_COMMON_PROPS[i];
  6486. var styleName = prop[0];
  6487. if (notCheckCache || style[styleName] !== prevStyle[styleName]) {
  6488. // FIXME Invalid property value will cause style leak from previous element.
  6489. ctx[styleName] =
  6490. fixShadow(ctx, styleName, style[styleName] || prop[1]);
  6491. }
  6492. }
  6493. if ((notCheckCache || style.fill !== prevStyle.fill)) {
  6494. ctx.fillStyle = style.fill;
  6495. }
  6496. if ((notCheckCache || style.stroke !== prevStyle.stroke)) {
  6497. ctx.strokeStyle = style.stroke;
  6498. }
  6499. if ((notCheckCache || style.opacity !== prevStyle.opacity)) {
  6500. ctx.globalAlpha = style.opacity == null ? 1 : style.opacity;
  6501. }
  6502. if ((notCheckCache || style.blend !== prevStyle.blend)) {
  6503. ctx.globalCompositeOperation = style.blend || 'source-over';
  6504. }
  6505. if (this.hasStroke()) {
  6506. var lineWidth = style.lineWidth;
  6507. ctx.lineWidth = lineWidth / (
  6508. (this.strokeNoScale && el && el.getLineScale) ? el.getLineScale() : 1
  6509. );
  6510. }
  6511. },
  6512. hasFill: function () {
  6513. var fill = this.fill;
  6514. return fill != null && fill !== 'none';
  6515. },
  6516. hasStroke: function () {
  6517. var stroke = this.stroke;
  6518. return stroke != null && stroke !== 'none' && this.lineWidth > 0;
  6519. },
  6520. /**
  6521. * Extend from other style
  6522. * @param {zrender/graphic/Style} otherStyle
  6523. * @param {boolean} overwrite true: overwrirte any way.
  6524. * false: overwrite only when !target.hasOwnProperty
  6525. * others: overwrite when property is not null/undefined.
  6526. */
  6527. extendFrom: function (otherStyle, overwrite) {
  6528. if (otherStyle) {
  6529. for (var name in otherStyle) {
  6530. if (otherStyle.hasOwnProperty(name)
  6531. && (overwrite === true
  6532. || (
  6533. overwrite === false
  6534. ? !this.hasOwnProperty(name)
  6535. : otherStyle[name] != null
  6536. )
  6537. )
  6538. ) {
  6539. this[name] = otherStyle[name];
  6540. }
  6541. }
  6542. }
  6543. },
  6544. /**
  6545. * Batch setting style with a given object
  6546. * @param {Object|string} obj
  6547. * @param {*} [obj]
  6548. */
  6549. set: function (obj, value) {
  6550. if (typeof obj === 'string') {
  6551. this[obj] = value;
  6552. }
  6553. else {
  6554. this.extendFrom(obj, true);
  6555. }
  6556. },
  6557. /**
  6558. * Clone
  6559. * @return {zrender/graphic/Style} [description]
  6560. */
  6561. clone: function () {
  6562. var newStyle = new this.constructor();
  6563. newStyle.extendFrom(this, true);
  6564. return newStyle;
  6565. },
  6566. getGradient: function (ctx, obj, rect) {
  6567. var method = obj.type === 'radial' ? createRadialGradient : createLinearGradient;
  6568. var canvasGradient = method(ctx, obj, rect);
  6569. var colorStops = obj.colorStops;
  6570. for (var i = 0; i < colorStops.length; i++) {
  6571. canvasGradient.addColorStop(
  6572. colorStops[i].offset, colorStops[i].color
  6573. );
  6574. }
  6575. return canvasGradient;
  6576. }
  6577. };
  6578. var styleProto = Style.prototype;
  6579. for (var i = 0; i < STYLE_COMMON_PROPS.length; i++) {
  6580. var prop = STYLE_COMMON_PROPS[i];
  6581. if (!(prop[0] in styleProto)) {
  6582. styleProto[prop[0]] = prop[1];
  6583. }
  6584. }
  6585. // Provide for others
  6586. Style.getGradient = styleProto.getGradient;
  6587. var Pattern = function (image, repeat) {
  6588. // Should do nothing more in this constructor. Because gradient can be
  6589. // declard by `color: {image: ...}`, where this constructor will not be called.
  6590. this.image = image;
  6591. this.repeat = repeat;
  6592. // Can be cloned
  6593. this.type = 'pattern';
  6594. };
  6595. Pattern.prototype.getCanvasPattern = function (ctx) {
  6596. return ctx.createPattern(this.image, this.repeat || 'repeat');
  6597. };
  6598. /**
  6599. * @module zrender/Layer
  6600. * @author pissang(https://www.github.com/pissang)
  6601. */
  6602. function returnFalse() {
  6603. return false;
  6604. }
  6605. /**
  6606. * 创建dom
  6607. *
  6608. * @inner
  6609. * @param {string} id dom id 待用
  6610. * @param {Painter} painter painter instance
  6611. * @param {number} number
  6612. */
  6613. function createDom(id, painter, dpr) {
  6614. var newDom = createCanvas();
  6615. var width = painter.getWidth();
  6616. var height = painter.getHeight();
  6617. var newDomStyle = newDom.style;
  6618. if (newDomStyle) { // In node or some other non-browser environment
  6619. newDomStyle.position = 'absolute';
  6620. newDomStyle.left = 0;
  6621. newDomStyle.top = 0;
  6622. newDomStyle.width = width + 'px';
  6623. newDomStyle.height = height + 'px';
  6624. newDom.setAttribute('data-zr-dom-id', id);
  6625. }
  6626. newDom.width = width * dpr;
  6627. newDom.height = height * dpr;
  6628. return newDom;
  6629. }
  6630. /**
  6631. * @alias module:zrender/Layer
  6632. * @constructor
  6633. * @extends module:zrender/mixin/Transformable
  6634. * @param {string} id
  6635. * @param {module:zrender/Painter} painter
  6636. * @param {number} [dpr]
  6637. */
  6638. var Layer = function (id, painter, dpr) {
  6639. var dom;
  6640. dpr = dpr || devicePixelRatio;
  6641. if (typeof id === 'string') {
  6642. dom = createDom(id, painter, dpr);
  6643. }
  6644. // Not using isDom because in node it will return false
  6645. else if (isObject$1(id)) {
  6646. dom = id;
  6647. id = dom.id;
  6648. }
  6649. this.id = id;
  6650. this.dom = dom;
  6651. var domStyle = dom.style;
  6652. if (domStyle) { // Not in node
  6653. dom.onselectstart = returnFalse; // 避免页面选中的尴尬
  6654. domStyle['-webkit-user-select'] = 'none';
  6655. domStyle['user-select'] = 'none';
  6656. domStyle['-webkit-touch-callout'] = 'none';
  6657. domStyle['-webkit-tap-highlight-color'] = 'rgba(0,0,0,0)';
  6658. domStyle['padding'] = 0; // eslint-disable-line dot-notation
  6659. domStyle['margin'] = 0; // eslint-disable-line dot-notation
  6660. domStyle['border-width'] = 0;
  6661. }
  6662. this.domBack = null;
  6663. this.ctxBack = null;
  6664. this.painter = painter;
  6665. this.config = null;
  6666. // Configs
  6667. /**
  6668. * 每次清空画布的颜色
  6669. * @type {string}
  6670. * @default 0
  6671. */
  6672. this.clearColor = 0;
  6673. /**
  6674. * 是否开启动态模糊
  6675. * @type {boolean}
  6676. * @default false
  6677. */
  6678. this.motionBlur = false;
  6679. /**
  6680. * 在开启动态模糊的时候使用,与上一帧混合的alpha值,值越大尾迹越明显
  6681. * @type {number}
  6682. * @default 0.7
  6683. */
  6684. this.lastFrameAlpha = 0.7;
  6685. /**
  6686. * Layer dpr
  6687. * @type {number}
  6688. */
  6689. this.dpr = dpr;
  6690. };
  6691. Layer.prototype = {
  6692. constructor: Layer,
  6693. __dirty: true,
  6694. __used: false,
  6695. __drawIndex: 0,
  6696. __startIndex: 0,
  6697. __endIndex: 0,
  6698. incremental: false,
  6699. getElementCount: function () {
  6700. return this.__endIndex - this.__startIndex;
  6701. },
  6702. initContext: function () {
  6703. this.ctx = this.dom.getContext('2d');
  6704. this.ctx.dpr = this.dpr;
  6705. },
  6706. createBackBuffer: function () {
  6707. var dpr = this.dpr;
  6708. this.domBack = createDom('back-' + this.id, this.painter, dpr);
  6709. this.ctxBack = this.domBack.getContext('2d');
  6710. if (dpr !== 1) {
  6711. this.ctxBack.scale(dpr, dpr);
  6712. }
  6713. },
  6714. /**
  6715. * @param {number} width
  6716. * @param {number} height
  6717. */
  6718. resize: function (width, height) {
  6719. var dpr = this.dpr;
  6720. var dom = this.dom;
  6721. var domStyle = dom.style;
  6722. var domBack = this.domBack;
  6723. if (domStyle) {
  6724. domStyle.width = width + 'px';
  6725. domStyle.height = height + 'px';
  6726. }
  6727. dom.width = width * dpr;
  6728. dom.height = height * dpr;
  6729. if (domBack) {
  6730. domBack.width = width * dpr;
  6731. domBack.height = height * dpr;
  6732. if (dpr !== 1) {
  6733. this.ctxBack.scale(dpr, dpr);
  6734. }
  6735. }
  6736. },
  6737. /**
  6738. * 清空该层画布
  6739. * @param {boolean} [clearAll]=false Clear all with out motion blur
  6740. * @param {Color} [clearColor]
  6741. */
  6742. clear: function (clearAll, clearColor) {
  6743. var dom = this.dom;
  6744. var ctx = this.ctx;
  6745. var width = dom.width;
  6746. var height = dom.height;
  6747. var clearColor = clearColor || this.clearColor;
  6748. var haveMotionBLur = this.motionBlur && !clearAll;
  6749. var lastFrameAlpha = this.lastFrameAlpha;
  6750. var dpr = this.dpr;
  6751. if (haveMotionBLur) {
  6752. if (!this.domBack) {
  6753. this.createBackBuffer();
  6754. }
  6755. this.ctxBack.globalCompositeOperation = 'copy';
  6756. this.ctxBack.drawImage(
  6757. dom, 0, 0,
  6758. width / dpr,
  6759. height / dpr
  6760. );
  6761. }
  6762. ctx.clearRect(0, 0, width, height);
  6763. if (clearColor && clearColor !== 'transparent') {
  6764. var clearColorGradientOrPattern;
  6765. // Gradient
  6766. if (clearColor.colorStops) {
  6767. // Cache canvas gradient
  6768. clearColorGradientOrPattern = clearColor.__canvasGradient || Style.getGradient(ctx, clearColor, {
  6769. x: 0,
  6770. y: 0,
  6771. width: width,
  6772. height: height
  6773. });
  6774. clearColor.__canvasGradient = clearColorGradientOrPattern;
  6775. }
  6776. // Pattern
  6777. else if (clearColor.image) {
  6778. clearColorGradientOrPattern = Pattern.prototype.getCanvasPattern.call(clearColor, ctx);
  6779. }
  6780. ctx.save();
  6781. ctx.fillStyle = clearColorGradientOrPattern || clearColor;
  6782. ctx.fillRect(0, 0, width, height);
  6783. ctx.restore();
  6784. }
  6785. if (haveMotionBLur) {
  6786. var domBack = this.domBack;
  6787. ctx.save();
  6788. ctx.globalAlpha = lastFrameAlpha;
  6789. ctx.drawImage(domBack, 0, 0, width, height);
  6790. ctx.restore();
  6791. }
  6792. }
  6793. };
  6794. var requestAnimationFrame = (
  6795. typeof window !== 'undefined'
  6796. && (
  6797. (window.requestAnimationFrame && window.requestAnimationFrame.bind(window))
  6798. // https://github.com/ecomfe/zrender/issues/189#issuecomment-224919809
  6799. || (window.msRequestAnimationFrame && window.msRequestAnimationFrame.bind(window))
  6800. || window.mozRequestAnimationFrame
  6801. || window.webkitRequestAnimationFrame
  6802. )
  6803. ) || function (func) {
  6804. setTimeout(func, 16);
  6805. };
  6806. var globalImageCache = new LRU(50);
  6807. /**
  6808. * @param {string|HTMLImageElement|HTMLCanvasElement|Canvas} newImageOrSrc
  6809. * @return {HTMLImageElement|HTMLCanvasElement|Canvas} image
  6810. */
  6811. function findExistImage(newImageOrSrc) {
  6812. if (typeof newImageOrSrc === 'string') {
  6813. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  6814. return cachedImgObj && cachedImgObj.image;
  6815. }
  6816. else {
  6817. return newImageOrSrc;
  6818. }
  6819. }
  6820. /**
  6821. * Caution: User should cache loaded images, but not just count on LRU.
  6822. * Consider if required images more than LRU size, will dead loop occur?
  6823. *
  6824. * @param {string|HTMLImageElement|HTMLCanvasElement|Canvas} newImageOrSrc
  6825. * @param {HTMLImageElement|HTMLCanvasElement|Canvas} image Existent image.
  6826. * @param {module:zrender/Element} [hostEl] For calling `dirty`.
  6827. * @param {Function} [cb] params: (image, cbPayload)
  6828. * @param {Object} [cbPayload] Payload on cb calling.
  6829. * @return {HTMLImageElement|HTMLCanvasElement|Canvas} image
  6830. */
  6831. function createOrUpdateImage(newImageOrSrc, image, hostEl, cb, cbPayload) {
  6832. if (!newImageOrSrc) {
  6833. return image;
  6834. }
  6835. else if (typeof newImageOrSrc === 'string') {
  6836. // Image should not be loaded repeatly.
  6837. if ((image && image.__zrImageSrc === newImageOrSrc) || !hostEl) {
  6838. return image;
  6839. }
  6840. // Only when there is no existent image or existent image src
  6841. // is different, this method is responsible for load.
  6842. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  6843. var pendingWrap = {hostEl: hostEl, cb: cb, cbPayload: cbPayload};
  6844. if (cachedImgObj) {
  6845. image = cachedImgObj.image;
  6846. !isImageReady(image) && cachedImgObj.pending.push(pendingWrap);
  6847. }
  6848. else {
  6849. image = new Image();
  6850. image.onload = image.onerror = imageOnLoad;
  6851. globalImageCache.put(
  6852. newImageOrSrc,
  6853. image.__cachedImgObj = {
  6854. image: image,
  6855. pending: [pendingWrap]
  6856. }
  6857. );
  6858. image.src = image.__zrImageSrc = newImageOrSrc;
  6859. }
  6860. return image;
  6861. }
  6862. // newImageOrSrc is an HTMLImageElement or HTMLCanvasElement or Canvas
  6863. else {
  6864. return newImageOrSrc;
  6865. }
  6866. }
  6867. function imageOnLoad() {
  6868. var cachedImgObj = this.__cachedImgObj;
  6869. this.onload = this.onerror = this.__cachedImgObj = null;
  6870. for (var i = 0; i < cachedImgObj.pending.length; i++) {
  6871. var pendingWrap = cachedImgObj.pending[i];
  6872. var cb = pendingWrap.cb;
  6873. cb && cb(this, pendingWrap.cbPayload);
  6874. pendingWrap.hostEl.dirty();
  6875. }
  6876. cachedImgObj.pending.length = 0;
  6877. }
  6878. function isImageReady(image) {
  6879. return image && image.width && image.height;
  6880. }
  6881. var textWidthCache = {};
  6882. var textWidthCacheCounter = 0;
  6883. var TEXT_CACHE_MAX = 5000;
  6884. var STYLE_REG = /\{([a-zA-Z0-9_]+)\|([^}]*)\}/g;
  6885. var DEFAULT_FONT$1 = '12px sans-serif';
  6886. // Avoid assign to an exported variable, for transforming to cjs.
  6887. var methods$1 = {};
  6888. function $override$1(name, fn) {
  6889. methods$1[name] = fn;
  6890. }
  6891. /**
  6892. * @public
  6893. * @param {string} text
  6894. * @param {string} font
  6895. * @return {number} width
  6896. */
  6897. function getWidth(text, font) {
  6898. font = font || DEFAULT_FONT$1;
  6899. var key = text + ':' + font;
  6900. if (textWidthCache[key]) {
  6901. return textWidthCache[key];
  6902. }
  6903. var textLines = (text + '').split('\n');
  6904. var width = 0;
  6905. for (var i = 0, l = textLines.length; i < l; i++) {
  6906. // textContain.measureText may be overrided in SVG or VML
  6907. width = Math.max(measureText(textLines[i], font).width, width);
  6908. }
  6909. if (textWidthCacheCounter > TEXT_CACHE_MAX) {
  6910. textWidthCacheCounter = 0;
  6911. textWidthCache = {};
  6912. }
  6913. textWidthCacheCounter++;
  6914. textWidthCache[key] = width;
  6915. return width;
  6916. }
  6917. /**
  6918. * @public
  6919. * @param {string} text
  6920. * @param {string} font
  6921. * @param {string} [textAlign='left']
  6922. * @param {string} [textVerticalAlign='top']
  6923. * @param {Array.<number>} [textPadding]
  6924. * @param {Object} [rich]
  6925. * @param {Object} [truncate]
  6926. * @return {Object} {x, y, width, height, lineHeight}
  6927. */
  6928. function getBoundingRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, rich, truncate) {
  6929. return rich
  6930. ? getRichTextRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, rich, truncate)
  6931. : getPlainTextRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, truncate);
  6932. }
  6933. function getPlainTextRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, truncate) {
  6934. var contentBlock = parsePlainText(text, font, textPadding, textLineHeight, truncate);
  6935. var outerWidth = getWidth(text, font);
  6936. if (textPadding) {
  6937. outerWidth += textPadding[1] + textPadding[3];
  6938. }
  6939. var outerHeight = contentBlock.outerHeight;
  6940. var x = adjustTextX(0, outerWidth, textAlign);
  6941. var y = adjustTextY(0, outerHeight, textVerticalAlign);
  6942. var rect = new BoundingRect(x, y, outerWidth, outerHeight);
  6943. rect.lineHeight = contentBlock.lineHeight;
  6944. return rect;
  6945. }
  6946. function getRichTextRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, rich, truncate) {
  6947. var contentBlock = parseRichText(text, {
  6948. rich: rich,
  6949. truncate: truncate,
  6950. font: font,
  6951. textAlign: textAlign,
  6952. textPadding: textPadding,
  6953. textLineHeight: textLineHeight
  6954. });
  6955. var outerWidth = contentBlock.outerWidth;
  6956. var outerHeight = contentBlock.outerHeight;
  6957. var x = adjustTextX(0, outerWidth, textAlign);
  6958. var y = adjustTextY(0, outerHeight, textVerticalAlign);
  6959. return new BoundingRect(x, y, outerWidth, outerHeight);
  6960. }
  6961. /**
  6962. * @public
  6963. * @param {number} x
  6964. * @param {number} width
  6965. * @param {string} [textAlign='left']
  6966. * @return {number} Adjusted x.
  6967. */
  6968. function adjustTextX(x, width, textAlign) {
  6969. // FIXME Right to left language
  6970. if (textAlign === 'right') {
  6971. x -= width;
  6972. }
  6973. else if (textAlign === 'center') {
  6974. x -= width / 2;
  6975. }
  6976. return x;
  6977. }
  6978. /**
  6979. * @public
  6980. * @param {number} y
  6981. * @param {number} height
  6982. * @param {string} [textVerticalAlign='top']
  6983. * @return {number} Adjusted y.
  6984. */
  6985. function adjustTextY(y, height, textVerticalAlign) {
  6986. if (textVerticalAlign === 'middle') {
  6987. y -= height / 2;
  6988. }
  6989. else if (textVerticalAlign === 'bottom') {
  6990. y -= height;
  6991. }
  6992. return y;
  6993. }
  6994. /**
  6995. * Follow same interface to `Displayable.prototype.calculateTextPosition`.
  6996. * @public
  6997. * @param {Obejct} [out] Prepared out object. If not input, auto created in the method.
  6998. * @param {module:zrender/graphic/Style} style where `textPosition` and `textDistance` are visited.
  6999. * @param {Object} rect {x, y, width, height} Rect of the host elment, according to which the text positioned.
  7000. * @return {Object} The input `out`. Set: {x, y, textAlign, textVerticalAlign}
  7001. */
  7002. function calculateTextPosition(out, style, rect) {
  7003. var textPosition = style.textPosition;
  7004. var distance = style.textDistance;
  7005. var x = rect.x;
  7006. var y = rect.y;
  7007. distance = distance || 0;
  7008. var height = rect.height;
  7009. var width = rect.width;
  7010. var halfHeight = height / 2;
  7011. var textAlign = 'left';
  7012. var textVerticalAlign = 'top';
  7013. switch (textPosition) {
  7014. case 'left':
  7015. x -= distance;
  7016. y += halfHeight;
  7017. textAlign = 'right';
  7018. textVerticalAlign = 'middle';
  7019. break;
  7020. case 'right':
  7021. x += distance + width;
  7022. y += halfHeight;
  7023. textVerticalAlign = 'middle';
  7024. break;
  7025. case 'top':
  7026. x += width / 2;
  7027. y -= distance;
  7028. textAlign = 'center';
  7029. textVerticalAlign = 'bottom';
  7030. break;
  7031. case 'bottom':
  7032. x += width / 2;
  7033. y += height + distance;
  7034. textAlign = 'center';
  7035. break;
  7036. case 'inside':
  7037. x += width / 2;
  7038. y += halfHeight;
  7039. textAlign = 'center';
  7040. textVerticalAlign = 'middle';
  7041. break;
  7042. case 'insideLeft':
  7043. x += distance;
  7044. y += halfHeight;
  7045. textVerticalAlign = 'middle';
  7046. break;
  7047. case 'insideRight':
  7048. x += width - distance;
  7049. y += halfHeight;
  7050. textAlign = 'right';
  7051. textVerticalAlign = 'middle';
  7052. break;
  7053. case 'insideTop':
  7054. x += width / 2;
  7055. y += distance;
  7056. textAlign = 'center';
  7057. break;
  7058. case 'insideBottom':
  7059. x += width / 2;
  7060. y += height - distance;
  7061. textAlign = 'center';
  7062. textVerticalAlign = 'bottom';
  7063. break;
  7064. case 'insideTopLeft':
  7065. x += distance;
  7066. y += distance;
  7067. break;
  7068. case 'insideTopRight':
  7069. x += width - distance;
  7070. y += distance;
  7071. textAlign = 'right';
  7072. break;
  7073. case 'insideBottomLeft':
  7074. x += distance;
  7075. y += height - distance;
  7076. textVerticalAlign = 'bottom';
  7077. break;
  7078. case 'insideBottomRight':
  7079. x += width - distance;
  7080. y += height - distance;
  7081. textAlign = 'right';
  7082. textVerticalAlign = 'bottom';
  7083. break;
  7084. }
  7085. out = out || {};
  7086. out.x = x;
  7087. out.y = y;
  7088. out.textAlign = textAlign;
  7089. out.textVerticalAlign = textVerticalAlign;
  7090. return out;
  7091. }
  7092. /**
  7093. * To be removed. But still do not remove in case that some one has imported it.
  7094. * @deprecated
  7095. * @public
  7096. * @param {stirng} textPosition
  7097. * @param {Object} rect {x, y, width, height}
  7098. * @param {number} distance
  7099. * @return {Object} {x, y, textAlign, textVerticalAlign}
  7100. */
  7101. /**
  7102. * Show ellipsis if overflow.
  7103. *
  7104. * @public
  7105. * @param {string} text
  7106. * @param {string} containerWidth
  7107. * @param {string} font
  7108. * @param {number} [ellipsis='...']
  7109. * @param {Object} [options]
  7110. * @param {number} [options.maxIterations=3]
  7111. * @param {number} [options.minChar=0] If truncate result are less
  7112. * then minChar, ellipsis will not show, which is
  7113. * better for user hint in some cases.
  7114. * @param {number} [options.placeholder=''] When all truncated, use the placeholder.
  7115. * @return {string}
  7116. */
  7117. function truncateText(text, containerWidth, font, ellipsis, options) {
  7118. if (!containerWidth) {
  7119. return '';
  7120. }
  7121. var textLines = (text + '').split('\n');
  7122. options = prepareTruncateOptions(containerWidth, font, ellipsis, options);
  7123. // FIXME
  7124. // It is not appropriate that every line has '...' when truncate multiple lines.
  7125. for (var i = 0, len = textLines.length; i < len; i++) {
  7126. textLines[i] = truncateSingleLine(textLines[i], options);
  7127. }
  7128. return textLines.join('\n');
  7129. }
  7130. function prepareTruncateOptions(containerWidth, font, ellipsis, options) {
  7131. options = extend({}, options);
  7132. options.font = font;
  7133. var ellipsis = retrieve2(ellipsis, '...');
  7134. options.maxIterations = retrieve2(options.maxIterations, 2);
  7135. var minChar = options.minChar = retrieve2(options.minChar, 0);
  7136. // FIXME
  7137. // Other languages?
  7138. options.cnCharWidth = getWidth('国', font);
  7139. // FIXME
  7140. // Consider proportional font?
  7141. var ascCharWidth = options.ascCharWidth = getWidth('a', font);
  7142. options.placeholder = retrieve2(options.placeholder, '');
  7143. // Example 1: minChar: 3, text: 'asdfzxcv', truncate result: 'asdf', but not: 'a...'.
  7144. // Example 2: minChar: 3, text: '维度', truncate result: '维', but not: '...'.
  7145. var contentWidth = containerWidth = Math.max(0, containerWidth - 1); // Reserve some gap.
  7146. for (var i = 0; i < minChar && contentWidth >= ascCharWidth; i++) {
  7147. contentWidth -= ascCharWidth;
  7148. }
  7149. var ellipsisWidth = getWidth(ellipsis, font);
  7150. if (ellipsisWidth > contentWidth) {
  7151. ellipsis = '';
  7152. ellipsisWidth = 0;
  7153. }
  7154. contentWidth = containerWidth - ellipsisWidth;
  7155. options.ellipsis = ellipsis;
  7156. options.ellipsisWidth = ellipsisWidth;
  7157. options.contentWidth = contentWidth;
  7158. options.containerWidth = containerWidth;
  7159. return options;
  7160. }
  7161. function truncateSingleLine(textLine, options) {
  7162. var containerWidth = options.containerWidth;
  7163. var font = options.font;
  7164. var contentWidth = options.contentWidth;
  7165. if (!containerWidth) {
  7166. return '';
  7167. }
  7168. var lineWidth = getWidth(textLine, font);
  7169. if (lineWidth <= containerWidth) {
  7170. return textLine;
  7171. }
  7172. for (var j = 0; ; j++) {
  7173. if (lineWidth <= contentWidth || j >= options.maxIterations) {
  7174. textLine += options.ellipsis;
  7175. break;
  7176. }
  7177. var subLength = j === 0
  7178. ? estimateLength(textLine, contentWidth, options.ascCharWidth, options.cnCharWidth)
  7179. : lineWidth > 0
  7180. ? Math.floor(textLine.length * contentWidth / lineWidth)
  7181. : 0;
  7182. textLine = textLine.substr(0, subLength);
  7183. lineWidth = getWidth(textLine, font);
  7184. }
  7185. if (textLine === '') {
  7186. textLine = options.placeholder;
  7187. }
  7188. return textLine;
  7189. }
  7190. function estimateLength(text, contentWidth, ascCharWidth, cnCharWidth) {
  7191. var width = 0;
  7192. var i = 0;
  7193. for (var len = text.length; i < len && width < contentWidth; i++) {
  7194. var charCode = text.charCodeAt(i);
  7195. width += (0 <= charCode && charCode <= 127) ? ascCharWidth : cnCharWidth;
  7196. }
  7197. return i;
  7198. }
  7199. /**
  7200. * @public
  7201. * @param {string} font
  7202. * @return {number} line height
  7203. */
  7204. function getLineHeight(font) {
  7205. // FIXME A rough approach.
  7206. return getWidth('国', font);
  7207. }
  7208. /**
  7209. * @public
  7210. * @param {string} text
  7211. * @param {string} font
  7212. * @return {Object} width
  7213. */
  7214. function measureText(text, font) {
  7215. return methods$1.measureText(text, font);
  7216. }
  7217. // Avoid assign to an exported variable, for transforming to cjs.
  7218. methods$1.measureText = function (text, font) {
  7219. var ctx = getContext();
  7220. ctx.font = font || DEFAULT_FONT$1;
  7221. return ctx.measureText(text);
  7222. };
  7223. /**
  7224. * @public
  7225. * @param {string} text
  7226. * @param {string} font
  7227. * @param {Object} [truncate]
  7228. * @return {Object} block: {lineHeight, lines, height, outerHeight, canCacheByTextString}
  7229. * Notice: for performance, do not calculate outerWidth util needed.
  7230. * `canCacheByTextString` means the result `lines` is only determined by the input `text`.
  7231. * Thus we can simply comparing the `input` text to determin whether the result changed,
  7232. * without travel the result `lines`.
  7233. */
  7234. function parsePlainText(text, font, padding, textLineHeight, truncate) {
  7235. text != null && (text += '');
  7236. var lineHeight = retrieve2(textLineHeight, getLineHeight(font));
  7237. var lines = text ? text.split('\n') : [];
  7238. var height = lines.length * lineHeight;
  7239. var outerHeight = height;
  7240. var canCacheByTextString = true;
  7241. if (padding) {
  7242. outerHeight += padding[0] + padding[2];
  7243. }
  7244. if (text && truncate) {
  7245. canCacheByTextString = false;
  7246. var truncOuterHeight = truncate.outerHeight;
  7247. var truncOuterWidth = truncate.outerWidth;
  7248. if (truncOuterHeight != null && outerHeight > truncOuterHeight) {
  7249. text = '';
  7250. lines = [];
  7251. }
  7252. else if (truncOuterWidth != null) {
  7253. var options = prepareTruncateOptions(
  7254. truncOuterWidth - (padding ? padding[1] + padding[3] : 0),
  7255. font,
  7256. truncate.ellipsis,
  7257. {minChar: truncate.minChar, placeholder: truncate.placeholder}
  7258. );
  7259. // FIXME
  7260. // It is not appropriate that every line has '...' when truncate multiple lines.
  7261. for (var i = 0, len = lines.length; i < len; i++) {
  7262. lines[i] = truncateSingleLine(lines[i], options);
  7263. }
  7264. }
  7265. }
  7266. return {
  7267. lines: lines,
  7268. height: height,
  7269. outerHeight: outerHeight,
  7270. lineHeight: lineHeight,
  7271. canCacheByTextString: canCacheByTextString
  7272. };
  7273. }
  7274. /**
  7275. * For example: 'some text {a|some text}other text{b|some text}xxx{c|}xxx'
  7276. * Also consider 'bbbb{a|xxx\nzzz}xxxx\naaaa'.
  7277. *
  7278. * @public
  7279. * @param {string} text
  7280. * @param {Object} style
  7281. * @return {Object} block
  7282. * {
  7283. * width,
  7284. * height,
  7285. * lines: [{
  7286. * lineHeight,
  7287. * width,
  7288. * tokens: [[{
  7289. * styleName,
  7290. * text,
  7291. * width, // include textPadding
  7292. * height, // include textPadding
  7293. * textWidth, // pure text width
  7294. * textHeight, // pure text height
  7295. * lineHeihgt,
  7296. * font,
  7297. * textAlign,
  7298. * textVerticalAlign
  7299. * }], [...], ...]
  7300. * }, ...]
  7301. * }
  7302. * If styleName is undefined, it is plain text.
  7303. */
  7304. function parseRichText(text, style) {
  7305. var contentBlock = {lines: [], width: 0, height: 0};
  7306. text != null && (text += '');
  7307. if (!text) {
  7308. return contentBlock;
  7309. }
  7310. var lastIndex = STYLE_REG.lastIndex = 0;
  7311. var result;
  7312. while ((result = STYLE_REG.exec(text)) != null) {
  7313. var matchedIndex = result.index;
  7314. if (matchedIndex > lastIndex) {
  7315. pushTokens(contentBlock, text.substring(lastIndex, matchedIndex));
  7316. }
  7317. pushTokens(contentBlock, result[2], result[1]);
  7318. lastIndex = STYLE_REG.lastIndex;
  7319. }
  7320. if (lastIndex < text.length) {
  7321. pushTokens(contentBlock, text.substring(lastIndex, text.length));
  7322. }
  7323. var lines = contentBlock.lines;
  7324. var contentHeight = 0;
  7325. var contentWidth = 0;
  7326. // For `textWidth: 100%`
  7327. var pendingList = [];
  7328. var stlPadding = style.textPadding;
  7329. var truncate = style.truncate;
  7330. var truncateWidth = truncate && truncate.outerWidth;
  7331. var truncateHeight = truncate && truncate.outerHeight;
  7332. if (stlPadding) {
  7333. truncateWidth != null && (truncateWidth -= stlPadding[1] + stlPadding[3]);
  7334. truncateHeight != null && (truncateHeight -= stlPadding[0] + stlPadding[2]);
  7335. }
  7336. // Calculate layout info of tokens.
  7337. for (var i = 0; i < lines.length; i++) {
  7338. var line = lines[i];
  7339. var lineHeight = 0;
  7340. var lineWidth = 0;
  7341. for (var j = 0; j < line.tokens.length; j++) {
  7342. var token = line.tokens[j];
  7343. var tokenStyle = token.styleName && style.rich[token.styleName] || {};
  7344. // textPadding should not inherit from style.
  7345. var textPadding = token.textPadding = tokenStyle.textPadding;
  7346. // textFont has been asigned to font by `normalizeStyle`.
  7347. var font = token.font = tokenStyle.font || style.font;
  7348. // textHeight can be used when textVerticalAlign is specified in token.
  7349. var tokenHeight = token.textHeight = retrieve2(
  7350. // textHeight should not be inherited, consider it can be specified
  7351. // as box height of the block.
  7352. tokenStyle.textHeight, getLineHeight(font)
  7353. );
  7354. textPadding && (tokenHeight += textPadding[0] + textPadding[2]);
  7355. token.height = tokenHeight;
  7356. token.lineHeight = retrieve3(
  7357. tokenStyle.textLineHeight, style.textLineHeight, tokenHeight
  7358. );
  7359. token.textAlign = tokenStyle && tokenStyle.textAlign || style.textAlign;
  7360. token.textVerticalAlign = tokenStyle && tokenStyle.textVerticalAlign || 'middle';
  7361. if (truncateHeight != null && contentHeight + token.lineHeight > truncateHeight) {
  7362. return {lines: [], width: 0, height: 0};
  7363. }
  7364. token.textWidth = getWidth(token.text, font);
  7365. var tokenWidth = tokenStyle.textWidth;
  7366. var tokenWidthNotSpecified = tokenWidth == null || tokenWidth === 'auto';
  7367. // Percent width, can be `100%`, can be used in drawing separate
  7368. // line when box width is needed to be auto.
  7369. if (typeof tokenWidth === 'string' && tokenWidth.charAt(tokenWidth.length - 1) === '%') {
  7370. token.percentWidth = tokenWidth;
  7371. pendingList.push(token);
  7372. tokenWidth = 0;
  7373. // Do not truncate in this case, because there is no user case
  7374. // and it is too complicated.
  7375. }
  7376. else {
  7377. if (tokenWidthNotSpecified) {
  7378. tokenWidth = token.textWidth;
  7379. // FIXME: If image is not loaded and textWidth is not specified, calling
  7380. // `getBoundingRect()` will not get correct result.
  7381. var textBackgroundColor = tokenStyle.textBackgroundColor;
  7382. var bgImg = textBackgroundColor && textBackgroundColor.image;
  7383. // Use cases:
  7384. // (1) If image is not loaded, it will be loaded at render phase and call
  7385. // `dirty()` and `textBackgroundColor.image` will be replaced with the loaded
  7386. // image, and then the right size will be calculated here at the next tick.
  7387. // See `graphic/helper/text.js`.
  7388. // (2) If image loaded, and `textBackgroundColor.image` is image src string,
  7389. // use `imageHelper.findExistImage` to find cached image.
  7390. // `imageHelper.findExistImage` will always be called here before
  7391. // `imageHelper.createOrUpdateImage` in `graphic/helper/text.js#renderRichText`
  7392. // which ensures that image will not be rendered before correct size calcualted.
  7393. if (bgImg) {
  7394. bgImg = findExistImage(bgImg);
  7395. if (isImageReady(bgImg)) {
  7396. tokenWidth = Math.max(tokenWidth, bgImg.width * tokenHeight / bgImg.height);
  7397. }
  7398. }
  7399. }
  7400. var paddingW = textPadding ? textPadding[1] + textPadding[3] : 0;
  7401. tokenWidth += paddingW;
  7402. var remianTruncWidth = truncateWidth != null ? truncateWidth - lineWidth : null;
  7403. if (remianTruncWidth != null && remianTruncWidth < tokenWidth) {
  7404. if (!tokenWidthNotSpecified || remianTruncWidth < paddingW) {
  7405. token.text = '';
  7406. token.textWidth = tokenWidth = 0;
  7407. }
  7408. else {
  7409. token.text = truncateText(
  7410. token.text, remianTruncWidth - paddingW, font, truncate.ellipsis,
  7411. {minChar: truncate.minChar}
  7412. );
  7413. token.textWidth = getWidth(token.text, font);
  7414. tokenWidth = token.textWidth + paddingW;
  7415. }
  7416. }
  7417. }
  7418. lineWidth += (token.width = tokenWidth);
  7419. tokenStyle && (lineHeight = Math.max(lineHeight, token.lineHeight));
  7420. }
  7421. line.width = lineWidth;
  7422. line.lineHeight = lineHeight;
  7423. contentHeight += lineHeight;
  7424. contentWidth = Math.max(contentWidth, lineWidth);
  7425. }
  7426. contentBlock.outerWidth = contentBlock.width = retrieve2(style.textWidth, contentWidth);
  7427. contentBlock.outerHeight = contentBlock.height = retrieve2(style.textHeight, contentHeight);
  7428. if (stlPadding) {
  7429. contentBlock.outerWidth += stlPadding[1] + stlPadding[3];
  7430. contentBlock.outerHeight += stlPadding[0] + stlPadding[2];
  7431. }
  7432. for (var i = 0; i < pendingList.length; i++) {
  7433. var token = pendingList[i];
  7434. var percentWidth = token.percentWidth;
  7435. // Should not base on outerWidth, because token can not be placed out of padding.
  7436. token.width = parseInt(percentWidth, 10) / 100 * contentWidth;
  7437. }
  7438. return contentBlock;
  7439. }
  7440. function pushTokens(block, str, styleName) {
  7441. var isEmptyStr = str === '';
  7442. var strs = str.split('\n');
  7443. var lines = block.lines;
  7444. for (var i = 0; i < strs.length; i++) {
  7445. var text = strs[i];
  7446. var token = {
  7447. styleName: styleName,
  7448. text: text,
  7449. isLineHolder: !text && !isEmptyStr
  7450. };
  7451. // The first token should be appended to the last line.
  7452. if (!i) {
  7453. var tokens = (lines[lines.length - 1] || (lines[0] = {tokens: []})).tokens;
  7454. // Consider cases:
  7455. // (1) ''.split('\n') => ['', '\n', ''], the '' at the first item
  7456. // (which is a placeholder) should be replaced by new token.
  7457. // (2) A image backage, where token likes {a|}.
  7458. // (3) A redundant '' will affect textAlign in line.
  7459. // (4) tokens with the same tplName should not be merged, because
  7460. // they should be displayed in different box (with border and padding).
  7461. var tokensLen = tokens.length;
  7462. (tokensLen === 1 && tokens[0].isLineHolder)
  7463. ? (tokens[0] = token)
  7464. // Consider text is '', only insert when it is the "lineHolder" or
  7465. // "emptyStr". Otherwise a redundant '' will affect textAlign in line.
  7466. : ((text || !tokensLen || isEmptyStr) && tokens.push(token));
  7467. }
  7468. // Other tokens always start a new line.
  7469. else {
  7470. // If there is '', insert it as a placeholder.
  7471. lines.push({tokens: [token]});
  7472. }
  7473. }
  7474. }
  7475. function makeFont(style) {
  7476. // FIXME in node-canvas fontWeight is before fontStyle
  7477. // Use `fontSize` `fontFamily` to check whether font properties are defined.
  7478. var font = (style.fontSize || style.fontFamily) && [
  7479. style.fontStyle,
  7480. style.fontWeight,
  7481. (style.fontSize || 12) + 'px',
  7482. // If font properties are defined, `fontFamily` should not be ignored.
  7483. style.fontFamily || 'sans-serif'
  7484. ].join(' ');
  7485. return font && trim(font) || style.textFont || style.font;
  7486. }
  7487. /**
  7488. * @param {Object} ctx
  7489. * @param {Object} shape
  7490. * @param {number} shape.x
  7491. * @param {number} shape.y
  7492. * @param {number} shape.width
  7493. * @param {number} shape.height
  7494. * @param {number} shape.r
  7495. */
  7496. function buildPath(ctx, shape) {
  7497. var x = shape.x;
  7498. var y = shape.y;
  7499. var width = shape.width;
  7500. var height = shape.height;
  7501. var r = shape.r;
  7502. var r1;
  7503. var r2;
  7504. var r3;
  7505. var r4;
  7506. // Convert width and height to positive for better borderRadius
  7507. if (width < 0) {
  7508. x = x + width;
  7509. width = -width;
  7510. }
  7511. if (height < 0) {
  7512. y = y + height;
  7513. height = -height;
  7514. }
  7515. if (typeof r === 'number') {
  7516. r1 = r2 = r3 = r4 = r;
  7517. }
  7518. else if (r instanceof Array) {
  7519. if (r.length === 1) {
  7520. r1 = r2 = r3 = r4 = r[0];
  7521. }
  7522. else if (r.length === 2) {
  7523. r1 = r3 = r[0];
  7524. r2 = r4 = r[1];
  7525. }
  7526. else if (r.length === 3) {
  7527. r1 = r[0];
  7528. r2 = r4 = r[1];
  7529. r3 = r[2];
  7530. }
  7531. else {
  7532. r1 = r[0];
  7533. r2 = r[1];
  7534. r3 = r[2];
  7535. r4 = r[3];
  7536. }
  7537. }
  7538. else {
  7539. r1 = r2 = r3 = r4 = 0;
  7540. }
  7541. var total;
  7542. if (r1 + r2 > width) {
  7543. total = r1 + r2;
  7544. r1 *= width / total;
  7545. r2 *= width / total;
  7546. }
  7547. if (r3 + r4 > width) {
  7548. total = r3 + r4;
  7549. r3 *= width / total;
  7550. r4 *= width / total;
  7551. }
  7552. if (r2 + r3 > height) {
  7553. total = r2 + r3;
  7554. r2 *= height / total;
  7555. r3 *= height / total;
  7556. }
  7557. if (r1 + r4 > height) {
  7558. total = r1 + r4;
  7559. r1 *= height / total;
  7560. r4 *= height / total;
  7561. }
  7562. ctx.moveTo(x + r1, y);
  7563. ctx.lineTo(x + width - r2, y);
  7564. r2 !== 0 && ctx.arc(x + width - r2, y + r2, r2, -Math.PI / 2, 0);
  7565. ctx.lineTo(x + width, y + height - r3);
  7566. r3 !== 0 && ctx.arc(x + width - r3, y + height - r3, r3, 0, Math.PI / 2);
  7567. ctx.lineTo(x + r4, y + height);
  7568. r4 !== 0 && ctx.arc(x + r4, y + height - r4, r4, Math.PI / 2, Math.PI);
  7569. ctx.lineTo(x, y + r1);
  7570. r1 !== 0 && ctx.arc(x + r1, y + r1, r1, Math.PI, Math.PI * 1.5);
  7571. }
  7572. var DEFAULT_FONT = DEFAULT_FONT$1;
  7573. // TODO: Have not support 'start', 'end' yet.
  7574. var VALID_TEXT_ALIGN = {left: 1, right: 1, center: 1};
  7575. var VALID_TEXT_VERTICAL_ALIGN = {top: 1, bottom: 1, middle: 1};
  7576. // Different from `STYLE_COMMON_PROPS` of `graphic/Style`,
  7577. // the default value of shadowColor is `'transparent'`.
  7578. var SHADOW_STYLE_COMMON_PROPS = [
  7579. ['textShadowBlur', 'shadowBlur', 0],
  7580. ['textShadowOffsetX', 'shadowOffsetX', 0],
  7581. ['textShadowOffsetY', 'shadowOffsetY', 0],
  7582. ['textShadowColor', 'shadowColor', 'transparent']
  7583. ];
  7584. var _tmpTextPositionResult = {};
  7585. var _tmpBoxPositionResult = {};
  7586. /**
  7587. * @param {module:zrender/graphic/Style} style
  7588. * @return {module:zrender/graphic/Style} The input style.
  7589. */
  7590. function normalizeTextStyle(style) {
  7591. normalizeStyle(style);
  7592. each$1(style.rich, normalizeStyle);
  7593. return style;
  7594. }
  7595. function normalizeStyle(style) {
  7596. if (style) {
  7597. style.font = makeFont(style);
  7598. var textAlign = style.textAlign;
  7599. textAlign === 'middle' && (textAlign = 'center');
  7600. style.textAlign = (
  7601. textAlign == null || VALID_TEXT_ALIGN[textAlign]
  7602. ) ? textAlign : 'left';
  7603. // Compatible with textBaseline.
  7604. var textVerticalAlign = style.textVerticalAlign || style.textBaseline;
  7605. textVerticalAlign === 'center' && (textVerticalAlign = 'middle');
  7606. style.textVerticalAlign = (
  7607. textVerticalAlign == null || VALID_TEXT_VERTICAL_ALIGN[textVerticalAlign]
  7608. ) ? textVerticalAlign : 'top';
  7609. var textPadding = style.textPadding;
  7610. if (textPadding) {
  7611. style.textPadding = normalizeCssArray(style.textPadding);
  7612. }
  7613. }
  7614. }
  7615. /**
  7616. * @param {CanvasRenderingContext2D} ctx
  7617. * @param {string} text
  7618. * @param {module:zrender/graphic/Style} style
  7619. * @param {Object|boolean} [rect] {x, y, width, height}
  7620. * If set false, rect text is not used.
  7621. * @param {Element|module:zrender/graphic/helper/constant.WILL_BE_RESTORED} [prevEl] For ctx prop cache.
  7622. */
  7623. function renderText(hostEl, ctx, text, style, rect, prevEl) {
  7624. style.rich
  7625. ? renderRichText(hostEl, ctx, text, style, rect, prevEl)
  7626. : renderPlainText(hostEl, ctx, text, style, rect, prevEl);
  7627. }
  7628. // Avoid setting to ctx according to prevEl if possible for
  7629. // performance in scenarios of large amount text.
  7630. function renderPlainText(hostEl, ctx, text, style, rect, prevEl) {
  7631. 'use strict';
  7632. var needDrawBg = needDrawBackground(style);
  7633. var prevStyle;
  7634. var checkCache = false;
  7635. var cachedByMe = ctx.__attrCachedBy === ContextCachedBy.PLAIN_TEXT;
  7636. // Only take and check cache for `Text` el, but not RectText.
  7637. if (prevEl !== WILL_BE_RESTORED) {
  7638. if (prevEl) {
  7639. prevStyle = prevEl.style;
  7640. checkCache = !needDrawBg && cachedByMe && prevStyle;
  7641. }
  7642. // Prevent from using cache in `Style::bind`, because of the case:
  7643. // ctx property is modified by other properties than `Style::bind`
  7644. // used, and Style::bind is called next.
  7645. ctx.__attrCachedBy = needDrawBg ? ContextCachedBy.NONE : ContextCachedBy.PLAIN_TEXT;
  7646. }
  7647. // Since this will be restored, prevent from using these props to check cache in the next
  7648. // entering of this method. But do not need to clear other cache like `Style::bind`.
  7649. else if (cachedByMe) {
  7650. ctx.__attrCachedBy = ContextCachedBy.NONE;
  7651. }
  7652. var styleFont = style.font || DEFAULT_FONT;
  7653. // PENDING
  7654. // Only `Text` el set `font` and keep it (`RectText` will restore). So theoretically
  7655. // we can make font cache on ctx, which can cache for text el that are discontinuous.
  7656. // But layer save/restore needed to be considered.
  7657. // if (styleFont !== ctx.__fontCache) {
  7658. // ctx.font = styleFont;
  7659. // if (prevEl !== WILL_BE_RESTORED) {
  7660. // ctx.__fontCache = styleFont;
  7661. // }
  7662. // }
  7663. if (!checkCache || styleFont !== (prevStyle.font || DEFAULT_FONT)) {
  7664. ctx.font = styleFont;
  7665. }
  7666. // Use the final font from context-2d, because the final
  7667. // font might not be the style.font when it is illegal.
  7668. // But get `ctx.font` might be time consuming.
  7669. var computedFont = hostEl.__computedFont;
  7670. if (hostEl.__styleFont !== styleFont) {
  7671. hostEl.__styleFont = styleFont;
  7672. computedFont = hostEl.__computedFont = ctx.font;
  7673. }
  7674. var textPadding = style.textPadding;
  7675. var textLineHeight = style.textLineHeight;
  7676. var contentBlock = hostEl.__textCotentBlock;
  7677. if (!contentBlock || hostEl.__dirtyText) {
  7678. contentBlock = hostEl.__textCotentBlock = parsePlainText(
  7679. text, computedFont, textPadding, textLineHeight, style.truncate
  7680. );
  7681. }
  7682. var outerHeight = contentBlock.outerHeight;
  7683. var textLines = contentBlock.lines;
  7684. var lineHeight = contentBlock.lineHeight;
  7685. var boxPos = getBoxPosition(_tmpBoxPositionResult, hostEl, style, rect);
  7686. var baseX = boxPos.baseX;
  7687. var baseY = boxPos.baseY;
  7688. var textAlign = boxPos.textAlign || 'left';
  7689. var textVerticalAlign = boxPos.textVerticalAlign;
  7690. // Origin of textRotation should be the base point of text drawing.
  7691. applyTextRotation(ctx, style, rect, baseX, baseY);
  7692. var boxY = adjustTextY(baseY, outerHeight, textVerticalAlign);
  7693. var textX = baseX;
  7694. var textY = boxY;
  7695. if (needDrawBg || textPadding) {
  7696. // Consider performance, do not call getTextWidth util necessary.
  7697. var textWidth = getWidth(text, computedFont);
  7698. var outerWidth = textWidth;
  7699. textPadding && (outerWidth += textPadding[1] + textPadding[3]);
  7700. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  7701. needDrawBg && drawBackground(hostEl, ctx, style, boxX, boxY, outerWidth, outerHeight);
  7702. if (textPadding) {
  7703. textX = getTextXForPadding(baseX, textAlign, textPadding);
  7704. textY += textPadding[0];
  7705. }
  7706. }
  7707. // Always set textAlign and textBase line, because it is difficute to calculate
  7708. // textAlign from prevEl, and we dont sure whether textAlign will be reset if
  7709. // font set happened.
  7710. ctx.textAlign = textAlign;
  7711. // Force baseline to be "middle". Otherwise, if using "top", the
  7712. // text will offset downward a little bit in font "Microsoft YaHei".
  7713. ctx.textBaseline = 'middle';
  7714. // Set text opacity
  7715. ctx.globalAlpha = style.opacity || 1;
  7716. // Always set shadowBlur and shadowOffset to avoid leak from displayable.
  7717. for (var i = 0; i < SHADOW_STYLE_COMMON_PROPS.length; i++) {
  7718. var propItem = SHADOW_STYLE_COMMON_PROPS[i];
  7719. var styleProp = propItem[0];
  7720. var ctxProp = propItem[1];
  7721. var val = style[styleProp];
  7722. if (!checkCache || val !== prevStyle[styleProp]) {
  7723. ctx[ctxProp] = fixShadow(ctx, ctxProp, val || propItem[2]);
  7724. }
  7725. }
  7726. // `textBaseline` is set as 'middle'.
  7727. textY += lineHeight / 2;
  7728. var textStrokeWidth = style.textStrokeWidth;
  7729. var textStrokeWidthPrev = checkCache ? prevStyle.textStrokeWidth : null;
  7730. var strokeWidthChanged = !checkCache || textStrokeWidth !== textStrokeWidthPrev;
  7731. var strokeChanged = !checkCache || strokeWidthChanged || style.textStroke !== prevStyle.textStroke;
  7732. var textStroke = getStroke(style.textStroke, textStrokeWidth);
  7733. var textFill = getFill(style.textFill);
  7734. if (textStroke) {
  7735. if (strokeWidthChanged) {
  7736. ctx.lineWidth = textStrokeWidth;
  7737. }
  7738. if (strokeChanged) {
  7739. ctx.strokeStyle = textStroke;
  7740. }
  7741. }
  7742. if (textFill) {
  7743. if (!checkCache || style.textFill !== prevStyle.textFill) {
  7744. ctx.fillStyle = textFill;
  7745. }
  7746. }
  7747. // Optimize simply, in most cases only one line exists.
  7748. if (textLines.length === 1) {
  7749. // Fill after stroke so the outline will not cover the main part.
  7750. textStroke && ctx.strokeText(textLines[0], textX, textY);
  7751. textFill && ctx.fillText(textLines[0], textX, textY);
  7752. }
  7753. else {
  7754. for (var i = 0; i < textLines.length; i++) {
  7755. // Fill after stroke so the outline will not cover the main part.
  7756. textStroke && ctx.strokeText(textLines[i], textX, textY);
  7757. textFill && ctx.fillText(textLines[i], textX, textY);
  7758. textY += lineHeight;
  7759. }
  7760. }
  7761. }
  7762. function renderRichText(hostEl, ctx, text, style, rect, prevEl) {
  7763. // Do not do cache for rich text because of the complexity.
  7764. // But `RectText` this will be restored, do not need to clear other cache like `Style::bind`.
  7765. if (prevEl !== WILL_BE_RESTORED) {
  7766. ctx.__attrCachedBy = ContextCachedBy.NONE;
  7767. }
  7768. var contentBlock = hostEl.__textCotentBlock;
  7769. if (!contentBlock || hostEl.__dirtyText) {
  7770. contentBlock = hostEl.__textCotentBlock = parseRichText(text, style);
  7771. }
  7772. drawRichText(hostEl, ctx, contentBlock, style, rect);
  7773. }
  7774. function drawRichText(hostEl, ctx, contentBlock, style, rect) {
  7775. var contentWidth = contentBlock.width;
  7776. var outerWidth = contentBlock.outerWidth;
  7777. var outerHeight = contentBlock.outerHeight;
  7778. var textPadding = style.textPadding;
  7779. var boxPos = getBoxPosition(_tmpBoxPositionResult, hostEl, style, rect);
  7780. var baseX = boxPos.baseX;
  7781. var baseY = boxPos.baseY;
  7782. var textAlign = boxPos.textAlign;
  7783. var textVerticalAlign = boxPos.textVerticalAlign;
  7784. // Origin of textRotation should be the base point of text drawing.
  7785. applyTextRotation(ctx, style, rect, baseX, baseY);
  7786. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  7787. var boxY = adjustTextY(baseY, outerHeight, textVerticalAlign);
  7788. var xLeft = boxX;
  7789. var lineTop = boxY;
  7790. if (textPadding) {
  7791. xLeft += textPadding[3];
  7792. lineTop += textPadding[0];
  7793. }
  7794. var xRight = xLeft + contentWidth;
  7795. needDrawBackground(style) && drawBackground(
  7796. hostEl, ctx, style, boxX, boxY, outerWidth, outerHeight
  7797. );
  7798. for (var i = 0; i < contentBlock.lines.length; i++) {
  7799. var line = contentBlock.lines[i];
  7800. var tokens = line.tokens;
  7801. var tokenCount = tokens.length;
  7802. var lineHeight = line.lineHeight;
  7803. var usedWidth = line.width;
  7804. var leftIndex = 0;
  7805. var lineXLeft = xLeft;
  7806. var lineXRight = xRight;
  7807. var rightIndex = tokenCount - 1;
  7808. var token;
  7809. while (
  7810. leftIndex < tokenCount
  7811. && (token = tokens[leftIndex], !token.textAlign || token.textAlign === 'left')
  7812. ) {
  7813. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXLeft, 'left');
  7814. usedWidth -= token.width;
  7815. lineXLeft += token.width;
  7816. leftIndex++;
  7817. }
  7818. while (
  7819. rightIndex >= 0
  7820. && (token = tokens[rightIndex], token.textAlign === 'right')
  7821. ) {
  7822. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXRight, 'right');
  7823. usedWidth -= token.width;
  7824. lineXRight -= token.width;
  7825. rightIndex--;
  7826. }
  7827. // The other tokens are placed as textAlign 'center' if there is enough space.
  7828. lineXLeft += (contentWidth - (lineXLeft - xLeft) - (xRight - lineXRight) - usedWidth) / 2;
  7829. while (leftIndex <= rightIndex) {
  7830. token = tokens[leftIndex];
  7831. // Consider width specified by user, use 'center' rather than 'left'.
  7832. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXLeft + token.width / 2, 'center');
  7833. lineXLeft += token.width;
  7834. leftIndex++;
  7835. }
  7836. lineTop += lineHeight;
  7837. }
  7838. }
  7839. function applyTextRotation(ctx, style, rect, x, y) {
  7840. // textRotation only apply in RectText.
  7841. if (rect && style.textRotation) {
  7842. var origin = style.textOrigin;
  7843. if (origin === 'center') {
  7844. x = rect.width / 2 + rect.x;
  7845. y = rect.height / 2 + rect.y;
  7846. }
  7847. else if (origin) {
  7848. x = origin[0] + rect.x;
  7849. y = origin[1] + rect.y;
  7850. }
  7851. ctx.translate(x, y);
  7852. // Positive: anticlockwise
  7853. ctx.rotate(-style.textRotation);
  7854. ctx.translate(-x, -y);
  7855. }
  7856. }
  7857. function placeToken(hostEl, ctx, token, style, lineHeight, lineTop, x, textAlign) {
  7858. var tokenStyle = style.rich[token.styleName] || {};
  7859. tokenStyle.text = token.text;
  7860. // 'ctx.textBaseline' is always set as 'middle', for sake of
  7861. // the bias of "Microsoft YaHei".
  7862. var textVerticalAlign = token.textVerticalAlign;
  7863. var y = lineTop + lineHeight / 2;
  7864. if (textVerticalAlign === 'top') {
  7865. y = lineTop + token.height / 2;
  7866. }
  7867. else if (textVerticalAlign === 'bottom') {
  7868. y = lineTop + lineHeight - token.height / 2;
  7869. }
  7870. !token.isLineHolder && needDrawBackground(tokenStyle) && drawBackground(
  7871. hostEl,
  7872. ctx,
  7873. tokenStyle,
  7874. textAlign === 'right'
  7875. ? x - token.width
  7876. : textAlign === 'center'
  7877. ? x - token.width / 2
  7878. : x,
  7879. y - token.height / 2,
  7880. token.width,
  7881. token.height
  7882. );
  7883. var textPadding = token.textPadding;
  7884. if (textPadding) {
  7885. x = getTextXForPadding(x, textAlign, textPadding);
  7886. y -= token.height / 2 - textPadding[2] - token.textHeight / 2;
  7887. }
  7888. setCtx(ctx, 'shadowBlur', retrieve3(tokenStyle.textShadowBlur, style.textShadowBlur, 0));
  7889. setCtx(ctx, 'shadowColor', tokenStyle.textShadowColor || style.textShadowColor || 'transparent');
  7890. setCtx(ctx, 'shadowOffsetX', retrieve3(tokenStyle.textShadowOffsetX, style.textShadowOffsetX, 0));
  7891. setCtx(ctx, 'shadowOffsetY', retrieve3(tokenStyle.textShadowOffsetY, style.textShadowOffsetY, 0));
  7892. setCtx(ctx, 'textAlign', textAlign);
  7893. // Force baseline to be "middle". Otherwise, if using "top", the
  7894. // text will offset downward a little bit in font "Microsoft YaHei".
  7895. setCtx(ctx, 'textBaseline', 'middle');
  7896. setCtx(ctx, 'font', token.font || DEFAULT_FONT);
  7897. var textStroke = getStroke(tokenStyle.textStroke || style.textStroke, textStrokeWidth);
  7898. var textFill = getFill(tokenStyle.textFill || style.textFill);
  7899. var textStrokeWidth = retrieve2(tokenStyle.textStrokeWidth, style.textStrokeWidth);
  7900. // Fill after stroke so the outline will not cover the main part.
  7901. if (textStroke) {
  7902. setCtx(ctx, 'lineWidth', textStrokeWidth);
  7903. setCtx(ctx, 'strokeStyle', textStroke);
  7904. ctx.strokeText(token.text, x, y);
  7905. }
  7906. if (textFill) {
  7907. setCtx(ctx, 'fillStyle', textFill);
  7908. ctx.fillText(token.text, x, y);
  7909. }
  7910. }
  7911. function needDrawBackground(style) {
  7912. return !!(
  7913. style.textBackgroundColor
  7914. || (style.textBorderWidth && style.textBorderColor)
  7915. );
  7916. }
  7917. // style: {textBackgroundColor, textBorderWidth, textBorderColor, textBorderRadius, text}
  7918. // shape: {x, y, width, height}
  7919. function drawBackground(hostEl, ctx, style, x, y, width, height) {
  7920. var textBackgroundColor = style.textBackgroundColor;
  7921. var textBorderWidth = style.textBorderWidth;
  7922. var textBorderColor = style.textBorderColor;
  7923. var isPlainBg = isString(textBackgroundColor);
  7924. setCtx(ctx, 'shadowBlur', style.textBoxShadowBlur || 0);
  7925. setCtx(ctx, 'shadowColor', style.textBoxShadowColor || 'transparent');
  7926. setCtx(ctx, 'shadowOffsetX', style.textBoxShadowOffsetX || 0);
  7927. setCtx(ctx, 'shadowOffsetY', style.textBoxShadowOffsetY || 0);
  7928. if (isPlainBg || (textBorderWidth && textBorderColor)) {
  7929. ctx.beginPath();
  7930. var textBorderRadius = style.textBorderRadius;
  7931. if (!textBorderRadius) {
  7932. ctx.rect(x, y, width, height);
  7933. }
  7934. else {
  7935. buildPath(ctx, {
  7936. x: x, y: y, width: width, height: height, r: textBorderRadius
  7937. });
  7938. }
  7939. ctx.closePath();
  7940. }
  7941. if (isPlainBg) {
  7942. setCtx(ctx, 'fillStyle', textBackgroundColor);
  7943. if (style.fillOpacity != null) {
  7944. var originalGlobalAlpha = ctx.globalAlpha;
  7945. ctx.globalAlpha = style.fillOpacity * style.opacity;
  7946. ctx.fill();
  7947. ctx.globalAlpha = originalGlobalAlpha;
  7948. }
  7949. else {
  7950. ctx.fill();
  7951. }
  7952. }
  7953. else if (isObject$1(textBackgroundColor)) {
  7954. var image = textBackgroundColor.image;
  7955. image = createOrUpdateImage(
  7956. image, null, hostEl, onBgImageLoaded, textBackgroundColor
  7957. );
  7958. if (image && isImageReady(image)) {
  7959. ctx.drawImage(image, x, y, width, height);
  7960. }
  7961. }
  7962. if (textBorderWidth && textBorderColor) {
  7963. setCtx(ctx, 'lineWidth', textBorderWidth);
  7964. setCtx(ctx, 'strokeStyle', textBorderColor);
  7965. if (style.strokeOpacity != null) {
  7966. var originalGlobalAlpha = ctx.globalAlpha;
  7967. ctx.globalAlpha = style.strokeOpacity * style.opacity;
  7968. ctx.stroke();
  7969. ctx.globalAlpha = originalGlobalAlpha;
  7970. }
  7971. else {
  7972. ctx.stroke();
  7973. }
  7974. }
  7975. }
  7976. function onBgImageLoaded(image, textBackgroundColor) {
  7977. // Replace image, so that `contain/text.js#parseRichText`
  7978. // will get correct result in next tick.
  7979. textBackgroundColor.image = image;
  7980. }
  7981. function getBoxPosition(out, hostEl, style, rect) {
  7982. var baseX = style.x || 0;
  7983. var baseY = style.y || 0;
  7984. var textAlign = style.textAlign;
  7985. var textVerticalAlign = style.textVerticalAlign;
  7986. // Text position represented by coord
  7987. if (rect) {
  7988. var textPosition = style.textPosition;
  7989. if (textPosition instanceof Array) {
  7990. // Percent
  7991. baseX = rect.x + parsePercent(textPosition[0], rect.width);
  7992. baseY = rect.y + parsePercent(textPosition[1], rect.height);
  7993. }
  7994. else {
  7995. var res = (hostEl && hostEl.calculateTextPosition)
  7996. ? hostEl.calculateTextPosition(_tmpTextPositionResult, style, rect)
  7997. : calculateTextPosition(_tmpTextPositionResult, style, rect);
  7998. baseX = res.x;
  7999. baseY = res.y;
  8000. // Default align and baseline when has textPosition
  8001. textAlign = textAlign || res.textAlign;
  8002. textVerticalAlign = textVerticalAlign || res.textVerticalAlign;
  8003. }
  8004. // textOffset is only support in RectText, otherwise
  8005. // we have to adjust boundingRect for textOffset.
  8006. var textOffset = style.textOffset;
  8007. if (textOffset) {
  8008. baseX += textOffset[0];
  8009. baseY += textOffset[1];
  8010. }
  8011. }
  8012. out = out || {};
  8013. out.baseX = baseX;
  8014. out.baseY = baseY;
  8015. out.textAlign = textAlign;
  8016. out.textVerticalAlign = textVerticalAlign;
  8017. return out;
  8018. }
  8019. function setCtx(ctx, prop, value) {
  8020. ctx[prop] = fixShadow(ctx, prop, value);
  8021. return ctx[prop];
  8022. }
  8023. /**
  8024. * @param {string} [stroke] If specified, do not check style.textStroke.
  8025. * @param {string} [lineWidth] If specified, do not check style.textStroke.
  8026. * @param {number} style
  8027. */
  8028. function getStroke(stroke, lineWidth) {
  8029. return (stroke == null || lineWidth <= 0 || stroke === 'transparent' || stroke === 'none')
  8030. ? null
  8031. // TODO pattern and gradient?
  8032. : (stroke.image || stroke.colorStops)
  8033. ? '#000'
  8034. : stroke;
  8035. }
  8036. function getFill(fill) {
  8037. return (fill == null || fill === 'none')
  8038. ? null
  8039. // TODO pattern and gradient?
  8040. : (fill.image || fill.colorStops)
  8041. ? '#000'
  8042. : fill;
  8043. }
  8044. function parsePercent(value, maxValue) {
  8045. if (typeof value === 'string') {
  8046. if (value.lastIndexOf('%') >= 0) {
  8047. return parseFloat(value) / 100 * maxValue;
  8048. }
  8049. return parseFloat(value);
  8050. }
  8051. return value;
  8052. }
  8053. function getTextXForPadding(x, textAlign, textPadding) {
  8054. return textAlign === 'right'
  8055. ? (x - textPadding[1])
  8056. : textAlign === 'center'
  8057. ? (x + textPadding[3] / 2 - textPadding[1] / 2)
  8058. : (x + textPadding[3]);
  8059. }
  8060. /**
  8061. * @param {string} text
  8062. * @param {module:zrender/Style} style
  8063. * @return {boolean}
  8064. */
  8065. function needDrawText(text, style) {
  8066. return text != null
  8067. && (text
  8068. || style.textBackgroundColor
  8069. || (style.textBorderWidth && style.textBorderColor)
  8070. || style.textPadding
  8071. );
  8072. }
  8073. /**
  8074. * Mixin for drawing text in a element bounding rect
  8075. * @module zrender/mixin/RectText
  8076. */
  8077. var tmpRect$1 = new BoundingRect();
  8078. var RectText = function () {};
  8079. RectText.prototype = {
  8080. constructor: RectText,
  8081. /**
  8082. * Draw text in a rect with specified position.
  8083. * @param {CanvasRenderingContext2D} ctx
  8084. * @param {Object} rect Displayable rect
  8085. */
  8086. drawRectText: function (ctx, rect) {
  8087. var style = this.style;
  8088. rect = style.textRect || rect;
  8089. // Optimize, avoid normalize every time.
  8090. this.__dirty && normalizeTextStyle(style, true);
  8091. var text = style.text;
  8092. // Convert to string
  8093. text != null && (text += '');
  8094. if (!needDrawText(text, style)) {
  8095. return;
  8096. }
  8097. // FIXME
  8098. // Do not provide prevEl to `textHelper.renderText` for ctx prop cache,
  8099. // but use `ctx.save()` and `ctx.restore()`. Because the cache for rect
  8100. // text propably break the cache for its host elements.
  8101. ctx.save();
  8102. // Transform rect to view space
  8103. var transform = this.transform;
  8104. if (!style.transformText) {
  8105. if (transform) {
  8106. tmpRect$1.copy(rect);
  8107. tmpRect$1.applyTransform(transform);
  8108. rect = tmpRect$1;
  8109. }
  8110. }
  8111. else {
  8112. this.setTransform(ctx);
  8113. }
  8114. // transformText and textRotation can not be used at the same time.
  8115. renderText(this, ctx, text, style, rect, WILL_BE_RESTORED);
  8116. ctx.restore();
  8117. }
  8118. };
  8119. /**
  8120. * Base class of all displayable graphic objects
  8121. * @module zrender/graphic/Displayable
  8122. */
  8123. /**
  8124. * @alias module:zrender/graphic/Displayable
  8125. * @extends module:zrender/Element
  8126. * @extends module:zrender/graphic/mixin/RectText
  8127. */
  8128. function Displayable(opts) {
  8129. opts = opts || {};
  8130. Element.call(this, opts);
  8131. // Extend properties
  8132. for (var name in opts) {
  8133. if (
  8134. opts.hasOwnProperty(name)
  8135. && name !== 'style'
  8136. ) {
  8137. this[name] = opts[name];
  8138. }
  8139. }
  8140. /**
  8141. * @type {module:zrender/graphic/Style}
  8142. */
  8143. this.style = new Style(opts.style, this);
  8144. this._rect = null;
  8145. // Shapes for cascade clipping.
  8146. // Can only be `null`/`undefined` or an non-empty array, MUST NOT be an empty array.
  8147. // because it is easy to only using null to check whether clipPaths changed.
  8148. this.__clipPaths = null;
  8149. // FIXME Stateful must be mixined after style is setted
  8150. // Stateful.call(this, opts);
  8151. }
  8152. Displayable.prototype = {
  8153. constructor: Displayable,
  8154. type: 'displayable',
  8155. /**
  8156. * Dirty flag. From which painter will determine if this displayable object needs brush.
  8157. * @name module:zrender/graphic/Displayable#__dirty
  8158. * @type {boolean}
  8159. */
  8160. __dirty: true,
  8161. /**
  8162. * Whether the displayable object is visible. when it is true, the displayable object
  8163. * is not drawn, but the mouse event can still trigger the object.
  8164. * @name module:/zrender/graphic/Displayable#invisible
  8165. * @type {boolean}
  8166. * @default false
  8167. */
  8168. invisible: false,
  8169. /**
  8170. * @name module:/zrender/graphic/Displayable#z
  8171. * @type {number}
  8172. * @default 0
  8173. */
  8174. z: 0,
  8175. /**
  8176. * @name module:/zrender/graphic/Displayable#z
  8177. * @type {number}
  8178. * @default 0
  8179. */
  8180. z2: 0,
  8181. /**
  8182. * The z level determines the displayable object can be drawn in which layer canvas.
  8183. * @name module:/zrender/graphic/Displayable#zlevel
  8184. * @type {number}
  8185. * @default 0
  8186. */
  8187. zlevel: 0,
  8188. /**
  8189. * Whether it can be dragged.
  8190. * @name module:/zrender/graphic/Displayable#draggable
  8191. * @type {boolean}
  8192. * @default false
  8193. */
  8194. draggable: false,
  8195. /**
  8196. * Whether is it dragging.
  8197. * @name module:/zrender/graphic/Displayable#draggable
  8198. * @type {boolean}
  8199. * @default false
  8200. */
  8201. dragging: false,
  8202. /**
  8203. * Whether to respond to mouse events.
  8204. * @name module:/zrender/graphic/Displayable#silent
  8205. * @type {boolean}
  8206. * @default false
  8207. */
  8208. silent: false,
  8209. /**
  8210. * If enable culling
  8211. * @type {boolean}
  8212. * @default false
  8213. */
  8214. culling: false,
  8215. /**
  8216. * Mouse cursor when hovered
  8217. * @name module:/zrender/graphic/Displayable#cursor
  8218. * @type {string}
  8219. */
  8220. cursor: 'pointer',
  8221. /**
  8222. * If hover area is bounding rect
  8223. * @name module:/zrender/graphic/Displayable#rectHover
  8224. * @type {string}
  8225. */
  8226. rectHover: false,
  8227. /**
  8228. * Render the element progressively when the value >= 0,
  8229. * usefull for large data.
  8230. * @type {boolean}
  8231. */
  8232. progressive: false,
  8233. /**
  8234. * @type {boolean}
  8235. */
  8236. incremental: false,
  8237. /**
  8238. * Scale ratio for global scale.
  8239. * @type {boolean}
  8240. */
  8241. globalScaleRatio: 1,
  8242. beforeBrush: function (ctx) {},
  8243. afterBrush: function (ctx) {},
  8244. /**
  8245. * Graphic drawing method.
  8246. * @param {CanvasRenderingContext2D} ctx
  8247. */
  8248. // Interface
  8249. brush: function (ctx, prevEl) {},
  8250. /**
  8251. * Get the minimum bounding box.
  8252. * @return {module:zrender/core/BoundingRect}
  8253. */
  8254. // Interface
  8255. getBoundingRect: function () {},
  8256. /**
  8257. * If displayable element contain coord x, y
  8258. * @param {number} x
  8259. * @param {number} y
  8260. * @return {boolean}
  8261. */
  8262. contain: function (x, y) {
  8263. return this.rectContain(x, y);
  8264. },
  8265. /**
  8266. * @param {Function} cb
  8267. * @param {} context
  8268. */
  8269. traverse: function (cb, context) {
  8270. cb.call(context, this);
  8271. },
  8272. /**
  8273. * If bounding rect of element contain coord x, y
  8274. * @param {number} x
  8275. * @param {number} y
  8276. * @return {boolean}
  8277. */
  8278. rectContain: function (x, y) {
  8279. var coord = this.transformCoordToLocal(x, y);
  8280. var rect = this.getBoundingRect();
  8281. return rect.contain(coord[0], coord[1]);
  8282. },
  8283. /**
  8284. * Mark displayable element dirty and refresh next frame
  8285. */
  8286. dirty: function () {
  8287. this.__dirty = this.__dirtyText = true;
  8288. this._rect = null;
  8289. this.__zr && this.__zr.refresh();
  8290. },
  8291. /**
  8292. * If displayable object binded any event
  8293. * @return {boolean}
  8294. */
  8295. // TODO, events bound by bind
  8296. // isSilent: function () {
  8297. // return !(
  8298. // this.hoverable || this.draggable
  8299. // || this.onmousemove || this.onmouseover || this.onmouseout
  8300. // || this.onmousedown || this.onmouseup || this.onclick
  8301. // || this.ondragenter || this.ondragover || this.ondragleave
  8302. // || this.ondrop
  8303. // );
  8304. // },
  8305. /**
  8306. * Alias for animate('style')
  8307. * @param {boolean} loop
  8308. */
  8309. animateStyle: function (loop) {
  8310. return this.animate('style', loop);
  8311. },
  8312. attrKV: function (key, value) {
  8313. if (key !== 'style') {
  8314. Element.prototype.attrKV.call(this, key, value);
  8315. }
  8316. else {
  8317. this.style.set(value);
  8318. }
  8319. },
  8320. /**
  8321. * @param {Object|string} key
  8322. * @param {*} value
  8323. */
  8324. setStyle: function (key, value) {
  8325. this.style.set(key, value);
  8326. this.dirty(false);
  8327. return this;
  8328. },
  8329. /**
  8330. * Use given style object
  8331. * @param {Object} obj
  8332. */
  8333. useStyle: function (obj) {
  8334. this.style = new Style(obj, this);
  8335. this.dirty(false);
  8336. return this;
  8337. },
  8338. /**
  8339. * The string value of `textPosition` needs to be calculated to a real postion.
  8340. * For example, `'inside'` is calculated to `[rect.width/2, rect.height/2]`
  8341. * by default. See `contain/text.js#calculateTextPosition` for more details.
  8342. * But some coutom shapes like "pin", "flag" have center that is not exactly
  8343. * `[width/2, height/2]`. So we provide this hook to customize the calculation
  8344. * for those shapes. It will be called if the `style.textPosition` is a string.
  8345. * @param {Obejct} [out] Prepared out object. If not provided, this method should
  8346. * be responsible for creating one.
  8347. * @param {module:zrender/graphic/Style} style
  8348. * @param {Object} rect {x, y, width, height}
  8349. * @return {Obejct} out The same as the input out.
  8350. * {
  8351. * x: number. mandatory.
  8352. * y: number. mandatory.
  8353. * textAlign: string. optional. use style.textAlign by default.
  8354. * textVerticalAlign: string. optional. use style.textVerticalAlign by default.
  8355. * }
  8356. */
  8357. calculateTextPosition: null
  8358. };
  8359. inherits(Displayable, Element);
  8360. mixin(Displayable, RectText);
  8361. /**
  8362. * @alias zrender/graphic/Image
  8363. * @extends module:zrender/graphic/Displayable
  8364. * @constructor
  8365. * @param {Object} opts
  8366. */
  8367. function ZImage(opts) {
  8368. Displayable.call(this, opts);
  8369. }
  8370. ZImage.prototype = {
  8371. constructor: ZImage,
  8372. type: 'image',
  8373. brush: function (ctx, prevEl) {
  8374. var style = this.style;
  8375. var src = style.image;
  8376. // Must bind each time
  8377. style.bind(ctx, this, prevEl);
  8378. var image = this._image = createOrUpdateImage(
  8379. src,
  8380. this._image,
  8381. this,
  8382. this.onload
  8383. );
  8384. if (!image || !isImageReady(image)) {
  8385. return;
  8386. }
  8387. // 图片已经加载完成
  8388. // if (image.nodeName.toUpperCase() == 'IMG') {
  8389. // if (!image.complete) {
  8390. // return;
  8391. // }
  8392. // }
  8393. // Else is canvas
  8394. var x = style.x || 0;
  8395. var y = style.y || 0;
  8396. var width = style.width;
  8397. var height = style.height;
  8398. var aspect = image.width / image.height;
  8399. if (width == null && height != null) {
  8400. // Keep image/height ratio
  8401. width = height * aspect;
  8402. }
  8403. else if (height == null && width != null) {
  8404. height = width / aspect;
  8405. }
  8406. else if (width == null && height == null) {
  8407. width = image.width;
  8408. height = image.height;
  8409. }
  8410. // 设置transform
  8411. this.setTransform(ctx);
  8412. if (style.sWidth && style.sHeight) {
  8413. var sx = style.sx || 0;
  8414. var sy = style.sy || 0;
  8415. ctx.drawImage(
  8416. image,
  8417. sx, sy, style.sWidth, style.sHeight,
  8418. x, y, width, height
  8419. );
  8420. }
  8421. else if (style.sx && style.sy) {
  8422. var sx = style.sx;
  8423. var sy = style.sy;
  8424. var sWidth = width - sx;
  8425. var sHeight = height - sy;
  8426. ctx.drawImage(
  8427. image,
  8428. sx, sy, sWidth, sHeight,
  8429. x, y, width, height
  8430. );
  8431. }
  8432. else {
  8433. ctx.drawImage(image, x, y, width, height);
  8434. }
  8435. // Draw rect text
  8436. if (style.text != null) {
  8437. // Only restore transform when needs draw text.
  8438. this.restoreTransform(ctx);
  8439. this.drawRectText(ctx, this.getBoundingRect());
  8440. }
  8441. },
  8442. getBoundingRect: function () {
  8443. var style = this.style;
  8444. if (!this._rect) {
  8445. this._rect = new BoundingRect(
  8446. style.x || 0, style.y || 0, style.width || 0, style.height || 0
  8447. );
  8448. }
  8449. return this._rect;
  8450. }
  8451. };
  8452. inherits(ZImage, Displayable);
  8453. var HOVER_LAYER_ZLEVEL = 1e5;
  8454. var CANVAS_ZLEVEL = 314159;
  8455. var EL_AFTER_INCREMENTAL_INC = 0.01;
  8456. var INCREMENTAL_INC = 0.001;
  8457. function parseInt10(val) {
  8458. return parseInt(val, 10);
  8459. }
  8460. function isLayerValid(layer) {
  8461. if (!layer) {
  8462. return false;
  8463. }
  8464. if (layer.__builtin__) {
  8465. return true;
  8466. }
  8467. if (typeof (layer.resize) !== 'function'
  8468. || typeof (layer.refresh) !== 'function'
  8469. ) {
  8470. return false;
  8471. }
  8472. return true;
  8473. }
  8474. var tmpRect = new BoundingRect(0, 0, 0, 0);
  8475. var viewRect = new BoundingRect(0, 0, 0, 0);
  8476. function isDisplayableCulled(el, width, height) {
  8477. tmpRect.copy(el.getBoundingRect());
  8478. if (el.transform) {
  8479. tmpRect.applyTransform(el.transform);
  8480. }
  8481. viewRect.width = width;
  8482. viewRect.height = height;
  8483. return !tmpRect.intersect(viewRect);
  8484. }
  8485. function isClipPathChanged(clipPaths, prevClipPaths) {
  8486. // displayable.__clipPaths can only be `null`/`undefined` or an non-empty array.
  8487. if (clipPaths === prevClipPaths) {
  8488. return false;
  8489. }
  8490. if (!clipPaths || !prevClipPaths || (clipPaths.length !== prevClipPaths.length)) {
  8491. return true;
  8492. }
  8493. for (var i = 0; i < clipPaths.length; i++) {
  8494. if (clipPaths[i] !== prevClipPaths[i]) {
  8495. return true;
  8496. }
  8497. }
  8498. return false;
  8499. }
  8500. function doClip(clipPaths, ctx) {
  8501. for (var i = 0; i < clipPaths.length; i++) {
  8502. var clipPath = clipPaths[i];
  8503. clipPath.setTransform(ctx);
  8504. ctx.beginPath();
  8505. clipPath.buildPath(ctx, clipPath.shape);
  8506. ctx.clip();
  8507. // Transform back
  8508. clipPath.restoreTransform(ctx);
  8509. }
  8510. }
  8511. function createRoot(width, height) {
  8512. var domRoot = document.createElement('div');
  8513. // domRoot.onselectstart = returnFalse; // Avoid page selected
  8514. domRoot.style.cssText = [
  8515. 'position:relative',
  8516. // IOS13 safari probably has a compositing bug (z order of the canvas and the consequent
  8517. // dom does not act as expected) when some of the parent dom has
  8518. // `-webkit-overflow-scrolling: touch;` and the webpage is longer than one screen and
  8519. // the canvas is not at the top part of the page.
  8520. // Check `https://bugs.webkit.org/show_bug.cgi?id=203681` for more details. We remove
  8521. // this `overflow:hidden` to avoid the bug.
  8522. // 'overflow:hidden',
  8523. 'width:' + width + 'px',
  8524. 'height:' + height + 'px',
  8525. 'padding:0',
  8526. 'margin:0',
  8527. 'border-width:0'
  8528. ].join(';') + ';';
  8529. return domRoot;
  8530. }
  8531. /**
  8532. * @alias module:zrender/Painter
  8533. * @constructor
  8534. * @param {HTMLElement} root 绘图容器
  8535. * @param {module:zrender/Storage} storage
  8536. * @param {Object} opts
  8537. */
  8538. var Painter = function (root, storage, opts) {
  8539. this.type = 'canvas';
  8540. // In node environment using node-canvas
  8541. var singleCanvas = !root.nodeName // In node ?
  8542. || root.nodeName.toUpperCase() === 'CANVAS';
  8543. this._opts = opts = extend({}, opts || {});
  8544. /**
  8545. * @type {number}
  8546. */
  8547. this.dpr = opts.devicePixelRatio || devicePixelRatio;
  8548. /**
  8549. * @type {boolean}
  8550. * @private
  8551. */
  8552. this._singleCanvas = singleCanvas;
  8553. /**
  8554. * 绘图容器
  8555. * @type {HTMLElement}
  8556. */
  8557. this.root = root;
  8558. var rootStyle = root.style;
  8559. if (rootStyle) {
  8560. rootStyle['-webkit-tap-highlight-color'] = 'transparent';
  8561. rootStyle['-webkit-user-select'] =
  8562. rootStyle['user-select'] =
  8563. rootStyle['-webkit-touch-callout'] = 'none';
  8564. root.innerHTML = '';
  8565. }
  8566. /**
  8567. * @type {module:zrender/Storage}
  8568. */
  8569. this.storage = storage;
  8570. /**
  8571. * @type {Array.<number>}
  8572. * @private
  8573. */
  8574. var zlevelList = this._zlevelList = [];
  8575. /**
  8576. * @type {Object.<string, module:zrender/Layer>}
  8577. * @private
  8578. */
  8579. var layers = this._layers = {};
  8580. /**
  8581. * @type {Object.<string, Object>}
  8582. * @private
  8583. */
  8584. this._layerConfig = {};
  8585. /**
  8586. * zrender will do compositing when root is a canvas and have multiple zlevels.
  8587. */
  8588. this._needsManuallyCompositing = false;
  8589. if (!singleCanvas) {
  8590. this._width = this._getSize(0);
  8591. this._height = this._getSize(1);
  8592. var domRoot = this._domRoot = createRoot(
  8593. this._width, this._height
  8594. );
  8595. root.appendChild(domRoot);
  8596. }
  8597. else {
  8598. var width = root.width;
  8599. var height = root.height;
  8600. if (opts.width != null) {
  8601. width = opts.width;
  8602. }
  8603. if (opts.height != null) {
  8604. height = opts.height;
  8605. }
  8606. this.dpr = opts.devicePixelRatio || 1;
  8607. // Use canvas width and height directly
  8608. root.width = width * this.dpr;
  8609. root.height = height * this.dpr;
  8610. this._width = width;
  8611. this._height = height;
  8612. // Create layer if only one given canvas
  8613. // Device can be specified to create a high dpi image.
  8614. var mainLayer = new Layer(root, this, this.dpr);
  8615. mainLayer.__builtin__ = true;
  8616. mainLayer.initContext();
  8617. // FIXME Use canvas width and height
  8618. // mainLayer.resize(width, height);
  8619. layers[CANVAS_ZLEVEL] = mainLayer;
  8620. mainLayer.zlevel = CANVAS_ZLEVEL;
  8621. // Not use common zlevel.
  8622. zlevelList.push(CANVAS_ZLEVEL);
  8623. this._domRoot = root;
  8624. }
  8625. /**
  8626. * @type {module:zrender/Layer}
  8627. * @private
  8628. */
  8629. this._hoverlayer = null;
  8630. this._hoverElements = [];
  8631. };
  8632. Painter.prototype = {
  8633. constructor: Painter,
  8634. getType: function () {
  8635. return 'canvas';
  8636. },
  8637. /**
  8638. * If painter use a single canvas
  8639. * @return {boolean}
  8640. */
  8641. isSingleCanvas: function () {
  8642. return this._singleCanvas;
  8643. },
  8644. /**
  8645. * @return {HTMLDivElement}
  8646. */
  8647. getViewportRoot: function () {
  8648. return this._domRoot;
  8649. },
  8650. getViewportRootOffset: function () {
  8651. var viewportRoot = this.getViewportRoot();
  8652. if (viewportRoot) {
  8653. return {
  8654. offsetLeft: viewportRoot.offsetLeft || 0,
  8655. offsetTop: viewportRoot.offsetTop || 0
  8656. };
  8657. }
  8658. },
  8659. /**
  8660. * 刷新
  8661. * @param {boolean} [paintAll=false] 强制绘制所有displayable
  8662. */
  8663. refresh: function (paintAll) {
  8664. var list = this.storage.getDisplayList(true);
  8665. var zlevelList = this._zlevelList;
  8666. this._redrawId = Math.random();
  8667. this._paintList(list, paintAll, this._redrawId);
  8668. // Paint custum layers
  8669. for (var i = 0; i < zlevelList.length; i++) {
  8670. var z = zlevelList[i];
  8671. var layer = this._layers[z];
  8672. if (!layer.__builtin__ && layer.refresh) {
  8673. var clearColor = i === 0 ? this._backgroundColor : null;
  8674. layer.refresh(clearColor);
  8675. }
  8676. }
  8677. this.refreshHover();
  8678. return this;
  8679. },
  8680. addHover: function (el, hoverStyle) {
  8681. if (el.__hoverMir) {
  8682. return;
  8683. }
  8684. var elMirror = new el.constructor({
  8685. style: el.style,
  8686. shape: el.shape,
  8687. z: el.z,
  8688. z2: el.z2,
  8689. silent: el.silent
  8690. });
  8691. elMirror.__from = el;
  8692. el.__hoverMir = elMirror;
  8693. hoverStyle && elMirror.setStyle(hoverStyle);
  8694. this._hoverElements.push(elMirror);
  8695. return elMirror;
  8696. },
  8697. removeHover: function (el) {
  8698. var elMirror = el.__hoverMir;
  8699. var hoverElements = this._hoverElements;
  8700. var idx = indexOf(hoverElements, elMirror);
  8701. if (idx >= 0) {
  8702. hoverElements.splice(idx, 1);
  8703. }
  8704. el.__hoverMir = null;
  8705. },
  8706. clearHover: function (el) {
  8707. var hoverElements = this._hoverElements;
  8708. for (var i = 0; i < hoverElements.length; i++) {
  8709. var from = hoverElements[i].__from;
  8710. if (from) {
  8711. from.__hoverMir = null;
  8712. }
  8713. }
  8714. hoverElements.length = 0;
  8715. },
  8716. refreshHover: function () {
  8717. var hoverElements = this._hoverElements;
  8718. var len = hoverElements.length;
  8719. var hoverLayer = this._hoverlayer;
  8720. hoverLayer && hoverLayer.clear();
  8721. if (!len) {
  8722. return;
  8723. }
  8724. sort(hoverElements, this.storage.displayableSortFunc);
  8725. // Use a extream large zlevel
  8726. // FIXME?
  8727. if (!hoverLayer) {
  8728. hoverLayer = this._hoverlayer = this.getLayer(HOVER_LAYER_ZLEVEL);
  8729. }
  8730. var scope = {};
  8731. hoverLayer.ctx.save();
  8732. for (var i = 0; i < len;) {
  8733. var el = hoverElements[i];
  8734. var originalEl = el.__from;
  8735. // Original el is removed
  8736. // PENDING
  8737. if (!(originalEl && originalEl.__zr)) {
  8738. hoverElements.splice(i, 1);
  8739. originalEl.__hoverMir = null;
  8740. len--;
  8741. continue;
  8742. }
  8743. i++;
  8744. // Use transform
  8745. // FIXME style and shape ?
  8746. if (!originalEl.invisible) {
  8747. el.transform = originalEl.transform;
  8748. el.invTransform = originalEl.invTransform;
  8749. el.__clipPaths = originalEl.__clipPaths;
  8750. // el.
  8751. this._doPaintEl(el, hoverLayer, true, scope);
  8752. }
  8753. }
  8754. hoverLayer.ctx.restore();
  8755. },
  8756. getHoverLayer: function () {
  8757. return this.getLayer(HOVER_LAYER_ZLEVEL);
  8758. },
  8759. _paintList: function (list, paintAll, redrawId) {
  8760. if (this._redrawId !== redrawId) {
  8761. return;
  8762. }
  8763. paintAll = paintAll || false;
  8764. this._updateLayerStatus(list);
  8765. var finished = this._doPaintList(list, paintAll);
  8766. if (this._needsManuallyCompositing) {
  8767. this._compositeManually();
  8768. }
  8769. if (!finished) {
  8770. var self = this;
  8771. requestAnimationFrame(function () {
  8772. self._paintList(list, paintAll, redrawId);
  8773. });
  8774. }
  8775. },
  8776. _compositeManually: function () {
  8777. var ctx = this.getLayer(CANVAS_ZLEVEL).ctx;
  8778. var width = this._domRoot.width;
  8779. var height = this._domRoot.height;
  8780. ctx.clearRect(0, 0, width, height);
  8781. // PENDING, If only builtin layer?
  8782. this.eachBuiltinLayer(function (layer) {
  8783. if (layer.virtual) {
  8784. ctx.drawImage(layer.dom, 0, 0, width, height);
  8785. }
  8786. });
  8787. },
  8788. _doPaintList: function (list, paintAll) {
  8789. var layerList = [];
  8790. for (var zi = 0; zi < this._zlevelList.length; zi++) {
  8791. var zlevel = this._zlevelList[zi];
  8792. var layer = this._layers[zlevel];
  8793. if (layer.__builtin__
  8794. && layer !== this._hoverlayer
  8795. && (layer.__dirty || paintAll)
  8796. ) {
  8797. layerList.push(layer);
  8798. }
  8799. }
  8800. var finished = true;
  8801. for (var k = 0; k < layerList.length; k++) {
  8802. var layer = layerList[k];
  8803. var ctx = layer.ctx;
  8804. var scope = {};
  8805. ctx.save();
  8806. var start = paintAll ? layer.__startIndex : layer.__drawIndex;
  8807. var useTimer = !paintAll && layer.incremental && Date.now;
  8808. var startTime = useTimer && Date.now();
  8809. var clearColor = layer.zlevel === this._zlevelList[0]
  8810. ? this._backgroundColor : null;
  8811. // All elements in this layer are cleared.
  8812. if (layer.__startIndex === layer.__endIndex) {
  8813. layer.clear(false, clearColor);
  8814. }
  8815. else if (start === layer.__startIndex) {
  8816. var firstEl = list[start];
  8817. if (!firstEl.incremental || !firstEl.notClear || paintAll) {
  8818. layer.clear(false, clearColor);
  8819. }
  8820. }
  8821. if (start === -1) {
  8822. console.error('For some unknown reason. drawIndex is -1');
  8823. start = layer.__startIndex;
  8824. }
  8825. for (var i = start; i < layer.__endIndex; i++) {
  8826. var el = list[i];
  8827. this._doPaintEl(el, layer, paintAll, scope);
  8828. el.__dirty = el.__dirtyText = false;
  8829. if (useTimer) {
  8830. // Date.now can be executed in 13,025,305 ops/second.
  8831. var dTime = Date.now() - startTime;
  8832. // Give 15 millisecond to draw.
  8833. // The rest elements will be drawn in the next frame.
  8834. if (dTime > 15) {
  8835. break;
  8836. }
  8837. }
  8838. }
  8839. layer.__drawIndex = i;
  8840. if (layer.__drawIndex < layer.__endIndex) {
  8841. finished = false;
  8842. }
  8843. if (scope.prevElClipPaths) {
  8844. // Needs restore the state. If last drawn element is in the clipping area.
  8845. ctx.restore();
  8846. }
  8847. ctx.restore();
  8848. }
  8849. if (env$1.wxa) {
  8850. // Flush for weixin application
  8851. each$1(this._layers, function (layer) {
  8852. if (layer && layer.ctx && layer.ctx.draw) {
  8853. layer.ctx.draw();
  8854. }
  8855. });
  8856. }
  8857. return finished;
  8858. },
  8859. _doPaintEl: function (el, currentLayer, forcePaint, scope) {
  8860. var ctx = currentLayer.ctx;
  8861. var m = el.transform;
  8862. if (
  8863. (currentLayer.__dirty || forcePaint)
  8864. // Ignore invisible element
  8865. && !el.invisible
  8866. // Ignore transparent element
  8867. && el.style.opacity !== 0
  8868. // Ignore scale 0 element, in some environment like node-canvas
  8869. // Draw a scale 0 element can cause all following draw wrong
  8870. // And setTransform with scale 0 will cause set back transform failed.
  8871. && !(m && !m[0] && !m[3])
  8872. // Ignore culled element
  8873. && !(el.culling && isDisplayableCulled(el, this._width, this._height))
  8874. ) {
  8875. var clipPaths = el.__clipPaths;
  8876. var prevElClipPaths = scope.prevElClipPaths;
  8877. // Optimize when clipping on group with several elements
  8878. if (!prevElClipPaths || isClipPathChanged(clipPaths, prevElClipPaths)) {
  8879. // If has previous clipping state, restore from it
  8880. if (prevElClipPaths) {
  8881. ctx.restore();
  8882. scope.prevElClipPaths = null;
  8883. // Reset prevEl since context has been restored
  8884. scope.prevEl = null;
  8885. }
  8886. // New clipping state
  8887. if (clipPaths) {
  8888. ctx.save();
  8889. doClip(clipPaths, ctx);
  8890. scope.prevElClipPaths = clipPaths;
  8891. }
  8892. }
  8893. el.beforeBrush && el.beforeBrush(ctx);
  8894. el.brush(ctx, scope.prevEl || null);
  8895. scope.prevEl = el;
  8896. el.afterBrush && el.afterBrush(ctx);
  8897. }
  8898. },
  8899. /**
  8900. * 获取 zlevel 所在层,如果不存在则会创建一个新的层
  8901. * @param {number} zlevel
  8902. * @param {boolean} virtual Virtual layer will not be inserted into dom.
  8903. * @return {module:zrender/Layer}
  8904. */
  8905. getLayer: function (zlevel, virtual) {
  8906. if (this._singleCanvas && !this._needsManuallyCompositing) {
  8907. zlevel = CANVAS_ZLEVEL;
  8908. }
  8909. var layer = this._layers[zlevel];
  8910. if (!layer) {
  8911. // Create a new layer
  8912. layer = new Layer('zr_' + zlevel, this, this.dpr);
  8913. layer.zlevel = zlevel;
  8914. layer.__builtin__ = true;
  8915. if (this._layerConfig[zlevel]) {
  8916. merge(layer, this._layerConfig[zlevel], true);
  8917. }
  8918. // TODO Remove EL_AFTER_INCREMENTAL_INC magic number
  8919. else if (this._layerConfig[zlevel - EL_AFTER_INCREMENTAL_INC]) {
  8920. merge(layer, this._layerConfig[zlevel - EL_AFTER_INCREMENTAL_INC], true);
  8921. }
  8922. if (virtual) {
  8923. layer.virtual = virtual;
  8924. }
  8925. this.insertLayer(zlevel, layer);
  8926. // Context is created after dom inserted to document
  8927. // Or excanvas will get 0px clientWidth and clientHeight
  8928. layer.initContext();
  8929. }
  8930. return layer;
  8931. },
  8932. insertLayer: function (zlevel, layer) {
  8933. var layersMap = this._layers;
  8934. var zlevelList = this._zlevelList;
  8935. var len = zlevelList.length;
  8936. var prevLayer = null;
  8937. var i = -1;
  8938. var domRoot = this._domRoot;
  8939. if (layersMap[zlevel]) {
  8940. logError$1('ZLevel ' + zlevel + ' has been used already');
  8941. return;
  8942. }
  8943. // Check if is a valid layer
  8944. if (!isLayerValid(layer)) {
  8945. logError$1('Layer of zlevel ' + zlevel + ' is not valid');
  8946. return;
  8947. }
  8948. if (len > 0 && zlevel > zlevelList[0]) {
  8949. for (i = 0; i < len - 1; i++) {
  8950. if (
  8951. zlevelList[i] < zlevel
  8952. && zlevelList[i + 1] > zlevel
  8953. ) {
  8954. break;
  8955. }
  8956. }
  8957. prevLayer = layersMap[zlevelList[i]];
  8958. }
  8959. zlevelList.splice(i + 1, 0, zlevel);
  8960. layersMap[zlevel] = layer;
  8961. // Vitual layer will not directly show on the screen.
  8962. // (It can be a WebGL layer and assigned to a ZImage element)
  8963. // But it still under management of zrender.
  8964. if (!layer.virtual) {
  8965. if (prevLayer) {
  8966. var prevDom = prevLayer.dom;
  8967. if (prevDom.nextSibling) {
  8968. domRoot.insertBefore(
  8969. layer.dom,
  8970. prevDom.nextSibling
  8971. );
  8972. }
  8973. else {
  8974. domRoot.appendChild(layer.dom);
  8975. }
  8976. }
  8977. else {
  8978. if (domRoot.firstChild) {
  8979. domRoot.insertBefore(layer.dom, domRoot.firstChild);
  8980. }
  8981. else {
  8982. domRoot.appendChild(layer.dom);
  8983. }
  8984. }
  8985. }
  8986. },
  8987. // Iterate each layer
  8988. eachLayer: function (cb, context) {
  8989. var zlevelList = this._zlevelList;
  8990. var z;
  8991. var i;
  8992. for (i = 0; i < zlevelList.length; i++) {
  8993. z = zlevelList[i];
  8994. cb.call(context, this._layers[z], z);
  8995. }
  8996. },
  8997. // Iterate each buildin layer
  8998. eachBuiltinLayer: function (cb, context) {
  8999. var zlevelList = this._zlevelList;
  9000. var layer;
  9001. var z;
  9002. var i;
  9003. for (i = 0; i < zlevelList.length; i++) {
  9004. z = zlevelList[i];
  9005. layer = this._layers[z];
  9006. if (layer.__builtin__) {
  9007. cb.call(context, layer, z);
  9008. }
  9009. }
  9010. },
  9011. // Iterate each other layer except buildin layer
  9012. eachOtherLayer: function (cb, context) {
  9013. var zlevelList = this._zlevelList;
  9014. var layer;
  9015. var z;
  9016. var i;
  9017. for (i = 0; i < zlevelList.length; i++) {
  9018. z = zlevelList[i];
  9019. layer = this._layers[z];
  9020. if (!layer.__builtin__) {
  9021. cb.call(context, layer, z);
  9022. }
  9023. }
  9024. },
  9025. /**
  9026. * 获取所有已创建的层
  9027. * @param {Array.<module:zrender/Layer>} [prevLayer]
  9028. */
  9029. getLayers: function () {
  9030. return this._layers;
  9031. },
  9032. _updateLayerStatus: function (list) {
  9033. this.eachBuiltinLayer(function (layer, z) {
  9034. layer.__dirty = layer.__used = false;
  9035. });
  9036. function updatePrevLayer(idx) {
  9037. if (prevLayer) {
  9038. if (prevLayer.__endIndex !== idx) {
  9039. prevLayer.__dirty = true;
  9040. }
  9041. prevLayer.__endIndex = idx;
  9042. }
  9043. }
  9044. if (this._singleCanvas) {
  9045. for (var i = 1; i < list.length; i++) {
  9046. var el = list[i];
  9047. if (el.zlevel !== list[i - 1].zlevel || el.incremental) {
  9048. this._needsManuallyCompositing = true;
  9049. break;
  9050. }
  9051. }
  9052. }
  9053. var prevLayer = null;
  9054. var incrementalLayerCount = 0;
  9055. var prevZlevel;
  9056. for (var i = 0; i < list.length; i++) {
  9057. var el = list[i];
  9058. var zlevel = el.zlevel;
  9059. var layer;
  9060. if (prevZlevel !== zlevel) {
  9061. prevZlevel = zlevel;
  9062. incrementalLayerCount = 0;
  9063. }
  9064. // TODO Not use magic number on zlevel.
  9065. // Each layer with increment element can be separated to 3 layers.
  9066. // (Other Element drawn after incremental element)
  9067. // -----------------zlevel + EL_AFTER_INCREMENTAL_INC--------------------
  9068. // (Incremental element)
  9069. // ----------------------zlevel + INCREMENTAL_INC------------------------
  9070. // (Element drawn before incremental element)
  9071. // --------------------------------zlevel--------------------------------
  9072. if (el.incremental) {
  9073. layer = this.getLayer(zlevel + INCREMENTAL_INC, this._needsManuallyCompositing);
  9074. layer.incremental = true;
  9075. incrementalLayerCount = 1;
  9076. }
  9077. else {
  9078. layer = this.getLayer(
  9079. zlevel + (incrementalLayerCount > 0 ? EL_AFTER_INCREMENTAL_INC : 0),
  9080. this._needsManuallyCompositing
  9081. );
  9082. }
  9083. if (!layer.__builtin__) {
  9084. logError$1('ZLevel ' + zlevel + ' has been used by unkown layer ' + layer.id);
  9085. }
  9086. if (layer !== prevLayer) {
  9087. layer.__used = true;
  9088. if (layer.__startIndex !== i) {
  9089. layer.__dirty = true;
  9090. }
  9091. layer.__startIndex = i;
  9092. if (!layer.incremental) {
  9093. layer.__drawIndex = i;
  9094. }
  9095. else {
  9096. // Mark layer draw index needs to update.
  9097. layer.__drawIndex = -1;
  9098. }
  9099. updatePrevLayer(i);
  9100. prevLayer = layer;
  9101. }
  9102. if (el.__dirty) {
  9103. layer.__dirty = true;
  9104. if (layer.incremental && layer.__drawIndex < 0) {
  9105. // Start draw from the first dirty element.
  9106. layer.__drawIndex = i;
  9107. }
  9108. }
  9109. }
  9110. updatePrevLayer(i);
  9111. this.eachBuiltinLayer(function (layer, z) {
  9112. // Used in last frame but not in this frame. Needs clear
  9113. if (!layer.__used && layer.getElementCount() > 0) {
  9114. layer.__dirty = true;
  9115. layer.__startIndex = layer.__endIndex = layer.__drawIndex = 0;
  9116. }
  9117. // For incremental layer. In case start index changed and no elements are dirty.
  9118. if (layer.__dirty && layer.__drawIndex < 0) {
  9119. layer.__drawIndex = layer.__startIndex;
  9120. }
  9121. });
  9122. },
  9123. /**
  9124. * 清除hover层外所有内容
  9125. */
  9126. clear: function () {
  9127. this.eachBuiltinLayer(this._clearLayer);
  9128. return this;
  9129. },
  9130. _clearLayer: function (layer) {
  9131. layer.clear();
  9132. },
  9133. setBackgroundColor: function (backgroundColor) {
  9134. this._backgroundColor = backgroundColor;
  9135. },
  9136. /**
  9137. * 修改指定zlevel的绘制参数
  9138. *
  9139. * @param {string} zlevel
  9140. * @param {Object} config 配置对象
  9141. * @param {string} [config.clearColor=0] 每次清空画布的颜色
  9142. * @param {string} [config.motionBlur=false] 是否开启动态模糊
  9143. * @param {number} [config.lastFrameAlpha=0.7]
  9144. * 在开启动态模糊的时候使用,与上一帧混合的alpha值,值越大尾迹越明显
  9145. */
  9146. configLayer: function (zlevel, config) {
  9147. if (config) {
  9148. var layerConfig = this._layerConfig;
  9149. if (!layerConfig[zlevel]) {
  9150. layerConfig[zlevel] = config;
  9151. }
  9152. else {
  9153. merge(layerConfig[zlevel], config, true);
  9154. }
  9155. for (var i = 0; i < this._zlevelList.length; i++) {
  9156. var _zlevel = this._zlevelList[i];
  9157. // TODO Remove EL_AFTER_INCREMENTAL_INC magic number
  9158. if (_zlevel === zlevel || _zlevel === zlevel + EL_AFTER_INCREMENTAL_INC) {
  9159. var layer = this._layers[_zlevel];
  9160. merge(layer, layerConfig[zlevel], true);
  9161. }
  9162. }
  9163. }
  9164. },
  9165. /**
  9166. * 删除指定层
  9167. * @param {number} zlevel 层所在的zlevel
  9168. */
  9169. delLayer: function (zlevel) {
  9170. var layers = this._layers;
  9171. var zlevelList = this._zlevelList;
  9172. var layer = layers[zlevel];
  9173. if (!layer) {
  9174. return;
  9175. }
  9176. layer.dom.parentNode.removeChild(layer.dom);
  9177. delete layers[zlevel];
  9178. zlevelList.splice(indexOf(zlevelList, zlevel), 1);
  9179. },
  9180. /**
  9181. * 区域大小变化后重绘
  9182. */
  9183. resize: function (width, height) {
  9184. if (!this._domRoot.style) { // Maybe in node or worker
  9185. if (width == null || height == null) {
  9186. return;
  9187. }
  9188. this._width = width;
  9189. this._height = height;
  9190. this.getLayer(CANVAS_ZLEVEL).resize(width, height);
  9191. }
  9192. else {
  9193. var domRoot = this._domRoot;
  9194. // FIXME Why ?
  9195. domRoot.style.display = 'none';
  9196. // Save input w/h
  9197. var opts = this._opts;
  9198. width != null && (opts.width = width);
  9199. height != null && (opts.height = height);
  9200. width = this._getSize(0);
  9201. height = this._getSize(1);
  9202. domRoot.style.display = '';
  9203. // 优化没有实际改变的resize
  9204. if (this._width !== width || height !== this._height) {
  9205. domRoot.style.width = width + 'px';
  9206. domRoot.style.height = height + 'px';
  9207. for (var id in this._layers) {
  9208. if (this._layers.hasOwnProperty(id)) {
  9209. this._layers[id].resize(width, height);
  9210. }
  9211. }
  9212. each$1(this._progressiveLayers, function (layer) {
  9213. layer.resize(width, height);
  9214. });
  9215. this.refresh(true);
  9216. }
  9217. this._width = width;
  9218. this._height = height;
  9219. }
  9220. return this;
  9221. },
  9222. /**
  9223. * 清除单独的一个层
  9224. * @param {number} zlevel
  9225. */
  9226. clearLayer: function (zlevel) {
  9227. var layer = this._layers[zlevel];
  9228. if (layer) {
  9229. layer.clear();
  9230. }
  9231. },
  9232. /**
  9233. * 释放
  9234. */
  9235. dispose: function () {
  9236. this.root.innerHTML = '';
  9237. this.root =
  9238. this.storage =
  9239. this._domRoot =
  9240. this._layers = null;
  9241. },
  9242. /**
  9243. * Get canvas which has all thing rendered
  9244. * @param {Object} opts
  9245. * @param {string} [opts.backgroundColor]
  9246. * @param {number} [opts.pixelRatio]
  9247. */
  9248. getRenderedCanvas: function (opts) {
  9249. opts = opts || {};
  9250. if (this._singleCanvas && !this._compositeManually) {
  9251. return this._layers[CANVAS_ZLEVEL].dom;
  9252. }
  9253. var imageLayer = new Layer('image', this, opts.pixelRatio || this.dpr);
  9254. imageLayer.initContext();
  9255. imageLayer.clear(false, opts.backgroundColor || this._backgroundColor);
  9256. if (opts.pixelRatio <= this.dpr) {
  9257. this.refresh();
  9258. var width = imageLayer.dom.width;
  9259. var height = imageLayer.dom.height;
  9260. var ctx = imageLayer.ctx;
  9261. this.eachLayer(function (layer) {
  9262. if (layer.__builtin__) {
  9263. ctx.drawImage(layer.dom, 0, 0, width, height);
  9264. }
  9265. else if (layer.renderToCanvas) {
  9266. imageLayer.ctx.save();
  9267. layer.renderToCanvas(imageLayer.ctx);
  9268. imageLayer.ctx.restore();
  9269. }
  9270. });
  9271. }
  9272. else {
  9273. // PENDING, echarts-gl and incremental rendering.
  9274. var scope = {};
  9275. var displayList = this.storage.getDisplayList(true);
  9276. for (var i = 0; i < displayList.length; i++) {
  9277. var el = displayList[i];
  9278. this._doPaintEl(el, imageLayer, true, scope);
  9279. }
  9280. }
  9281. return imageLayer.dom;
  9282. },
  9283. /**
  9284. * 获取绘图区域宽度
  9285. */
  9286. getWidth: function () {
  9287. return this._width;
  9288. },
  9289. /**
  9290. * 获取绘图区域高度
  9291. */
  9292. getHeight: function () {
  9293. return this._height;
  9294. },
  9295. _getSize: function (whIdx) {
  9296. var opts = this._opts;
  9297. var wh = ['width', 'height'][whIdx];
  9298. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  9299. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  9300. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  9301. if (opts[wh] != null && opts[wh] !== 'auto') {
  9302. return parseFloat(opts[wh]);
  9303. }
  9304. var root = this.root;
  9305. // IE8 does not support getComputedStyle, but it use VML.
  9306. var stl = document.defaultView.getComputedStyle(root);
  9307. return (
  9308. (root[cwh] || parseInt10(stl[wh]) || parseInt10(root.style[wh]))
  9309. - (parseInt10(stl[plt]) || 0)
  9310. - (parseInt10(stl[prb]) || 0)
  9311. ) | 0;
  9312. },
  9313. pathToImage: function (path, dpr) {
  9314. dpr = dpr || this.dpr;
  9315. var canvas = document.createElement('canvas');
  9316. var ctx = canvas.getContext('2d');
  9317. var rect = path.getBoundingRect();
  9318. var style = path.style;
  9319. var shadowBlurSize = style.shadowBlur * dpr;
  9320. var shadowOffsetX = style.shadowOffsetX * dpr;
  9321. var shadowOffsetY = style.shadowOffsetY * dpr;
  9322. var lineWidth = style.hasStroke() ? style.lineWidth : 0;
  9323. var leftMargin = Math.max(lineWidth / 2, -shadowOffsetX + shadowBlurSize);
  9324. var rightMargin = Math.max(lineWidth / 2, shadowOffsetX + shadowBlurSize);
  9325. var topMargin = Math.max(lineWidth / 2, -shadowOffsetY + shadowBlurSize);
  9326. var bottomMargin = Math.max(lineWidth / 2, shadowOffsetY + shadowBlurSize);
  9327. var width = rect.width + leftMargin + rightMargin;
  9328. var height = rect.height + topMargin + bottomMargin;
  9329. canvas.width = width * dpr;
  9330. canvas.height = height * dpr;
  9331. ctx.scale(dpr, dpr);
  9332. ctx.clearRect(0, 0, width, height);
  9333. ctx.dpr = dpr;
  9334. var pathTransform = {
  9335. position: path.position,
  9336. rotation: path.rotation,
  9337. scale: path.scale
  9338. };
  9339. path.position = [leftMargin - rect.x, topMargin - rect.y];
  9340. path.rotation = 0;
  9341. path.scale = [1, 1];
  9342. path.updateTransform();
  9343. if (path) {
  9344. path.brush(ctx);
  9345. }
  9346. var ImageShape = ZImage;
  9347. var imgShape = new ImageShape({
  9348. style: {
  9349. x: 0,
  9350. y: 0,
  9351. image: canvas
  9352. }
  9353. });
  9354. if (pathTransform.position != null) {
  9355. imgShape.position = path.position = pathTransform.position;
  9356. }
  9357. if (pathTransform.rotation != null) {
  9358. imgShape.rotation = path.rotation = pathTransform.rotation;
  9359. }
  9360. if (pathTransform.scale != null) {
  9361. imgShape.scale = path.scale = pathTransform.scale;
  9362. }
  9363. return imgShape;
  9364. }
  9365. };
  9366. /**
  9367. * Animation main class, dispatch and manage all animation controllers
  9368. *
  9369. * @module zrender/animation/Animation
  9370. * @author pissang(https://github.com/pissang)
  9371. */
  9372. // TODO Additive animation
  9373. // http://iosoteric.com/additive-animations-animatewithduration-in-ios-8/
  9374. // https://developer.apple.com/videos/wwdc2014/#236
  9375. /**
  9376. * @typedef {Object} IZRenderStage
  9377. * @property {Function} update
  9378. */
  9379. /**
  9380. * @alias module:zrender/animation/Animation
  9381. * @constructor
  9382. * @param {Object} [options]
  9383. * @param {Function} [options.onframe]
  9384. * @param {IZRenderStage} [options.stage]
  9385. * @example
  9386. * var animation = new Animation();
  9387. * var obj = {
  9388. * x: 100,
  9389. * y: 100
  9390. * };
  9391. * animation.animate(node.position)
  9392. * .when(1000, {
  9393. * x: 500,
  9394. * y: 500
  9395. * })
  9396. * .when(2000, {
  9397. * x: 100,
  9398. * y: 100
  9399. * })
  9400. * .start('spline');
  9401. */
  9402. var Animation = function (options) {
  9403. options = options || {};
  9404. this.stage = options.stage || {};
  9405. this.onframe = options.onframe || function () {};
  9406. // private properties
  9407. this._clips = [];
  9408. this._running = false;
  9409. this._time;
  9410. this._pausedTime;
  9411. this._pauseStart;
  9412. this._paused = false;
  9413. Eventful.call(this);
  9414. };
  9415. Animation.prototype = {
  9416. constructor: Animation,
  9417. /**
  9418. * Add clip
  9419. * @param {module:zrender/animation/Clip} clip
  9420. */
  9421. addClip: function (clip) {
  9422. this._clips.push(clip);
  9423. },
  9424. /**
  9425. * Add animator
  9426. * @param {module:zrender/animation/Animator} animator
  9427. */
  9428. addAnimator: function (animator) {
  9429. animator.animation = this;
  9430. var clips = animator.getClips();
  9431. for (var i = 0; i < clips.length; i++) {
  9432. this.addClip(clips[i]);
  9433. }
  9434. },
  9435. /**
  9436. * Delete animation clip
  9437. * @param {module:zrender/animation/Clip} clip
  9438. */
  9439. removeClip: function (clip) {
  9440. var idx = indexOf(this._clips, clip);
  9441. if (idx >= 0) {
  9442. this._clips.splice(idx, 1);
  9443. }
  9444. },
  9445. /**
  9446. * Delete animation clip
  9447. * @param {module:zrender/animation/Animator} animator
  9448. */
  9449. removeAnimator: function (animator) {
  9450. var clips = animator.getClips();
  9451. for (var i = 0; i < clips.length; i++) {
  9452. this.removeClip(clips[i]);
  9453. }
  9454. animator.animation = null;
  9455. },
  9456. _update: function () {
  9457. var time = new Date().getTime() - this._pausedTime;
  9458. var delta = time - this._time;
  9459. var clips = this._clips;
  9460. var len = clips.length;
  9461. var deferredEvents = [];
  9462. var deferredClips = [];
  9463. for (var i = 0; i < len; i++) {
  9464. var clip = clips[i];
  9465. var e = clip.step(time, delta);
  9466. // Throw out the events need to be called after
  9467. // stage.update, like destroy
  9468. if (e) {
  9469. deferredEvents.push(e);
  9470. deferredClips.push(clip);
  9471. }
  9472. }
  9473. // Remove the finished clip
  9474. for (var i = 0; i < len;) {
  9475. if (clips[i]._needsRemove) {
  9476. clips[i] = clips[len - 1];
  9477. clips.pop();
  9478. len--;
  9479. }
  9480. else {
  9481. i++;
  9482. }
  9483. }
  9484. len = deferredEvents.length;
  9485. for (var i = 0; i < len; i++) {
  9486. deferredClips[i].fire(deferredEvents[i]);
  9487. }
  9488. this._time = time;
  9489. this.onframe(delta);
  9490. // 'frame' should be triggered before stage, because upper application
  9491. // depends on the sequence (e.g., echarts-stream and finish
  9492. // event judge)
  9493. this.trigger('frame', delta);
  9494. if (this.stage.update) {
  9495. this.stage.update();
  9496. }
  9497. },
  9498. _startLoop: function () {
  9499. var self = this;
  9500. this._running = true;
  9501. function step() {
  9502. if (self._running) {
  9503. requestAnimationFrame(step);
  9504. !self._paused && self._update();
  9505. }
  9506. }
  9507. requestAnimationFrame(step);
  9508. },
  9509. /**
  9510. * Start animation.
  9511. */
  9512. start: function () {
  9513. this._time = new Date().getTime();
  9514. this._pausedTime = 0;
  9515. this._startLoop();
  9516. },
  9517. /**
  9518. * Stop animation.
  9519. */
  9520. stop: function () {
  9521. this._running = false;
  9522. },
  9523. /**
  9524. * Pause animation.
  9525. */
  9526. pause: function () {
  9527. if (!this._paused) {
  9528. this._pauseStart = new Date().getTime();
  9529. this._paused = true;
  9530. }
  9531. },
  9532. /**
  9533. * Resume animation.
  9534. */
  9535. resume: function () {
  9536. if (this._paused) {
  9537. this._pausedTime += (new Date().getTime()) - this._pauseStart;
  9538. this._paused = false;
  9539. }
  9540. },
  9541. /**
  9542. * Clear animation.
  9543. */
  9544. clear: function () {
  9545. this._clips = [];
  9546. },
  9547. /**
  9548. * Whether animation finished.
  9549. */
  9550. isFinished: function () {
  9551. return !this._clips.length;
  9552. },
  9553. /**
  9554. * Creat animator for a target, whose props can be animated.
  9555. *
  9556. * @param {Object} target
  9557. * @param {Object} options
  9558. * @param {boolean} [options.loop=false] Whether loop animation.
  9559. * @param {Function} [options.getter=null] Get value from target.
  9560. * @param {Function} [options.setter=null] Set value to target.
  9561. * @return {module:zrender/animation/Animation~Animator}
  9562. */
  9563. // TODO Gap
  9564. animate: function (target, options) {
  9565. options = options || {};
  9566. var animator = new Animator(
  9567. target,
  9568. options.loop,
  9569. options.getter,
  9570. options.setter
  9571. );
  9572. this.addAnimator(animator);
  9573. return animator;
  9574. }
  9575. };
  9576. mixin(Animation, Eventful);
  9577. /* global document */
  9578. var TOUCH_CLICK_DELAY = 300;
  9579. var globalEventSupported = env$1.domSupported;
  9580. var localNativeListenerNames = (function () {
  9581. var mouseHandlerNames = [
  9582. 'click', 'dblclick', 'mousewheel', 'mouseout',
  9583. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  9584. ];
  9585. var touchHandlerNames = [
  9586. 'touchstart', 'touchend', 'touchmove'
  9587. ];
  9588. var pointerEventNameMap = {
  9589. pointerdown: 1, pointerup: 1, pointermove: 1, pointerout: 1
  9590. };
  9591. var pointerHandlerNames = map(mouseHandlerNames, function (name) {
  9592. var nm = name.replace('mouse', 'pointer');
  9593. return pointerEventNameMap.hasOwnProperty(nm) ? nm : name;
  9594. });
  9595. return {
  9596. mouse: mouseHandlerNames,
  9597. touch: touchHandlerNames,
  9598. pointer: pointerHandlerNames
  9599. };
  9600. })();
  9601. var globalNativeListenerNames = {
  9602. mouse: ['mousemove', 'mouseup'],
  9603. pointer: ['pointermove', 'pointerup']
  9604. };
  9605. function eventNameFix(name) {
  9606. return (name === 'mousewheel' && env$1.browser.firefox) ? 'DOMMouseScroll' : name;
  9607. }
  9608. function isPointerFromTouch(event) {
  9609. var pointerType = event.pointerType;
  9610. return pointerType === 'pen' || pointerType === 'touch';
  9611. }
  9612. // function useMSGuesture(handlerProxy, event) {
  9613. // return isPointerFromTouch(event) && !!handlerProxy._msGesture;
  9614. // }
  9615. // function onMSGestureChange(proxy, event) {
  9616. // if (event.translationX || event.translationY) {
  9617. // // mousemove is carried by MSGesture to reduce the sensitivity.
  9618. // proxy.handler.dispatchToElement(event.target, 'mousemove', event);
  9619. // }
  9620. // if (event.scale !== 1) {
  9621. // event.pinchX = event.offsetX;
  9622. // event.pinchY = event.offsetY;
  9623. // event.pinchScale = event.scale;
  9624. // proxy.handler.dispatchToElement(event.target, 'pinch', event);
  9625. // }
  9626. // }
  9627. /**
  9628. * Prevent mouse event from being dispatched after Touch Events action
  9629. * @see <https://github.com/deltakosh/handjs/blob/master/src/hand.base.js>
  9630. * 1. Mobile browsers dispatch mouse events 300ms after touchend.
  9631. * 2. Chrome for Android dispatch mousedown for long-touch about 650ms
  9632. * Result: Blocking Mouse Events for 700ms.
  9633. *
  9634. * @param {DOMHandlerScope} scope
  9635. */
  9636. function setTouchTimer(scope) {
  9637. scope.touching = true;
  9638. if (scope.touchTimer != null) {
  9639. clearTimeout(scope.touchTimer);
  9640. scope.touchTimer = null;
  9641. }
  9642. scope.touchTimer = setTimeout(function () {
  9643. scope.touching = false;
  9644. scope.touchTimer = null;
  9645. }, 700);
  9646. }
  9647. // Mark touch, which is useful in distinguish touch and
  9648. // mouse event in upper applicatoin.
  9649. function markTouch(event) {
  9650. event && (event.zrByTouch = true);
  9651. }
  9652. // function markTriggeredFromLocal(event) {
  9653. // event && (event.__zrIsFromLocal = true);
  9654. // }
  9655. // function isTriggeredFromLocal(instance, event) {
  9656. // return !!(event && event.__zrIsFromLocal);
  9657. // }
  9658. function normalizeGlobalEvent(instance, event) {
  9659. // offsetX, offsetY still need to be calculated. They are necessary in the event
  9660. // handlers of the upper applications. Set `true` to force calculate them.
  9661. return normalizeEvent(instance.dom, new FakeGlobalEvent(instance, event), true);
  9662. }
  9663. /**
  9664. * Detect whether the given el is in `painterRoot`.
  9665. */
  9666. function isLocalEl(instance, el) {
  9667. var elTmp = el;
  9668. var isLocal = false;
  9669. while (elTmp && elTmp.nodeType !== 9
  9670. && !(
  9671. isLocal = elTmp.domBelongToZr
  9672. || (elTmp !== el && elTmp === instance.painterRoot)
  9673. )
  9674. ) {
  9675. elTmp = elTmp.parentNode;
  9676. }
  9677. return isLocal;
  9678. }
  9679. /**
  9680. * Make a fake event but not change the original event,
  9681. * becuase the global event probably be used by other
  9682. * listeners not belonging to zrender.
  9683. * @class
  9684. */
  9685. function FakeGlobalEvent(instance, event) {
  9686. this.type = event.type;
  9687. this.target = this.currentTarget = instance.dom;
  9688. this.pointerType = event.pointerType;
  9689. // Necessray for the force calculation of zrX, zrY
  9690. this.clientX = event.clientX;
  9691. this.clientY = event.clientY;
  9692. // Because we do not mount global listeners to touch events,
  9693. // we do not copy `targetTouches` and `changedTouches` here.
  9694. }
  9695. var fakeGlobalEventProto = FakeGlobalEvent.prototype;
  9696. // we make the default methods on the event do nothing,
  9697. // otherwise it is dangerous. See more details in
  9698. // [Drag outside] in `Handler.js`.
  9699. fakeGlobalEventProto.stopPropagation =
  9700. fakeGlobalEventProto.stopImmediatePropagation =
  9701. fakeGlobalEventProto.preventDefault = noop;
  9702. /**
  9703. * Local DOM Handlers
  9704. * @this {HandlerProxy}
  9705. */
  9706. var localDOMHandlers = {
  9707. mousedown: function (event) {
  9708. event = normalizeEvent(this.dom, event);
  9709. this._mayPointerCapture = [event.zrX, event.zrY];
  9710. this.trigger('mousedown', event);
  9711. },
  9712. mousemove: function (event) {
  9713. event = normalizeEvent(this.dom, event);
  9714. var downPoint = this._mayPointerCapture;
  9715. if (downPoint && (event.zrX !== downPoint[0] || event.zrY !== downPoint[1])) {
  9716. togglePointerCapture(this, true);
  9717. }
  9718. this.trigger('mousemove', event);
  9719. },
  9720. mouseup: function (event) {
  9721. event = normalizeEvent(this.dom, event);
  9722. togglePointerCapture(this, false);
  9723. this.trigger('mouseup', event);
  9724. },
  9725. mouseout: function (event) {
  9726. event = normalizeEvent(this.dom, event);
  9727. // Similarly to the browser did on `document` and touch event,
  9728. // `globalout` will be delayed to final pointer cature release.
  9729. if (this._pointerCapturing) {
  9730. event.zrEventControl = 'no_globalout';
  9731. }
  9732. // There might be some doms created by upper layer application
  9733. // at the same level of painter.getViewportRoot() (e.g., tooltip
  9734. // dom created by echarts), where 'globalout' event should not
  9735. // be triggered when mouse enters these doms. (But 'mouseout'
  9736. // should be triggered at the original hovered element as usual).
  9737. var element = event.toElement || event.relatedTarget;
  9738. event.zrIsToLocalDOM = isLocalEl(this, element);
  9739. this.trigger('mouseout', event);
  9740. },
  9741. touchstart: function (event) {
  9742. // Default mouse behaviour should not be disabled here.
  9743. // For example, page may needs to be slided.
  9744. event = normalizeEvent(this.dom, event);
  9745. markTouch(event);
  9746. this._lastTouchMoment = new Date();
  9747. this.handler.processGesture(event, 'start');
  9748. // For consistent event listener for both touch device and mouse device,
  9749. // we simulate "mouseover-->mousedown" in touch device. So we trigger
  9750. // `mousemove` here (to trigger `mouseover` inside), and then trigger
  9751. // `mousedown`.
  9752. localDOMHandlers.mousemove.call(this, event);
  9753. localDOMHandlers.mousedown.call(this, event);
  9754. },
  9755. touchmove: function (event) {
  9756. event = normalizeEvent(this.dom, event);
  9757. markTouch(event);
  9758. this.handler.processGesture(event, 'change');
  9759. // Mouse move should always be triggered no matter whether
  9760. // there is gestrue event, because mouse move and pinch may
  9761. // be used at the same time.
  9762. localDOMHandlers.mousemove.call(this, event);
  9763. },
  9764. touchend: function (event) {
  9765. event = normalizeEvent(this.dom, event);
  9766. markTouch(event);
  9767. this.handler.processGesture(event, 'end');
  9768. localDOMHandlers.mouseup.call(this, event);
  9769. // Do not trigger `mouseout` here, in spite of `mousemove`(`mouseover`) is
  9770. // triggered in `touchstart`. This seems to be illogical, but by this mechanism,
  9771. // we can conveniently implement "hover style" in both PC and touch device just
  9772. // by listening to `mouseover` to add "hover style" and listening to `mouseout`
  9773. // to remove "hover style" on an element, without any additional code for
  9774. // compatibility. (`mouseout` will not be triggered in `touchend`, so "hover
  9775. // style" will remain for user view)
  9776. // click event should always be triggered no matter whether
  9777. // there is gestrue event. System click can not be prevented.
  9778. if (+new Date() - this._lastTouchMoment < TOUCH_CLICK_DELAY) {
  9779. localDOMHandlers.click.call(this, event);
  9780. }
  9781. },
  9782. pointerdown: function (event) {
  9783. localDOMHandlers.mousedown.call(this, event);
  9784. // if (useMSGuesture(this, event)) {
  9785. // this._msGesture.addPointer(event.pointerId);
  9786. // }
  9787. },
  9788. pointermove: function (event) {
  9789. // FIXME
  9790. // pointermove is so sensitive that it always triggered when
  9791. // tap(click) on touch screen, which affect some judgement in
  9792. // upper application. So, we dont support mousemove on MS touch
  9793. // device yet.
  9794. if (!isPointerFromTouch(event)) {
  9795. localDOMHandlers.mousemove.call(this, event);
  9796. }
  9797. },
  9798. pointerup: function (event) {
  9799. localDOMHandlers.mouseup.call(this, event);
  9800. },
  9801. pointerout: function (event) {
  9802. // pointerout will be triggered when tap on touch screen
  9803. // (IE11+/Edge on MS Surface) after click event triggered,
  9804. // which is inconsistent with the mousout behavior we defined
  9805. // in touchend. So we unify them.
  9806. // (check localDOMHandlers.touchend for detailed explanation)
  9807. if (!isPointerFromTouch(event)) {
  9808. localDOMHandlers.mouseout.call(this, event);
  9809. }
  9810. }
  9811. };
  9812. /**
  9813. * Othere DOM UI Event handlers for zr dom.
  9814. * @this {HandlerProxy}
  9815. */
  9816. each$1(['click', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  9817. localDOMHandlers[name] = function (event) {
  9818. event = normalizeEvent(this.dom, event);
  9819. this.trigger(name, event);
  9820. };
  9821. });
  9822. /**
  9823. * DOM UI Event handlers for global page.
  9824. *
  9825. * [Caution]:
  9826. * those handlers should both support in capture phase and bubble phase!
  9827. *
  9828. * @this {HandlerProxy}
  9829. */
  9830. var globalDOMHandlers = {
  9831. pointermove: function (event) {
  9832. // FIXME
  9833. // pointermove is so sensitive that it always triggered when
  9834. // tap(click) on touch screen, which affect some judgement in
  9835. // upper application. So, we dont support mousemove on MS touch
  9836. // device yet.
  9837. if (!isPointerFromTouch(event)) {
  9838. globalDOMHandlers.mousemove.call(this, event);
  9839. }
  9840. },
  9841. pointerup: function (event) {
  9842. globalDOMHandlers.mouseup.call(this, event);
  9843. },
  9844. mousemove: function (event) {
  9845. this.trigger('mousemove', event);
  9846. },
  9847. mouseup: function (event) {
  9848. var pointerCaptureReleasing = this._pointerCapturing;
  9849. togglePointerCapture(this, false);
  9850. this.trigger('mouseup', event);
  9851. if (pointerCaptureReleasing) {
  9852. event.zrEventControl = 'only_globalout';
  9853. this.trigger('mouseout', event);
  9854. }
  9855. }
  9856. };
  9857. /**
  9858. * @param {HandlerProxy} instance
  9859. * @param {DOMHandlerScope} scope
  9860. */
  9861. function mountLocalDOMEventListeners(instance, scope) {
  9862. var domHandlers = scope.domHandlers;
  9863. if (env$1.pointerEventsSupported) { // Only IE11+/Edge
  9864. // 1. On devices that both enable touch and mouse (e.g., MS Surface and lenovo X240),
  9865. // IE11+/Edge do not trigger touch event, but trigger pointer event and mouse event
  9866. // at the same time.
  9867. // 2. On MS Surface, it probablely only trigger mousedown but no mouseup when tap on
  9868. // screen, which do not occurs in pointer event.
  9869. // So we use pointer event to both detect touch gesture and mouse behavior.
  9870. each$1(localNativeListenerNames.pointer, function (nativeEventName) {
  9871. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  9872. // markTriggeredFromLocal(event);
  9873. domHandlers[nativeEventName].call(instance, event);
  9874. });
  9875. });
  9876. // FIXME
  9877. // Note: MS Gesture require CSS touch-action set. But touch-action is not reliable,
  9878. // which does not prevent defuault behavior occasionally (which may cause view port
  9879. // zoomed in but use can not zoom it back). And event.preventDefault() does not work.
  9880. // So we have to not to use MSGesture and not to support touchmove and pinch on MS
  9881. // touch screen. And we only support click behavior on MS touch screen now.
  9882. // MS Gesture Event is only supported on IE11+/Edge and on Windows 8+.
  9883. // We dont support touch on IE on win7.
  9884. // See <https://msdn.microsoft.com/en-us/library/dn433243(v=vs.85).aspx>
  9885. // if (typeof MSGesture === 'function') {
  9886. // (this._msGesture = new MSGesture()).target = dom; // jshint ignore:line
  9887. // dom.addEventListener('MSGestureChange', onMSGestureChange);
  9888. // }
  9889. }
  9890. else {
  9891. if (env$1.touchEventsSupported) {
  9892. each$1(localNativeListenerNames.touch, function (nativeEventName) {
  9893. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  9894. // markTriggeredFromLocal(event);
  9895. domHandlers[nativeEventName].call(instance, event);
  9896. setTouchTimer(scope);
  9897. });
  9898. });
  9899. // Handler of 'mouseout' event is needed in touch mode, which will be mounted below.
  9900. // addEventListener(root, 'mouseout', this._mouseoutHandler);
  9901. }
  9902. // 1. Considering some devices that both enable touch and mouse event (like on MS Surface
  9903. // and lenovo X240, @see #2350), we make mouse event be always listened, otherwise
  9904. // mouse event can not be handle in those devices.
  9905. // 2. On MS Surface, Chrome will trigger both touch event and mouse event. How to prevent
  9906. // mouseevent after touch event triggered, see `setTouchTimer`.
  9907. each$1(localNativeListenerNames.mouse, function (nativeEventName) {
  9908. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  9909. event = getNativeEvent(event);
  9910. if (!scope.touching) {
  9911. // markTriggeredFromLocal(event);
  9912. domHandlers[nativeEventName].call(instance, event);
  9913. }
  9914. });
  9915. });
  9916. }
  9917. }
  9918. /**
  9919. * @param {HandlerProxy} instance
  9920. * @param {DOMHandlerScope} scope
  9921. */
  9922. function mountGlobalDOMEventListeners(instance, scope) {
  9923. // Only IE11+/Edge. See the comment in `mountLocalDOMEventListeners`.
  9924. if (env$1.pointerEventsSupported) {
  9925. each$1(globalNativeListenerNames.pointer, mount);
  9926. }
  9927. // Touch event has implemented "drag outside" so we do not mount global listener for touch event.
  9928. // (see https://www.w3.org/TR/touch-events/#the-touchmove-event)
  9929. // We do not consider "both-support-touch-and-mouse device" for this feature (see the comment of
  9930. // `mountLocalDOMEventListeners`) to avoid bugs util some requirements come.
  9931. else if (!env$1.touchEventsSupported) {
  9932. each$1(globalNativeListenerNames.mouse, mount);
  9933. }
  9934. function mount(nativeEventName) {
  9935. function nativeEventListener(event) {
  9936. event = getNativeEvent(event);
  9937. // See the reason in [Drag outside] in `Handler.js`
  9938. // This checking supports both `useCapture` or not.
  9939. // PENDING: if there is performance issue in some devices,
  9940. // we probably can not use `useCapture` and change a easier
  9941. // to judes whether local (mark).
  9942. if (!isLocalEl(instance, event.target)) {
  9943. event = normalizeGlobalEvent(instance, event);
  9944. scope.domHandlers[nativeEventName].call(instance, event);
  9945. }
  9946. }
  9947. mountSingleDOMEventListener(
  9948. scope, nativeEventName, nativeEventListener,
  9949. {capture: true} // See [Drag Outside] in `Handler.js`
  9950. );
  9951. }
  9952. }
  9953. function mountSingleDOMEventListener(scope, nativeEventName, listener, opt) {
  9954. scope.mounted[nativeEventName] = listener;
  9955. scope.listenerOpts[nativeEventName] = opt;
  9956. addEventListener(scope.domTarget, eventNameFix(nativeEventName), listener, opt);
  9957. }
  9958. function unmountDOMEventListeners(scope) {
  9959. var mounted = scope.mounted;
  9960. for (var nativeEventName in mounted) {
  9961. if (mounted.hasOwnProperty(nativeEventName)) {
  9962. removeEventListener(
  9963. scope.domTarget, eventNameFix(nativeEventName), mounted[nativeEventName],
  9964. scope.listenerOpts[nativeEventName]
  9965. );
  9966. }
  9967. }
  9968. scope.mounted = {};
  9969. }
  9970. /**
  9971. * See [Drag Outside] in `Handler.js`.
  9972. * @implement
  9973. * @param {boolean} isPointerCapturing Should never be `null`/`undefined`.
  9974. * `true`: start to capture pointer if it is not capturing.
  9975. * `false`: end the capture if it is capturing.
  9976. */
  9977. function togglePointerCapture(instance, isPointerCapturing) {
  9978. instance._mayPointerCapture = null;
  9979. if (globalEventSupported && (instance._pointerCapturing ^ isPointerCapturing)) {
  9980. instance._pointerCapturing = isPointerCapturing;
  9981. var globalHandlerScope = instance._globalHandlerScope;
  9982. isPointerCapturing
  9983. ? mountGlobalDOMEventListeners(instance, globalHandlerScope)
  9984. : unmountDOMEventListeners(globalHandlerScope);
  9985. }
  9986. }
  9987. /**
  9988. * @inner
  9989. * @class
  9990. */
  9991. function DOMHandlerScope(domTarget, domHandlers) {
  9992. this.domTarget = domTarget;
  9993. this.domHandlers = domHandlers;
  9994. // Key: eventName, value: mounted handler funcitons.
  9995. // Used for unmount.
  9996. this.mounted = {};
  9997. this.listenerOpts = {};
  9998. this.touchTimer = null;
  9999. this.touching = false;
  10000. }
  10001. /**
  10002. * @public
  10003. * @class
  10004. */
  10005. function HandlerDomProxy(dom, painterRoot) {
  10006. Eventful.call(this);
  10007. this.dom = dom;
  10008. this.painterRoot = painterRoot;
  10009. this._localHandlerScope = new DOMHandlerScope(dom, localDOMHandlers);
  10010. if (globalEventSupported) {
  10011. this._globalHandlerScope = new DOMHandlerScope(document, globalDOMHandlers);
  10012. }
  10013. /**
  10014. * @type {boolean}
  10015. */
  10016. this._pointerCapturing = false;
  10017. /**
  10018. * @type {Array.<number>} [x, y] or null.
  10019. */
  10020. this._mayPointerCapture = null;
  10021. mountLocalDOMEventListeners(this, this._localHandlerScope);
  10022. }
  10023. var handlerDomProxyProto = HandlerDomProxy.prototype;
  10024. handlerDomProxyProto.dispose = function () {
  10025. unmountDOMEventListeners(this._localHandlerScope);
  10026. if (globalEventSupported) {
  10027. unmountDOMEventListeners(this._globalHandlerScope);
  10028. }
  10029. };
  10030. handlerDomProxyProto.setCursor = function (cursorStyle) {
  10031. this.dom.style && (this.dom.style.cursor = cursorStyle || 'default');
  10032. };
  10033. mixin(HandlerDomProxy, Eventful);
  10034. /*!
  10035. * ZRender, a high performance 2d drawing library.
  10036. *
  10037. * Copyright (c) 2013, Baidu Inc.
  10038. * All rights reserved.
  10039. *
  10040. * LICENSE
  10041. * https://github.com/ecomfe/zrender/blob/master/LICENSE.txt
  10042. */
  10043. var useVML = !env$1.canvasSupported;
  10044. var painterCtors = {
  10045. canvas: Painter
  10046. };
  10047. var instances$1 = {}; // ZRender实例map索引
  10048. /**
  10049. * @type {string}
  10050. */
  10051. var version$1 = '4.3.1';
  10052. /**
  10053. * Initializing a zrender instance
  10054. * @param {HTMLElement} dom
  10055. * @param {Object} [opts]
  10056. * @param {string} [opts.renderer='canvas'] 'canvas' or 'svg'
  10057. * @param {number} [opts.devicePixelRatio]
  10058. * @param {number|string} [opts.width] Can be 'auto' (the same as null/undefined)
  10059. * @param {number|string} [opts.height] Can be 'auto' (the same as null/undefined)
  10060. * @return {module:zrender/ZRender}
  10061. */
  10062. function init$1(dom, opts) {
  10063. var zr = new ZRender(guid(), dom, opts);
  10064. instances$1[zr.id] = zr;
  10065. return zr;
  10066. }
  10067. /**
  10068. * Dispose zrender instance
  10069. * @param {module:zrender/ZRender} zr
  10070. */
  10071. function dispose$1(zr) {
  10072. if (zr) {
  10073. zr.dispose();
  10074. }
  10075. else {
  10076. for (var key in instances$1) {
  10077. if (instances$1.hasOwnProperty(key)) {
  10078. instances$1[key].dispose();
  10079. }
  10080. }
  10081. instances$1 = {};
  10082. }
  10083. return this;
  10084. }
  10085. /**
  10086. * Get zrender instance by id
  10087. * @param {string} id zrender instance id
  10088. * @return {module:zrender/ZRender}
  10089. */
  10090. function getInstance(id) {
  10091. return instances$1[id];
  10092. }
  10093. function registerPainter(name, Ctor) {
  10094. painterCtors[name] = Ctor;
  10095. }
  10096. function delInstance(id) {
  10097. delete instances$1[id];
  10098. }
  10099. /**
  10100. * @module zrender/ZRender
  10101. */
  10102. /**
  10103. * @constructor
  10104. * @alias module:zrender/ZRender
  10105. * @param {string} id
  10106. * @param {HTMLElement} dom
  10107. * @param {Object} opts
  10108. * @param {string} [opts.renderer='canvas'] 'canvas' or 'svg'
  10109. * @param {number} [opts.devicePixelRatio]
  10110. * @param {number} [opts.width] Can be 'auto' (the same as null/undefined)
  10111. * @param {number} [opts.height] Can be 'auto' (the same as null/undefined)
  10112. */
  10113. var ZRender = function (id, dom, opts) {
  10114. opts = opts || {};
  10115. /**
  10116. * @type {HTMLDomElement}
  10117. */
  10118. this.dom = dom;
  10119. /**
  10120. * @type {string}
  10121. */
  10122. this.id = id;
  10123. var self = this;
  10124. var storage = new Storage();
  10125. var rendererType = opts.renderer;
  10126. // TODO WebGL
  10127. if (useVML) {
  10128. if (!painterCtors.vml) {
  10129. throw new Error('You need to require \'zrender/vml/vml\' to support IE8');
  10130. }
  10131. rendererType = 'vml';
  10132. }
  10133. else if (!rendererType || !painterCtors[rendererType]) {
  10134. rendererType = 'canvas';
  10135. }
  10136. var painter = new painterCtors[rendererType](dom, storage, opts, id);
  10137. this.storage = storage;
  10138. this.painter = painter;
  10139. var handerProxy = (!env$1.node && !env$1.worker) ? new HandlerDomProxy(painter.getViewportRoot(), painter.root) : null;
  10140. this.handler = new Handler(storage, painter, handerProxy, painter.root);
  10141. /**
  10142. * @type {module:zrender/animation/Animation}
  10143. */
  10144. this.animation = new Animation({
  10145. stage: {
  10146. update: bind(this.flush, this)
  10147. }
  10148. });
  10149. this.animation.start();
  10150. /**
  10151. * @type {boolean}
  10152. * @private
  10153. */
  10154. this._needsRefresh;
  10155. // 修改 storage.delFromStorage, 每次删除元素之前删除动画
  10156. // FIXME 有点ugly
  10157. var oldDelFromStorage = storage.delFromStorage;
  10158. var oldAddToStorage = storage.addToStorage;
  10159. storage.delFromStorage = function (el) {
  10160. oldDelFromStorage.call(storage, el);
  10161. el && el.removeSelfFromZr(self);
  10162. };
  10163. storage.addToStorage = function (el) {
  10164. oldAddToStorage.call(storage, el);
  10165. el.addSelfToZr(self);
  10166. };
  10167. };
  10168. ZRender.prototype = {
  10169. constructor: ZRender,
  10170. /**
  10171. * 获取实例唯一标识
  10172. * @return {string}
  10173. */
  10174. getId: function () {
  10175. return this.id;
  10176. },
  10177. /**
  10178. * 添加元素
  10179. * @param {module:zrender/Element} el
  10180. */
  10181. add: function (el) {
  10182. this.storage.addRoot(el);
  10183. this._needsRefresh = true;
  10184. },
  10185. /**
  10186. * 删除元素
  10187. * @param {module:zrender/Element} el
  10188. */
  10189. remove: function (el) {
  10190. this.storage.delRoot(el);
  10191. this._needsRefresh = true;
  10192. },
  10193. /**
  10194. * Change configuration of layer
  10195. * @param {string} zLevel
  10196. * @param {Object} config
  10197. * @param {string} [config.clearColor=0] Clear color
  10198. * @param {string} [config.motionBlur=false] If enable motion blur
  10199. * @param {number} [config.lastFrameAlpha=0.7] Motion blur factor. Larger value cause longer trailer
  10200. */
  10201. configLayer: function (zLevel, config) {
  10202. if (this.painter.configLayer) {
  10203. this.painter.configLayer(zLevel, config);
  10204. }
  10205. this._needsRefresh = true;
  10206. },
  10207. /**
  10208. * Set background color
  10209. * @param {string} backgroundColor
  10210. */
  10211. setBackgroundColor: function (backgroundColor) {
  10212. if (this.painter.setBackgroundColor) {
  10213. this.painter.setBackgroundColor(backgroundColor);
  10214. }
  10215. this._needsRefresh = true;
  10216. },
  10217. /**
  10218. * Repaint the canvas immediately
  10219. */
  10220. refreshImmediately: function () {
  10221. // var start = new Date();
  10222. // Clear needsRefresh ahead to avoid something wrong happens in refresh
  10223. // Or it will cause zrender refreshes again and again.
  10224. this._needsRefresh = this._needsRefreshHover = false;
  10225. this.painter.refresh();
  10226. // Avoid trigger zr.refresh in Element#beforeUpdate hook
  10227. this._needsRefresh = this._needsRefreshHover = false;
  10228. // var end = new Date();
  10229. // var log = document.getElementById('log');
  10230. // if (log) {
  10231. // log.innerHTML = log.innerHTML + '<br>' + (end - start);
  10232. // }
  10233. },
  10234. /**
  10235. * Mark and repaint the canvas in the next frame of browser
  10236. */
  10237. refresh: function () {
  10238. this._needsRefresh = true;
  10239. },
  10240. /**
  10241. * Perform all refresh
  10242. */
  10243. flush: function () {
  10244. var triggerRendered;
  10245. if (this._needsRefresh) {
  10246. triggerRendered = true;
  10247. this.refreshImmediately();
  10248. }
  10249. if (this._needsRefreshHover) {
  10250. triggerRendered = true;
  10251. this.refreshHoverImmediately();
  10252. }
  10253. triggerRendered && this.trigger('rendered');
  10254. },
  10255. /**
  10256. * Add element to hover layer
  10257. * @param {module:zrender/Element} el
  10258. * @param {Object} style
  10259. */
  10260. addHover: function (el, style) {
  10261. if (this.painter.addHover) {
  10262. var elMirror = this.painter.addHover(el, style);
  10263. this.refreshHover();
  10264. return elMirror;
  10265. }
  10266. },
  10267. /**
  10268. * Add element from hover layer
  10269. * @param {module:zrender/Element} el
  10270. */
  10271. removeHover: function (el) {
  10272. if (this.painter.removeHover) {
  10273. this.painter.removeHover(el);
  10274. this.refreshHover();
  10275. }
  10276. },
  10277. /**
  10278. * Clear all hover elements in hover layer
  10279. * @param {module:zrender/Element} el
  10280. */
  10281. clearHover: function () {
  10282. if (this.painter.clearHover) {
  10283. this.painter.clearHover();
  10284. this.refreshHover();
  10285. }
  10286. },
  10287. /**
  10288. * Refresh hover in next frame
  10289. */
  10290. refreshHover: function () {
  10291. this._needsRefreshHover = true;
  10292. },
  10293. /**
  10294. * Refresh hover immediately
  10295. */
  10296. refreshHoverImmediately: function () {
  10297. this._needsRefreshHover = false;
  10298. this.painter.refreshHover && this.painter.refreshHover();
  10299. },
  10300. /**
  10301. * Resize the canvas.
  10302. * Should be invoked when container size is changed
  10303. * @param {Object} [opts]
  10304. * @param {number|string} [opts.width] Can be 'auto' (the same as null/undefined)
  10305. * @param {number|string} [opts.height] Can be 'auto' (the same as null/undefined)
  10306. */
  10307. resize: function (opts) {
  10308. opts = opts || {};
  10309. this.painter.resize(opts.width, opts.height);
  10310. this.handler.resize();
  10311. },
  10312. /**
  10313. * Stop and clear all animation immediately
  10314. */
  10315. clearAnimation: function () {
  10316. this.animation.clear();
  10317. },
  10318. /**
  10319. * Get container width
  10320. */
  10321. getWidth: function () {
  10322. return this.painter.getWidth();
  10323. },
  10324. /**
  10325. * Get container height
  10326. */
  10327. getHeight: function () {
  10328. return this.painter.getHeight();
  10329. },
  10330. /**
  10331. * Export the canvas as Base64 URL
  10332. * @param {string} type
  10333. * @param {string} [backgroundColor='#fff']
  10334. * @return {string} Base64 URL
  10335. */
  10336. // toDataURL: function(type, backgroundColor) {
  10337. // return this.painter.getRenderedCanvas({
  10338. // backgroundColor: backgroundColor
  10339. // }).toDataURL(type);
  10340. // },
  10341. /**
  10342. * Converting a path to image.
  10343. * It has much better performance of drawing image rather than drawing a vector path.
  10344. * @param {module:zrender/graphic/Path} e
  10345. * @param {number} width
  10346. * @param {number} height
  10347. */
  10348. pathToImage: function (e, dpr) {
  10349. return this.painter.pathToImage(e, dpr);
  10350. },
  10351. /**
  10352. * Set default cursor
  10353. * @param {string} [cursorStyle='default'] 例如 crosshair
  10354. */
  10355. setCursorStyle: function (cursorStyle) {
  10356. this.handler.setCursorStyle(cursorStyle);
  10357. },
  10358. /**
  10359. * Find hovered element
  10360. * @param {number} x
  10361. * @param {number} y
  10362. * @return {Object} {target, topTarget}
  10363. */
  10364. findHover: function (x, y) {
  10365. return this.handler.findHover(x, y);
  10366. },
  10367. /**
  10368. * Bind event
  10369. *
  10370. * @param {string} eventName Event name
  10371. * @param {Function} eventHandler Handler function
  10372. * @param {Object} [context] Context object
  10373. */
  10374. on: function (eventName, eventHandler, context) {
  10375. this.handler.on(eventName, eventHandler, context);
  10376. },
  10377. /**
  10378. * Unbind event
  10379. * @param {string} eventName Event name
  10380. * @param {Function} [eventHandler] Handler function
  10381. */
  10382. off: function (eventName, eventHandler) {
  10383. this.handler.off(eventName, eventHandler);
  10384. },
  10385. /**
  10386. * Trigger event manually
  10387. *
  10388. * @param {string} eventName Event name
  10389. * @param {event=} event Event object
  10390. */
  10391. trigger: function (eventName, event) {
  10392. this.handler.trigger(eventName, event);
  10393. },
  10394. /**
  10395. * Clear all objects and the canvas.
  10396. */
  10397. clear: function () {
  10398. this.storage.delRoot();
  10399. this.painter.clear();
  10400. },
  10401. /**
  10402. * Dispose self.
  10403. */
  10404. dispose: function () {
  10405. this.animation.stop();
  10406. this.clear();
  10407. this.storage.dispose();
  10408. this.painter.dispose();
  10409. this.handler.dispose();
  10410. this.animation =
  10411. this.storage =
  10412. this.painter =
  10413. this.handler = null;
  10414. delInstance(this.id);
  10415. }
  10416. };
  10417. var zrender = (Object.freeze || Object)({
  10418. version: version$1,
  10419. init: init$1,
  10420. dispose: dispose$1,
  10421. getInstance: getInstance,
  10422. registerPainter: registerPainter
  10423. });
  10424. /*
  10425. * Licensed to the Apache Software Foundation (ASF) under one
  10426. * or more contributor license agreements. See the NOTICE file
  10427. * distributed with this work for additional information
  10428. * regarding copyright ownership. The ASF licenses this file
  10429. * to you under the Apache License, Version 2.0 (the
  10430. * "License"); you may not use this file except in compliance
  10431. * with the License. You may obtain a copy of the License at
  10432. *
  10433. * http://www.apache.org/licenses/LICENSE-2.0
  10434. *
  10435. * Unless required by applicable law or agreed to in writing,
  10436. * software distributed under the License is distributed on an
  10437. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10438. * KIND, either express or implied. See the License for the
  10439. * specific language governing permissions and limitations
  10440. * under the License.
  10441. */
  10442. var each$2 = each$1;
  10443. var isObject$2 = isObject$1;
  10444. var isArray$1 = isArray;
  10445. /**
  10446. * Make the name displayable. But we should
  10447. * make sure it is not duplicated with user
  10448. * specified name, so use '\0';
  10449. */
  10450. var DUMMY_COMPONENT_NAME_PREFIX = 'series\0';
  10451. /**
  10452. * If value is not array, then translate it to array.
  10453. * @param {*} value
  10454. * @return {Array} [value] or value
  10455. */
  10456. function normalizeToArray(value) {
  10457. return value instanceof Array
  10458. ? value
  10459. : value == null
  10460. ? []
  10461. : [value];
  10462. }
  10463. /**
  10464. * Sync default option between normal and emphasis like `position` and `show`
  10465. * In case some one will write code like
  10466. * label: {
  10467. * show: false,
  10468. * position: 'outside',
  10469. * fontSize: 18
  10470. * },
  10471. * emphasis: {
  10472. * label: { show: true }
  10473. * }
  10474. * @param {Object} opt
  10475. * @param {string} key
  10476. * @param {Array.<string>} subOpts
  10477. */
  10478. function defaultEmphasis(opt, key, subOpts) {
  10479. // Caution: performance sensitive.
  10480. if (opt) {
  10481. opt[key] = opt[key] || {};
  10482. opt.emphasis = opt.emphasis || {};
  10483. opt.emphasis[key] = opt.emphasis[key] || {};
  10484. // Default emphasis option from normal
  10485. for (var i = 0, len = subOpts.length; i < len; i++) {
  10486. var subOptName = subOpts[i];
  10487. if (!opt.emphasis[key].hasOwnProperty(subOptName)
  10488. && opt[key].hasOwnProperty(subOptName)
  10489. ) {
  10490. opt.emphasis[key][subOptName] = opt[key][subOptName];
  10491. }
  10492. }
  10493. }
  10494. }
  10495. var TEXT_STYLE_OPTIONS = [
  10496. 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  10497. 'rich', 'tag', 'color', 'textBorderColor', 'textBorderWidth',
  10498. 'width', 'height', 'lineHeight', 'align', 'verticalAlign', 'baseline',
  10499. 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY',
  10500. 'textShadowColor', 'textShadowBlur', 'textShadowOffsetX', 'textShadowOffsetY',
  10501. 'backgroundColor', 'borderColor', 'borderWidth', 'borderRadius', 'padding'
  10502. ];
  10503. // modelUtil.LABEL_OPTIONS = modelUtil.TEXT_STYLE_OPTIONS.concat([
  10504. // 'position', 'offset', 'rotate', 'origin', 'show', 'distance', 'formatter',
  10505. // 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  10506. // // FIXME: deprecated, check and remove it.
  10507. // 'textStyle'
  10508. // ]);
  10509. /**
  10510. * The method do not ensure performance.
  10511. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  10512. * This helper method retieves value from data.
  10513. * @param {string|number|Date|Array|Object} dataItem
  10514. * @return {number|string|Date|Array.<number|string|Date>}
  10515. */
  10516. function getDataItemValue(dataItem) {
  10517. return (isObject$2(dataItem) && !isArray$1(dataItem) && !(dataItem instanceof Date))
  10518. ? dataItem.value : dataItem;
  10519. }
  10520. /**
  10521. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  10522. * This helper method determine if dataItem has extra option besides value
  10523. * @param {string|number|Date|Array|Object} dataItem
  10524. */
  10525. function isDataItemOption(dataItem) {
  10526. return isObject$2(dataItem)
  10527. && !(dataItem instanceof Array);
  10528. // // markLine data can be array
  10529. // && !(dataItem[0] && isObject(dataItem[0]) && !(dataItem[0] instanceof Array));
  10530. }
  10531. /**
  10532. * Mapping to exists for merge.
  10533. *
  10534. * @public
  10535. * @param {Array.<Object>|Array.<module:echarts/model/Component>} exists
  10536. * @param {Object|Array.<Object>} newCptOptions
  10537. * @return {Array.<Object>} Result, like [{exist: ..., option: ...}, {}],
  10538. * index of which is the same as exists.
  10539. */
  10540. function mappingToExists(exists, newCptOptions) {
  10541. // Mapping by the order by original option (but not order of
  10542. // new option) in merge mode. Because we should ensure
  10543. // some specified index (like xAxisIndex) is consistent with
  10544. // original option, which is easy to understand, espatially in
  10545. // media query. And in most case, merge option is used to
  10546. // update partial option but not be expected to change order.
  10547. newCptOptions = (newCptOptions || []).slice();
  10548. var result = map(exists || [], function (obj, index) {
  10549. return {exist: obj};
  10550. });
  10551. // Mapping by id or name if specified.
  10552. each$2(newCptOptions, function (cptOption, index) {
  10553. if (!isObject$2(cptOption)) {
  10554. return;
  10555. }
  10556. // id has highest priority.
  10557. for (var i = 0; i < result.length; i++) {
  10558. if (!result[i].option // Consider name: two map to one.
  10559. && cptOption.id != null
  10560. && result[i].exist.id === cptOption.id + ''
  10561. ) {
  10562. result[i].option = cptOption;
  10563. newCptOptions[index] = null;
  10564. return;
  10565. }
  10566. }
  10567. for (var i = 0; i < result.length; i++) {
  10568. var exist = result[i].exist;
  10569. if (!result[i].option // Consider name: two map to one.
  10570. // Can not match when both ids exist but different.
  10571. && (exist.id == null || cptOption.id == null)
  10572. && cptOption.name != null
  10573. && !isIdInner(cptOption)
  10574. && !isIdInner(exist)
  10575. && exist.name === cptOption.name + ''
  10576. ) {
  10577. result[i].option = cptOption;
  10578. newCptOptions[index] = null;
  10579. return;
  10580. }
  10581. }
  10582. });
  10583. // Otherwise mapping by index.
  10584. each$2(newCptOptions, function (cptOption, index) {
  10585. if (!isObject$2(cptOption)) {
  10586. return;
  10587. }
  10588. var i = 0;
  10589. for (; i < result.length; i++) {
  10590. var exist = result[i].exist;
  10591. if (!result[i].option
  10592. // Existing model that already has id should be able to
  10593. // mapped to (because after mapping performed model may
  10594. // be assigned with a id, whish should not affect next
  10595. // mapping), except those has inner id.
  10596. && !isIdInner(exist)
  10597. // Caution:
  10598. // Do not overwrite id. But name can be overwritten,
  10599. // because axis use name as 'show label text'.
  10600. // 'exist' always has id and name and we dont
  10601. // need to check it.
  10602. && cptOption.id == null
  10603. ) {
  10604. result[i].option = cptOption;
  10605. break;
  10606. }
  10607. }
  10608. if (i >= result.length) {
  10609. result.push({option: cptOption});
  10610. }
  10611. });
  10612. return result;
  10613. }
  10614. /**
  10615. * Make id and name for mapping result (result of mappingToExists)
  10616. * into `keyInfo` field.
  10617. *
  10618. * @public
  10619. * @param {Array.<Object>} Result, like [{exist: ..., option: ...}, {}],
  10620. * which order is the same as exists.
  10621. * @return {Array.<Object>} The input.
  10622. */
  10623. function makeIdAndName(mapResult) {
  10624. // We use this id to hash component models and view instances
  10625. // in echarts. id can be specified by user, or auto generated.
  10626. // The id generation rule ensures new view instance are able
  10627. // to mapped to old instance when setOption are called in
  10628. // no-merge mode. So we generate model id by name and plus
  10629. // type in view id.
  10630. // name can be duplicated among components, which is convenient
  10631. // to specify multi components (like series) by one name.
  10632. // Ensure that each id is distinct.
  10633. var idMap = createHashMap();
  10634. each$2(mapResult, function (item, index) {
  10635. var existCpt = item.exist;
  10636. existCpt && idMap.set(existCpt.id, item);
  10637. });
  10638. each$2(mapResult, function (item, index) {
  10639. var opt = item.option;
  10640. assert$1(
  10641. !opt || opt.id == null || !idMap.get(opt.id) || idMap.get(opt.id) === item,
  10642. 'id duplicates: ' + (opt && opt.id)
  10643. );
  10644. opt && opt.id != null && idMap.set(opt.id, item);
  10645. !item.keyInfo && (item.keyInfo = {});
  10646. });
  10647. // Make name and id.
  10648. each$2(mapResult, function (item, index) {
  10649. var existCpt = item.exist;
  10650. var opt = item.option;
  10651. var keyInfo = item.keyInfo;
  10652. if (!isObject$2(opt)) {
  10653. return;
  10654. }
  10655. // name can be overwitten. Consider case: axis.name = '20km'.
  10656. // But id generated by name will not be changed, which affect
  10657. // only in that case: setOption with 'not merge mode' and view
  10658. // instance will be recreated, which can be accepted.
  10659. keyInfo.name = opt.name != null
  10660. ? opt.name + ''
  10661. : existCpt
  10662. ? existCpt.name
  10663. // Avoid diffferent series has the same name,
  10664. // because name may be used like in color pallet.
  10665. : DUMMY_COMPONENT_NAME_PREFIX + index;
  10666. if (existCpt) {
  10667. keyInfo.id = existCpt.id;
  10668. }
  10669. else if (opt.id != null) {
  10670. keyInfo.id = opt.id + '';
  10671. }
  10672. else {
  10673. // Consider this situatoin:
  10674. // optionA: [{name: 'a'}, {name: 'a'}, {..}]
  10675. // optionB [{..}, {name: 'a'}, {name: 'a'}]
  10676. // Series with the same name between optionA and optionB
  10677. // should be mapped.
  10678. var idNum = 0;
  10679. do {
  10680. keyInfo.id = '\0' + keyInfo.name + '\0' + idNum++;
  10681. }
  10682. while (idMap.get(keyInfo.id));
  10683. }
  10684. idMap.set(keyInfo.id, item);
  10685. });
  10686. }
  10687. function isNameSpecified(componentModel) {
  10688. var name = componentModel.name;
  10689. // Is specified when `indexOf` get -1 or > 0.
  10690. return !!(name && name.indexOf(DUMMY_COMPONENT_NAME_PREFIX));
  10691. }
  10692. /**
  10693. * @public
  10694. * @param {Object} cptOption
  10695. * @return {boolean}
  10696. */
  10697. function isIdInner(cptOption) {
  10698. return isObject$2(cptOption)
  10699. && cptOption.id
  10700. && (cptOption.id + '').indexOf('\0_ec_\0') === 0;
  10701. }
  10702. /**
  10703. * A helper for removing duplicate items between batchA and batchB,
  10704. * and in themselves, and categorize by series.
  10705. *
  10706. * @param {Array.<Object>} batchA Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...]
  10707. * @param {Array.<Object>} batchB Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...]
  10708. * @return {Array.<Array.<Object>, Array.<Object>>} result: [resultBatchA, resultBatchB]
  10709. */
  10710. function compressBatches(batchA, batchB) {
  10711. var mapA = {};
  10712. var mapB = {};
  10713. makeMap(batchA || [], mapA);
  10714. makeMap(batchB || [], mapB, mapA);
  10715. return [mapToArray(mapA), mapToArray(mapB)];
  10716. function makeMap(sourceBatch, map$$1, otherMap) {
  10717. for (var i = 0, len = sourceBatch.length; i < len; i++) {
  10718. var seriesId = sourceBatch[i].seriesId;
  10719. var dataIndices = normalizeToArray(sourceBatch[i].dataIndex);
  10720. var otherDataIndices = otherMap && otherMap[seriesId];
  10721. for (var j = 0, lenj = dataIndices.length; j < lenj; j++) {
  10722. var dataIndex = dataIndices[j];
  10723. if (otherDataIndices && otherDataIndices[dataIndex]) {
  10724. otherDataIndices[dataIndex] = null;
  10725. }
  10726. else {
  10727. (map$$1[seriesId] || (map$$1[seriesId] = {}))[dataIndex] = 1;
  10728. }
  10729. }
  10730. }
  10731. }
  10732. function mapToArray(map$$1, isData) {
  10733. var result = [];
  10734. for (var i in map$$1) {
  10735. if (map$$1.hasOwnProperty(i) && map$$1[i] != null) {
  10736. if (isData) {
  10737. result.push(+i);
  10738. }
  10739. else {
  10740. var dataIndices = mapToArray(map$$1[i], true);
  10741. dataIndices.length && result.push({seriesId: i, dataIndex: dataIndices});
  10742. }
  10743. }
  10744. }
  10745. return result;
  10746. }
  10747. }
  10748. /**
  10749. * @param {module:echarts/data/List} data
  10750. * @param {Object} payload Contains dataIndex (means rawIndex) / dataIndexInside / name
  10751. * each of which can be Array or primary type.
  10752. * @return {number|Array.<number>} dataIndex If not found, return undefined/null.
  10753. */
  10754. function queryDataIndex(data, payload) {
  10755. if (payload.dataIndexInside != null) {
  10756. return payload.dataIndexInside;
  10757. }
  10758. else if (payload.dataIndex != null) {
  10759. return isArray(payload.dataIndex)
  10760. ? map(payload.dataIndex, function (value) {
  10761. return data.indexOfRawIndex(value);
  10762. })
  10763. : data.indexOfRawIndex(payload.dataIndex);
  10764. }
  10765. else if (payload.name != null) {
  10766. return isArray(payload.name)
  10767. ? map(payload.name, function (value) {
  10768. return data.indexOfName(value);
  10769. })
  10770. : data.indexOfName(payload.name);
  10771. }
  10772. }
  10773. /**
  10774. * Enable property storage to any host object.
  10775. * Notice: Serialization is not supported.
  10776. *
  10777. * For example:
  10778. * var inner = zrUitl.makeInner();
  10779. *
  10780. * function some1(hostObj) {
  10781. * inner(hostObj).someProperty = 1212;
  10782. * ...
  10783. * }
  10784. * function some2() {
  10785. * var fields = inner(this);
  10786. * fields.someProperty1 = 1212;
  10787. * fields.someProperty2 = 'xx';
  10788. * ...
  10789. * }
  10790. *
  10791. * @return {Function}
  10792. */
  10793. function makeInner() {
  10794. // Consider different scope by es module import.
  10795. var key = '__\0ec_inner_' + innerUniqueIndex++ + '_' + Math.random().toFixed(5);
  10796. return function (hostObj) {
  10797. return hostObj[key] || (hostObj[key] = {});
  10798. };
  10799. }
  10800. var innerUniqueIndex = 0;
  10801. /**
  10802. * @param {module:echarts/model/Global} ecModel
  10803. * @param {string|Object} finder
  10804. * If string, e.g., 'geo', means {geoIndex: 0}.
  10805. * If Object, could contain some of these properties below:
  10806. * {
  10807. * seriesIndex, seriesId, seriesName,
  10808. * geoIndex, geoId, geoName,
  10809. * bmapIndex, bmapId, bmapName,
  10810. * xAxisIndex, xAxisId, xAxisName,
  10811. * yAxisIndex, yAxisId, yAxisName,
  10812. * gridIndex, gridId, gridName,
  10813. * ... (can be extended)
  10814. * }
  10815. * Each properties can be number|string|Array.<number>|Array.<string>
  10816. * For example, a finder could be
  10817. * {
  10818. * seriesIndex: 3,
  10819. * geoId: ['aa', 'cc'],
  10820. * gridName: ['xx', 'rr']
  10821. * }
  10822. * xxxIndex can be set as 'all' (means all xxx) or 'none' (means not specify)
  10823. * If nothing or null/undefined specified, return nothing.
  10824. * @param {Object} [opt]
  10825. * @param {string} [opt.defaultMainType]
  10826. * @param {Array.<string>} [opt.includeMainTypes]
  10827. * @return {Object} result like:
  10828. * {
  10829. * seriesModels: [seriesModel1, seriesModel2],
  10830. * seriesModel: seriesModel1, // The first model
  10831. * geoModels: [geoModel1, geoModel2],
  10832. * geoModel: geoModel1, // The first model
  10833. * ...
  10834. * }
  10835. */
  10836. function parseFinder(ecModel, finder, opt) {
  10837. if (isString(finder)) {
  10838. var obj = {};
  10839. obj[finder + 'Index'] = 0;
  10840. finder = obj;
  10841. }
  10842. var defaultMainType = opt && opt.defaultMainType;
  10843. if (defaultMainType
  10844. && !has(finder, defaultMainType + 'Index')
  10845. && !has(finder, defaultMainType + 'Id')
  10846. && !has(finder, defaultMainType + 'Name')
  10847. ) {
  10848. finder[defaultMainType + 'Index'] = 0;
  10849. }
  10850. var result = {};
  10851. each$2(finder, function (value, key) {
  10852. var value = finder[key];
  10853. // Exclude 'dataIndex' and other illgal keys.
  10854. if (key === 'dataIndex' || key === 'dataIndexInside') {
  10855. result[key] = value;
  10856. return;
  10857. }
  10858. var parsedKey = key.match(/^(\w+)(Index|Id|Name)$/) || [];
  10859. var mainType = parsedKey[1];
  10860. var queryType = (parsedKey[2] || '').toLowerCase();
  10861. if (!mainType
  10862. || !queryType
  10863. || value == null
  10864. || (queryType === 'index' && value === 'none')
  10865. || (opt && opt.includeMainTypes && indexOf(opt.includeMainTypes, mainType) < 0)
  10866. ) {
  10867. return;
  10868. }
  10869. var queryParam = {mainType: mainType};
  10870. if (queryType !== 'index' || value !== 'all') {
  10871. queryParam[queryType] = value;
  10872. }
  10873. var models = ecModel.queryComponents(queryParam);
  10874. result[mainType + 'Models'] = models;
  10875. result[mainType + 'Model'] = models[0];
  10876. });
  10877. return result;
  10878. }
  10879. function has(obj, prop) {
  10880. return obj && obj.hasOwnProperty(prop);
  10881. }
  10882. function setAttribute(dom, key, value) {
  10883. dom.setAttribute
  10884. ? dom.setAttribute(key, value)
  10885. : (dom[key] = value);
  10886. }
  10887. function getAttribute(dom, key) {
  10888. return dom.getAttribute
  10889. ? dom.getAttribute(key)
  10890. : dom[key];
  10891. }
  10892. function getTooltipRenderMode(renderModeOption) {
  10893. if (renderModeOption === 'auto') {
  10894. // Using html when `document` exists, use richText otherwise
  10895. return env$1.domSupported ? 'html' : 'richText';
  10896. }
  10897. else {
  10898. return renderModeOption || 'html';
  10899. }
  10900. }
  10901. /**
  10902. * Group a list by key.
  10903. *
  10904. * @param {Array} array
  10905. * @param {Function} getKey
  10906. * param {*} Array item
  10907. * return {string} key
  10908. * @return {Object} Result
  10909. * {Array}: keys,
  10910. * {module:zrender/core/util/HashMap} buckets: {key -> Array}
  10911. */
  10912. function groupData(array, getKey) {
  10913. var buckets = createHashMap();
  10914. var keys = [];
  10915. each$1(array, function (item) {
  10916. var key = getKey(item);
  10917. (buckets.get(key)
  10918. || (keys.push(key), buckets.set(key, []))
  10919. ).push(item);
  10920. });
  10921. return {keys: keys, buckets: buckets};
  10922. }
  10923. /*
  10924. * Licensed to the Apache Software Foundation (ASF) under one
  10925. * or more contributor license agreements. See the NOTICE file
  10926. * distributed with this work for additional information
  10927. * regarding copyright ownership. The ASF licenses this file
  10928. * to you under the Apache License, Version 2.0 (the
  10929. * "License"); you may not use this file except in compliance
  10930. * with the License. You may obtain a copy of the License at
  10931. *
  10932. * http://www.apache.org/licenses/LICENSE-2.0
  10933. *
  10934. * Unless required by applicable law or agreed to in writing,
  10935. * software distributed under the License is distributed on an
  10936. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10937. * KIND, either express or implied. See the License for the
  10938. * specific language governing permissions and limitations
  10939. * under the License.
  10940. */
  10941. var TYPE_DELIMITER = '.';
  10942. var IS_CONTAINER = '___EC__COMPONENT__CONTAINER___';
  10943. /**
  10944. * Notice, parseClassType('') should returns {main: '', sub: ''}
  10945. * @public
  10946. */
  10947. function parseClassType$1(componentType) {
  10948. var ret = {main: '', sub: ''};
  10949. if (componentType) {
  10950. componentType = componentType.split(TYPE_DELIMITER);
  10951. ret.main = componentType[0] || '';
  10952. ret.sub = componentType[1] || '';
  10953. }
  10954. return ret;
  10955. }
  10956. /**
  10957. * @public
  10958. */
  10959. function checkClassType(componentType) {
  10960. assert$1(
  10961. /^[a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)?$/.test(componentType),
  10962. 'componentType "' + componentType + '" illegal'
  10963. );
  10964. }
  10965. /**
  10966. * @public
  10967. */
  10968. function enableClassExtend(RootClass, mandatoryMethods) {
  10969. RootClass.$constructor = RootClass;
  10970. RootClass.extend = function (proto) {
  10971. if (__DEV__) {
  10972. each$1(mandatoryMethods, function (method) {
  10973. if (!proto[method]) {
  10974. console.warn(
  10975. 'Method `' + method + '` should be implemented'
  10976. + (proto.type ? ' in ' + proto.type : '') + '.'
  10977. );
  10978. }
  10979. });
  10980. }
  10981. var superClass = this;
  10982. var ExtendedClass = function () {
  10983. if (!proto.$constructor) {
  10984. superClass.apply(this, arguments);
  10985. }
  10986. else {
  10987. proto.$constructor.apply(this, arguments);
  10988. }
  10989. };
  10990. extend(ExtendedClass.prototype, proto);
  10991. ExtendedClass.extend = this.extend;
  10992. ExtendedClass.superCall = superCall;
  10993. ExtendedClass.superApply = superApply;
  10994. inherits(ExtendedClass, this);
  10995. ExtendedClass.superClass = superClass;
  10996. return ExtendedClass;
  10997. };
  10998. }
  10999. var classBase = 0;
  11000. /**
  11001. * Can not use instanceof, consider different scope by
  11002. * cross domain or es module import in ec extensions.
  11003. * Mount a method "isInstance()" to Clz.
  11004. */
  11005. function enableClassCheck(Clz) {
  11006. var classAttr = ['__\0is_clz', classBase++, Math.random().toFixed(3)].join('_');
  11007. Clz.prototype[classAttr] = true;
  11008. if (__DEV__) {
  11009. assert$1(!Clz.isInstance, 'The method "is" can not be defined.');
  11010. }
  11011. Clz.isInstance = function (obj) {
  11012. return !!(obj && obj[classAttr]);
  11013. };
  11014. }
  11015. // superCall should have class info, which can not be fetch from 'this'.
  11016. // Consider this case:
  11017. // class A has method f,
  11018. // class B inherits class A, overrides method f, f call superApply('f'),
  11019. // class C inherits class B, do not overrides method f,
  11020. // then when method of class C is called, dead loop occured.
  11021. function superCall(context, methodName) {
  11022. var args = slice(arguments, 2);
  11023. return this.superClass.prototype[methodName].apply(context, args);
  11024. }
  11025. function superApply(context, methodName, args) {
  11026. return this.superClass.prototype[methodName].apply(context, args);
  11027. }
  11028. /**
  11029. * @param {Object} entity
  11030. * @param {Object} options
  11031. * @param {boolean} [options.registerWhenExtend]
  11032. * @public
  11033. */
  11034. function enableClassManagement(entity, options) {
  11035. options = options || {};
  11036. /**
  11037. * Component model classes
  11038. * key: componentType,
  11039. * value:
  11040. * componentClass, when componentType is 'xxx'
  11041. * or Object.<subKey, componentClass>, when componentType is 'xxx.yy'
  11042. * @type {Object}
  11043. */
  11044. var storage = {};
  11045. entity.registerClass = function (Clazz, componentType) {
  11046. if (componentType) {
  11047. checkClassType(componentType);
  11048. componentType = parseClassType$1(componentType);
  11049. if (!componentType.sub) {
  11050. if (__DEV__) {
  11051. if (storage[componentType.main]) {
  11052. console.warn(componentType.main + ' exists.');
  11053. }
  11054. }
  11055. storage[componentType.main] = Clazz;
  11056. }
  11057. else if (componentType.sub !== IS_CONTAINER) {
  11058. var container = makeContainer(componentType);
  11059. container[componentType.sub] = Clazz;
  11060. }
  11061. }
  11062. return Clazz;
  11063. };
  11064. entity.getClass = function (componentMainType, subType, throwWhenNotFound) {
  11065. var Clazz = storage[componentMainType];
  11066. if (Clazz && Clazz[IS_CONTAINER]) {
  11067. Clazz = subType ? Clazz[subType] : null;
  11068. }
  11069. if (throwWhenNotFound && !Clazz) {
  11070. throw new Error(
  11071. !subType
  11072. ? componentMainType + '.' + 'type should be specified.'
  11073. : 'Component ' + componentMainType + '.' + (subType || '') + ' not exists. Load it first.'
  11074. );
  11075. }
  11076. return Clazz;
  11077. };
  11078. entity.getClassesByMainType = function (componentType) {
  11079. componentType = parseClassType$1(componentType);
  11080. var result = [];
  11081. var obj = storage[componentType.main];
  11082. if (obj && obj[IS_CONTAINER]) {
  11083. each$1(obj, function (o, type) {
  11084. type !== IS_CONTAINER && result.push(o);
  11085. });
  11086. }
  11087. else {
  11088. result.push(obj);
  11089. }
  11090. return result;
  11091. };
  11092. entity.hasClass = function (componentType) {
  11093. // Just consider componentType.main.
  11094. componentType = parseClassType$1(componentType);
  11095. return !!storage[componentType.main];
  11096. };
  11097. /**
  11098. * @return {Array.<string>} Like ['aa', 'bb'], but can not be ['aa.xx']
  11099. */
  11100. entity.getAllClassMainTypes = function () {
  11101. var types = [];
  11102. each$1(storage, function (obj, type) {
  11103. types.push(type);
  11104. });
  11105. return types;
  11106. };
  11107. /**
  11108. * If a main type is container and has sub types
  11109. * @param {string} mainType
  11110. * @return {boolean}
  11111. */
  11112. entity.hasSubTypes = function (componentType) {
  11113. componentType = parseClassType$1(componentType);
  11114. var obj = storage[componentType.main];
  11115. return obj && obj[IS_CONTAINER];
  11116. };
  11117. entity.parseClassType = parseClassType$1;
  11118. function makeContainer(componentType) {
  11119. var container = storage[componentType.main];
  11120. if (!container || !container[IS_CONTAINER]) {
  11121. container = storage[componentType.main] = {};
  11122. container[IS_CONTAINER] = true;
  11123. }
  11124. return container;
  11125. }
  11126. if (options.registerWhenExtend) {
  11127. var originalExtend = entity.extend;
  11128. if (originalExtend) {
  11129. entity.extend = function (proto) {
  11130. var ExtendedClass = originalExtend.call(this, proto);
  11131. return entity.registerClass(ExtendedClass, proto.type);
  11132. };
  11133. }
  11134. }
  11135. return entity;
  11136. }
  11137. /**
  11138. * @param {string|Array.<string>} properties
  11139. */
  11140. /*
  11141. * Licensed to the Apache Software Foundation (ASF) under one
  11142. * or more contributor license agreements. See the NOTICE file
  11143. * distributed with this work for additional information
  11144. * regarding copyright ownership. The ASF licenses this file
  11145. * to you under the Apache License, Version 2.0 (the
  11146. * "License"); you may not use this file except in compliance
  11147. * with the License. You may obtain a copy of the License at
  11148. *
  11149. * http://www.apache.org/licenses/LICENSE-2.0
  11150. *
  11151. * Unless required by applicable law or agreed to in writing,
  11152. * software distributed under the License is distributed on an
  11153. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  11154. * KIND, either express or implied. See the License for the
  11155. * specific language governing permissions and limitations
  11156. * under the License.
  11157. */
  11158. // TODO Parse shadow style
  11159. // TODO Only shallow path support
  11160. var makeStyleMapper = function (properties) {
  11161. // Normalize
  11162. for (var i = 0; i < properties.length; i++) {
  11163. if (!properties[i][1]) {
  11164. properties[i][1] = properties[i][0];
  11165. }
  11166. }
  11167. return function (model, excludes, includes) {
  11168. var style = {};
  11169. for (var i = 0; i < properties.length; i++) {
  11170. var propName = properties[i][1];
  11171. if ((excludes && indexOf(excludes, propName) >= 0)
  11172. || (includes && indexOf(includes, propName) < 0)
  11173. ) {
  11174. continue;
  11175. }
  11176. var val = model.getShallow(propName);
  11177. if (val != null) {
  11178. style[properties[i][0]] = val;
  11179. }
  11180. }
  11181. return style;
  11182. };
  11183. };
  11184. /*
  11185. * Licensed to the Apache Software Foundation (ASF) under one
  11186. * or more contributor license agreements. See the NOTICE file
  11187. * distributed with this work for additional information
  11188. * regarding copyright ownership. The ASF licenses this file
  11189. * to you under the Apache License, Version 2.0 (the
  11190. * "License"); you may not use this file except in compliance
  11191. * with the License. You may obtain a copy of the License at
  11192. *
  11193. * http://www.apache.org/licenses/LICENSE-2.0
  11194. *
  11195. * Unless required by applicable law or agreed to in writing,
  11196. * software distributed under the License is distributed on an
  11197. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  11198. * KIND, either express or implied. See the License for the
  11199. * specific language governing permissions and limitations
  11200. * under the License.
  11201. */
  11202. var getLineStyle = makeStyleMapper(
  11203. [
  11204. ['lineWidth', 'width'],
  11205. ['stroke', 'color'],
  11206. ['opacity'],
  11207. ['shadowBlur'],
  11208. ['shadowOffsetX'],
  11209. ['shadowOffsetY'],
  11210. ['shadowColor']
  11211. ]
  11212. );
  11213. var lineStyleMixin = {
  11214. getLineStyle: function (excludes) {
  11215. var style = getLineStyle(this, excludes);
  11216. // Always set lineDash whether dashed, otherwise we can not
  11217. // erase the previous style when assigning to el.style.
  11218. style.lineDash = this.getLineDash(style.lineWidth);
  11219. return style;
  11220. },
  11221. getLineDash: function (lineWidth) {
  11222. if (lineWidth == null) {
  11223. lineWidth = 1;
  11224. }
  11225. var lineType = this.get('type');
  11226. var dotSize = Math.max(lineWidth, 2);
  11227. var dashSize = lineWidth * 4;
  11228. return (lineType === 'solid' || lineType == null)
  11229. // Use `false` but not `null` for the solid line here, because `null` might be
  11230. // ignored when assigning to `el.style`. e.g., when setting `lineStyle.type` as
  11231. // `'dashed'` and `emphasis.lineStyle.type` as `'solid'` in graph series, the
  11232. // `lineDash` gotten form the latter one is not able to erase that from the former
  11233. // one if using `null` here according to the emhpsis strategy in `util/graphic.js`.
  11234. ? false
  11235. : lineType === 'dashed'
  11236. ? [dashSize, dashSize]
  11237. : [dotSize, dotSize];
  11238. }
  11239. };
  11240. /*
  11241. * Licensed to the Apache Software Foundation (ASF) under one
  11242. * or more contributor license agreements. See the NOTICE file
  11243. * distributed with this work for additional information
  11244. * regarding copyright ownership. The ASF licenses this file
  11245. * to you under the Apache License, Version 2.0 (the
  11246. * "License"); you may not use this file except in compliance
  11247. * with the License. You may obtain a copy of the License at
  11248. *
  11249. * http://www.apache.org/licenses/LICENSE-2.0
  11250. *
  11251. * Unless required by applicable law or agreed to in writing,
  11252. * software distributed under the License is distributed on an
  11253. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  11254. * KIND, either express or implied. See the License for the
  11255. * specific language governing permissions and limitations
  11256. * under the License.
  11257. */
  11258. var getAreaStyle = makeStyleMapper(
  11259. [
  11260. ['fill', 'color'],
  11261. ['shadowBlur'],
  11262. ['shadowOffsetX'],
  11263. ['shadowOffsetY'],
  11264. ['opacity'],
  11265. ['shadowColor']
  11266. ]
  11267. );
  11268. var areaStyleMixin = {
  11269. getAreaStyle: function (excludes, includes) {
  11270. return getAreaStyle(this, excludes, includes);
  11271. }
  11272. };
  11273. /**
  11274. * 曲线辅助模块
  11275. * @module zrender/core/curve
  11276. * @author pissang(https://www.github.com/pissang)
  11277. */
  11278. var mathPow = Math.pow;
  11279. var mathSqrt$2 = Math.sqrt;
  11280. var EPSILON$1 = 1e-8;
  11281. var EPSILON_NUMERIC = 1e-4;
  11282. var THREE_SQRT = mathSqrt$2(3);
  11283. var ONE_THIRD = 1 / 3;
  11284. // 临时变量
  11285. var _v0 = create();
  11286. var _v1 = create();
  11287. var _v2 = create();
  11288. function isAroundZero(val) {
  11289. return val > -EPSILON$1 && val < EPSILON$1;
  11290. }
  11291. function isNotAroundZero$1(val) {
  11292. return val > EPSILON$1 || val < -EPSILON$1;
  11293. }
  11294. /**
  11295. * 计算三次贝塞尔值
  11296. * @memberOf module:zrender/core/curve
  11297. * @param {number} p0
  11298. * @param {number} p1
  11299. * @param {number} p2
  11300. * @param {number} p3
  11301. * @param {number} t
  11302. * @return {number}
  11303. */
  11304. function cubicAt(p0, p1, p2, p3, t) {
  11305. var onet = 1 - t;
  11306. return onet * onet * (onet * p0 + 3 * t * p1)
  11307. + t * t * (t * p3 + 3 * onet * p2);
  11308. }
  11309. /**
  11310. * 计算三次贝塞尔导数值
  11311. * @memberOf module:zrender/core/curve
  11312. * @param {number} p0
  11313. * @param {number} p1
  11314. * @param {number} p2
  11315. * @param {number} p3
  11316. * @param {number} t
  11317. * @return {number}
  11318. */
  11319. function cubicDerivativeAt(p0, p1, p2, p3, t) {
  11320. var onet = 1 - t;
  11321. return 3 * (
  11322. ((p1 - p0) * onet + 2 * (p2 - p1) * t) * onet
  11323. + (p3 - p2) * t * t
  11324. );
  11325. }
  11326. /**
  11327. * 计算三次贝塞尔方程根,使用盛金公式
  11328. * @memberOf module:zrender/core/curve
  11329. * @param {number} p0
  11330. * @param {number} p1
  11331. * @param {number} p2
  11332. * @param {number} p3
  11333. * @param {number} val
  11334. * @param {Array.<number>} roots
  11335. * @return {number} 有效根数目
  11336. */
  11337. function cubicRootAt(p0, p1, p2, p3, val, roots) {
  11338. // Evaluate roots of cubic functions
  11339. var a = p3 + 3 * (p1 - p2) - p0;
  11340. var b = 3 * (p2 - p1 * 2 + p0);
  11341. var c = 3 * (p1 - p0);
  11342. var d = p0 - val;
  11343. var A = b * b - 3 * a * c;
  11344. var B = b * c - 9 * a * d;
  11345. var C = c * c - 3 * b * d;
  11346. var n = 0;
  11347. if (isAroundZero(A) && isAroundZero(B)) {
  11348. if (isAroundZero(b)) {
  11349. roots[0] = 0;
  11350. }
  11351. else {
  11352. var t1 = -c / b; //t1, t2, t3, b is not zero
  11353. if (t1 >= 0 && t1 <= 1) {
  11354. roots[n++] = t1;
  11355. }
  11356. }
  11357. }
  11358. else {
  11359. var disc = B * B - 4 * A * C;
  11360. if (isAroundZero(disc)) {
  11361. var K = B / A;
  11362. var t1 = -b / a + K; // t1, a is not zero
  11363. var t2 = -K / 2; // t2, t3
  11364. if (t1 >= 0 && t1 <= 1) {
  11365. roots[n++] = t1;
  11366. }
  11367. if (t2 >= 0 && t2 <= 1) {
  11368. roots[n++] = t2;
  11369. }
  11370. }
  11371. else if (disc > 0) {
  11372. var discSqrt = mathSqrt$2(disc);
  11373. var Y1 = A * b + 1.5 * a * (-B + discSqrt);
  11374. var Y2 = A * b + 1.5 * a * (-B - discSqrt);
  11375. if (Y1 < 0) {
  11376. Y1 = -mathPow(-Y1, ONE_THIRD);
  11377. }
  11378. else {
  11379. Y1 = mathPow(Y1, ONE_THIRD);
  11380. }
  11381. if (Y2 < 0) {
  11382. Y2 = -mathPow(-Y2, ONE_THIRD);
  11383. }
  11384. else {
  11385. Y2 = mathPow(Y2, ONE_THIRD);
  11386. }
  11387. var t1 = (-b - (Y1 + Y2)) / (3 * a);
  11388. if (t1 >= 0 && t1 <= 1) {
  11389. roots[n++] = t1;
  11390. }
  11391. }
  11392. else {
  11393. var T = (2 * A * b - 3 * a * B) / (2 * mathSqrt$2(A * A * A));
  11394. var theta = Math.acos(T) / 3;
  11395. var ASqrt = mathSqrt$2(A);
  11396. var tmp = Math.cos(theta);
  11397. var t1 = (-b - 2 * ASqrt * tmp) / (3 * a);
  11398. var t2 = (-b + ASqrt * (tmp + THREE_SQRT * Math.sin(theta))) / (3 * a);
  11399. var t3 = (-b + ASqrt * (tmp - THREE_SQRT * Math.sin(theta))) / (3 * a);
  11400. if (t1 >= 0 && t1 <= 1) {
  11401. roots[n++] = t1;
  11402. }
  11403. if (t2 >= 0 && t2 <= 1) {
  11404. roots[n++] = t2;
  11405. }
  11406. if (t3 >= 0 && t3 <= 1) {
  11407. roots[n++] = t3;
  11408. }
  11409. }
  11410. }
  11411. return n;
  11412. }
  11413. /**
  11414. * 计算三次贝塞尔方程极限值的位置
  11415. * @memberOf module:zrender/core/curve
  11416. * @param {number} p0
  11417. * @param {number} p1
  11418. * @param {number} p2
  11419. * @param {number} p3
  11420. * @param {Array.<number>} extrema
  11421. * @return {number} 有效数目
  11422. */
  11423. function cubicExtrema(p0, p1, p2, p3, extrema) {
  11424. var b = 6 * p2 - 12 * p1 + 6 * p0;
  11425. var a = 9 * p1 + 3 * p3 - 3 * p0 - 9 * p2;
  11426. var c = 3 * p1 - 3 * p0;
  11427. var n = 0;
  11428. if (isAroundZero(a)) {
  11429. if (isNotAroundZero$1(b)) {
  11430. var t1 = -c / b;
  11431. if (t1 >= 0 && t1 <= 1) {
  11432. extrema[n++] = t1;
  11433. }
  11434. }
  11435. }
  11436. else {
  11437. var disc = b * b - 4 * a * c;
  11438. if (isAroundZero(disc)) {
  11439. extrema[0] = -b / (2 * a);
  11440. }
  11441. else if (disc > 0) {
  11442. var discSqrt = mathSqrt$2(disc);
  11443. var t1 = (-b + discSqrt) / (2 * a);
  11444. var t2 = (-b - discSqrt) / (2 * a);
  11445. if (t1 >= 0 && t1 <= 1) {
  11446. extrema[n++] = t1;
  11447. }
  11448. if (t2 >= 0 && t2 <= 1) {
  11449. extrema[n++] = t2;
  11450. }
  11451. }
  11452. }
  11453. return n;
  11454. }
  11455. /**
  11456. * 细分三次贝塞尔曲线
  11457. * @memberOf module:zrender/core/curve
  11458. * @param {number} p0
  11459. * @param {number} p1
  11460. * @param {number} p2
  11461. * @param {number} p3
  11462. * @param {number} t
  11463. * @param {Array.<number>} out
  11464. */
  11465. function cubicSubdivide(p0, p1, p2, p3, t, out) {
  11466. var p01 = (p1 - p0) * t + p0;
  11467. var p12 = (p2 - p1) * t + p1;
  11468. var p23 = (p3 - p2) * t + p2;
  11469. var p012 = (p12 - p01) * t + p01;
  11470. var p123 = (p23 - p12) * t + p12;
  11471. var p0123 = (p123 - p012) * t + p012;
  11472. // Seg0
  11473. out[0] = p0;
  11474. out[1] = p01;
  11475. out[2] = p012;
  11476. out[3] = p0123;
  11477. // Seg1
  11478. out[4] = p0123;
  11479. out[5] = p123;
  11480. out[6] = p23;
  11481. out[7] = p3;
  11482. }
  11483. /**
  11484. * 投射点到三次贝塞尔曲线上,返回投射距离。
  11485. * 投射点有可能会有一个或者多个,这里只返回其中距离最短的一个。
  11486. * @param {number} x0
  11487. * @param {number} y0
  11488. * @param {number} x1
  11489. * @param {number} y1
  11490. * @param {number} x2
  11491. * @param {number} y2
  11492. * @param {number} x3
  11493. * @param {number} y3
  11494. * @param {number} x
  11495. * @param {number} y
  11496. * @param {Array.<number>} [out] 投射点
  11497. * @return {number}
  11498. */
  11499. function cubicProjectPoint(
  11500. x0, y0, x1, y1, x2, y2, x3, y3,
  11501. x, y, out
  11502. ) {
  11503. // http://pomax.github.io/bezierinfo/#projections
  11504. var t;
  11505. var interval = 0.005;
  11506. var d = Infinity;
  11507. var prev;
  11508. var next;
  11509. var d1;
  11510. var d2;
  11511. _v0[0] = x;
  11512. _v0[1] = y;
  11513. // 先粗略估计一下可能的最小距离的 t 值
  11514. // PENDING
  11515. for (var _t = 0; _t < 1; _t += 0.05) {
  11516. _v1[0] = cubicAt(x0, x1, x2, x3, _t);
  11517. _v1[1] = cubicAt(y0, y1, y2, y3, _t);
  11518. d1 = distSquare(_v0, _v1);
  11519. if (d1 < d) {
  11520. t = _t;
  11521. d = d1;
  11522. }
  11523. }
  11524. d = Infinity;
  11525. // At most 32 iteration
  11526. for (var i = 0; i < 32; i++) {
  11527. if (interval < EPSILON_NUMERIC) {
  11528. break;
  11529. }
  11530. prev = t - interval;
  11531. next = t + interval;
  11532. // t - interval
  11533. _v1[0] = cubicAt(x0, x1, x2, x3, prev);
  11534. _v1[1] = cubicAt(y0, y1, y2, y3, prev);
  11535. d1 = distSquare(_v1, _v0);
  11536. if (prev >= 0 && d1 < d) {
  11537. t = prev;
  11538. d = d1;
  11539. }
  11540. else {
  11541. // t + interval
  11542. _v2[0] = cubicAt(x0, x1, x2, x3, next);
  11543. _v2[1] = cubicAt(y0, y1, y2, y3, next);
  11544. d2 = distSquare(_v2, _v0);
  11545. if (next <= 1 && d2 < d) {
  11546. t = next;
  11547. d = d2;
  11548. }
  11549. else {
  11550. interval *= 0.5;
  11551. }
  11552. }
  11553. }
  11554. // t
  11555. if (out) {
  11556. out[0] = cubicAt(x0, x1, x2, x3, t);
  11557. out[1] = cubicAt(y0, y1, y2, y3, t);
  11558. }
  11559. // console.log(interval, i);
  11560. return mathSqrt$2(d);
  11561. }
  11562. /**
  11563. * 计算二次方贝塞尔值
  11564. * @param {number} p0
  11565. * @param {number} p1
  11566. * @param {number} p2
  11567. * @param {number} t
  11568. * @return {number}
  11569. */
  11570. function quadraticAt(p0, p1, p2, t) {
  11571. var onet = 1 - t;
  11572. return onet * (onet * p0 + 2 * t * p1) + t * t * p2;
  11573. }
  11574. /**
  11575. * 计算二次方贝塞尔导数值
  11576. * @param {number} p0
  11577. * @param {number} p1
  11578. * @param {number} p2
  11579. * @param {number} t
  11580. * @return {number}
  11581. */
  11582. function quadraticDerivativeAt(p0, p1, p2, t) {
  11583. return 2 * ((1 - t) * (p1 - p0) + t * (p2 - p1));
  11584. }
  11585. /**
  11586. * 计算二次方贝塞尔方程根
  11587. * @param {number} p0
  11588. * @param {number} p1
  11589. * @param {number} p2
  11590. * @param {number} t
  11591. * @param {Array.<number>} roots
  11592. * @return {number} 有效根数目
  11593. */
  11594. function quadraticRootAt(p0, p1, p2, val, roots) {
  11595. var a = p0 - 2 * p1 + p2;
  11596. var b = 2 * (p1 - p0);
  11597. var c = p0 - val;
  11598. var n = 0;
  11599. if (isAroundZero(a)) {
  11600. if (isNotAroundZero$1(b)) {
  11601. var t1 = -c / b;
  11602. if (t1 >= 0 && t1 <= 1) {
  11603. roots[n++] = t1;
  11604. }
  11605. }
  11606. }
  11607. else {
  11608. var disc = b * b - 4 * a * c;
  11609. if (isAroundZero(disc)) {
  11610. var t1 = -b / (2 * a);
  11611. if (t1 >= 0 && t1 <= 1) {
  11612. roots[n++] = t1;
  11613. }
  11614. }
  11615. else if (disc > 0) {
  11616. var discSqrt = mathSqrt$2(disc);
  11617. var t1 = (-b + discSqrt) / (2 * a);
  11618. var t2 = (-b - discSqrt) / (2 * a);
  11619. if (t1 >= 0 && t1 <= 1) {
  11620. roots[n++] = t1;
  11621. }
  11622. if (t2 >= 0 && t2 <= 1) {
  11623. roots[n++] = t2;
  11624. }
  11625. }
  11626. }
  11627. return n;
  11628. }
  11629. /**
  11630. * 计算二次贝塞尔方程极限值
  11631. * @memberOf module:zrender/core/curve
  11632. * @param {number} p0
  11633. * @param {number} p1
  11634. * @param {number} p2
  11635. * @return {number}
  11636. */
  11637. function quadraticExtremum(p0, p1, p2) {
  11638. var divider = p0 + p2 - 2 * p1;
  11639. if (divider === 0) {
  11640. // p1 is center of p0 and p2
  11641. return 0.5;
  11642. }
  11643. else {
  11644. return (p0 - p1) / divider;
  11645. }
  11646. }
  11647. /**
  11648. * 细分二次贝塞尔曲线
  11649. * @memberOf module:zrender/core/curve
  11650. * @param {number} p0
  11651. * @param {number} p1
  11652. * @param {number} p2
  11653. * @param {number} t
  11654. * @param {Array.<number>} out
  11655. */
  11656. function quadraticSubdivide(p0, p1, p2, t, out) {
  11657. var p01 = (p1 - p0) * t + p0;
  11658. var p12 = (p2 - p1) * t + p1;
  11659. var p012 = (p12 - p01) * t + p01;
  11660. // Seg0
  11661. out[0] = p0;
  11662. out[1] = p01;
  11663. out[2] = p012;
  11664. // Seg1
  11665. out[3] = p012;
  11666. out[4] = p12;
  11667. out[5] = p2;
  11668. }
  11669. /**
  11670. * 投射点到二次贝塞尔曲线上,返回投射距离。
  11671. * 投射点有可能会有一个或者多个,这里只返回其中距离最短的一个。
  11672. * @param {number} x0
  11673. * @param {number} y0
  11674. * @param {number} x1
  11675. * @param {number} y1
  11676. * @param {number} x2
  11677. * @param {number} y2
  11678. * @param {number} x
  11679. * @param {number} y
  11680. * @param {Array.<number>} out 投射点
  11681. * @return {number}
  11682. */
  11683. function quadraticProjectPoint(
  11684. x0, y0, x1, y1, x2, y2,
  11685. x, y, out
  11686. ) {
  11687. // http://pomax.github.io/bezierinfo/#projections
  11688. var t;
  11689. var interval = 0.005;
  11690. var d = Infinity;
  11691. _v0[0] = x;
  11692. _v0[1] = y;
  11693. // 先粗略估计一下可能的最小距离的 t 值
  11694. // PENDING
  11695. for (var _t = 0; _t < 1; _t += 0.05) {
  11696. _v1[0] = quadraticAt(x0, x1, x2, _t);
  11697. _v1[1] = quadraticAt(y0, y1, y2, _t);
  11698. var d1 = distSquare(_v0, _v1);
  11699. if (d1 < d) {
  11700. t = _t;
  11701. d = d1;
  11702. }
  11703. }
  11704. d = Infinity;
  11705. // At most 32 iteration
  11706. for (var i = 0; i < 32; i++) {
  11707. if (interval < EPSILON_NUMERIC) {
  11708. break;
  11709. }
  11710. var prev = t - interval;
  11711. var next = t + interval;
  11712. // t - interval
  11713. _v1[0] = quadraticAt(x0, x1, x2, prev);
  11714. _v1[1] = quadraticAt(y0, y1, y2, prev);
  11715. var d1 = distSquare(_v1, _v0);
  11716. if (prev >= 0 && d1 < d) {
  11717. t = prev;
  11718. d = d1;
  11719. }
  11720. else {
  11721. // t + interval
  11722. _v2[0] = quadraticAt(x0, x1, x2, next);
  11723. _v2[1] = quadraticAt(y0, y1, y2, next);
  11724. var d2 = distSquare(_v2, _v0);
  11725. if (next <= 1 && d2 < d) {
  11726. t = next;
  11727. d = d2;
  11728. }
  11729. else {
  11730. interval *= 0.5;
  11731. }
  11732. }
  11733. }
  11734. // t
  11735. if (out) {
  11736. out[0] = quadraticAt(x0, x1, x2, t);
  11737. out[1] = quadraticAt(y0, y1, y2, t);
  11738. }
  11739. // console.log(interval, i);
  11740. return mathSqrt$2(d);
  11741. }
  11742. /**
  11743. * @author Yi Shen(https://github.com/pissang)
  11744. */
  11745. var mathMin$3 = Math.min;
  11746. var mathMax$3 = Math.max;
  11747. var mathSin$2 = Math.sin;
  11748. var mathCos$2 = Math.cos;
  11749. var PI2 = Math.PI * 2;
  11750. var start = create();
  11751. var end = create();
  11752. var extremity = create();
  11753. /**
  11754. * 从顶点数组中计算出最小包围盒,写入`min`和`max`中
  11755. * @module zrender/core/bbox
  11756. * @param {Array<Object>} points 顶点数组
  11757. * @param {number} min
  11758. * @param {number} max
  11759. */
  11760. function fromPoints(points, min$$1, max$$1) {
  11761. if (points.length === 0) {
  11762. return;
  11763. }
  11764. var p = points[0];
  11765. var left = p[0];
  11766. var right = p[0];
  11767. var top = p[1];
  11768. var bottom = p[1];
  11769. var i;
  11770. for (i = 1; i < points.length; i++) {
  11771. p = points[i];
  11772. left = mathMin$3(left, p[0]);
  11773. right = mathMax$3(right, p[0]);
  11774. top = mathMin$3(top, p[1]);
  11775. bottom = mathMax$3(bottom, p[1]);
  11776. }
  11777. min$$1[0] = left;
  11778. min$$1[1] = top;
  11779. max$$1[0] = right;
  11780. max$$1[1] = bottom;
  11781. }
  11782. /**
  11783. * @memberOf module:zrender/core/bbox
  11784. * @param {number} x0
  11785. * @param {number} y0
  11786. * @param {number} x1
  11787. * @param {number} y1
  11788. * @param {Array.<number>} min
  11789. * @param {Array.<number>} max
  11790. */
  11791. function fromLine(x0, y0, x1, y1, min$$1, max$$1) {
  11792. min$$1[0] = mathMin$3(x0, x1);
  11793. min$$1[1] = mathMin$3(y0, y1);
  11794. max$$1[0] = mathMax$3(x0, x1);
  11795. max$$1[1] = mathMax$3(y0, y1);
  11796. }
  11797. var xDim = [];
  11798. var yDim = [];
  11799. /**
  11800. * 从三阶贝塞尔曲线(p0, p1, p2, p3)中计算出最小包围盒,写入`min`和`max`中
  11801. * @memberOf module:zrender/core/bbox
  11802. * @param {number} x0
  11803. * @param {number} y0
  11804. * @param {number} x1
  11805. * @param {number} y1
  11806. * @param {number} x2
  11807. * @param {number} y2
  11808. * @param {number} x3
  11809. * @param {number} y3
  11810. * @param {Array.<number>} min
  11811. * @param {Array.<number>} max
  11812. */
  11813. function fromCubic(
  11814. x0, y0, x1, y1, x2, y2, x3, y3, min$$1, max$$1
  11815. ) {
  11816. var cubicExtrema$$1 = cubicExtrema;
  11817. var cubicAt$$1 = cubicAt;
  11818. var i;
  11819. var n = cubicExtrema$$1(x0, x1, x2, x3, xDim);
  11820. min$$1[0] = Infinity;
  11821. min$$1[1] = Infinity;
  11822. max$$1[0] = -Infinity;
  11823. max$$1[1] = -Infinity;
  11824. for (i = 0; i < n; i++) {
  11825. var x = cubicAt$$1(x0, x1, x2, x3, xDim[i]);
  11826. min$$1[0] = mathMin$3(x, min$$1[0]);
  11827. max$$1[0] = mathMax$3(x, max$$1[0]);
  11828. }
  11829. n = cubicExtrema$$1(y0, y1, y2, y3, yDim);
  11830. for (i = 0; i < n; i++) {
  11831. var y = cubicAt$$1(y0, y1, y2, y3, yDim[i]);
  11832. min$$1[1] = mathMin$3(y, min$$1[1]);
  11833. max$$1[1] = mathMax$3(y, max$$1[1]);
  11834. }
  11835. min$$1[0] = mathMin$3(x0, min$$1[0]);
  11836. max$$1[0] = mathMax$3(x0, max$$1[0]);
  11837. min$$1[0] = mathMin$3(x3, min$$1[0]);
  11838. max$$1[0] = mathMax$3(x3, max$$1[0]);
  11839. min$$1[1] = mathMin$3(y0, min$$1[1]);
  11840. max$$1[1] = mathMax$3(y0, max$$1[1]);
  11841. min$$1[1] = mathMin$3(y3, min$$1[1]);
  11842. max$$1[1] = mathMax$3(y3, max$$1[1]);
  11843. }
  11844. /**
  11845. * 从二阶贝塞尔曲线(p0, p1, p2)中计算出最小包围盒,写入`min`和`max`中
  11846. * @memberOf module:zrender/core/bbox
  11847. * @param {number} x0
  11848. * @param {number} y0
  11849. * @param {number} x1
  11850. * @param {number} y1
  11851. * @param {number} x2
  11852. * @param {number} y2
  11853. * @param {Array.<number>} min
  11854. * @param {Array.<number>} max
  11855. */
  11856. function fromQuadratic(x0, y0, x1, y1, x2, y2, min$$1, max$$1) {
  11857. var quadraticExtremum$$1 = quadraticExtremum;
  11858. var quadraticAt$$1 = quadraticAt;
  11859. // Find extremities, where derivative in x dim or y dim is zero
  11860. var tx =
  11861. mathMax$3(
  11862. mathMin$3(quadraticExtremum$$1(x0, x1, x2), 1), 0
  11863. );
  11864. var ty =
  11865. mathMax$3(
  11866. mathMin$3(quadraticExtremum$$1(y0, y1, y2), 1), 0
  11867. );
  11868. var x = quadraticAt$$1(x0, x1, x2, tx);
  11869. var y = quadraticAt$$1(y0, y1, y2, ty);
  11870. min$$1[0] = mathMin$3(x0, x2, x);
  11871. min$$1[1] = mathMin$3(y0, y2, y);
  11872. max$$1[0] = mathMax$3(x0, x2, x);
  11873. max$$1[1] = mathMax$3(y0, y2, y);
  11874. }
  11875. /**
  11876. * 从圆弧中计算出最小包围盒,写入`min`和`max`中
  11877. * @method
  11878. * @memberOf module:zrender/core/bbox
  11879. * @param {number} x
  11880. * @param {number} y
  11881. * @param {number} rx
  11882. * @param {number} ry
  11883. * @param {number} startAngle
  11884. * @param {number} endAngle
  11885. * @param {number} anticlockwise
  11886. * @param {Array.<number>} min
  11887. * @param {Array.<number>} max
  11888. */
  11889. function fromArc(
  11890. x, y, rx, ry, startAngle, endAngle, anticlockwise, min$$1, max$$1
  11891. ) {
  11892. var vec2Min = min;
  11893. var vec2Max = max;
  11894. var diff = Math.abs(startAngle - endAngle);
  11895. if (diff % PI2 < 1e-4 && diff > 1e-4) {
  11896. // Is a circle
  11897. min$$1[0] = x - rx;
  11898. min$$1[1] = y - ry;
  11899. max$$1[0] = x + rx;
  11900. max$$1[1] = y + ry;
  11901. return;
  11902. }
  11903. start[0] = mathCos$2(startAngle) * rx + x;
  11904. start[1] = mathSin$2(startAngle) * ry + y;
  11905. end[0] = mathCos$2(endAngle) * rx + x;
  11906. end[1] = mathSin$2(endAngle) * ry + y;
  11907. vec2Min(min$$1, start, end);
  11908. vec2Max(max$$1, start, end);
  11909. // Thresh to [0, Math.PI * 2]
  11910. startAngle = startAngle % (PI2);
  11911. if (startAngle < 0) {
  11912. startAngle = startAngle + PI2;
  11913. }
  11914. endAngle = endAngle % (PI2);
  11915. if (endAngle < 0) {
  11916. endAngle = endAngle + PI2;
  11917. }
  11918. if (startAngle > endAngle && !anticlockwise) {
  11919. endAngle += PI2;
  11920. }
  11921. else if (startAngle < endAngle && anticlockwise) {
  11922. startAngle += PI2;
  11923. }
  11924. if (anticlockwise) {
  11925. var tmp = endAngle;
  11926. endAngle = startAngle;
  11927. startAngle = tmp;
  11928. }
  11929. // var number = 0;
  11930. // var step = (anticlockwise ? -Math.PI : Math.PI) / 2;
  11931. for (var angle = 0; angle < endAngle; angle += Math.PI / 2) {
  11932. if (angle > startAngle) {
  11933. extremity[0] = mathCos$2(angle) * rx + x;
  11934. extremity[1] = mathSin$2(angle) * ry + y;
  11935. vec2Min(min$$1, extremity, min$$1);
  11936. vec2Max(max$$1, extremity, max$$1);
  11937. }
  11938. }
  11939. }
  11940. /**
  11941. * Path 代理,可以在`buildPath`中用于替代`ctx`, 会保存每个path操作的命令到pathCommands属性中
  11942. * 可以用于 isInsidePath 判断以及获取boundingRect
  11943. *
  11944. * @module zrender/core/PathProxy
  11945. * @author Yi Shen (http://www.github.com/pissang)
  11946. */
  11947. // TODO getTotalLength, getPointAtLength
  11948. /* global Float32Array */
  11949. var CMD = {
  11950. M: 1,
  11951. L: 2,
  11952. C: 3,
  11953. Q: 4,
  11954. A: 5,
  11955. Z: 6,
  11956. // Rect
  11957. R: 7
  11958. };
  11959. // var CMD_MEM_SIZE = {
  11960. // M: 3,
  11961. // L: 3,
  11962. // C: 7,
  11963. // Q: 5,
  11964. // A: 9,
  11965. // R: 5,
  11966. // Z: 1
  11967. // };
  11968. var min$1 = [];
  11969. var max$1 = [];
  11970. var min2 = [];
  11971. var max2 = [];
  11972. var mathMin$2 = Math.min;
  11973. var mathMax$2 = Math.max;
  11974. var mathCos$1 = Math.cos;
  11975. var mathSin$1 = Math.sin;
  11976. var mathSqrt$1 = Math.sqrt;
  11977. var mathAbs = Math.abs;
  11978. var hasTypedArray = typeof Float32Array !== 'undefined';
  11979. /**
  11980. * @alias module:zrender/core/PathProxy
  11981. * @constructor
  11982. */
  11983. var PathProxy = function (notSaveData) {
  11984. this._saveData = !(notSaveData || false);
  11985. if (this._saveData) {
  11986. /**
  11987. * Path data. Stored as flat array
  11988. * @type {Array.<Object>}
  11989. */
  11990. this.data = [];
  11991. }
  11992. this._ctx = null;
  11993. };
  11994. /**
  11995. * 快速计算Path包围盒(并不是最小包围盒)
  11996. * @return {Object}
  11997. */
  11998. PathProxy.prototype = {
  11999. constructor: PathProxy,
  12000. _xi: 0,
  12001. _yi: 0,
  12002. _x0: 0,
  12003. _y0: 0,
  12004. // Unit x, Unit y. Provide for avoiding drawing that too short line segment
  12005. _ux: 0,
  12006. _uy: 0,
  12007. _len: 0,
  12008. _lineDash: null,
  12009. _dashOffset: 0,
  12010. _dashIdx: 0,
  12011. _dashSum: 0,
  12012. /**
  12013. * @readOnly
  12014. */
  12015. setScale: function (sx, sy, segmentIgnoreThreshold) {
  12016. // Compat. Previously there is no segmentIgnoreThreshold.
  12017. segmentIgnoreThreshold = segmentIgnoreThreshold || 0;
  12018. this._ux = mathAbs(segmentIgnoreThreshold / devicePixelRatio / sx) || 0;
  12019. this._uy = mathAbs(segmentIgnoreThreshold / devicePixelRatio / sy) || 0;
  12020. },
  12021. getContext: function () {
  12022. return this._ctx;
  12023. },
  12024. /**
  12025. * @param {CanvasRenderingContext2D} ctx
  12026. * @return {module:zrender/core/PathProxy}
  12027. */
  12028. beginPath: function (ctx) {
  12029. this._ctx = ctx;
  12030. ctx && ctx.beginPath();
  12031. ctx && (this.dpr = ctx.dpr);
  12032. // Reset
  12033. if (this._saveData) {
  12034. this._len = 0;
  12035. }
  12036. if (this._lineDash) {
  12037. this._lineDash = null;
  12038. this._dashOffset = 0;
  12039. }
  12040. return this;
  12041. },
  12042. /**
  12043. * @param {number} x
  12044. * @param {number} y
  12045. * @return {module:zrender/core/PathProxy}
  12046. */
  12047. moveTo: function (x, y) {
  12048. this.addData(CMD.M, x, y);
  12049. this._ctx && this._ctx.moveTo(x, y);
  12050. // x0, y0, xi, yi 是记录在 _dashedXXXXTo 方法中使用
  12051. // xi, yi 记录当前点, x0, y0 在 closePath 的时候回到起始点。
  12052. // 有可能在 beginPath 之后直接调用 lineTo,这时候 x0, y0 需要
  12053. // 在 lineTo 方法中记录,这里先不考虑这种情况,dashed line 也只在 IE10- 中不支持
  12054. this._x0 = x;
  12055. this._y0 = y;
  12056. this._xi = x;
  12057. this._yi = y;
  12058. return this;
  12059. },
  12060. /**
  12061. * @param {number} x
  12062. * @param {number} y
  12063. * @return {module:zrender/core/PathProxy}
  12064. */
  12065. lineTo: function (x, y) {
  12066. var exceedUnit = mathAbs(x - this._xi) > this._ux
  12067. || mathAbs(y - this._yi) > this._uy
  12068. // Force draw the first segment
  12069. || this._len < 5;
  12070. this.addData(CMD.L, x, y);
  12071. if (this._ctx && exceedUnit) {
  12072. this._needsDash() ? this._dashedLineTo(x, y)
  12073. : this._ctx.lineTo(x, y);
  12074. }
  12075. if (exceedUnit) {
  12076. this._xi = x;
  12077. this._yi = y;
  12078. }
  12079. return this;
  12080. },
  12081. /**
  12082. * @param {number} x1
  12083. * @param {number} y1
  12084. * @param {number} x2
  12085. * @param {number} y2
  12086. * @param {number} x3
  12087. * @param {number} y3
  12088. * @return {module:zrender/core/PathProxy}
  12089. */
  12090. bezierCurveTo: function (x1, y1, x2, y2, x3, y3) {
  12091. this.addData(CMD.C, x1, y1, x2, y2, x3, y3);
  12092. if (this._ctx) {
  12093. this._needsDash() ? this._dashedBezierTo(x1, y1, x2, y2, x3, y3)
  12094. : this._ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
  12095. }
  12096. this._xi = x3;
  12097. this._yi = y3;
  12098. return this;
  12099. },
  12100. /**
  12101. * @param {number} x1
  12102. * @param {number} y1
  12103. * @param {number} x2
  12104. * @param {number} y2
  12105. * @return {module:zrender/core/PathProxy}
  12106. */
  12107. quadraticCurveTo: function (x1, y1, x2, y2) {
  12108. this.addData(CMD.Q, x1, y1, x2, y2);
  12109. if (this._ctx) {
  12110. this._needsDash() ? this._dashedQuadraticTo(x1, y1, x2, y2)
  12111. : this._ctx.quadraticCurveTo(x1, y1, x2, y2);
  12112. }
  12113. this._xi = x2;
  12114. this._yi = y2;
  12115. return this;
  12116. },
  12117. /**
  12118. * @param {number} cx
  12119. * @param {number} cy
  12120. * @param {number} r
  12121. * @param {number} startAngle
  12122. * @param {number} endAngle
  12123. * @param {boolean} anticlockwise
  12124. * @return {module:zrender/core/PathProxy}
  12125. */
  12126. arc: function (cx, cy, r, startAngle, endAngle, anticlockwise) {
  12127. this.addData(
  12128. CMD.A, cx, cy, r, r, startAngle, endAngle - startAngle, 0, anticlockwise ? 0 : 1
  12129. );
  12130. this._ctx && this._ctx.arc(cx, cy, r, startAngle, endAngle, anticlockwise);
  12131. this._xi = mathCos$1(endAngle) * r + cx;
  12132. this._yi = mathSin$1(endAngle) * r + cy;
  12133. return this;
  12134. },
  12135. // TODO
  12136. arcTo: function (x1, y1, x2, y2, radius) {
  12137. if (this._ctx) {
  12138. this._ctx.arcTo(x1, y1, x2, y2, radius);
  12139. }
  12140. return this;
  12141. },
  12142. // TODO
  12143. rect: function (x, y, w, h) {
  12144. this._ctx && this._ctx.rect(x, y, w, h);
  12145. this.addData(CMD.R, x, y, w, h);
  12146. return this;
  12147. },
  12148. /**
  12149. * @return {module:zrender/core/PathProxy}
  12150. */
  12151. closePath: function () {
  12152. this.addData(CMD.Z);
  12153. var ctx = this._ctx;
  12154. var x0 = this._x0;
  12155. var y0 = this._y0;
  12156. if (ctx) {
  12157. this._needsDash() && this._dashedLineTo(x0, y0);
  12158. ctx.closePath();
  12159. }
  12160. this._xi = x0;
  12161. this._yi = y0;
  12162. return this;
  12163. },
  12164. /**
  12165. * Context 从外部传入,因为有可能是 rebuildPath 完之后再 fill。
  12166. * stroke 同样
  12167. * @param {CanvasRenderingContext2D} ctx
  12168. * @return {module:zrender/core/PathProxy}
  12169. */
  12170. fill: function (ctx) {
  12171. ctx && ctx.fill();
  12172. this.toStatic();
  12173. },
  12174. /**
  12175. * @param {CanvasRenderingContext2D} ctx
  12176. * @return {module:zrender/core/PathProxy}
  12177. */
  12178. stroke: function (ctx) {
  12179. ctx && ctx.stroke();
  12180. this.toStatic();
  12181. },
  12182. /**
  12183. * 必须在其它绘制命令前调用
  12184. * Must be invoked before all other path drawing methods
  12185. * @return {module:zrender/core/PathProxy}
  12186. */
  12187. setLineDash: function (lineDash) {
  12188. if (lineDash instanceof Array) {
  12189. this._lineDash = lineDash;
  12190. this._dashIdx = 0;
  12191. var lineDashSum = 0;
  12192. for (var i = 0; i < lineDash.length; i++) {
  12193. lineDashSum += lineDash[i];
  12194. }
  12195. this._dashSum = lineDashSum;
  12196. }
  12197. return this;
  12198. },
  12199. /**
  12200. * 必须在其它绘制命令前调用
  12201. * Must be invoked before all other path drawing methods
  12202. * @return {module:zrender/core/PathProxy}
  12203. */
  12204. setLineDashOffset: function (offset) {
  12205. this._dashOffset = offset;
  12206. return this;
  12207. },
  12208. /**
  12209. *
  12210. * @return {boolean}
  12211. */
  12212. len: function () {
  12213. return this._len;
  12214. },
  12215. /**
  12216. * 直接设置 Path 数据
  12217. */
  12218. setData: function (data) {
  12219. var len$$1 = data.length;
  12220. if (!(this.data && this.data.length === len$$1) && hasTypedArray) {
  12221. this.data = new Float32Array(len$$1);
  12222. }
  12223. for (var i = 0; i < len$$1; i++) {
  12224. this.data[i] = data[i];
  12225. }
  12226. this._len = len$$1;
  12227. },
  12228. /**
  12229. * 添加子路径
  12230. * @param {module:zrender/core/PathProxy|Array.<module:zrender/core/PathProxy>} path
  12231. */
  12232. appendPath: function (path) {
  12233. if (!(path instanceof Array)) {
  12234. path = [path];
  12235. }
  12236. var len$$1 = path.length;
  12237. var appendSize = 0;
  12238. var offset = this._len;
  12239. for (var i = 0; i < len$$1; i++) {
  12240. appendSize += path[i].len();
  12241. }
  12242. if (hasTypedArray && (this.data instanceof Float32Array)) {
  12243. this.data = new Float32Array(offset + appendSize);
  12244. }
  12245. for (var i = 0; i < len$$1; i++) {
  12246. var appendPathData = path[i].data;
  12247. for (var k = 0; k < appendPathData.length; k++) {
  12248. this.data[offset++] = appendPathData[k];
  12249. }
  12250. }
  12251. this._len = offset;
  12252. },
  12253. /**
  12254. * 填充 Path 数据。
  12255. * 尽量复用而不申明新的数组。大部分图形重绘的指令数据长度都是不变的。
  12256. */
  12257. addData: function (cmd) {
  12258. if (!this._saveData) {
  12259. return;
  12260. }
  12261. var data = this.data;
  12262. if (this._len + arguments.length > data.length) {
  12263. // 因为之前的数组已经转换成静态的 Float32Array
  12264. // 所以不够用时需要扩展一个新的动态数组
  12265. this._expandData();
  12266. data = this.data;
  12267. }
  12268. for (var i = 0; i < arguments.length; i++) {
  12269. data[this._len++] = arguments[i];
  12270. }
  12271. this._prevCmd = cmd;
  12272. },
  12273. _expandData: function () {
  12274. // Only if data is Float32Array
  12275. if (!(this.data instanceof Array)) {
  12276. var newData = [];
  12277. for (var i = 0; i < this._len; i++) {
  12278. newData[i] = this.data[i];
  12279. }
  12280. this.data = newData;
  12281. }
  12282. },
  12283. /**
  12284. * If needs js implemented dashed line
  12285. * @return {boolean}
  12286. * @private
  12287. */
  12288. _needsDash: function () {
  12289. return this._lineDash;
  12290. },
  12291. _dashedLineTo: function (x1, y1) {
  12292. var dashSum = this._dashSum;
  12293. var offset = this._dashOffset;
  12294. var lineDash = this._lineDash;
  12295. var ctx = this._ctx;
  12296. var x0 = this._xi;
  12297. var y0 = this._yi;
  12298. var dx = x1 - x0;
  12299. var dy = y1 - y0;
  12300. var dist$$1 = mathSqrt$1(dx * dx + dy * dy);
  12301. var x = x0;
  12302. var y = y0;
  12303. var dash;
  12304. var nDash = lineDash.length;
  12305. var idx;
  12306. dx /= dist$$1;
  12307. dy /= dist$$1;
  12308. if (offset < 0) {
  12309. // Convert to positive offset
  12310. offset = dashSum + offset;
  12311. }
  12312. offset %= dashSum;
  12313. x -= offset * dx;
  12314. y -= offset * dy;
  12315. while ((dx > 0 && x <= x1) || (dx < 0 && x >= x1)
  12316. || (dx === 0 && ((dy > 0 && y <= y1) || (dy < 0 && y >= y1)))) {
  12317. idx = this._dashIdx;
  12318. dash = lineDash[idx];
  12319. x += dx * dash;
  12320. y += dy * dash;
  12321. this._dashIdx = (idx + 1) % nDash;
  12322. // Skip positive offset
  12323. if ((dx > 0 && x < x0) || (dx < 0 && x > x0) || (dy > 0 && y < y0) || (dy < 0 && y > y0)) {
  12324. continue;
  12325. }
  12326. ctx[idx % 2 ? 'moveTo' : 'lineTo'](
  12327. dx >= 0 ? mathMin$2(x, x1) : mathMax$2(x, x1),
  12328. dy >= 0 ? mathMin$2(y, y1) : mathMax$2(y, y1)
  12329. );
  12330. }
  12331. // Offset for next lineTo
  12332. dx = x - x1;
  12333. dy = y - y1;
  12334. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  12335. },
  12336. // Not accurate dashed line to
  12337. _dashedBezierTo: function (x1, y1, x2, y2, x3, y3) {
  12338. var dashSum = this._dashSum;
  12339. var offset = this._dashOffset;
  12340. var lineDash = this._lineDash;
  12341. var ctx = this._ctx;
  12342. var x0 = this._xi;
  12343. var y0 = this._yi;
  12344. var t;
  12345. var dx;
  12346. var dy;
  12347. var cubicAt$$1 = cubicAt;
  12348. var bezierLen = 0;
  12349. var idx = this._dashIdx;
  12350. var nDash = lineDash.length;
  12351. var x;
  12352. var y;
  12353. var tmpLen = 0;
  12354. if (offset < 0) {
  12355. // Convert to positive offset
  12356. offset = dashSum + offset;
  12357. }
  12358. offset %= dashSum;
  12359. // Bezier approx length
  12360. for (t = 0; t < 1; t += 0.1) {
  12361. dx = cubicAt$$1(x0, x1, x2, x3, t + 0.1)
  12362. - cubicAt$$1(x0, x1, x2, x3, t);
  12363. dy = cubicAt$$1(y0, y1, y2, y3, t + 0.1)
  12364. - cubicAt$$1(y0, y1, y2, y3, t);
  12365. bezierLen += mathSqrt$1(dx * dx + dy * dy);
  12366. }
  12367. // Find idx after add offset
  12368. for (; idx < nDash; idx++) {
  12369. tmpLen += lineDash[idx];
  12370. if (tmpLen > offset) {
  12371. break;
  12372. }
  12373. }
  12374. t = (tmpLen - offset) / bezierLen;
  12375. while (t <= 1) {
  12376. x = cubicAt$$1(x0, x1, x2, x3, t);
  12377. y = cubicAt$$1(y0, y1, y2, y3, t);
  12378. // Use line to approximate dashed bezier
  12379. // Bad result if dash is long
  12380. idx % 2 ? ctx.moveTo(x, y)
  12381. : ctx.lineTo(x, y);
  12382. t += lineDash[idx] / bezierLen;
  12383. idx = (idx + 1) % nDash;
  12384. }
  12385. // Finish the last segment and calculate the new offset
  12386. (idx % 2 !== 0) && ctx.lineTo(x3, y3);
  12387. dx = x3 - x;
  12388. dy = y3 - y;
  12389. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  12390. },
  12391. _dashedQuadraticTo: function (x1, y1, x2, y2) {
  12392. // Convert quadratic to cubic using degree elevation
  12393. var x3 = x2;
  12394. var y3 = y2;
  12395. x2 = (x2 + 2 * x1) / 3;
  12396. y2 = (y2 + 2 * y1) / 3;
  12397. x1 = (this._xi + 2 * x1) / 3;
  12398. y1 = (this._yi + 2 * y1) / 3;
  12399. this._dashedBezierTo(x1, y1, x2, y2, x3, y3);
  12400. },
  12401. /**
  12402. * 转成静态的 Float32Array 减少堆内存占用
  12403. * Convert dynamic array to static Float32Array
  12404. */
  12405. toStatic: function () {
  12406. var data = this.data;
  12407. if (data instanceof Array) {
  12408. data.length = this._len;
  12409. if (hasTypedArray) {
  12410. this.data = new Float32Array(data);
  12411. }
  12412. }
  12413. },
  12414. /**
  12415. * @return {module:zrender/core/BoundingRect}
  12416. */
  12417. getBoundingRect: function () {
  12418. min$1[0] = min$1[1] = min2[0] = min2[1] = Number.MAX_VALUE;
  12419. max$1[0] = max$1[1] = max2[0] = max2[1] = -Number.MAX_VALUE;
  12420. var data = this.data;
  12421. var xi = 0;
  12422. var yi = 0;
  12423. var x0 = 0;
  12424. var y0 = 0;
  12425. for (var i = 0; i < data.length;) {
  12426. var cmd = data[i++];
  12427. if (i === 1) {
  12428. // 如果第一个命令是 L, C, Q
  12429. // 则 previous point 同绘制命令的第一个 point
  12430. //
  12431. // 第一个命令为 Arc 的情况下会在后面特殊处理
  12432. xi = data[i];
  12433. yi = data[i + 1];
  12434. x0 = xi;
  12435. y0 = yi;
  12436. }
  12437. switch (cmd) {
  12438. case CMD.M:
  12439. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  12440. // 在 closePath 的时候使用
  12441. x0 = data[i++];
  12442. y0 = data[i++];
  12443. xi = x0;
  12444. yi = y0;
  12445. min2[0] = x0;
  12446. min2[1] = y0;
  12447. max2[0] = x0;
  12448. max2[1] = y0;
  12449. break;
  12450. case CMD.L:
  12451. fromLine(xi, yi, data[i], data[i + 1], min2, max2);
  12452. xi = data[i++];
  12453. yi = data[i++];
  12454. break;
  12455. case CMD.C:
  12456. fromCubic(
  12457. xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  12458. min2, max2
  12459. );
  12460. xi = data[i++];
  12461. yi = data[i++];
  12462. break;
  12463. case CMD.Q:
  12464. fromQuadratic(
  12465. xi, yi, data[i++], data[i++], data[i], data[i + 1],
  12466. min2, max2
  12467. );
  12468. xi = data[i++];
  12469. yi = data[i++];
  12470. break;
  12471. case CMD.A:
  12472. // TODO Arc 判断的开销比较大
  12473. var cx = data[i++];
  12474. var cy = data[i++];
  12475. var rx = data[i++];
  12476. var ry = data[i++];
  12477. var startAngle = data[i++];
  12478. var endAngle = data[i++] + startAngle;
  12479. // TODO Arc 旋转
  12480. i += 1;
  12481. var anticlockwise = 1 - data[i++];
  12482. if (i === 1) {
  12483. // 直接使用 arc 命令
  12484. // 第一个命令起点还未定义
  12485. x0 = mathCos$1(startAngle) * rx + cx;
  12486. y0 = mathSin$1(startAngle) * ry + cy;
  12487. }
  12488. fromArc(
  12489. cx, cy, rx, ry, startAngle, endAngle,
  12490. anticlockwise, min2, max2
  12491. );
  12492. xi = mathCos$1(endAngle) * rx + cx;
  12493. yi = mathSin$1(endAngle) * ry + cy;
  12494. break;
  12495. case CMD.R:
  12496. x0 = xi = data[i++];
  12497. y0 = yi = data[i++];
  12498. var width = data[i++];
  12499. var height = data[i++];
  12500. // Use fromLine
  12501. fromLine(x0, y0, x0 + width, y0 + height, min2, max2);
  12502. break;
  12503. case CMD.Z:
  12504. xi = x0;
  12505. yi = y0;
  12506. break;
  12507. }
  12508. // Union
  12509. min(min$1, min$1, min2);
  12510. max(max$1, max$1, max2);
  12511. }
  12512. // No data
  12513. if (i === 0) {
  12514. min$1[0] = min$1[1] = max$1[0] = max$1[1] = 0;
  12515. }
  12516. return new BoundingRect(
  12517. min$1[0], min$1[1], max$1[0] - min$1[0], max$1[1] - min$1[1]
  12518. );
  12519. },
  12520. /**
  12521. * Rebuild path from current data
  12522. * Rebuild path will not consider javascript implemented line dash.
  12523. * @param {CanvasRenderingContext2D} ctx
  12524. */
  12525. rebuildPath: function (ctx) {
  12526. var d = this.data;
  12527. var x0;
  12528. var y0;
  12529. var xi;
  12530. var yi;
  12531. var x;
  12532. var y;
  12533. var ux = this._ux;
  12534. var uy = this._uy;
  12535. var len$$1 = this._len;
  12536. for (var i = 0; i < len$$1;) {
  12537. var cmd = d[i++];
  12538. if (i === 1) {
  12539. // 如果第一个命令是 L, C, Q
  12540. // 则 previous point 同绘制命令的第一个 point
  12541. //
  12542. // 第一个命令为 Arc 的情况下会在后面特殊处理
  12543. xi = d[i];
  12544. yi = d[i + 1];
  12545. x0 = xi;
  12546. y0 = yi;
  12547. }
  12548. switch (cmd) {
  12549. case CMD.M:
  12550. x0 = xi = d[i++];
  12551. y0 = yi = d[i++];
  12552. ctx.moveTo(xi, yi);
  12553. break;
  12554. case CMD.L:
  12555. x = d[i++];
  12556. y = d[i++];
  12557. // Not draw too small seg between
  12558. if (mathAbs(x - xi) > ux || mathAbs(y - yi) > uy || i === len$$1 - 1) {
  12559. ctx.lineTo(x, y);
  12560. xi = x;
  12561. yi = y;
  12562. }
  12563. break;
  12564. case CMD.C:
  12565. ctx.bezierCurveTo(
  12566. d[i++], d[i++], d[i++], d[i++], d[i++], d[i++]
  12567. );
  12568. xi = d[i - 2];
  12569. yi = d[i - 1];
  12570. break;
  12571. case CMD.Q:
  12572. ctx.quadraticCurveTo(d[i++], d[i++], d[i++], d[i++]);
  12573. xi = d[i - 2];
  12574. yi = d[i - 1];
  12575. break;
  12576. case CMD.A:
  12577. var cx = d[i++];
  12578. var cy = d[i++];
  12579. var rx = d[i++];
  12580. var ry = d[i++];
  12581. var theta = d[i++];
  12582. var dTheta = d[i++];
  12583. var psi = d[i++];
  12584. var fs = d[i++];
  12585. var r = (rx > ry) ? rx : ry;
  12586. var scaleX = (rx > ry) ? 1 : rx / ry;
  12587. var scaleY = (rx > ry) ? ry / rx : 1;
  12588. var isEllipse = Math.abs(rx - ry) > 1e-3;
  12589. var endAngle = theta + dTheta;
  12590. if (isEllipse) {
  12591. ctx.translate(cx, cy);
  12592. ctx.rotate(psi);
  12593. ctx.scale(scaleX, scaleY);
  12594. ctx.arc(0, 0, r, theta, endAngle, 1 - fs);
  12595. ctx.scale(1 / scaleX, 1 / scaleY);
  12596. ctx.rotate(-psi);
  12597. ctx.translate(-cx, -cy);
  12598. }
  12599. else {
  12600. ctx.arc(cx, cy, r, theta, endAngle, 1 - fs);
  12601. }
  12602. if (i === 1) {
  12603. // 直接使用 arc 命令
  12604. // 第一个命令起点还未定义
  12605. x0 = mathCos$1(theta) * rx + cx;
  12606. y0 = mathSin$1(theta) * ry + cy;
  12607. }
  12608. xi = mathCos$1(endAngle) * rx + cx;
  12609. yi = mathSin$1(endAngle) * ry + cy;
  12610. break;
  12611. case CMD.R:
  12612. x0 = xi = d[i];
  12613. y0 = yi = d[i + 1];
  12614. ctx.rect(d[i++], d[i++], d[i++], d[i++]);
  12615. break;
  12616. case CMD.Z:
  12617. ctx.closePath();
  12618. xi = x0;
  12619. yi = y0;
  12620. }
  12621. }
  12622. }
  12623. };
  12624. PathProxy.CMD = CMD;
  12625. /**
  12626. * 线段包含判断
  12627. * @param {number} x0
  12628. * @param {number} y0
  12629. * @param {number} x1
  12630. * @param {number} y1
  12631. * @param {number} lineWidth
  12632. * @param {number} x
  12633. * @param {number} y
  12634. * @return {boolean}
  12635. */
  12636. function containStroke$1(x0, y0, x1, y1, lineWidth, x, y) {
  12637. if (lineWidth === 0) {
  12638. return false;
  12639. }
  12640. var _l = lineWidth;
  12641. var _a = 0;
  12642. var _b = x0;
  12643. // Quick reject
  12644. if (
  12645. (y > y0 + _l && y > y1 + _l)
  12646. || (y < y0 - _l && y < y1 - _l)
  12647. || (x > x0 + _l && x > x1 + _l)
  12648. || (x < x0 - _l && x < x1 - _l)
  12649. ) {
  12650. return false;
  12651. }
  12652. if (x0 !== x1) {
  12653. _a = (y0 - y1) / (x0 - x1);
  12654. _b = (x0 * y1 - x1 * y0) / (x0 - x1);
  12655. }
  12656. else {
  12657. return Math.abs(x - x0) <= _l / 2;
  12658. }
  12659. var tmp = _a * x - y + _b;
  12660. var _s = tmp * tmp / (_a * _a + 1);
  12661. return _s <= _l / 2 * _l / 2;
  12662. }
  12663. /**
  12664. * 三次贝塞尔曲线描边包含判断
  12665. * @param {number} x0
  12666. * @param {number} y0
  12667. * @param {number} x1
  12668. * @param {number} y1
  12669. * @param {number} x2
  12670. * @param {number} y2
  12671. * @param {number} x3
  12672. * @param {number} y3
  12673. * @param {number} lineWidth
  12674. * @param {number} x
  12675. * @param {number} y
  12676. * @return {boolean}
  12677. */
  12678. function containStroke$2(x0, y0, x1, y1, x2, y2, x3, y3, lineWidth, x, y) {
  12679. if (lineWidth === 0) {
  12680. return false;
  12681. }
  12682. var _l = lineWidth;
  12683. // Quick reject
  12684. if (
  12685. (y > y0 + _l && y > y1 + _l && y > y2 + _l && y > y3 + _l)
  12686. || (y < y0 - _l && y < y1 - _l && y < y2 - _l && y < y3 - _l)
  12687. || (x > x0 + _l && x > x1 + _l && x > x2 + _l && x > x3 + _l)
  12688. || (x < x0 - _l && x < x1 - _l && x < x2 - _l && x < x3 - _l)
  12689. ) {
  12690. return false;
  12691. }
  12692. var d = cubicProjectPoint(
  12693. x0, y0, x1, y1, x2, y2, x3, y3,
  12694. x, y, null
  12695. );
  12696. return d <= _l / 2;
  12697. }
  12698. /**
  12699. * 二次贝塞尔曲线描边包含判断
  12700. * @param {number} x0
  12701. * @param {number} y0
  12702. * @param {number} x1
  12703. * @param {number} y1
  12704. * @param {number} x2
  12705. * @param {number} y2
  12706. * @param {number} lineWidth
  12707. * @param {number} x
  12708. * @param {number} y
  12709. * @return {boolean}
  12710. */
  12711. function containStroke$3(x0, y0, x1, y1, x2, y2, lineWidth, x, y) {
  12712. if (lineWidth === 0) {
  12713. return false;
  12714. }
  12715. var _l = lineWidth;
  12716. // Quick reject
  12717. if (
  12718. (y > y0 + _l && y > y1 + _l && y > y2 + _l)
  12719. || (y < y0 - _l && y < y1 - _l && y < y2 - _l)
  12720. || (x > x0 + _l && x > x1 + _l && x > x2 + _l)
  12721. || (x < x0 - _l && x < x1 - _l && x < x2 - _l)
  12722. ) {
  12723. return false;
  12724. }
  12725. var d = quadraticProjectPoint(
  12726. x0, y0, x1, y1, x2, y2,
  12727. x, y, null
  12728. );
  12729. return d <= _l / 2;
  12730. }
  12731. var PI2$3 = Math.PI * 2;
  12732. function normalizeRadian(angle) {
  12733. angle %= PI2$3;
  12734. if (angle < 0) {
  12735. angle += PI2$3;
  12736. }
  12737. return angle;
  12738. }
  12739. var PI2$2 = Math.PI * 2;
  12740. /**
  12741. * 圆弧描边包含判断
  12742. * @param {number} cx
  12743. * @param {number} cy
  12744. * @param {number} r
  12745. * @param {number} startAngle
  12746. * @param {number} endAngle
  12747. * @param {boolean} anticlockwise
  12748. * @param {number} lineWidth
  12749. * @param {number} x
  12750. * @param {number} y
  12751. * @return {Boolean}
  12752. */
  12753. function containStroke$4(
  12754. cx, cy, r, startAngle, endAngle, anticlockwise,
  12755. lineWidth, x, y
  12756. ) {
  12757. if (lineWidth === 0) {
  12758. return false;
  12759. }
  12760. var _l = lineWidth;
  12761. x -= cx;
  12762. y -= cy;
  12763. var d = Math.sqrt(x * x + y * y);
  12764. if ((d - _l > r) || (d + _l < r)) {
  12765. return false;
  12766. }
  12767. if (Math.abs(startAngle - endAngle) % PI2$2 < 1e-4) {
  12768. // Is a circle
  12769. return true;
  12770. }
  12771. if (anticlockwise) {
  12772. var tmp = startAngle;
  12773. startAngle = normalizeRadian(endAngle);
  12774. endAngle = normalizeRadian(tmp);
  12775. }
  12776. else {
  12777. startAngle = normalizeRadian(startAngle);
  12778. endAngle = normalizeRadian(endAngle);
  12779. }
  12780. if (startAngle > endAngle) {
  12781. endAngle += PI2$2;
  12782. }
  12783. var angle = Math.atan2(y, x);
  12784. if (angle < 0) {
  12785. angle += PI2$2;
  12786. }
  12787. return (angle >= startAngle && angle <= endAngle)
  12788. || (angle + PI2$2 >= startAngle && angle + PI2$2 <= endAngle);
  12789. }
  12790. function windingLine(x0, y0, x1, y1, x, y) {
  12791. if ((y > y0 && y > y1) || (y < y0 && y < y1)) {
  12792. return 0;
  12793. }
  12794. // Ignore horizontal line
  12795. if (y1 === y0) {
  12796. return 0;
  12797. }
  12798. var dir = y1 < y0 ? 1 : -1;
  12799. var t = (y - y0) / (y1 - y0);
  12800. // Avoid winding error when intersection point is the connect point of two line of polygon
  12801. if (t === 1 || t === 0) {
  12802. dir = y1 < y0 ? 0.5 : -0.5;
  12803. }
  12804. var x_ = t * (x1 - x0) + x0;
  12805. // If (x, y) on the line, considered as "contain".
  12806. return x_ === x ? Infinity : x_ > x ? dir : 0;
  12807. }
  12808. var CMD$1 = PathProxy.CMD;
  12809. var PI2$1 = Math.PI * 2;
  12810. var EPSILON$2 = 1e-4;
  12811. function isAroundEqual(a, b) {
  12812. return Math.abs(a - b) < EPSILON$2;
  12813. }
  12814. // 临时数组
  12815. var roots = [-1, -1, -1];
  12816. var extrema = [-1, -1];
  12817. function swapExtrema() {
  12818. var tmp = extrema[0];
  12819. extrema[0] = extrema[1];
  12820. extrema[1] = tmp;
  12821. }
  12822. function windingCubic(x0, y0, x1, y1, x2, y2, x3, y3, x, y) {
  12823. // Quick reject
  12824. if (
  12825. (y > y0 && y > y1 && y > y2 && y > y3)
  12826. || (y < y0 && y < y1 && y < y2 && y < y3)
  12827. ) {
  12828. return 0;
  12829. }
  12830. var nRoots = cubicRootAt(y0, y1, y2, y3, y, roots);
  12831. if (nRoots === 0) {
  12832. return 0;
  12833. }
  12834. else {
  12835. var w = 0;
  12836. var nExtrema = -1;
  12837. var y0_;
  12838. var y1_;
  12839. for (var i = 0; i < nRoots; i++) {
  12840. var t = roots[i];
  12841. // Avoid winding error when intersection point is the connect point of two line of polygon
  12842. var unit = (t === 0 || t === 1) ? 0.5 : 1;
  12843. var x_ = cubicAt(x0, x1, x2, x3, t);
  12844. if (x_ < x) { // Quick reject
  12845. continue;
  12846. }
  12847. if (nExtrema < 0) {
  12848. nExtrema = cubicExtrema(y0, y1, y2, y3, extrema);
  12849. if (extrema[1] < extrema[0] && nExtrema > 1) {
  12850. swapExtrema();
  12851. }
  12852. y0_ = cubicAt(y0, y1, y2, y3, extrema[0]);
  12853. if (nExtrema > 1) {
  12854. y1_ = cubicAt(y0, y1, y2, y3, extrema[1]);
  12855. }
  12856. }
  12857. if (nExtrema === 2) {
  12858. // 分成三段单调函数
  12859. if (t < extrema[0]) {
  12860. w += y0_ < y0 ? unit : -unit;
  12861. }
  12862. else if (t < extrema[1]) {
  12863. w += y1_ < y0_ ? unit : -unit;
  12864. }
  12865. else {
  12866. w += y3 < y1_ ? unit : -unit;
  12867. }
  12868. }
  12869. else {
  12870. // 分成两段单调函数
  12871. if (t < extrema[0]) {
  12872. w += y0_ < y0 ? unit : -unit;
  12873. }
  12874. else {
  12875. w += y3 < y0_ ? unit : -unit;
  12876. }
  12877. }
  12878. }
  12879. return w;
  12880. }
  12881. }
  12882. function windingQuadratic(x0, y0, x1, y1, x2, y2, x, y) {
  12883. // Quick reject
  12884. if (
  12885. (y > y0 && y > y1 && y > y2)
  12886. || (y < y0 && y < y1 && y < y2)
  12887. ) {
  12888. return 0;
  12889. }
  12890. var nRoots = quadraticRootAt(y0, y1, y2, y, roots);
  12891. if (nRoots === 0) {
  12892. return 0;
  12893. }
  12894. else {
  12895. var t = quadraticExtremum(y0, y1, y2);
  12896. if (t >= 0 && t <= 1) {
  12897. var w = 0;
  12898. var y_ = quadraticAt(y0, y1, y2, t);
  12899. for (var i = 0; i < nRoots; i++) {
  12900. // Remove one endpoint.
  12901. var unit = (roots[i] === 0 || roots[i] === 1) ? 0.5 : 1;
  12902. var x_ = quadraticAt(x0, x1, x2, roots[i]);
  12903. if (x_ < x) { // Quick reject
  12904. continue;
  12905. }
  12906. if (roots[i] < t) {
  12907. w += y_ < y0 ? unit : -unit;
  12908. }
  12909. else {
  12910. w += y2 < y_ ? unit : -unit;
  12911. }
  12912. }
  12913. return w;
  12914. }
  12915. else {
  12916. // Remove one endpoint.
  12917. var unit = (roots[0] === 0 || roots[0] === 1) ? 0.5 : 1;
  12918. var x_ = quadraticAt(x0, x1, x2, roots[0]);
  12919. if (x_ < x) { // Quick reject
  12920. return 0;
  12921. }
  12922. return y2 < y0 ? unit : -unit;
  12923. }
  12924. }
  12925. }
  12926. // TODO
  12927. // Arc 旋转
  12928. function windingArc(
  12929. cx, cy, r, startAngle, endAngle, anticlockwise, x, y
  12930. ) {
  12931. y -= cy;
  12932. if (y > r || y < -r) {
  12933. return 0;
  12934. }
  12935. var tmp = Math.sqrt(r * r - y * y);
  12936. roots[0] = -tmp;
  12937. roots[1] = tmp;
  12938. var diff = Math.abs(startAngle - endAngle);
  12939. if (diff < 1e-4) {
  12940. return 0;
  12941. }
  12942. if (diff % PI2$1 < 1e-4) {
  12943. // Is a circle
  12944. startAngle = 0;
  12945. endAngle = PI2$1;
  12946. var dir = anticlockwise ? 1 : -1;
  12947. if (x >= roots[0] + cx && x <= roots[1] + cx) {
  12948. return dir;
  12949. }
  12950. else {
  12951. return 0;
  12952. }
  12953. }
  12954. if (anticlockwise) {
  12955. var tmp = startAngle;
  12956. startAngle = normalizeRadian(endAngle);
  12957. endAngle = normalizeRadian(tmp);
  12958. }
  12959. else {
  12960. startAngle = normalizeRadian(startAngle);
  12961. endAngle = normalizeRadian(endAngle);
  12962. }
  12963. if (startAngle > endAngle) {
  12964. endAngle += PI2$1;
  12965. }
  12966. var w = 0;
  12967. for (var i = 0; i < 2; i++) {
  12968. var x_ = roots[i];
  12969. if (x_ + cx > x) {
  12970. var angle = Math.atan2(y, x_);
  12971. var dir = anticlockwise ? 1 : -1;
  12972. if (angle < 0) {
  12973. angle = PI2$1 + angle;
  12974. }
  12975. if (
  12976. (angle >= startAngle && angle <= endAngle)
  12977. || (angle + PI2$1 >= startAngle && angle + PI2$1 <= endAngle)
  12978. ) {
  12979. if (angle > Math.PI / 2 && angle < Math.PI * 1.5) {
  12980. dir = -dir;
  12981. }
  12982. w += dir;
  12983. }
  12984. }
  12985. }
  12986. return w;
  12987. }
  12988. function containPath(data, lineWidth, isStroke, x, y) {
  12989. var w = 0;
  12990. var xi = 0;
  12991. var yi = 0;
  12992. var x0 = 0;
  12993. var y0 = 0;
  12994. for (var i = 0; i < data.length;) {
  12995. var cmd = data[i++];
  12996. // Begin a new subpath
  12997. if (cmd === CMD$1.M && i > 1) {
  12998. // Close previous subpath
  12999. if (!isStroke) {
  13000. w += windingLine(xi, yi, x0, y0, x, y);
  13001. }
  13002. // 如果被任何一个 subpath 包含
  13003. // if (w !== 0) {
  13004. // return true;
  13005. // }
  13006. }
  13007. if (i === 1) {
  13008. // 如果第一个命令是 L, C, Q
  13009. // 则 previous point 同绘制命令的第一个 point
  13010. //
  13011. // 第一个命令为 Arc 的情况下会在后面特殊处理
  13012. xi = data[i];
  13013. yi = data[i + 1];
  13014. x0 = xi;
  13015. y0 = yi;
  13016. }
  13017. switch (cmd) {
  13018. case CMD$1.M:
  13019. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  13020. // 在 closePath 的时候使用
  13021. x0 = data[i++];
  13022. y0 = data[i++];
  13023. xi = x0;
  13024. yi = y0;
  13025. break;
  13026. case CMD$1.L:
  13027. if (isStroke) {
  13028. if (containStroke$1(xi, yi, data[i], data[i + 1], lineWidth, x, y)) {
  13029. return true;
  13030. }
  13031. }
  13032. else {
  13033. // NOTE 在第一个命令为 L, C, Q 的时候会计算出 NaN
  13034. w += windingLine(xi, yi, data[i], data[i + 1], x, y) || 0;
  13035. }
  13036. xi = data[i++];
  13037. yi = data[i++];
  13038. break;
  13039. case CMD$1.C:
  13040. if (isStroke) {
  13041. if (containStroke$2(xi, yi,
  13042. data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  13043. lineWidth, x, y
  13044. )) {
  13045. return true;
  13046. }
  13047. }
  13048. else {
  13049. w += windingCubic(
  13050. xi, yi,
  13051. data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  13052. x, y
  13053. ) || 0;
  13054. }
  13055. xi = data[i++];
  13056. yi = data[i++];
  13057. break;
  13058. case CMD$1.Q:
  13059. if (isStroke) {
  13060. if (containStroke$3(xi, yi,
  13061. data[i++], data[i++], data[i], data[i + 1],
  13062. lineWidth, x, y
  13063. )) {
  13064. return true;
  13065. }
  13066. }
  13067. else {
  13068. w += windingQuadratic(
  13069. xi, yi,
  13070. data[i++], data[i++], data[i], data[i + 1],
  13071. x, y
  13072. ) || 0;
  13073. }
  13074. xi = data[i++];
  13075. yi = data[i++];
  13076. break;
  13077. case CMD$1.A:
  13078. // TODO Arc 判断的开销比较大
  13079. var cx = data[i++];
  13080. var cy = data[i++];
  13081. var rx = data[i++];
  13082. var ry = data[i++];
  13083. var theta = data[i++];
  13084. var dTheta = data[i++];
  13085. // TODO Arc 旋转
  13086. i += 1;
  13087. var anticlockwise = 1 - data[i++];
  13088. var x1 = Math.cos(theta) * rx + cx;
  13089. var y1 = Math.sin(theta) * ry + cy;
  13090. // 不是直接使用 arc 命令
  13091. if (i > 1) {
  13092. w += windingLine(xi, yi, x1, y1, x, y);
  13093. }
  13094. else {
  13095. // 第一个命令起点还未定义
  13096. x0 = x1;
  13097. y0 = y1;
  13098. }
  13099. // zr 使用scale来模拟椭圆, 这里也对x做一定的缩放
  13100. var _x = (x - cx) * ry / rx + cx;
  13101. if (isStroke) {
  13102. if (containStroke$4(
  13103. cx, cy, ry, theta, theta + dTheta, anticlockwise,
  13104. lineWidth, _x, y
  13105. )) {
  13106. return true;
  13107. }
  13108. }
  13109. else {
  13110. w += windingArc(
  13111. cx, cy, ry, theta, theta + dTheta, anticlockwise,
  13112. _x, y
  13113. );
  13114. }
  13115. xi = Math.cos(theta + dTheta) * rx + cx;
  13116. yi = Math.sin(theta + dTheta) * ry + cy;
  13117. break;
  13118. case CMD$1.R:
  13119. x0 = xi = data[i++];
  13120. y0 = yi = data[i++];
  13121. var width = data[i++];
  13122. var height = data[i++];
  13123. var x1 = x0 + width;
  13124. var y1 = y0 + height;
  13125. if (isStroke) {
  13126. if (containStroke$1(x0, y0, x1, y0, lineWidth, x, y)
  13127. || containStroke$1(x1, y0, x1, y1, lineWidth, x, y)
  13128. || containStroke$1(x1, y1, x0, y1, lineWidth, x, y)
  13129. || containStroke$1(x0, y1, x0, y0, lineWidth, x, y)
  13130. ) {
  13131. return true;
  13132. }
  13133. }
  13134. else {
  13135. // FIXME Clockwise ?
  13136. w += windingLine(x1, y0, x1, y1, x, y);
  13137. w += windingLine(x0, y1, x0, y0, x, y);
  13138. }
  13139. break;
  13140. case CMD$1.Z:
  13141. if (isStroke) {
  13142. if (containStroke$1(
  13143. xi, yi, x0, y0, lineWidth, x, y
  13144. )) {
  13145. return true;
  13146. }
  13147. }
  13148. else {
  13149. // Close a subpath
  13150. w += windingLine(xi, yi, x0, y0, x, y);
  13151. // 如果被任何一个 subpath 包含
  13152. // FIXME subpaths may overlap
  13153. // if (w !== 0) {
  13154. // return true;
  13155. // }
  13156. }
  13157. xi = x0;
  13158. yi = y0;
  13159. break;
  13160. }
  13161. }
  13162. if (!isStroke && !isAroundEqual(yi, y0)) {
  13163. w += windingLine(xi, yi, x0, y0, x, y) || 0;
  13164. }
  13165. return w !== 0;
  13166. }
  13167. function contain(pathData, x, y) {
  13168. return containPath(pathData, 0, false, x, y);
  13169. }
  13170. function containStroke(pathData, lineWidth, x, y) {
  13171. return containPath(pathData, lineWidth, true, x, y);
  13172. }
  13173. var getCanvasPattern = Pattern.prototype.getCanvasPattern;
  13174. var abs = Math.abs;
  13175. var pathProxyForDraw = new PathProxy(true);
  13176. /**
  13177. * @alias module:zrender/graphic/Path
  13178. * @extends module:zrender/graphic/Displayable
  13179. * @constructor
  13180. * @param {Object} opts
  13181. */
  13182. function Path(opts) {
  13183. Displayable.call(this, opts);
  13184. /**
  13185. * @type {module:zrender/core/PathProxy}
  13186. * @readOnly
  13187. */
  13188. this.path = null;
  13189. }
  13190. Path.prototype = {
  13191. constructor: Path,
  13192. type: 'path',
  13193. __dirtyPath: true,
  13194. strokeContainThreshold: 5,
  13195. // This item default to be false. But in map series in echarts,
  13196. // in order to improve performance, it should be set to true,
  13197. // so the shorty segment won't draw.
  13198. segmentIgnoreThreshold: 0,
  13199. /**
  13200. * See `module:zrender/src/graphic/helper/subPixelOptimize`.
  13201. * @type {boolean}
  13202. */
  13203. subPixelOptimize: false,
  13204. brush: function (ctx, prevEl) {
  13205. var style = this.style;
  13206. var path = this.path || pathProxyForDraw;
  13207. var hasStroke = style.hasStroke();
  13208. var hasFill = style.hasFill();
  13209. var fill = style.fill;
  13210. var stroke = style.stroke;
  13211. var hasFillGradient = hasFill && !!(fill.colorStops);
  13212. var hasStrokeGradient = hasStroke && !!(stroke.colorStops);
  13213. var hasFillPattern = hasFill && !!(fill.image);
  13214. var hasStrokePattern = hasStroke && !!(stroke.image);
  13215. style.bind(ctx, this, prevEl);
  13216. this.setTransform(ctx);
  13217. if (this.__dirty) {
  13218. var rect;
  13219. // Update gradient because bounding rect may changed
  13220. if (hasFillGradient) {
  13221. rect = rect || this.getBoundingRect();
  13222. this._fillGradient = style.getGradient(ctx, fill, rect);
  13223. }
  13224. if (hasStrokeGradient) {
  13225. rect = rect || this.getBoundingRect();
  13226. this._strokeGradient = style.getGradient(ctx, stroke, rect);
  13227. }
  13228. }
  13229. // Use the gradient or pattern
  13230. if (hasFillGradient) {
  13231. // PENDING If may have affect the state
  13232. ctx.fillStyle = this._fillGradient;
  13233. }
  13234. else if (hasFillPattern) {
  13235. ctx.fillStyle = getCanvasPattern.call(fill, ctx);
  13236. }
  13237. if (hasStrokeGradient) {
  13238. ctx.strokeStyle = this._strokeGradient;
  13239. }
  13240. else if (hasStrokePattern) {
  13241. ctx.strokeStyle = getCanvasPattern.call(stroke, ctx);
  13242. }
  13243. var lineDash = style.lineDash;
  13244. var lineDashOffset = style.lineDashOffset;
  13245. var ctxLineDash = !!ctx.setLineDash;
  13246. // Update path sx, sy
  13247. var scale = this.getGlobalScale();
  13248. path.setScale(scale[0], scale[1], this.segmentIgnoreThreshold);
  13249. // Proxy context
  13250. // Rebuild path in following 2 cases
  13251. // 1. Path is dirty
  13252. // 2. Path needs javascript implemented lineDash stroking.
  13253. // In this case, lineDash information will not be saved in PathProxy
  13254. if (this.__dirtyPath
  13255. || (lineDash && !ctxLineDash && hasStroke)
  13256. ) {
  13257. path.beginPath(ctx);
  13258. // Setting line dash before build path
  13259. if (lineDash && !ctxLineDash) {
  13260. path.setLineDash(lineDash);
  13261. path.setLineDashOffset(lineDashOffset);
  13262. }
  13263. this.buildPath(path, this.shape, false);
  13264. // Clear path dirty flag
  13265. if (this.path) {
  13266. this.__dirtyPath = false;
  13267. }
  13268. }
  13269. else {
  13270. // Replay path building
  13271. ctx.beginPath();
  13272. this.path.rebuildPath(ctx);
  13273. }
  13274. if (hasFill) {
  13275. if (style.fillOpacity != null) {
  13276. var originalGlobalAlpha = ctx.globalAlpha;
  13277. ctx.globalAlpha = style.fillOpacity * style.opacity;
  13278. path.fill(ctx);
  13279. ctx.globalAlpha = originalGlobalAlpha;
  13280. }
  13281. else {
  13282. path.fill(ctx);
  13283. }
  13284. }
  13285. if (lineDash && ctxLineDash) {
  13286. ctx.setLineDash(lineDash);
  13287. ctx.lineDashOffset = lineDashOffset;
  13288. }
  13289. if (hasStroke) {
  13290. if (style.strokeOpacity != null) {
  13291. var originalGlobalAlpha = ctx.globalAlpha;
  13292. ctx.globalAlpha = style.strokeOpacity * style.opacity;
  13293. path.stroke(ctx);
  13294. ctx.globalAlpha = originalGlobalAlpha;
  13295. }
  13296. else {
  13297. path.stroke(ctx);
  13298. }
  13299. }
  13300. if (lineDash && ctxLineDash) {
  13301. // PENDING
  13302. // Remove lineDash
  13303. ctx.setLineDash([]);
  13304. }
  13305. // Draw rect text
  13306. if (style.text != null) {
  13307. // Only restore transform when needs draw text.
  13308. this.restoreTransform(ctx);
  13309. this.drawRectText(ctx, this.getBoundingRect());
  13310. }
  13311. },
  13312. // When bundling path, some shape may decide if use moveTo to begin a new subpath or closePath
  13313. // Like in circle
  13314. buildPath: function (ctx, shapeCfg, inBundle) {},
  13315. createPathProxy: function () {
  13316. this.path = new PathProxy();
  13317. },
  13318. getBoundingRect: function () {
  13319. var rect = this._rect;
  13320. var style = this.style;
  13321. var needsUpdateRect = !rect;
  13322. if (needsUpdateRect) {
  13323. var path = this.path;
  13324. if (!path) {
  13325. // Create path on demand.
  13326. path = this.path = new PathProxy();
  13327. }
  13328. if (this.__dirtyPath) {
  13329. path.beginPath();
  13330. this.buildPath(path, this.shape, false);
  13331. }
  13332. rect = path.getBoundingRect();
  13333. }
  13334. this._rect = rect;
  13335. if (style.hasStroke()) {
  13336. // Needs update rect with stroke lineWidth when
  13337. // 1. Element changes scale or lineWidth
  13338. // 2. Shape is changed
  13339. var rectWithStroke = this._rectWithStroke || (this._rectWithStroke = rect.clone());
  13340. if (this.__dirty || needsUpdateRect) {
  13341. rectWithStroke.copy(rect);
  13342. // FIXME Must after updateTransform
  13343. var w = style.lineWidth;
  13344. // PENDING, Min line width is needed when line is horizontal or vertical
  13345. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  13346. // Only add extra hover lineWidth when there are no fill
  13347. if (!style.hasFill()) {
  13348. w = Math.max(w, this.strokeContainThreshold || 4);
  13349. }
  13350. // Consider line width
  13351. // Line scale can't be 0;
  13352. if (lineScale > 1e-10) {
  13353. rectWithStroke.width += w / lineScale;
  13354. rectWithStroke.height += w / lineScale;
  13355. rectWithStroke.x -= w / lineScale / 2;
  13356. rectWithStroke.y -= w / lineScale / 2;
  13357. }
  13358. }
  13359. // Return rect with stroke
  13360. return rectWithStroke;
  13361. }
  13362. return rect;
  13363. },
  13364. contain: function (x, y) {
  13365. var localPos = this.transformCoordToLocal(x, y);
  13366. var rect = this.getBoundingRect();
  13367. var style = this.style;
  13368. x = localPos[0];
  13369. y = localPos[1];
  13370. if (rect.contain(x, y)) {
  13371. var pathData = this.path.data;
  13372. if (style.hasStroke()) {
  13373. var lineWidth = style.lineWidth;
  13374. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  13375. // Line scale can't be 0;
  13376. if (lineScale > 1e-10) {
  13377. // Only add extra hover lineWidth when there are no fill
  13378. if (!style.hasFill()) {
  13379. lineWidth = Math.max(lineWidth, this.strokeContainThreshold);
  13380. }
  13381. if (containStroke(
  13382. pathData, lineWidth / lineScale, x, y
  13383. )) {
  13384. return true;
  13385. }
  13386. }
  13387. }
  13388. if (style.hasFill()) {
  13389. return contain(pathData, x, y);
  13390. }
  13391. }
  13392. return false;
  13393. },
  13394. /**
  13395. * @param {boolean} dirtyPath
  13396. */
  13397. dirty: function (dirtyPath) {
  13398. if (dirtyPath == null) {
  13399. dirtyPath = true;
  13400. }
  13401. // Only mark dirty, not mark clean
  13402. if (dirtyPath) {
  13403. this.__dirtyPath = dirtyPath;
  13404. this._rect = null;
  13405. }
  13406. this.__dirty = this.__dirtyText = true;
  13407. this.__zr && this.__zr.refresh();
  13408. // Used as a clipping path
  13409. if (this.__clipTarget) {
  13410. this.__clipTarget.dirty();
  13411. }
  13412. },
  13413. /**
  13414. * Alias for animate('shape')
  13415. * @param {boolean} loop
  13416. */
  13417. animateShape: function (loop) {
  13418. return this.animate('shape', loop);
  13419. },
  13420. // Overwrite attrKV
  13421. attrKV: function (key, value) {
  13422. // FIXME
  13423. if (key === 'shape') {
  13424. this.setShape(value);
  13425. this.__dirtyPath = true;
  13426. this._rect = null;
  13427. }
  13428. else {
  13429. Displayable.prototype.attrKV.call(this, key, value);
  13430. }
  13431. },
  13432. /**
  13433. * @param {Object|string} key
  13434. * @param {*} value
  13435. */
  13436. setShape: function (key, value) {
  13437. var shape = this.shape;
  13438. // Path from string may not have shape
  13439. if (shape) {
  13440. if (isObject$1(key)) {
  13441. for (var name in key) {
  13442. if (key.hasOwnProperty(name)) {
  13443. shape[name] = key[name];
  13444. }
  13445. }
  13446. }
  13447. else {
  13448. shape[key] = value;
  13449. }
  13450. this.dirty(true);
  13451. }
  13452. return this;
  13453. },
  13454. getLineScale: function () {
  13455. var m = this.transform;
  13456. // Get the line scale.
  13457. // Determinant of `m` means how much the area is enlarged by the
  13458. // transformation. So its square root can be used as a scale factor
  13459. // for width.
  13460. return m && abs(m[0] - 1) > 1e-10 && abs(m[3] - 1) > 1e-10
  13461. ? Math.sqrt(abs(m[0] * m[3] - m[2] * m[1]))
  13462. : 1;
  13463. }
  13464. };
  13465. /**
  13466. * 扩展一个 Path element, 比如星形,圆等。
  13467. * Extend a path element
  13468. * @param {Object} props
  13469. * @param {string} props.type Path type
  13470. * @param {Function} props.init Initialize
  13471. * @param {Function} props.buildPath Overwrite buildPath method
  13472. * @param {Object} [props.style] Extended default style config
  13473. * @param {Object} [props.shape] Extended default shape config
  13474. */
  13475. Path.extend = function (defaults$$1) {
  13476. var Sub = function (opts) {
  13477. Path.call(this, opts);
  13478. if (defaults$$1.style) {
  13479. // Extend default style
  13480. this.style.extendFrom(defaults$$1.style, false);
  13481. }
  13482. // Extend default shape
  13483. var defaultShape = defaults$$1.shape;
  13484. if (defaultShape) {
  13485. this.shape = this.shape || {};
  13486. var thisShape = this.shape;
  13487. for (var name in defaultShape) {
  13488. if (
  13489. !thisShape.hasOwnProperty(name)
  13490. && defaultShape.hasOwnProperty(name)
  13491. ) {
  13492. thisShape[name] = defaultShape[name];
  13493. }
  13494. }
  13495. }
  13496. defaults$$1.init && defaults$$1.init.call(this, opts);
  13497. };
  13498. inherits(Sub, Path);
  13499. // FIXME 不能 extend position, rotation 等引用对象
  13500. for (var name in defaults$$1) {
  13501. // Extending prototype values and methods
  13502. if (name !== 'style' && name !== 'shape') {
  13503. Sub.prototype[name] = defaults$$1[name];
  13504. }
  13505. }
  13506. return Sub;
  13507. };
  13508. inherits(Path, Displayable);
  13509. var CMD$2 = PathProxy.CMD;
  13510. var points = [[], [], []];
  13511. var mathSqrt$3 = Math.sqrt;
  13512. var mathAtan2 = Math.atan2;
  13513. var transformPath = function (path, m) {
  13514. var data = path.data;
  13515. var cmd;
  13516. var nPoint;
  13517. var i;
  13518. var j;
  13519. var k;
  13520. var p;
  13521. var M = CMD$2.M;
  13522. var C = CMD$2.C;
  13523. var L = CMD$2.L;
  13524. var R = CMD$2.R;
  13525. var A = CMD$2.A;
  13526. var Q = CMD$2.Q;
  13527. for (i = 0, j = 0; i < data.length;) {
  13528. cmd = data[i++];
  13529. j = i;
  13530. nPoint = 0;
  13531. switch (cmd) {
  13532. case M:
  13533. nPoint = 1;
  13534. break;
  13535. case L:
  13536. nPoint = 1;
  13537. break;
  13538. case C:
  13539. nPoint = 3;
  13540. break;
  13541. case Q:
  13542. nPoint = 2;
  13543. break;
  13544. case A:
  13545. var x = m[4];
  13546. var y = m[5];
  13547. var sx = mathSqrt$3(m[0] * m[0] + m[1] * m[1]);
  13548. var sy = mathSqrt$3(m[2] * m[2] + m[3] * m[3]);
  13549. var angle = mathAtan2(-m[1] / sy, m[0] / sx);
  13550. // cx
  13551. data[i] *= sx;
  13552. data[i++] += x;
  13553. // cy
  13554. data[i] *= sy;
  13555. data[i++] += y;
  13556. // Scale rx and ry
  13557. // FIXME Assume psi is 0 here
  13558. data[i++] *= sx;
  13559. data[i++] *= sy;
  13560. // Start angle
  13561. data[i++] += angle;
  13562. // end angle
  13563. data[i++] += angle;
  13564. // FIXME psi
  13565. i += 2;
  13566. j = i;
  13567. break;
  13568. case R:
  13569. // x0, y0
  13570. p[0] = data[i++];
  13571. p[1] = data[i++];
  13572. applyTransform(p, p, m);
  13573. data[j++] = p[0];
  13574. data[j++] = p[1];
  13575. // x1, y1
  13576. p[0] += data[i++];
  13577. p[1] += data[i++];
  13578. applyTransform(p, p, m);
  13579. data[j++] = p[0];
  13580. data[j++] = p[1];
  13581. }
  13582. for (k = 0; k < nPoint; k++) {
  13583. var p = points[k];
  13584. p[0] = data[i++];
  13585. p[1] = data[i++];
  13586. applyTransform(p, p, m);
  13587. // Write back
  13588. data[j++] = p[0];
  13589. data[j++] = p[1];
  13590. }
  13591. }
  13592. };
  13593. // command chars
  13594. // var cc = [
  13595. // 'm', 'M', 'l', 'L', 'v', 'V', 'h', 'H', 'z', 'Z',
  13596. // 'c', 'C', 'q', 'Q', 't', 'T', 's', 'S', 'a', 'A'
  13597. // ];
  13598. var mathSqrt = Math.sqrt;
  13599. var mathSin = Math.sin;
  13600. var mathCos = Math.cos;
  13601. var PI = Math.PI;
  13602. var vMag = function (v) {
  13603. return Math.sqrt(v[0] * v[0] + v[1] * v[1]);
  13604. };
  13605. var vRatio = function (u, v) {
  13606. return (u[0] * v[0] + u[1] * v[1]) / (vMag(u) * vMag(v));
  13607. };
  13608. var vAngle = function (u, v) {
  13609. return (u[0] * v[1] < u[1] * v[0] ? -1 : 1)
  13610. * Math.acos(vRatio(u, v));
  13611. };
  13612. function processArc(x1, y1, x2, y2, fa, fs, rx, ry, psiDeg, cmd, path) {
  13613. var psi = psiDeg * (PI / 180.0);
  13614. var xp = mathCos(psi) * (x1 - x2) / 2.0
  13615. + mathSin(psi) * (y1 - y2) / 2.0;
  13616. var yp = -1 * mathSin(psi) * (x1 - x2) / 2.0
  13617. + mathCos(psi) * (y1 - y2) / 2.0;
  13618. var lambda = (xp * xp) / (rx * rx) + (yp * yp) / (ry * ry);
  13619. if (lambda > 1) {
  13620. rx *= mathSqrt(lambda);
  13621. ry *= mathSqrt(lambda);
  13622. }
  13623. var f = (fa === fs ? -1 : 1)
  13624. * mathSqrt((((rx * rx) * (ry * ry))
  13625. - ((rx * rx) * (yp * yp))
  13626. - ((ry * ry) * (xp * xp))) / ((rx * rx) * (yp * yp)
  13627. + (ry * ry) * (xp * xp))
  13628. ) || 0;
  13629. var cxp = f * rx * yp / ry;
  13630. var cyp = f * -ry * xp / rx;
  13631. var cx = (x1 + x2) / 2.0
  13632. + mathCos(psi) * cxp
  13633. - mathSin(psi) * cyp;
  13634. var cy = (y1 + y2) / 2.0
  13635. + mathSin(psi) * cxp
  13636. + mathCos(psi) * cyp;
  13637. var theta = vAngle([ 1, 0 ], [ (xp - cxp) / rx, (yp - cyp) / ry ]);
  13638. var u = [ (xp - cxp) / rx, (yp - cyp) / ry ];
  13639. var v = [ (-1 * xp - cxp) / rx, (-1 * yp - cyp) / ry ];
  13640. var dTheta = vAngle(u, v);
  13641. if (vRatio(u, v) <= -1) {
  13642. dTheta = PI;
  13643. }
  13644. if (vRatio(u, v) >= 1) {
  13645. dTheta = 0;
  13646. }
  13647. if (fs === 0 && dTheta > 0) {
  13648. dTheta = dTheta - 2 * PI;
  13649. }
  13650. if (fs === 1 && dTheta < 0) {
  13651. dTheta = dTheta + 2 * PI;
  13652. }
  13653. path.addData(cmd, cx, cy, rx, ry, theta, dTheta, psi, fs);
  13654. }
  13655. var commandReg = /([mlvhzcqtsa])([^mlvhzcqtsa]*)/ig;
  13656. // Consider case:
  13657. // (1) delimiter can be comma or space, where continuous commas
  13658. // or spaces should be seen as one comma.
  13659. // (2) value can be like:
  13660. // '2e-4', 'l.5.9' (ignore 0), 'M-10-10', 'l-2.43e-1,34.9983',
  13661. // 'l-.5E1,54', '121-23-44-11' (no delimiter)
  13662. var numberReg = /-?([0-9]*\.)?[0-9]+([eE]-?[0-9]+)?/g;
  13663. // var valueSplitReg = /[\s,]+/;
  13664. function createPathProxyFromString(data) {
  13665. if (!data) {
  13666. return new PathProxy();
  13667. }
  13668. // var data = data.replace(/-/g, ' -')
  13669. // .replace(/ /g, ' ')
  13670. // .replace(/ /g, ',')
  13671. // .replace(/,,/g, ',');
  13672. // var n;
  13673. // create pipes so that we can split the data
  13674. // for (n = 0; n < cc.length; n++) {
  13675. // cs = cs.replace(new RegExp(cc[n], 'g'), '|' + cc[n]);
  13676. // }
  13677. // data = data.replace(/-/g, ',-');
  13678. // create array
  13679. // var arr = cs.split('|');
  13680. // init context point
  13681. var cpx = 0;
  13682. var cpy = 0;
  13683. var subpathX = cpx;
  13684. var subpathY = cpy;
  13685. var prevCmd;
  13686. var path = new PathProxy();
  13687. var CMD = PathProxy.CMD;
  13688. // commandReg.lastIndex = 0;
  13689. // var cmdResult;
  13690. // while ((cmdResult = commandReg.exec(data)) != null) {
  13691. // var cmdStr = cmdResult[1];
  13692. // var cmdContent = cmdResult[2];
  13693. var cmdList = data.match(commandReg);
  13694. for (var l = 0; l < cmdList.length; l++) {
  13695. var cmdText = cmdList[l];
  13696. var cmdStr = cmdText.charAt(0);
  13697. var cmd;
  13698. // String#split is faster a little bit than String#replace or RegExp#exec.
  13699. // var p = cmdContent.split(valueSplitReg);
  13700. // var pLen = 0;
  13701. // for (var i = 0; i < p.length; i++) {
  13702. // // '' and other invalid str => NaN
  13703. // var val = parseFloat(p[i]);
  13704. // !isNaN(val) && (p[pLen++] = val);
  13705. // }
  13706. var p = cmdText.match(numberReg) || [];
  13707. var pLen = p.length;
  13708. for (var i = 0; i < pLen; i++) {
  13709. p[i] = parseFloat(p[i]);
  13710. }
  13711. var off = 0;
  13712. while (off < pLen) {
  13713. var ctlPtx;
  13714. var ctlPty;
  13715. var rx;
  13716. var ry;
  13717. var psi;
  13718. var fa;
  13719. var fs;
  13720. var x1 = cpx;
  13721. var y1 = cpy;
  13722. // convert l, H, h, V, and v to L
  13723. switch (cmdStr) {
  13724. case 'l':
  13725. cpx += p[off++];
  13726. cpy += p[off++];
  13727. cmd = CMD.L;
  13728. path.addData(cmd, cpx, cpy);
  13729. break;
  13730. case 'L':
  13731. cpx = p[off++];
  13732. cpy = p[off++];
  13733. cmd = CMD.L;
  13734. path.addData(cmd, cpx, cpy);
  13735. break;
  13736. case 'm':
  13737. cpx += p[off++];
  13738. cpy += p[off++];
  13739. cmd = CMD.M;
  13740. path.addData(cmd, cpx, cpy);
  13741. subpathX = cpx;
  13742. subpathY = cpy;
  13743. cmdStr = 'l';
  13744. break;
  13745. case 'M':
  13746. cpx = p[off++];
  13747. cpy = p[off++];
  13748. cmd = CMD.M;
  13749. path.addData(cmd, cpx, cpy);
  13750. subpathX = cpx;
  13751. subpathY = cpy;
  13752. cmdStr = 'L';
  13753. break;
  13754. case 'h':
  13755. cpx += p[off++];
  13756. cmd = CMD.L;
  13757. path.addData(cmd, cpx, cpy);
  13758. break;
  13759. case 'H':
  13760. cpx = p[off++];
  13761. cmd = CMD.L;
  13762. path.addData(cmd, cpx, cpy);
  13763. break;
  13764. case 'v':
  13765. cpy += p[off++];
  13766. cmd = CMD.L;
  13767. path.addData(cmd, cpx, cpy);
  13768. break;
  13769. case 'V':
  13770. cpy = p[off++];
  13771. cmd = CMD.L;
  13772. path.addData(cmd, cpx, cpy);
  13773. break;
  13774. case 'C':
  13775. cmd = CMD.C;
  13776. path.addData(
  13777. cmd, p[off++], p[off++], p[off++], p[off++], p[off++], p[off++]
  13778. );
  13779. cpx = p[off - 2];
  13780. cpy = p[off - 1];
  13781. break;
  13782. case 'c':
  13783. cmd = CMD.C;
  13784. path.addData(
  13785. cmd,
  13786. p[off++] + cpx, p[off++] + cpy,
  13787. p[off++] + cpx, p[off++] + cpy,
  13788. p[off++] + cpx, p[off++] + cpy
  13789. );
  13790. cpx += p[off - 2];
  13791. cpy += p[off - 1];
  13792. break;
  13793. case 'S':
  13794. ctlPtx = cpx;
  13795. ctlPty = cpy;
  13796. var len = path.len();
  13797. var pathData = path.data;
  13798. if (prevCmd === CMD.C) {
  13799. ctlPtx += cpx - pathData[len - 4];
  13800. ctlPty += cpy - pathData[len - 3];
  13801. }
  13802. cmd = CMD.C;
  13803. x1 = p[off++];
  13804. y1 = p[off++];
  13805. cpx = p[off++];
  13806. cpy = p[off++];
  13807. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  13808. break;
  13809. case 's':
  13810. ctlPtx = cpx;
  13811. ctlPty = cpy;
  13812. var len = path.len();
  13813. var pathData = path.data;
  13814. if (prevCmd === CMD.C) {
  13815. ctlPtx += cpx - pathData[len - 4];
  13816. ctlPty += cpy - pathData[len - 3];
  13817. }
  13818. cmd = CMD.C;
  13819. x1 = cpx + p[off++];
  13820. y1 = cpy + p[off++];
  13821. cpx += p[off++];
  13822. cpy += p[off++];
  13823. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  13824. break;
  13825. case 'Q':
  13826. x1 = p[off++];
  13827. y1 = p[off++];
  13828. cpx = p[off++];
  13829. cpy = p[off++];
  13830. cmd = CMD.Q;
  13831. path.addData(cmd, x1, y1, cpx, cpy);
  13832. break;
  13833. case 'q':
  13834. x1 = p[off++] + cpx;
  13835. y1 = p[off++] + cpy;
  13836. cpx += p[off++];
  13837. cpy += p[off++];
  13838. cmd = CMD.Q;
  13839. path.addData(cmd, x1, y1, cpx, cpy);
  13840. break;
  13841. case 'T':
  13842. ctlPtx = cpx;
  13843. ctlPty = cpy;
  13844. var len = path.len();
  13845. var pathData = path.data;
  13846. if (prevCmd === CMD.Q) {
  13847. ctlPtx += cpx - pathData[len - 4];
  13848. ctlPty += cpy - pathData[len - 3];
  13849. }
  13850. cpx = p[off++];
  13851. cpy = p[off++];
  13852. cmd = CMD.Q;
  13853. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  13854. break;
  13855. case 't':
  13856. ctlPtx = cpx;
  13857. ctlPty = cpy;
  13858. var len = path.len();
  13859. var pathData = path.data;
  13860. if (prevCmd === CMD.Q) {
  13861. ctlPtx += cpx - pathData[len - 4];
  13862. ctlPty += cpy - pathData[len - 3];
  13863. }
  13864. cpx += p[off++];
  13865. cpy += p[off++];
  13866. cmd = CMD.Q;
  13867. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  13868. break;
  13869. case 'A':
  13870. rx = p[off++];
  13871. ry = p[off++];
  13872. psi = p[off++];
  13873. fa = p[off++];
  13874. fs = p[off++];
  13875. x1 = cpx, y1 = cpy;
  13876. cpx = p[off++];
  13877. cpy = p[off++];
  13878. cmd = CMD.A;
  13879. processArc(
  13880. x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path
  13881. );
  13882. break;
  13883. case 'a':
  13884. rx = p[off++];
  13885. ry = p[off++];
  13886. psi = p[off++];
  13887. fa = p[off++];
  13888. fs = p[off++];
  13889. x1 = cpx, y1 = cpy;
  13890. cpx += p[off++];
  13891. cpy += p[off++];
  13892. cmd = CMD.A;
  13893. processArc(
  13894. x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path
  13895. );
  13896. break;
  13897. }
  13898. }
  13899. if (cmdStr === 'z' || cmdStr === 'Z') {
  13900. cmd = CMD.Z;
  13901. path.addData(cmd);
  13902. // z may be in the middle of the path.
  13903. cpx = subpathX;
  13904. cpy = subpathY;
  13905. }
  13906. prevCmd = cmd;
  13907. }
  13908. path.toStatic();
  13909. return path;
  13910. }
  13911. // TODO Optimize double memory cost problem
  13912. function createPathOptions(str, opts) {
  13913. var pathProxy = createPathProxyFromString(str);
  13914. opts = opts || {};
  13915. opts.buildPath = function (path) {
  13916. if (path.setData) {
  13917. path.setData(pathProxy.data);
  13918. // Svg and vml renderer don't have context
  13919. var ctx = path.getContext();
  13920. if (ctx) {
  13921. path.rebuildPath(ctx);
  13922. }
  13923. }
  13924. else {
  13925. var ctx = path;
  13926. pathProxy.rebuildPath(ctx);
  13927. }
  13928. };
  13929. opts.applyTransform = function (m) {
  13930. transformPath(pathProxy, m);
  13931. this.dirty(true);
  13932. };
  13933. return opts;
  13934. }
  13935. /**
  13936. * Create a Path object from path string data
  13937. * http://www.w3.org/TR/SVG/paths.html#PathData
  13938. * @param {Object} opts Other options
  13939. */
  13940. function createFromString(str, opts) {
  13941. return new Path(createPathOptions(str, opts));
  13942. }
  13943. /**
  13944. * Create a Path class from path string data
  13945. * @param {string} str
  13946. * @param {Object} opts Other options
  13947. */
  13948. function extendFromString(str, opts) {
  13949. return Path.extend(createPathOptions(str, opts));
  13950. }
  13951. /**
  13952. * Merge multiple paths
  13953. */
  13954. // TODO Apply transform
  13955. // TODO stroke dash
  13956. // TODO Optimize double memory cost problem
  13957. function mergePath$1(pathEls, opts) {
  13958. var pathList = [];
  13959. var len = pathEls.length;
  13960. for (var i = 0; i < len; i++) {
  13961. var pathEl = pathEls[i];
  13962. if (!pathEl.path) {
  13963. pathEl.createPathProxy();
  13964. }
  13965. if (pathEl.__dirtyPath) {
  13966. pathEl.buildPath(pathEl.path, pathEl.shape, true);
  13967. }
  13968. pathList.push(pathEl.path);
  13969. }
  13970. var pathBundle = new Path(opts);
  13971. // Need path proxy.
  13972. pathBundle.createPathProxy();
  13973. pathBundle.buildPath = function (path) {
  13974. path.appendPath(pathList);
  13975. // Svg and vml renderer don't have context
  13976. var ctx = path.getContext();
  13977. if (ctx) {
  13978. path.rebuildPath(ctx);
  13979. }
  13980. };
  13981. return pathBundle;
  13982. }
  13983. /**
  13984. * @alias zrender/graphic/Text
  13985. * @extends module:zrender/graphic/Displayable
  13986. * @constructor
  13987. * @param {Object} opts
  13988. */
  13989. var Text = function (opts) { // jshint ignore:line
  13990. Displayable.call(this, opts);
  13991. };
  13992. Text.prototype = {
  13993. constructor: Text,
  13994. type: 'text',
  13995. brush: function (ctx, prevEl) {
  13996. var style = this.style;
  13997. // Optimize, avoid normalize every time.
  13998. this.__dirty && normalizeTextStyle(style, true);
  13999. // Use props with prefix 'text'.
  14000. style.fill = style.stroke = style.shadowBlur = style.shadowColor =
  14001. style.shadowOffsetX = style.shadowOffsetY = null;
  14002. var text = style.text;
  14003. // Convert to string
  14004. text != null && (text += '');
  14005. // Do not apply style.bind in Text node. Because the real bind job
  14006. // is in textHelper.renderText, and performance of text render should
  14007. // be considered.
  14008. // style.bind(ctx, this, prevEl);
  14009. if (!needDrawText(text, style)) {
  14010. // The current el.style is not applied
  14011. // and should not be used as cache.
  14012. ctx.__attrCachedBy = ContextCachedBy.NONE;
  14013. return;
  14014. }
  14015. this.setTransform(ctx);
  14016. renderText(this, ctx, text, style, null, prevEl);
  14017. this.restoreTransform(ctx);
  14018. },
  14019. getBoundingRect: function () {
  14020. var style = this.style;
  14021. // Optimize, avoid normalize every time.
  14022. this.__dirty && normalizeTextStyle(style, true);
  14023. if (!this._rect) {
  14024. var text = style.text;
  14025. text != null ? (text += '') : (text = '');
  14026. var rect = getBoundingRect(
  14027. style.text + '',
  14028. style.font,
  14029. style.textAlign,
  14030. style.textVerticalAlign,
  14031. style.textPadding,
  14032. style.textLineHeight,
  14033. style.rich
  14034. );
  14035. rect.x += style.x || 0;
  14036. rect.y += style.y || 0;
  14037. if (getStroke(style.textStroke, style.textStrokeWidth)) {
  14038. var w = style.textStrokeWidth;
  14039. rect.x -= w / 2;
  14040. rect.y -= w / 2;
  14041. rect.width += w;
  14042. rect.height += w;
  14043. }
  14044. this._rect = rect;
  14045. }
  14046. return this._rect;
  14047. }
  14048. };
  14049. inherits(Text, Displayable);
  14050. /**
  14051. * 圆形
  14052. * @module zrender/shape/Circle
  14053. */
  14054. var Circle = Path.extend({
  14055. type: 'circle',
  14056. shape: {
  14057. cx: 0,
  14058. cy: 0,
  14059. r: 0
  14060. },
  14061. buildPath: function (ctx, shape, inBundle) {
  14062. // Better stroking in ShapeBundle
  14063. // Always do it may have performence issue ( fill may be 2x more cost)
  14064. if (inBundle) {
  14065. ctx.moveTo(shape.cx + shape.r, shape.cy);
  14066. }
  14067. // else {
  14068. // if (ctx.allocate && !ctx.data.length) {
  14069. // ctx.allocate(ctx.CMD_MEM_SIZE.A);
  14070. // }
  14071. // }
  14072. // Better stroking in ShapeBundle
  14073. // ctx.moveTo(shape.cx + shape.r, shape.cy);
  14074. ctx.arc(shape.cx, shape.cy, shape.r, 0, Math.PI * 2, true);
  14075. }
  14076. });
  14077. // Fix weird bug in some version of IE11 (like 11.0.9600.178**),
  14078. // where exception "unexpected call to method or property access"
  14079. // might be thrown when calling ctx.fill or ctx.stroke after a path
  14080. // whose area size is zero is drawn and ctx.clip() is called and
  14081. // shadowBlur is set. See #4572, #3112, #5777.
  14082. // (e.g.,
  14083. // ctx.moveTo(10, 10);
  14084. // ctx.lineTo(20, 10);
  14085. // ctx.closePath();
  14086. // ctx.clip();
  14087. // ctx.shadowBlur = 10;
  14088. // ...
  14089. // ctx.fill();
  14090. // )
  14091. var shadowTemp = [
  14092. ['shadowBlur', 0],
  14093. ['shadowColor', '#000'],
  14094. ['shadowOffsetX', 0],
  14095. ['shadowOffsetY', 0]
  14096. ];
  14097. var fixClipWithShadow = function (orignalBrush) {
  14098. // version string can be: '11.0'
  14099. return (env$1.browser.ie && env$1.browser.version >= 11)
  14100. ? function () {
  14101. var clipPaths = this.__clipPaths;
  14102. var style = this.style;
  14103. var modified;
  14104. if (clipPaths) {
  14105. for (var i = 0; i < clipPaths.length; i++) {
  14106. var clipPath = clipPaths[i];
  14107. var shape = clipPath && clipPath.shape;
  14108. var type = clipPath && clipPath.type;
  14109. if (shape && (
  14110. (type === 'sector' && shape.startAngle === shape.endAngle)
  14111. || (type === 'rect' && (!shape.width || !shape.height))
  14112. )) {
  14113. for (var j = 0; j < shadowTemp.length; j++) {
  14114. // It is save to put shadowTemp static, because shadowTemp
  14115. // will be all modified each item brush called.
  14116. shadowTemp[j][2] = style[shadowTemp[j][0]];
  14117. style[shadowTemp[j][0]] = shadowTemp[j][1];
  14118. }
  14119. modified = true;
  14120. break;
  14121. }
  14122. }
  14123. }
  14124. orignalBrush.apply(this, arguments);
  14125. if (modified) {
  14126. for (var j = 0; j < shadowTemp.length; j++) {
  14127. style[shadowTemp[j][0]] = shadowTemp[j][2];
  14128. }
  14129. }
  14130. }
  14131. : orignalBrush;
  14132. };
  14133. /**
  14134. * 扇形
  14135. * @module zrender/graphic/shape/Sector
  14136. */
  14137. var Sector = Path.extend({
  14138. type: 'sector',
  14139. shape: {
  14140. cx: 0,
  14141. cy: 0,
  14142. r0: 0,
  14143. r: 0,
  14144. startAngle: 0,
  14145. endAngle: Math.PI * 2,
  14146. clockwise: true
  14147. },
  14148. brush: fixClipWithShadow(Path.prototype.brush),
  14149. buildPath: function (ctx, shape) {
  14150. var x = shape.cx;
  14151. var y = shape.cy;
  14152. var r0 = Math.max(shape.r0 || 0, 0);
  14153. var r = Math.max(shape.r, 0);
  14154. var startAngle = shape.startAngle;
  14155. var endAngle = shape.endAngle;
  14156. var clockwise = shape.clockwise;
  14157. var unitX = Math.cos(startAngle);
  14158. var unitY = Math.sin(startAngle);
  14159. ctx.moveTo(unitX * r0 + x, unitY * r0 + y);
  14160. ctx.lineTo(unitX * r + x, unitY * r + y);
  14161. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  14162. ctx.lineTo(
  14163. Math.cos(endAngle) * r0 + x,
  14164. Math.sin(endAngle) * r0 + y
  14165. );
  14166. if (r0 !== 0) {
  14167. ctx.arc(x, y, r0, endAngle, startAngle, clockwise);
  14168. }
  14169. ctx.closePath();
  14170. }
  14171. });
  14172. /**
  14173. * 圆环
  14174. * @module zrender/graphic/shape/Ring
  14175. */
  14176. var Ring = Path.extend({
  14177. type: 'ring',
  14178. shape: {
  14179. cx: 0,
  14180. cy: 0,
  14181. r: 0,
  14182. r0: 0
  14183. },
  14184. buildPath: function (ctx, shape) {
  14185. var x = shape.cx;
  14186. var y = shape.cy;
  14187. var PI2 = Math.PI * 2;
  14188. ctx.moveTo(x + shape.r, y);
  14189. ctx.arc(x, y, shape.r, 0, PI2, false);
  14190. ctx.moveTo(x + shape.r0, y);
  14191. ctx.arc(x, y, shape.r0, 0, PI2, true);
  14192. }
  14193. });
  14194. /**
  14195. * Catmull-Rom spline 插值折线
  14196. * @module zrender/shape/util/smoothSpline
  14197. * @author pissang (https://www.github.com/pissang)
  14198. * Kener (@Kener-林峰, kener.linfeng@gmail.com)
  14199. * errorrik (errorrik@gmail.com)
  14200. */
  14201. /**
  14202. * @inner
  14203. */
  14204. function interpolate(p0, p1, p2, p3, t, t2, t3) {
  14205. var v0 = (p2 - p0) * 0.5;
  14206. var v1 = (p3 - p1) * 0.5;
  14207. return (2 * (p1 - p2) + v0 + v1) * t3
  14208. + (-3 * (p1 - p2) - 2 * v0 - v1) * t2
  14209. + v0 * t + p1;
  14210. }
  14211. /**
  14212. * @alias module:zrender/shape/util/smoothSpline
  14213. * @param {Array} points 线段顶点数组
  14214. * @param {boolean} isLoop
  14215. * @return {Array}
  14216. */
  14217. var smoothSpline = function (points, isLoop) {
  14218. var len$$1 = points.length;
  14219. var ret = [];
  14220. var distance$$1 = 0;
  14221. for (var i = 1; i < len$$1; i++) {
  14222. distance$$1 += distance(points[i - 1], points[i]);
  14223. }
  14224. var segs = distance$$1 / 2;
  14225. segs = segs < len$$1 ? len$$1 : segs;
  14226. for (var i = 0; i < segs; i++) {
  14227. var pos = i / (segs - 1) * (isLoop ? len$$1 : len$$1 - 1);
  14228. var idx = Math.floor(pos);
  14229. var w = pos - idx;
  14230. var p0;
  14231. var p1 = points[idx % len$$1];
  14232. var p2;
  14233. var p3;
  14234. if (!isLoop) {
  14235. p0 = points[idx === 0 ? idx : idx - 1];
  14236. p2 = points[idx > len$$1 - 2 ? len$$1 - 1 : idx + 1];
  14237. p3 = points[idx > len$$1 - 3 ? len$$1 - 1 : idx + 2];
  14238. }
  14239. else {
  14240. p0 = points[(idx - 1 + len$$1) % len$$1];
  14241. p2 = points[(idx + 1) % len$$1];
  14242. p3 = points[(idx + 2) % len$$1];
  14243. }
  14244. var w2 = w * w;
  14245. var w3 = w * w2;
  14246. ret.push([
  14247. interpolate(p0[0], p1[0], p2[0], p3[0], w, w2, w3),
  14248. interpolate(p0[1], p1[1], p2[1], p3[1], w, w2, w3)
  14249. ]);
  14250. }
  14251. return ret;
  14252. };
  14253. /**
  14254. * 贝塞尔平滑曲线
  14255. * @module zrender/shape/util/smoothBezier
  14256. * @author pissang (https://www.github.com/pissang)
  14257. * Kener (@Kener-林峰, kener.linfeng@gmail.com)
  14258. * errorrik (errorrik@gmail.com)
  14259. */
  14260. /**
  14261. * 贝塞尔平滑曲线
  14262. * @alias module:zrender/shape/util/smoothBezier
  14263. * @param {Array} points 线段顶点数组
  14264. * @param {number} smooth 平滑等级, 0-1
  14265. * @param {boolean} isLoop
  14266. * @param {Array} constraint 将计算出来的控制点约束在一个包围盒内
  14267. * 比如 [[0, 0], [100, 100]], 这个包围盒会与
  14268. * 整个折线的包围盒做一个并集用来约束控制点。
  14269. * @param {Array} 计算出来的控制点数组
  14270. */
  14271. var smoothBezier = function (points, smooth, isLoop, constraint) {
  14272. var cps = [];
  14273. var v = [];
  14274. var v1 = [];
  14275. var v2 = [];
  14276. var prevPoint;
  14277. var nextPoint;
  14278. var min$$1;
  14279. var max$$1;
  14280. if (constraint) {
  14281. min$$1 = [Infinity, Infinity];
  14282. max$$1 = [-Infinity, -Infinity];
  14283. for (var i = 0, len$$1 = points.length; i < len$$1; i++) {
  14284. min(min$$1, min$$1, points[i]);
  14285. max(max$$1, max$$1, points[i]);
  14286. }
  14287. // 与指定的包围盒做并集
  14288. min(min$$1, min$$1, constraint[0]);
  14289. max(max$$1, max$$1, constraint[1]);
  14290. }
  14291. for (var i = 0, len$$1 = points.length; i < len$$1; i++) {
  14292. var point = points[i];
  14293. if (isLoop) {
  14294. prevPoint = points[i ? i - 1 : len$$1 - 1];
  14295. nextPoint = points[(i + 1) % len$$1];
  14296. }
  14297. else {
  14298. if (i === 0 || i === len$$1 - 1) {
  14299. cps.push(clone$1(points[i]));
  14300. continue;
  14301. }
  14302. else {
  14303. prevPoint = points[i - 1];
  14304. nextPoint = points[i + 1];
  14305. }
  14306. }
  14307. sub(v, nextPoint, prevPoint);
  14308. // use degree to scale the handle length
  14309. scale(v, v, smooth);
  14310. var d0 = distance(point, prevPoint);
  14311. var d1 = distance(point, nextPoint);
  14312. var sum = d0 + d1;
  14313. if (sum !== 0) {
  14314. d0 /= sum;
  14315. d1 /= sum;
  14316. }
  14317. scale(v1, v, -d0);
  14318. scale(v2, v, d1);
  14319. var cp0 = add([], point, v1);
  14320. var cp1 = add([], point, v2);
  14321. if (constraint) {
  14322. max(cp0, cp0, min$$1);
  14323. min(cp0, cp0, max$$1);
  14324. max(cp1, cp1, min$$1);
  14325. min(cp1, cp1, max$$1);
  14326. }
  14327. cps.push(cp0);
  14328. cps.push(cp1);
  14329. }
  14330. if (isLoop) {
  14331. cps.push(cps.shift());
  14332. }
  14333. return cps;
  14334. };
  14335. function buildPath$1(ctx, shape, closePath) {
  14336. var points = shape.points;
  14337. var smooth = shape.smooth;
  14338. if (points && points.length >= 2) {
  14339. if (smooth && smooth !== 'spline') {
  14340. var controlPoints = smoothBezier(
  14341. points, smooth, closePath, shape.smoothConstraint
  14342. );
  14343. ctx.moveTo(points[0][0], points[0][1]);
  14344. var len = points.length;
  14345. for (var i = 0; i < (closePath ? len : len - 1); i++) {
  14346. var cp1 = controlPoints[i * 2];
  14347. var cp2 = controlPoints[i * 2 + 1];
  14348. var p = points[(i + 1) % len];
  14349. ctx.bezierCurveTo(
  14350. cp1[0], cp1[1], cp2[0], cp2[1], p[0], p[1]
  14351. );
  14352. }
  14353. }
  14354. else {
  14355. if (smooth === 'spline') {
  14356. points = smoothSpline(points, closePath);
  14357. }
  14358. ctx.moveTo(points[0][0], points[0][1]);
  14359. for (var i = 1, l = points.length; i < l; i++) {
  14360. ctx.lineTo(points[i][0], points[i][1]);
  14361. }
  14362. }
  14363. closePath && ctx.closePath();
  14364. }
  14365. }
  14366. /**
  14367. * 多边形
  14368. * @module zrender/shape/Polygon
  14369. */
  14370. var Polygon = Path.extend({
  14371. type: 'polygon',
  14372. shape: {
  14373. points: null,
  14374. smooth: false,
  14375. smoothConstraint: null
  14376. },
  14377. buildPath: function (ctx, shape) {
  14378. buildPath$1(ctx, shape, true);
  14379. }
  14380. });
  14381. /**
  14382. * @module zrender/graphic/shape/Polyline
  14383. */
  14384. var Polyline = Path.extend({
  14385. type: 'polyline',
  14386. shape: {
  14387. points: null,
  14388. smooth: false,
  14389. smoothConstraint: null
  14390. },
  14391. style: {
  14392. stroke: '#000',
  14393. fill: null
  14394. },
  14395. buildPath: function (ctx, shape) {
  14396. buildPath$1(ctx, shape, false);
  14397. }
  14398. });
  14399. /**
  14400. * Sub-pixel optimize for canvas rendering, prevent from blur
  14401. * when rendering a thin vertical/horizontal line.
  14402. */
  14403. var round = Math.round;
  14404. /**
  14405. * Sub pixel optimize line for canvas
  14406. *
  14407. * @param {Object} outputShape The modification will be performed on `outputShape`.
  14408. * `outputShape` and `inputShape` can be the same object.
  14409. * `outputShape` object can be used repeatly, because all of
  14410. * the `x1`, `x2`, `y1`, `y2` will be assigned in this method.
  14411. * @param {Object} [inputShape]
  14412. * @param {number} [inputShape.x1]
  14413. * @param {number} [inputShape.y1]
  14414. * @param {number} [inputShape.x2]
  14415. * @param {number} [inputShape.y2]
  14416. * @param {Object} [style]
  14417. * @param {number} [style.lineWidth] If `null`/`undefined`/`0`, do not optimize.
  14418. */
  14419. function subPixelOptimizeLine$1(outputShape, inputShape, style) {
  14420. if (!inputShape) {
  14421. return;
  14422. }
  14423. var x1 = inputShape.x1;
  14424. var x2 = inputShape.x2;
  14425. var y1 = inputShape.y1;
  14426. var y2 = inputShape.y2;
  14427. outputShape.x1 = x1;
  14428. outputShape.x2 = x2;
  14429. outputShape.y1 = y1;
  14430. outputShape.y2 = y2;
  14431. var lineWidth = style && style.lineWidth;
  14432. if (!lineWidth) {
  14433. return;
  14434. }
  14435. if (round(x1 * 2) === round(x2 * 2)) {
  14436. outputShape.x1 = outputShape.x2 = subPixelOptimize$1(x1, lineWidth, true);
  14437. }
  14438. if (round(y1 * 2) === round(y2 * 2)) {
  14439. outputShape.y1 = outputShape.y2 = subPixelOptimize$1(y1, lineWidth, true);
  14440. }
  14441. }
  14442. /**
  14443. * Sub pixel optimize rect for canvas
  14444. *
  14445. * @param {Object} outputShape The modification will be performed on `outputShape`.
  14446. * `outputShape` and `inputShape` can be the same object.
  14447. * `outputShape` object can be used repeatly, because all of
  14448. * the `x`, `y`, `width`, `height` will be assigned in this method.
  14449. * @param {Object} [inputShape]
  14450. * @param {number} [inputShape.x]
  14451. * @param {number} [inputShape.y]
  14452. * @param {number} [inputShape.width]
  14453. * @param {number} [inputShape.height]
  14454. * @param {Object} [style]
  14455. * @param {number} [style.lineWidth] If `null`/`undefined`/`0`, do not optimize.
  14456. */
  14457. function subPixelOptimizeRect$1(outputShape, inputShape, style) {
  14458. if (!inputShape) {
  14459. return;
  14460. }
  14461. var originX = inputShape.x;
  14462. var originY = inputShape.y;
  14463. var originWidth = inputShape.width;
  14464. var originHeight = inputShape.height;
  14465. outputShape.x = originX;
  14466. outputShape.y = originY;
  14467. outputShape.width = originWidth;
  14468. outputShape.height = originHeight;
  14469. var lineWidth = style && style.lineWidth;
  14470. if (!lineWidth) {
  14471. return;
  14472. }
  14473. outputShape.x = subPixelOptimize$1(originX, lineWidth, true);
  14474. outputShape.y = subPixelOptimize$1(originY, lineWidth, true);
  14475. outputShape.width = Math.max(
  14476. subPixelOptimize$1(originX + originWidth, lineWidth, false) - outputShape.x,
  14477. originWidth === 0 ? 0 : 1
  14478. );
  14479. outputShape.height = Math.max(
  14480. subPixelOptimize$1(originY + originHeight, lineWidth, false) - outputShape.y,
  14481. originHeight === 0 ? 0 : 1
  14482. );
  14483. }
  14484. /**
  14485. * Sub pixel optimize for canvas
  14486. *
  14487. * @param {number} position Coordinate, such as x, y
  14488. * @param {number} lineWidth If `null`/`undefined`/`0`, do not optimize.
  14489. * @param {boolean=} positiveOrNegative Default false (negative).
  14490. * @return {number} Optimized position.
  14491. */
  14492. function subPixelOptimize$1(position, lineWidth, positiveOrNegative) {
  14493. if (!lineWidth) {
  14494. return position;
  14495. }
  14496. // Assure that (position + lineWidth / 2) is near integer edge,
  14497. // otherwise line will be fuzzy in canvas.
  14498. var doubledPosition = round(position * 2);
  14499. return (doubledPosition + round(lineWidth)) % 2 === 0
  14500. ? doubledPosition / 2
  14501. : (doubledPosition + (positiveOrNegative ? 1 : -1)) / 2;
  14502. }
  14503. /**
  14504. * 矩形
  14505. * @module zrender/graphic/shape/Rect
  14506. */
  14507. // Avoid create repeatly.
  14508. var subPixelOptimizeOutputShape = {};
  14509. var Rect = Path.extend({
  14510. type: 'rect',
  14511. shape: {
  14512. // 左上、右上、右下、左下角的半径依次为r1、r2、r3、r4
  14513. // r缩写为1 相当于 [1, 1, 1, 1]
  14514. // r缩写为[1] 相当于 [1, 1, 1, 1]
  14515. // r缩写为[1, 2] 相当于 [1, 2, 1, 2]
  14516. // r缩写为[1, 2, 3] 相当于 [1, 2, 3, 2]
  14517. r: 0,
  14518. x: 0,
  14519. y: 0,
  14520. width: 0,
  14521. height: 0
  14522. },
  14523. buildPath: function (ctx, shape) {
  14524. var x;
  14525. var y;
  14526. var width;
  14527. var height;
  14528. if (this.subPixelOptimize) {
  14529. subPixelOptimizeRect$1(subPixelOptimizeOutputShape, shape, this.style);
  14530. x = subPixelOptimizeOutputShape.x;
  14531. y = subPixelOptimizeOutputShape.y;
  14532. width = subPixelOptimizeOutputShape.width;
  14533. height = subPixelOptimizeOutputShape.height;
  14534. subPixelOptimizeOutputShape.r = shape.r;
  14535. shape = subPixelOptimizeOutputShape;
  14536. }
  14537. else {
  14538. x = shape.x;
  14539. y = shape.y;
  14540. width = shape.width;
  14541. height = shape.height;
  14542. }
  14543. if (!shape.r) {
  14544. ctx.rect(x, y, width, height);
  14545. }
  14546. else {
  14547. buildPath(ctx, shape);
  14548. }
  14549. ctx.closePath();
  14550. return;
  14551. }
  14552. });
  14553. /**
  14554. * 直线
  14555. * @module zrender/graphic/shape/Line
  14556. */
  14557. // Avoid create repeatly.
  14558. var subPixelOptimizeOutputShape$1 = {};
  14559. var Line = Path.extend({
  14560. type: 'line',
  14561. shape: {
  14562. // Start point
  14563. x1: 0,
  14564. y1: 0,
  14565. // End point
  14566. x2: 0,
  14567. y2: 0,
  14568. percent: 1
  14569. },
  14570. style: {
  14571. stroke: '#000',
  14572. fill: null
  14573. },
  14574. buildPath: function (ctx, shape) {
  14575. var x1;
  14576. var y1;
  14577. var x2;
  14578. var y2;
  14579. if (this.subPixelOptimize) {
  14580. subPixelOptimizeLine$1(subPixelOptimizeOutputShape$1, shape, this.style);
  14581. x1 = subPixelOptimizeOutputShape$1.x1;
  14582. y1 = subPixelOptimizeOutputShape$1.y1;
  14583. x2 = subPixelOptimizeOutputShape$1.x2;
  14584. y2 = subPixelOptimizeOutputShape$1.y2;
  14585. }
  14586. else {
  14587. x1 = shape.x1;
  14588. y1 = shape.y1;
  14589. x2 = shape.x2;
  14590. y2 = shape.y2;
  14591. }
  14592. var percent = shape.percent;
  14593. if (percent === 0) {
  14594. return;
  14595. }
  14596. ctx.moveTo(x1, y1);
  14597. if (percent < 1) {
  14598. x2 = x1 * (1 - percent) + x2 * percent;
  14599. y2 = y1 * (1 - percent) + y2 * percent;
  14600. }
  14601. ctx.lineTo(x2, y2);
  14602. },
  14603. /**
  14604. * Get point at percent
  14605. * @param {number} percent
  14606. * @return {Array.<number>}
  14607. */
  14608. pointAt: function (p) {
  14609. var shape = this.shape;
  14610. return [
  14611. shape.x1 * (1 - p) + shape.x2 * p,
  14612. shape.y1 * (1 - p) + shape.y2 * p
  14613. ];
  14614. }
  14615. });
  14616. /**
  14617. * 贝塞尔曲线
  14618. * @module zrender/shape/BezierCurve
  14619. */
  14620. var out = [];
  14621. function someVectorAt(shape, t, isTangent) {
  14622. var cpx2 = shape.cpx2;
  14623. var cpy2 = shape.cpy2;
  14624. if (cpx2 === null || cpy2 === null) {
  14625. return [
  14626. (isTangent ? cubicDerivativeAt : cubicAt)(shape.x1, shape.cpx1, shape.cpx2, shape.x2, t),
  14627. (isTangent ? cubicDerivativeAt : cubicAt)(shape.y1, shape.cpy1, shape.cpy2, shape.y2, t)
  14628. ];
  14629. }
  14630. else {
  14631. return [
  14632. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.x1, shape.cpx1, shape.x2, t),
  14633. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.y1, shape.cpy1, shape.y2, t)
  14634. ];
  14635. }
  14636. }
  14637. var BezierCurve = Path.extend({
  14638. type: 'bezier-curve',
  14639. shape: {
  14640. x1: 0,
  14641. y1: 0,
  14642. x2: 0,
  14643. y2: 0,
  14644. cpx1: 0,
  14645. cpy1: 0,
  14646. // cpx2: 0,
  14647. // cpy2: 0
  14648. // Curve show percent, for animating
  14649. percent: 1
  14650. },
  14651. style: {
  14652. stroke: '#000',
  14653. fill: null
  14654. },
  14655. buildPath: function (ctx, shape) {
  14656. var x1 = shape.x1;
  14657. var y1 = shape.y1;
  14658. var x2 = shape.x2;
  14659. var y2 = shape.y2;
  14660. var cpx1 = shape.cpx1;
  14661. var cpy1 = shape.cpy1;
  14662. var cpx2 = shape.cpx2;
  14663. var cpy2 = shape.cpy2;
  14664. var percent = shape.percent;
  14665. if (percent === 0) {
  14666. return;
  14667. }
  14668. ctx.moveTo(x1, y1);
  14669. if (cpx2 == null || cpy2 == null) {
  14670. if (percent < 1) {
  14671. quadraticSubdivide(
  14672. x1, cpx1, x2, percent, out
  14673. );
  14674. cpx1 = out[1];
  14675. x2 = out[2];
  14676. quadraticSubdivide(
  14677. y1, cpy1, y2, percent, out
  14678. );
  14679. cpy1 = out[1];
  14680. y2 = out[2];
  14681. }
  14682. ctx.quadraticCurveTo(
  14683. cpx1, cpy1,
  14684. x2, y2
  14685. );
  14686. }
  14687. else {
  14688. if (percent < 1) {
  14689. cubicSubdivide(
  14690. x1, cpx1, cpx2, x2, percent, out
  14691. );
  14692. cpx1 = out[1];
  14693. cpx2 = out[2];
  14694. x2 = out[3];
  14695. cubicSubdivide(
  14696. y1, cpy1, cpy2, y2, percent, out
  14697. );
  14698. cpy1 = out[1];
  14699. cpy2 = out[2];
  14700. y2 = out[3];
  14701. }
  14702. ctx.bezierCurveTo(
  14703. cpx1, cpy1,
  14704. cpx2, cpy2,
  14705. x2, y2
  14706. );
  14707. }
  14708. },
  14709. /**
  14710. * Get point at percent
  14711. * @param {number} t
  14712. * @return {Array.<number>}
  14713. */
  14714. pointAt: function (t) {
  14715. return someVectorAt(this.shape, t, false);
  14716. },
  14717. /**
  14718. * Get tangent at percent
  14719. * @param {number} t
  14720. * @return {Array.<number>}
  14721. */
  14722. tangentAt: function (t) {
  14723. var p = someVectorAt(this.shape, t, true);
  14724. return normalize(p, p);
  14725. }
  14726. });
  14727. /**
  14728. * 圆弧
  14729. * @module zrender/graphic/shape/Arc
  14730. */
  14731. var Arc = Path.extend({
  14732. type: 'arc',
  14733. shape: {
  14734. cx: 0,
  14735. cy: 0,
  14736. r: 0,
  14737. startAngle: 0,
  14738. endAngle: Math.PI * 2,
  14739. clockwise: true
  14740. },
  14741. style: {
  14742. stroke: '#000',
  14743. fill: null
  14744. },
  14745. buildPath: function (ctx, shape) {
  14746. var x = shape.cx;
  14747. var y = shape.cy;
  14748. var r = Math.max(shape.r, 0);
  14749. var startAngle = shape.startAngle;
  14750. var endAngle = shape.endAngle;
  14751. var clockwise = shape.clockwise;
  14752. var unitX = Math.cos(startAngle);
  14753. var unitY = Math.sin(startAngle);
  14754. ctx.moveTo(unitX * r + x, unitY * r + y);
  14755. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  14756. }
  14757. });
  14758. // CompoundPath to improve performance
  14759. var CompoundPath = Path.extend({
  14760. type: 'compound',
  14761. shape: {
  14762. paths: null
  14763. },
  14764. _updatePathDirty: function () {
  14765. var dirtyPath = this.__dirtyPath;
  14766. var paths = this.shape.paths;
  14767. for (var i = 0; i < paths.length; i++) {
  14768. // Mark as dirty if any subpath is dirty
  14769. dirtyPath = dirtyPath || paths[i].__dirtyPath;
  14770. }
  14771. this.__dirtyPath = dirtyPath;
  14772. this.__dirty = this.__dirty || dirtyPath;
  14773. },
  14774. beforeBrush: function () {
  14775. this._updatePathDirty();
  14776. var paths = this.shape.paths || [];
  14777. var scale = this.getGlobalScale();
  14778. // Update path scale
  14779. for (var i = 0; i < paths.length; i++) {
  14780. if (!paths[i].path) {
  14781. paths[i].createPathProxy();
  14782. }
  14783. paths[i].path.setScale(scale[0], scale[1], paths[i].segmentIgnoreThreshold);
  14784. }
  14785. },
  14786. buildPath: function (ctx, shape) {
  14787. var paths = shape.paths || [];
  14788. for (var i = 0; i < paths.length; i++) {
  14789. paths[i].buildPath(ctx, paths[i].shape, true);
  14790. }
  14791. },
  14792. afterBrush: function () {
  14793. var paths = this.shape.paths || [];
  14794. for (var i = 0; i < paths.length; i++) {
  14795. paths[i].__dirtyPath = false;
  14796. }
  14797. },
  14798. getBoundingRect: function () {
  14799. this._updatePathDirty();
  14800. return Path.prototype.getBoundingRect.call(this);
  14801. }
  14802. });
  14803. /**
  14804. * @param {Array.<Object>} colorStops
  14805. */
  14806. var Gradient = function (colorStops) {
  14807. this.colorStops = colorStops || [];
  14808. };
  14809. Gradient.prototype = {
  14810. constructor: Gradient,
  14811. addColorStop: function (offset, color) {
  14812. this.colorStops.push({
  14813. offset: offset,
  14814. color: color
  14815. });
  14816. }
  14817. };
  14818. /**
  14819. * x, y, x2, y2 are all percent from 0 to 1
  14820. * @param {number} [x=0]
  14821. * @param {number} [y=0]
  14822. * @param {number} [x2=1]
  14823. * @param {number} [y2=0]
  14824. * @param {Array.<Object>} colorStops
  14825. * @param {boolean} [globalCoord=false]
  14826. */
  14827. var LinearGradient = function (x, y, x2, y2, colorStops, globalCoord) {
  14828. // Should do nothing more in this constructor. Because gradient can be
  14829. // declard by `color: {type: 'linear', colorStops: ...}`, where
  14830. // this constructor will not be called.
  14831. this.x = x == null ? 0 : x;
  14832. this.y = y == null ? 0 : y;
  14833. this.x2 = x2 == null ? 1 : x2;
  14834. this.y2 = y2 == null ? 0 : y2;
  14835. // Can be cloned
  14836. this.type = 'linear';
  14837. // If use global coord
  14838. this.global = globalCoord || false;
  14839. Gradient.call(this, colorStops);
  14840. };
  14841. LinearGradient.prototype = {
  14842. constructor: LinearGradient
  14843. };
  14844. inherits(LinearGradient, Gradient);
  14845. /**
  14846. * x, y, r are all percent from 0 to 1
  14847. * @param {number} [x=0.5]
  14848. * @param {number} [y=0.5]
  14849. * @param {number} [r=0.5]
  14850. * @param {Array.<Object>} [colorStops]
  14851. * @param {boolean} [globalCoord=false]
  14852. */
  14853. var RadialGradient = function (x, y, r, colorStops, globalCoord) {
  14854. // Should do nothing more in this constructor. Because gradient can be
  14855. // declard by `color: {type: 'radial', colorStops: ...}`, where
  14856. // this constructor will not be called.
  14857. this.x = x == null ? 0.5 : x;
  14858. this.y = y == null ? 0.5 : y;
  14859. this.r = r == null ? 0.5 : r;
  14860. // Can be cloned
  14861. this.type = 'radial';
  14862. // If use global coord
  14863. this.global = globalCoord || false;
  14864. Gradient.call(this, colorStops);
  14865. };
  14866. RadialGradient.prototype = {
  14867. constructor: RadialGradient
  14868. };
  14869. inherits(RadialGradient, Gradient);
  14870. /**
  14871. * Displayable for incremental rendering. It will be rendered in a separate layer
  14872. * IncrementalDisplay have two main methods. `clearDisplayables` and `addDisplayables`
  14873. * addDisplayables will render the added displayables incremetally.
  14874. *
  14875. * It use a not clearFlag to tell the painter don't clear the layer if it's the first element.
  14876. */
  14877. // TODO Style override ?
  14878. function IncrementalDisplayble(opts) {
  14879. Displayable.call(this, opts);
  14880. this._displayables = [];
  14881. this._temporaryDisplayables = [];
  14882. this._cursor = 0;
  14883. this.notClear = true;
  14884. }
  14885. IncrementalDisplayble.prototype.incremental = true;
  14886. IncrementalDisplayble.prototype.clearDisplaybles = function () {
  14887. this._displayables = [];
  14888. this._temporaryDisplayables = [];
  14889. this._cursor = 0;
  14890. this.dirty();
  14891. this.notClear = false;
  14892. };
  14893. IncrementalDisplayble.prototype.addDisplayable = function (displayable, notPersistent) {
  14894. if (notPersistent) {
  14895. this._temporaryDisplayables.push(displayable);
  14896. }
  14897. else {
  14898. this._displayables.push(displayable);
  14899. }
  14900. this.dirty();
  14901. };
  14902. IncrementalDisplayble.prototype.addDisplayables = function (displayables, notPersistent) {
  14903. notPersistent = notPersistent || false;
  14904. for (var i = 0; i < displayables.length; i++) {
  14905. this.addDisplayable(displayables[i], notPersistent);
  14906. }
  14907. };
  14908. IncrementalDisplayble.prototype.eachPendingDisplayable = function (cb) {
  14909. for (var i = this._cursor; i < this._displayables.length; i++) {
  14910. cb && cb(this._displayables[i]);
  14911. }
  14912. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  14913. cb && cb(this._temporaryDisplayables[i]);
  14914. }
  14915. };
  14916. IncrementalDisplayble.prototype.update = function () {
  14917. this.updateTransform();
  14918. for (var i = this._cursor; i < this._displayables.length; i++) {
  14919. var displayable = this._displayables[i];
  14920. // PENDING
  14921. displayable.parent = this;
  14922. displayable.update();
  14923. displayable.parent = null;
  14924. }
  14925. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  14926. var displayable = this._temporaryDisplayables[i];
  14927. // PENDING
  14928. displayable.parent = this;
  14929. displayable.update();
  14930. displayable.parent = null;
  14931. }
  14932. };
  14933. IncrementalDisplayble.prototype.brush = function (ctx, prevEl) {
  14934. // Render persistant displayables.
  14935. for (var i = this._cursor; i < this._displayables.length; i++) {
  14936. var displayable = this._displayables[i];
  14937. displayable.beforeBrush && displayable.beforeBrush(ctx);
  14938. displayable.brush(ctx, i === this._cursor ? null : this._displayables[i - 1]);
  14939. displayable.afterBrush && displayable.afterBrush(ctx);
  14940. }
  14941. this._cursor = i;
  14942. // Render temporary displayables.
  14943. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  14944. var displayable = this._temporaryDisplayables[i];
  14945. displayable.beforeBrush && displayable.beforeBrush(ctx);
  14946. displayable.brush(ctx, i === 0 ? null : this._temporaryDisplayables[i - 1]);
  14947. displayable.afterBrush && displayable.afterBrush(ctx);
  14948. }
  14949. this._temporaryDisplayables = [];
  14950. this.notClear = true;
  14951. };
  14952. var m = [];
  14953. IncrementalDisplayble.prototype.getBoundingRect = function () {
  14954. if (!this._rect) {
  14955. var rect = new BoundingRect(Infinity, Infinity, -Infinity, -Infinity);
  14956. for (var i = 0; i < this._displayables.length; i++) {
  14957. var displayable = this._displayables[i];
  14958. var childRect = displayable.getBoundingRect().clone();
  14959. if (displayable.needLocalTransform()) {
  14960. childRect.applyTransform(displayable.getLocalTransform(m));
  14961. }
  14962. rect.union(childRect);
  14963. }
  14964. this._rect = rect;
  14965. }
  14966. return this._rect;
  14967. };
  14968. IncrementalDisplayble.prototype.contain = function (x, y) {
  14969. var localPos = this.transformCoordToLocal(x, y);
  14970. var rect = this.getBoundingRect();
  14971. if (rect.contain(localPos[0], localPos[1])) {
  14972. for (var i = 0; i < this._displayables.length; i++) {
  14973. var displayable = this._displayables[i];
  14974. if (displayable.contain(x, y)) {
  14975. return true;
  14976. }
  14977. }
  14978. }
  14979. return false;
  14980. };
  14981. inherits(IncrementalDisplayble, Displayable);
  14982. /*
  14983. * Licensed to the Apache Software Foundation (ASF) under one
  14984. * or more contributor license agreements. See the NOTICE file
  14985. * distributed with this work for additional information
  14986. * regarding copyright ownership. The ASF licenses this file
  14987. * to you under the Apache License, Version 2.0 (the
  14988. * "License"); you may not use this file except in compliance
  14989. * with the License. You may obtain a copy of the License at
  14990. *
  14991. * http://www.apache.org/licenses/LICENSE-2.0
  14992. *
  14993. * Unless required by applicable law or agreed to in writing,
  14994. * software distributed under the License is distributed on an
  14995. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14996. * KIND, either express or implied. See the License for the
  14997. * specific language governing permissions and limitations
  14998. * under the License.
  14999. */
  15000. var mathMax$1 = Math.max;
  15001. var mathMin$1 = Math.min;
  15002. var EMPTY_OBJ = {};
  15003. var Z2_EMPHASIS_LIFT = 1;
  15004. // key: label model property nane, value: style property name.
  15005. var CACHED_LABEL_STYLE_PROPERTIES = {
  15006. color: 'textFill',
  15007. textBorderColor: 'textStroke',
  15008. textBorderWidth: 'textStrokeWidth'
  15009. };
  15010. var EMPHASIS = 'emphasis';
  15011. var NORMAL = 'normal';
  15012. // Reserve 0 as default.
  15013. var _highlightNextDigit = 1;
  15014. var _highlightKeyMap = {};
  15015. var _customShapeMap = {};
  15016. /**
  15017. * Extend shape with parameters
  15018. */
  15019. function extendShape(opts) {
  15020. return Path.extend(opts);
  15021. }
  15022. /**
  15023. * Extend path
  15024. */
  15025. function extendPath(pathData, opts) {
  15026. return extendFromString(pathData, opts);
  15027. }
  15028. /**
  15029. * Register a user defined shape.
  15030. * The shape class can be fetched by `getShapeClass`
  15031. * This method will overwrite the registered shapes, including
  15032. * the registered built-in shapes, if using the same `name`.
  15033. * The shape can be used in `custom series` and
  15034. * `graphic component` by declaring `{type: name}`.
  15035. *
  15036. * @param {string} name
  15037. * @param {Object} ShapeClass Can be generated by `extendShape`.
  15038. */
  15039. function registerShape(name, ShapeClass) {
  15040. _customShapeMap[name] = ShapeClass;
  15041. }
  15042. /**
  15043. * Find shape class registered by `registerShape`. Usually used in
  15044. * fetching user defined shape.
  15045. *
  15046. * [Caution]:
  15047. * (1) This method **MUST NOT be used inside echarts !!!**, unless it is prepared
  15048. * to use user registered shapes.
  15049. * Because the built-in shape (see `getBuiltInShape`) will be registered by
  15050. * `registerShape` by default. That enables users to get both built-in
  15051. * shapes as well as the shapes belonging to themsleves. But users can overwrite
  15052. * the built-in shapes by using names like 'circle', 'rect' via calling
  15053. * `registerShape`. So the echarts inner featrues should not fetch shapes from here
  15054. * in case that it is overwritten by users, except that some features, like
  15055. * `custom series`, `graphic component`, do it deliberately.
  15056. *
  15057. * (2) In the features like `custom series`, `graphic component`, the user input
  15058. * `{tpye: 'xxx'}` does not only specify shapes but also specify other graphic
  15059. * elements like `'group'`, `'text'`, `'image'` or event `'path'`. Those names
  15060. * are reserved names, that is, if some user register a shape named `'image'`,
  15061. * the shape will not be used. If we intending to add some more reserved names
  15062. * in feature, that might bring break changes (disable some existing user shape
  15063. * names). But that case probably rearly happen. So we dont make more mechanism
  15064. * to resolve this issue here.
  15065. *
  15066. * @param {string} name
  15067. * @return {Object} The shape class. If not found, return nothing.
  15068. */
  15069. function getShapeClass(name) {
  15070. if (_customShapeMap.hasOwnProperty(name)) {
  15071. return _customShapeMap[name];
  15072. }
  15073. }
  15074. /**
  15075. * Create a path element from path data string
  15076. * @param {string} pathData
  15077. * @param {Object} opts
  15078. * @param {module:zrender/core/BoundingRect} rect
  15079. * @param {string} [layout=cover] 'center' or 'cover'
  15080. */
  15081. function makePath(pathData, opts, rect, layout) {
  15082. var path = createFromString(pathData, opts);
  15083. if (rect) {
  15084. if (layout === 'center') {
  15085. rect = centerGraphic(rect, path.getBoundingRect());
  15086. }
  15087. resizePath(path, rect);
  15088. }
  15089. return path;
  15090. }
  15091. /**
  15092. * Create a image element from image url
  15093. * @param {string} imageUrl image url
  15094. * @param {Object} opts options
  15095. * @param {module:zrender/core/BoundingRect} rect constrain rect
  15096. * @param {string} [layout=cover] 'center' or 'cover'
  15097. */
  15098. function makeImage(imageUrl, rect, layout) {
  15099. var path = new ZImage({
  15100. style: {
  15101. image: imageUrl,
  15102. x: rect.x,
  15103. y: rect.y,
  15104. width: rect.width,
  15105. height: rect.height
  15106. },
  15107. onload: function (img) {
  15108. if (layout === 'center') {
  15109. var boundingRect = {
  15110. width: img.width,
  15111. height: img.height
  15112. };
  15113. path.setStyle(centerGraphic(rect, boundingRect));
  15114. }
  15115. }
  15116. });
  15117. return path;
  15118. }
  15119. /**
  15120. * Get position of centered element in bounding box.
  15121. *
  15122. * @param {Object} rect element local bounding box
  15123. * @param {Object} boundingRect constraint bounding box
  15124. * @return {Object} element position containing x, y, width, and height
  15125. */
  15126. function centerGraphic(rect, boundingRect) {
  15127. // Set rect to center, keep width / height ratio.
  15128. var aspect = boundingRect.width / boundingRect.height;
  15129. var width = rect.height * aspect;
  15130. var height;
  15131. if (width <= rect.width) {
  15132. height = rect.height;
  15133. }
  15134. else {
  15135. width = rect.width;
  15136. height = width / aspect;
  15137. }
  15138. var cx = rect.x + rect.width / 2;
  15139. var cy = rect.y + rect.height / 2;
  15140. return {
  15141. x: cx - width / 2,
  15142. y: cy - height / 2,
  15143. width: width,
  15144. height: height
  15145. };
  15146. }
  15147. var mergePath = mergePath$1;
  15148. /**
  15149. * Resize a path to fit the rect
  15150. * @param {module:zrender/graphic/Path} path
  15151. * @param {Object} rect
  15152. */
  15153. function resizePath(path, rect) {
  15154. if (!path.applyTransform) {
  15155. return;
  15156. }
  15157. var pathRect = path.getBoundingRect();
  15158. var m = pathRect.calculateTransform(rect);
  15159. path.applyTransform(m);
  15160. }
  15161. /**
  15162. * Sub pixel optimize line for canvas
  15163. *
  15164. * @param {Object} param
  15165. * @param {Object} [param.shape]
  15166. * @param {number} [param.shape.x1]
  15167. * @param {number} [param.shape.y1]
  15168. * @param {number} [param.shape.x2]
  15169. * @param {number} [param.shape.y2]
  15170. * @param {Object} [param.style]
  15171. * @param {number} [param.style.lineWidth]
  15172. * @return {Object} Modified param
  15173. */
  15174. function subPixelOptimizeLine(param) {
  15175. subPixelOptimizeLine$1(param.shape, param.shape, param.style);
  15176. return param;
  15177. }
  15178. /**
  15179. * Sub pixel optimize rect for canvas
  15180. *
  15181. * @param {Object} param
  15182. * @param {Object} [param.shape]
  15183. * @param {number} [param.shape.x]
  15184. * @param {number} [param.shape.y]
  15185. * @param {number} [param.shape.width]
  15186. * @param {number} [param.shape.height]
  15187. * @param {Object} [param.style]
  15188. * @param {number} [param.style.lineWidth]
  15189. * @return {Object} Modified param
  15190. */
  15191. function subPixelOptimizeRect(param) {
  15192. subPixelOptimizeRect$1(param.shape, param.shape, param.style);
  15193. return param;
  15194. }
  15195. /**
  15196. * Sub pixel optimize for canvas
  15197. *
  15198. * @param {number} position Coordinate, such as x, y
  15199. * @param {number} lineWidth Should be nonnegative integer.
  15200. * @param {boolean=} positiveOrNegative Default false (negative).
  15201. * @return {number} Optimized position.
  15202. */
  15203. var subPixelOptimize = subPixelOptimize$1;
  15204. function hasFillOrStroke(fillOrStroke) {
  15205. return fillOrStroke != null && fillOrStroke !== 'none';
  15206. }
  15207. // Most lifted color are duplicated.
  15208. var liftedColorMap = createHashMap();
  15209. var liftedColorCount = 0;
  15210. function liftColor(color) {
  15211. if (typeof color !== 'string') {
  15212. return color;
  15213. }
  15214. var liftedColor = liftedColorMap.get(color);
  15215. if (!liftedColor) {
  15216. liftedColor = lift(color, -0.1);
  15217. if (liftedColorCount < 10000) {
  15218. liftedColorMap.set(color, liftedColor);
  15219. liftedColorCount++;
  15220. }
  15221. }
  15222. return liftedColor;
  15223. }
  15224. function cacheElementStl(el) {
  15225. if (!el.__hoverStlDirty) {
  15226. return;
  15227. }
  15228. el.__hoverStlDirty = false;
  15229. var hoverStyle = el.__hoverStl;
  15230. if (!hoverStyle) {
  15231. el.__cachedNormalStl = el.__cachedNormalZ2 = null;
  15232. return;
  15233. }
  15234. var normalStyle = el.__cachedNormalStl = {};
  15235. el.__cachedNormalZ2 = el.z2;
  15236. var elStyle = el.style;
  15237. for (var name in hoverStyle) {
  15238. // See comment in `singleEnterEmphasis`.
  15239. if (hoverStyle[name] != null) {
  15240. normalStyle[name] = elStyle[name];
  15241. }
  15242. }
  15243. // Always cache fill and stroke to normalStyle for lifting color.
  15244. normalStyle.fill = elStyle.fill;
  15245. normalStyle.stroke = elStyle.stroke;
  15246. }
  15247. function singleEnterEmphasis(el) {
  15248. var hoverStl = el.__hoverStl;
  15249. if (!hoverStl || el.__highlighted) {
  15250. return;
  15251. }
  15252. var zr = el.__zr;
  15253. var useHoverLayer = el.useHoverLayer && zr && zr.painter.type === 'canvas';
  15254. el.__highlighted = useHoverLayer ? 'layer' : 'plain';
  15255. if (el.isGroup || (!zr && el.useHoverLayer)) {
  15256. return;
  15257. }
  15258. var elTarget = el;
  15259. var targetStyle = el.style;
  15260. if (useHoverLayer) {
  15261. elTarget = zr.addHover(el);
  15262. targetStyle = elTarget.style;
  15263. }
  15264. rollbackDefaultTextStyle(targetStyle);
  15265. if (!useHoverLayer) {
  15266. cacheElementStl(elTarget);
  15267. }
  15268. // styles can be:
  15269. // {
  15270. // label: {
  15271. // show: false,
  15272. // position: 'outside',
  15273. // fontSize: 18
  15274. // },
  15275. // emphasis: {
  15276. // label: {
  15277. // show: true
  15278. // }
  15279. // }
  15280. // },
  15281. // where properties of `emphasis` may not appear in `normal`. We previously use
  15282. // module:echarts/util/model#defaultEmphasis to merge `normal` to `emphasis`.
  15283. // But consider rich text and setOption in merge mode, it is impossible to cover
  15284. // all properties in merge. So we use merge mode when setting style here.
  15285. // But we choose the merge strategy that only properties that is not `null/undefined`.
  15286. // Because when making a textStyle (espacially rich text), it is not easy to distinguish
  15287. // `hasOwnProperty` and `null/undefined` in code, so we trade them as the same for simplicity.
  15288. // But this strategy brings a trouble that `null/undefined` can not be used to remove
  15289. // style any more in `emphasis`. Users can both set properties directly on normal and
  15290. // emphasis to avoid this issue, or we might support `'none'` for this case if required.
  15291. targetStyle.extendFrom(hoverStl);
  15292. setDefaultHoverFillStroke(targetStyle, hoverStl, 'fill');
  15293. setDefaultHoverFillStroke(targetStyle, hoverStl, 'stroke');
  15294. applyDefaultTextStyle(targetStyle);
  15295. if (!useHoverLayer) {
  15296. el.dirty(false);
  15297. el.z2 += Z2_EMPHASIS_LIFT;
  15298. }
  15299. }
  15300. function setDefaultHoverFillStroke(targetStyle, hoverStyle, prop) {
  15301. if (!hasFillOrStroke(hoverStyle[prop]) && hasFillOrStroke(targetStyle[prop])) {
  15302. targetStyle[prop] = liftColor(targetStyle[prop]);
  15303. }
  15304. }
  15305. function singleEnterNormal(el) {
  15306. var highlighted = el.__highlighted;
  15307. if (!highlighted) {
  15308. return;
  15309. }
  15310. el.__highlighted = false;
  15311. if (el.isGroup) {
  15312. return;
  15313. }
  15314. if (highlighted === 'layer') {
  15315. el.__zr && el.__zr.removeHover(el);
  15316. }
  15317. else {
  15318. var style = el.style;
  15319. var normalStl = el.__cachedNormalStl;
  15320. if (normalStl) {
  15321. rollbackDefaultTextStyle(style);
  15322. el.setStyle(normalStl);
  15323. applyDefaultTextStyle(style);
  15324. }
  15325. // `__cachedNormalZ2` will not be reset if calling `setElementHoverStyle`
  15326. // when `el` is on emphasis state. So here by comparing with 1, we try
  15327. // hard to make the bug case rare.
  15328. var normalZ2 = el.__cachedNormalZ2;
  15329. if (normalZ2 != null && el.z2 - normalZ2 === Z2_EMPHASIS_LIFT) {
  15330. el.z2 = normalZ2;
  15331. }
  15332. }
  15333. }
  15334. function traverseUpdate(el, updater, commonParam) {
  15335. // If root is group, also enter updater for `highDownOnUpdate`.
  15336. var fromState = NORMAL;
  15337. var toState = NORMAL;
  15338. var trigger;
  15339. // See the rule of `highDownOnUpdate` on `graphic.setAsHighDownDispatcher`.
  15340. el.__highlighted && (fromState = EMPHASIS, trigger = true);
  15341. updater(el, commonParam);
  15342. el.__highlighted && (toState = EMPHASIS, trigger = true);
  15343. el.isGroup && el.traverse(function (child) {
  15344. !child.isGroup && updater(child, commonParam);
  15345. });
  15346. trigger && el.__highDownOnUpdate && el.__highDownOnUpdate(fromState, toState);
  15347. }
  15348. /**
  15349. * Set hover style (namely "emphasis style") of element, based on the current
  15350. * style of the given `el`.
  15351. * This method should be called after all of the normal styles have been adopted
  15352. * to the `el`. See the reason on `setHoverStyle`.
  15353. *
  15354. * @param {module:zrender/Element} el Should not be `zrender/container/Group`.
  15355. * @param {Object} [el.hoverStyle] Can be set on el or its descendants,
  15356. * e.g., `el.hoverStyle = ...; graphic.setHoverStyle(el); `.
  15357. * Often used when item group has a label element and it's hoverStyle is different.
  15358. * @param {Object|boolean} [hoverStl] The specified hover style.
  15359. * If set as `false`, disable the hover style.
  15360. * Similarly, The `el.hoverStyle` can alse be set
  15361. * as `false` to disable the hover style.
  15362. * Otherwise, use the default hover style if not provided.
  15363. */
  15364. function setElementHoverStyle(el, hoverStl) {
  15365. // For performance consideration, it might be better to make the "hover style" only the
  15366. // difference properties from the "normal style", but not a entire copy of all styles.
  15367. hoverStl = el.__hoverStl = hoverStl !== false && (el.hoverStyle || hoverStl || {});
  15368. el.__hoverStlDirty = true;
  15369. // FIXME
  15370. // It is not completely right to save "normal"/"emphasis" flag on elements.
  15371. // It probably should be saved on `data` of series. Consider the cases:
  15372. // (1) A highlighted elements are moved out of the view port and re-enter
  15373. // again by dataZoom.
  15374. // (2) call `setOption` and replace elements totally when they are highlighted.
  15375. if (el.__highlighted) {
  15376. // Consider the case:
  15377. // The styles of a highlighted `el` is being updated. The new "emphasis style"
  15378. // should be adapted to the `el`. Notice here new "normal styles" should have
  15379. // been set outside and the cached "normal style" is out of date.
  15380. el.__cachedNormalStl = null;
  15381. // Do not clear `__cachedNormalZ2` here, because setting `z2` is not a constraint
  15382. // of this method. In most cases, `z2` is not set and hover style should be able
  15383. // to rollback. Of course, that would bring bug, but only in a rare case, see
  15384. // `doSingleLeaveHover` for details.
  15385. singleEnterNormal(el);
  15386. singleEnterEmphasis(el);
  15387. }
  15388. }
  15389. function onElementMouseOver(e) {
  15390. !shouldSilent(this, e)
  15391. // "emphasis" event highlight has higher priority than mouse highlight.
  15392. && !this.__highByOuter
  15393. && traverseUpdate(this, singleEnterEmphasis);
  15394. }
  15395. function onElementMouseOut(e) {
  15396. !shouldSilent(this, e)
  15397. // "emphasis" event highlight has higher priority than mouse highlight.
  15398. && !this.__highByOuter
  15399. && traverseUpdate(this, singleEnterNormal);
  15400. }
  15401. function onElementEmphasisEvent(highlightDigit) {
  15402. this.__highByOuter |= 1 << (highlightDigit || 0);
  15403. traverseUpdate(this, singleEnterEmphasis);
  15404. }
  15405. function onElementNormalEvent(highlightDigit) {
  15406. !(this.__highByOuter &= ~(1 << (highlightDigit || 0)))
  15407. && traverseUpdate(this, singleEnterNormal);
  15408. }
  15409. function shouldSilent(el, e) {
  15410. return el.__highDownSilentOnTouch && e.zrByTouch;
  15411. }
  15412. /**
  15413. * Set hover style (namely "emphasis style") of element,
  15414. * based on the current style of the given `el`.
  15415. *
  15416. * (1)
  15417. * **CONSTRAINTS** for this method:
  15418. * <A> This method MUST be called after all of the normal styles having been adopted
  15419. * to the `el`.
  15420. * <B> The input `hoverStyle` (that is, "emphasis style") MUST be the subset of the
  15421. * "normal style" having been set to the el.
  15422. * <C> `color` MUST be one of the "normal styles" (because color might be lifted as
  15423. * a default hover style).
  15424. *
  15425. * The reason: this method treat the current style of the `el` as the "normal style"
  15426. * and cache them when enter/update the "emphasis style". Consider the case: the `el`
  15427. * is in "emphasis" state and `setOption`/`dispatchAction` trigger the style updating
  15428. * logic, where the el should shift from the original emphasis style to the new
  15429. * "emphasis style" and should be able to "downplay" back to the new "normal style".
  15430. *
  15431. * Indeed, it is error-prone to make a interface has so many constraints, but I have
  15432. * not found a better solution yet to fit the backward compatibility, performance and
  15433. * the current programming style.
  15434. *
  15435. * (2)
  15436. * Call the method for a "root" element once. Do not call it for each descendants.
  15437. * If the descendants elemenets of a group has itself hover style different from the
  15438. * root group, we can simply mount the style on `el.hoverStyle` for them, but should
  15439. * not call this method for them.
  15440. *
  15441. * (3) These input parameters can be set directly on `el`:
  15442. *
  15443. * @param {module:zrender/Element} el
  15444. * @param {Object} [el.hoverStyle] See `graphic.setElementHoverStyle`.
  15445. * @param {boolean} [el.highDownSilentOnTouch=false] See `graphic.setAsHighDownDispatcher`.
  15446. * @param {Function} [el.highDownOnUpdate] See `graphic.setAsHighDownDispatcher`.
  15447. * @param {Object|boolean} [hoverStyle] See `graphic.setElementHoverStyle`.
  15448. */
  15449. function setHoverStyle(el, hoverStyle) {
  15450. setAsHighDownDispatcher(el, true);
  15451. traverseUpdate(el, setElementHoverStyle, hoverStyle);
  15452. }
  15453. /**
  15454. * @param {module:zrender/Element} el
  15455. * @param {Function} [el.highDownOnUpdate] Called when state updated.
  15456. * Since `setHoverStyle` has the constraint that it must be called after
  15457. * all of the normal style updated, `highDownOnUpdate` is not needed to
  15458. * trigger if both `fromState` and `toState` is 'normal', and needed to
  15459. * trigger if both `fromState` and `toState` is 'emphasis', which enables
  15460. * to sync outside style settings to "emphasis" state.
  15461. * @this {string} This dispatcher `el`.
  15462. * @param {string} fromState Can be "normal" or "emphasis".
  15463. * `fromState` might equal to `toState`,
  15464. * for example, when this method is called when `el` is
  15465. * on "emphasis" state.
  15466. * @param {string} toState Can be "normal" or "emphasis".
  15467. *
  15468. * FIXME
  15469. * CAUTION: Do not expose `highDownOnUpdate` outside echarts.
  15470. * Because it is not a complete solution. The update
  15471. * listener should not have been mount in element,
  15472. * and the normal/emphasis state should not have
  15473. * mantained on elements.
  15474. *
  15475. * @param {boolean} [el.highDownSilentOnTouch=false]
  15476. * In touch device, mouseover event will be trigger on touchstart event
  15477. * (see module:zrender/dom/HandlerProxy). By this mechanism, we can
  15478. * conveniently use hoverStyle when tap on touch screen without additional
  15479. * code for compatibility.
  15480. * But if the chart/component has select feature, which usually also use
  15481. * hoverStyle, there might be conflict between 'select-highlight' and
  15482. * 'hover-highlight' especially when roam is enabled (see geo for example).
  15483. * In this case, `highDownSilentOnTouch` should be used to disable
  15484. * hover-highlight on touch device.
  15485. * @param {boolean} [asDispatcher=true] If `false`, do not set as "highDownDispatcher".
  15486. */
  15487. function setAsHighDownDispatcher(el, asDispatcher) {
  15488. var disable = asDispatcher === false;
  15489. // Make `highDownSilentOnTouch` and `highDownOnUpdate` only work after
  15490. // `setAsHighDownDispatcher` called. Avoid it is modified by user unexpectedly.
  15491. el.__highDownSilentOnTouch = el.highDownSilentOnTouch;
  15492. el.__highDownOnUpdate = el.highDownOnUpdate;
  15493. // Simple optimize, since this method might be
  15494. // called for each elements of a group in some cases.
  15495. if (!disable || el.__highDownDispatcher) {
  15496. var method = disable ? 'off' : 'on';
  15497. // Duplicated function will be auto-ignored, see Eventful.js.
  15498. el[method]('mouseover', onElementMouseOver)[method]('mouseout', onElementMouseOut);
  15499. // Emphasis, normal can be triggered manually by API or other components like hover link.
  15500. el[method]('emphasis', onElementEmphasisEvent)[method]('normal', onElementNormalEvent);
  15501. // Also keep previous record.
  15502. el.__highByOuter = el.__highByOuter || 0;
  15503. el.__highDownDispatcher = !disable;
  15504. }
  15505. }
  15506. /**
  15507. * @param {module:zrender/src/Element} el
  15508. * @return {boolean}
  15509. */
  15510. function isHighDownDispatcher(el) {
  15511. return !!(el && el.__highDownDispatcher);
  15512. }
  15513. /**
  15514. * Support hightlight/downplay record on each elements.
  15515. * For the case: hover highlight/downplay (legend, visualMap, ...) and
  15516. * user triggerred hightlight/downplay should not conflict.
  15517. * Only all of the highlightDigit cleared, return to normal.
  15518. * @param {string} highlightKey
  15519. * @return {number} highlightDigit
  15520. */
  15521. function getHighlightDigit(highlightKey) {
  15522. var highlightDigit = _highlightKeyMap[highlightKey];
  15523. if (highlightDigit == null && _highlightNextDigit <= 32) {
  15524. highlightDigit = _highlightKeyMap[highlightKey] = _highlightNextDigit++;
  15525. }
  15526. return highlightDigit;
  15527. }
  15528. /**
  15529. * See more info in `setTextStyleCommon`.
  15530. * @param {Object|module:zrender/graphic/Style} normalStyle
  15531. * @param {Object} emphasisStyle
  15532. * @param {module:echarts/model/Model} normalModel
  15533. * @param {module:echarts/model/Model} emphasisModel
  15534. * @param {Object} opt Check `opt` of `setTextStyleCommon` to find other props.
  15535. * @param {string|Function} [opt.defaultText]
  15536. * @param {module:echarts/model/Model} [opt.labelFetcher] Fetch text by
  15537. * `opt.labelFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex, opt.labelProp)`
  15538. * @param {number} [opt.labelDataIndex] Fetch text by
  15539. * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex, opt.labelProp)`
  15540. * @param {number} [opt.labelDimIndex] Fetch text by
  15541. * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex, opt.labelProp)`
  15542. * @param {string} [opt.labelProp] Fetch text by
  15543. * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex, opt.labelProp)`
  15544. * @param {Object} [normalSpecified]
  15545. * @param {Object} [emphasisSpecified]
  15546. */
  15547. function setLabelStyle(
  15548. normalStyle, emphasisStyle,
  15549. normalModel, emphasisModel,
  15550. opt,
  15551. normalSpecified, emphasisSpecified
  15552. ) {
  15553. opt = opt || EMPTY_OBJ;
  15554. var labelFetcher = opt.labelFetcher;
  15555. var labelDataIndex = opt.labelDataIndex;
  15556. var labelDimIndex = opt.labelDimIndex;
  15557. var labelProp = opt.labelProp;
  15558. // This scenario, `label.normal.show = true; label.emphasis.show = false`,
  15559. // is not supported util someone requests.
  15560. var showNormal = normalModel.getShallow('show');
  15561. var showEmphasis = emphasisModel.getShallow('show');
  15562. // Consider performance, only fetch label when necessary.
  15563. // If `normal.show` is `false` and `emphasis.show` is `true` and `emphasis.formatter` is not set,
  15564. // label should be displayed, where text is fetched by `normal.formatter` or `opt.defaultText`.
  15565. var baseText;
  15566. if (showNormal || showEmphasis) {
  15567. if (labelFetcher) {
  15568. baseText = labelFetcher.getFormattedLabel(labelDataIndex, 'normal', null, labelDimIndex, labelProp);
  15569. }
  15570. if (baseText == null) {
  15571. baseText = isFunction$1(opt.defaultText) ? opt.defaultText(labelDataIndex, opt) : opt.defaultText;
  15572. }
  15573. }
  15574. var normalStyleText = showNormal ? baseText : null;
  15575. var emphasisStyleText = showEmphasis
  15576. ? retrieve2(
  15577. labelFetcher
  15578. ? labelFetcher.getFormattedLabel(labelDataIndex, 'emphasis', null, labelDimIndex, labelProp)
  15579. : null,
  15580. baseText
  15581. )
  15582. : null;
  15583. // Optimize: If style.text is null, text will not be drawn.
  15584. if (normalStyleText != null || emphasisStyleText != null) {
  15585. // Always set `textStyle` even if `normalStyle.text` is null, because default
  15586. // values have to be set on `normalStyle`.
  15587. // If we set default values on `emphasisStyle`, consider case:
  15588. // Firstly, `setOption(... label: {normal: {text: null}, emphasis: {show: true}} ...);`
  15589. // Secondly, `setOption(... label: {noraml: {show: true, text: 'abc', color: 'red'} ...);`
  15590. // Then the 'red' will not work on emphasis.
  15591. setTextStyle(normalStyle, normalModel, normalSpecified, opt);
  15592. setTextStyle(emphasisStyle, emphasisModel, emphasisSpecified, opt, true);
  15593. }
  15594. normalStyle.text = normalStyleText;
  15595. emphasisStyle.text = emphasisStyleText;
  15596. }
  15597. /**
  15598. * Modify label style manually.
  15599. * Only works after `setLabelStyle` and `setElementHoverStyle` called.
  15600. *
  15601. * @param {module:zrender/src/Element} el
  15602. * @param {Object} [normalStyleProps] optional
  15603. * @param {Object} [emphasisStyleProps] optional
  15604. */
  15605. function modifyLabelStyle(el, normalStyleProps, emphasisStyleProps) {
  15606. var elStyle = el.style;
  15607. if (normalStyleProps) {
  15608. rollbackDefaultTextStyle(elStyle);
  15609. el.setStyle(normalStyleProps);
  15610. applyDefaultTextStyle(elStyle);
  15611. }
  15612. elStyle = el.__hoverStl;
  15613. if (emphasisStyleProps && elStyle) {
  15614. rollbackDefaultTextStyle(elStyle);
  15615. extend(elStyle, emphasisStyleProps);
  15616. applyDefaultTextStyle(elStyle);
  15617. }
  15618. }
  15619. /**
  15620. * Set basic textStyle properties.
  15621. * See more info in `setTextStyleCommon`.
  15622. * @param {Object|module:zrender/graphic/Style} textStyle
  15623. * @param {module:echarts/model/Model} model
  15624. * @param {Object} [specifiedTextStyle] Can be overrided by settings in model.
  15625. * @param {Object} [opt] See `opt` of `setTextStyleCommon`.
  15626. * @param {boolean} [isEmphasis]
  15627. */
  15628. function setTextStyle(
  15629. textStyle, textStyleModel, specifiedTextStyle, opt, isEmphasis
  15630. ) {
  15631. setTextStyleCommon(textStyle, textStyleModel, opt, isEmphasis);
  15632. specifiedTextStyle && extend(textStyle, specifiedTextStyle);
  15633. // textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  15634. return textStyle;
  15635. }
  15636. /**
  15637. * Set text option in the style.
  15638. * See more info in `setTextStyleCommon`.
  15639. * @deprecated
  15640. * @param {Object} textStyle
  15641. * @param {module:echarts/model/Model} labelModel
  15642. * @param {string|boolean} defaultColor Default text color.
  15643. * If set as false, it will be processed as a emphasis style.
  15644. */
  15645. function setText(textStyle, labelModel, defaultColor) {
  15646. var opt = {isRectText: true};
  15647. var isEmphasis;
  15648. if (defaultColor === false) {
  15649. isEmphasis = true;
  15650. }
  15651. else {
  15652. // Support setting color as 'auto' to get visual color.
  15653. opt.autoColor = defaultColor;
  15654. }
  15655. setTextStyleCommon(textStyle, labelModel, opt, isEmphasis);
  15656. // textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  15657. }
  15658. /**
  15659. * The uniform entry of set text style, that is, retrieve style definitions
  15660. * from `model` and set to `textStyle` object.
  15661. *
  15662. * Never in merge mode, but in overwrite mode, that is, all of the text style
  15663. * properties will be set. (Consider the states of normal and emphasis and
  15664. * default value can be adopted, merge would make the logic too complicated
  15665. * to manage.)
  15666. *
  15667. * The `textStyle` object can either be a plain object or an instance of
  15668. * `zrender/src/graphic/Style`, and either be the style of normal or emphasis.
  15669. * After this mothod called, the `textStyle` object can then be used in
  15670. * `el.setStyle(textStyle)` or `el.hoverStyle = textStyle`.
  15671. *
  15672. * Default value will be adopted and `insideRollbackOpt` will be created.
  15673. * See `applyDefaultTextStyle` `rollbackDefaultTextStyle` for more details.
  15674. *
  15675. * opt: {
  15676. * disableBox: boolean, Whether diable drawing box of block (outer most).
  15677. * isRectText: boolean,
  15678. * autoColor: string, specify a color when color is 'auto',
  15679. * for textFill, textStroke, textBackgroundColor, and textBorderColor.
  15680. * If autoColor specified, it is used as default textFill.
  15681. * useInsideStyle:
  15682. * `true`: Use inside style (textFill, textStroke, textStrokeWidth)
  15683. * if `textFill` is not specified.
  15684. * `false`: Do not use inside style.
  15685. * `null/undefined`: use inside style if `isRectText` is true and
  15686. * `textFill` is not specified and textPosition contains `'inside'`.
  15687. * forceRich: boolean
  15688. * }
  15689. */
  15690. function setTextStyleCommon(textStyle, textStyleModel, opt, isEmphasis) {
  15691. // Consider there will be abnormal when merge hover style to normal style if given default value.
  15692. opt = opt || EMPTY_OBJ;
  15693. if (opt.isRectText) {
  15694. var textPosition;
  15695. if (opt.getTextPosition) {
  15696. textPosition = opt.getTextPosition(textStyleModel, isEmphasis);
  15697. }
  15698. else {
  15699. textPosition = textStyleModel.getShallow('position')
  15700. || (isEmphasis ? null : 'inside');
  15701. // 'outside' is not a valid zr textPostion value, but used
  15702. // in bar series, and magric type should be considered.
  15703. textPosition === 'outside' && (textPosition = 'top');
  15704. }
  15705. textStyle.textPosition = textPosition;
  15706. textStyle.textOffset = textStyleModel.getShallow('offset');
  15707. var labelRotate = textStyleModel.getShallow('rotate');
  15708. labelRotate != null && (labelRotate *= Math.PI / 180);
  15709. textStyle.textRotation = labelRotate;
  15710. textStyle.textDistance = retrieve2(
  15711. textStyleModel.getShallow('distance'), isEmphasis ? null : 5
  15712. );
  15713. }
  15714. var ecModel = textStyleModel.ecModel;
  15715. var globalTextStyle = ecModel && ecModel.option.textStyle;
  15716. // Consider case:
  15717. // {
  15718. // data: [{
  15719. // value: 12,
  15720. // label: {
  15721. // rich: {
  15722. // // no 'a' here but using parent 'a'.
  15723. // }
  15724. // }
  15725. // }],
  15726. // rich: {
  15727. // a: { ... }
  15728. // }
  15729. // }
  15730. var richItemNames = getRichItemNames(textStyleModel);
  15731. var richResult;
  15732. if (richItemNames) {
  15733. richResult = {};
  15734. for (var name in richItemNames) {
  15735. if (richItemNames.hasOwnProperty(name)) {
  15736. // Cascade is supported in rich.
  15737. var richTextStyle = textStyleModel.getModel(['rich', name]);
  15738. // In rich, never `disableBox`.
  15739. // FIXME: consider `label: {formatter: '{a|xx}', color: 'blue', rich: {a: {}}}`,
  15740. // the default color `'blue'` will not be adopted if no color declared in `rich`.
  15741. // That might confuses users. So probably we should put `textStyleModel` as the
  15742. // root ancestor of the `richTextStyle`. But that would be a break change.
  15743. setTokenTextStyle(richResult[name] = {}, richTextStyle, globalTextStyle, opt, isEmphasis);
  15744. }
  15745. }
  15746. }
  15747. textStyle.rich = richResult;
  15748. setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isEmphasis, true);
  15749. if (opt.forceRich && !opt.textStyle) {
  15750. opt.textStyle = {};
  15751. }
  15752. return textStyle;
  15753. }
  15754. // Consider case:
  15755. // {
  15756. // data: [{
  15757. // value: 12,
  15758. // label: {
  15759. // rich: {
  15760. // // no 'a' here but using parent 'a'.
  15761. // }
  15762. // }
  15763. // }],
  15764. // rich: {
  15765. // a: { ... }
  15766. // }
  15767. // }
  15768. function getRichItemNames(textStyleModel) {
  15769. // Use object to remove duplicated names.
  15770. var richItemNameMap;
  15771. while (textStyleModel && textStyleModel !== textStyleModel.ecModel) {
  15772. var rich = (textStyleModel.option || EMPTY_OBJ).rich;
  15773. if (rich) {
  15774. richItemNameMap = richItemNameMap || {};
  15775. for (var name in rich) {
  15776. if (rich.hasOwnProperty(name)) {
  15777. richItemNameMap[name] = 1;
  15778. }
  15779. }
  15780. }
  15781. textStyleModel = textStyleModel.parentModel;
  15782. }
  15783. return richItemNameMap;
  15784. }
  15785. function setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isEmphasis, isBlock) {
  15786. // In merge mode, default value should not be given.
  15787. globalTextStyle = !isEmphasis && globalTextStyle || EMPTY_OBJ;
  15788. textStyle.textFill = getAutoColor(textStyleModel.getShallow('color'), opt)
  15789. || globalTextStyle.color;
  15790. textStyle.textStroke = getAutoColor(textStyleModel.getShallow('textBorderColor'), opt)
  15791. || globalTextStyle.textBorderColor;
  15792. textStyle.textStrokeWidth = retrieve2(
  15793. textStyleModel.getShallow('textBorderWidth'),
  15794. globalTextStyle.textBorderWidth
  15795. );
  15796. if (!isEmphasis) {
  15797. if (isBlock) {
  15798. textStyle.insideRollbackOpt = opt;
  15799. applyDefaultTextStyle(textStyle);
  15800. }
  15801. // Set default finally.
  15802. if (textStyle.textFill == null) {
  15803. textStyle.textFill = opt.autoColor;
  15804. }
  15805. }
  15806. // Do not use `getFont` here, because merge should be supported, where
  15807. // part of these properties may be changed in emphasis style, and the
  15808. // others should remain their original value got from normal style.
  15809. textStyle.fontStyle = textStyleModel.getShallow('fontStyle') || globalTextStyle.fontStyle;
  15810. textStyle.fontWeight = textStyleModel.getShallow('fontWeight') || globalTextStyle.fontWeight;
  15811. textStyle.fontSize = textStyleModel.getShallow('fontSize') || globalTextStyle.fontSize;
  15812. textStyle.fontFamily = textStyleModel.getShallow('fontFamily') || globalTextStyle.fontFamily;
  15813. textStyle.textAlign = textStyleModel.getShallow('align');
  15814. textStyle.textVerticalAlign = textStyleModel.getShallow('verticalAlign')
  15815. || textStyleModel.getShallow('baseline');
  15816. textStyle.textLineHeight = textStyleModel.getShallow('lineHeight');
  15817. textStyle.textWidth = textStyleModel.getShallow('width');
  15818. textStyle.textHeight = textStyleModel.getShallow('height');
  15819. textStyle.textTag = textStyleModel.getShallow('tag');
  15820. if (!isBlock || !opt.disableBox) {
  15821. textStyle.textBackgroundColor = getAutoColor(textStyleModel.getShallow('backgroundColor'), opt);
  15822. textStyle.textPadding = textStyleModel.getShallow('padding');
  15823. textStyle.textBorderColor = getAutoColor(textStyleModel.getShallow('borderColor'), opt);
  15824. textStyle.textBorderWidth = textStyleModel.getShallow('borderWidth');
  15825. textStyle.textBorderRadius = textStyleModel.getShallow('borderRadius');
  15826. textStyle.textBoxShadowColor = textStyleModel.getShallow('shadowColor');
  15827. textStyle.textBoxShadowBlur = textStyleModel.getShallow('shadowBlur');
  15828. textStyle.textBoxShadowOffsetX = textStyleModel.getShallow('shadowOffsetX');
  15829. textStyle.textBoxShadowOffsetY = textStyleModel.getShallow('shadowOffsetY');
  15830. }
  15831. textStyle.textShadowColor = textStyleModel.getShallow('textShadowColor')
  15832. || globalTextStyle.textShadowColor;
  15833. textStyle.textShadowBlur = textStyleModel.getShallow('textShadowBlur')
  15834. || globalTextStyle.textShadowBlur;
  15835. textStyle.textShadowOffsetX = textStyleModel.getShallow('textShadowOffsetX')
  15836. || globalTextStyle.textShadowOffsetX;
  15837. textStyle.textShadowOffsetY = textStyleModel.getShallow('textShadowOffsetY')
  15838. || globalTextStyle.textShadowOffsetY;
  15839. }
  15840. function getAutoColor(color, opt) {
  15841. return color !== 'auto' ? color : (opt && opt.autoColor) ? opt.autoColor : null;
  15842. }
  15843. /**
  15844. * Give some default value to the input `textStyle` object, based on the current settings
  15845. * in this `textStyle` object.
  15846. *
  15847. * The Scenario:
  15848. * when text position is `inside` and `textFill` is not specified, we show
  15849. * text border by default for better view. But it should be considered that text position
  15850. * might be changed when hovering or being emphasis, where the `insideRollback` is used to
  15851. * restore the style.
  15852. *
  15853. * Usage (& NOTICE):
  15854. * When a style object (eithor plain object or instance of `zrender/src/graphic/Style`) is
  15855. * about to be modified on its text related properties, `rollbackDefaultTextStyle` should
  15856. * be called before the modification and `applyDefaultTextStyle` should be called after that.
  15857. * (For the case that all of the text related properties is reset, like `setTextStyleCommon`
  15858. * does, `rollbackDefaultTextStyle` is not needed to be called).
  15859. */
  15860. function applyDefaultTextStyle(textStyle) {
  15861. var textPosition = textStyle.textPosition;
  15862. var opt = textStyle.insideRollbackOpt;
  15863. var insideRollback;
  15864. if (opt && textStyle.textFill == null) {
  15865. var autoColor = opt.autoColor;
  15866. var isRectText = opt.isRectText;
  15867. var useInsideStyle = opt.useInsideStyle;
  15868. var useInsideStyleCache = useInsideStyle !== false
  15869. && (useInsideStyle === true
  15870. || (isRectText
  15871. && textPosition
  15872. // textPosition can be [10, 30]
  15873. && typeof textPosition === 'string'
  15874. && textPosition.indexOf('inside') >= 0
  15875. )
  15876. );
  15877. var useAutoColorCache = !useInsideStyleCache && autoColor != null;
  15878. // All of the props declared in `CACHED_LABEL_STYLE_PROPERTIES` are to be cached.
  15879. if (useInsideStyleCache || useAutoColorCache) {
  15880. insideRollback = {
  15881. textFill: textStyle.textFill,
  15882. textStroke: textStyle.textStroke,
  15883. textStrokeWidth: textStyle.textStrokeWidth
  15884. };
  15885. }
  15886. if (useInsideStyleCache) {
  15887. textStyle.textFill = '#fff';
  15888. // Consider text with #fff overflow its container.
  15889. if (textStyle.textStroke == null) {
  15890. textStyle.textStroke = autoColor;
  15891. textStyle.textStrokeWidth == null && (textStyle.textStrokeWidth = 2);
  15892. }
  15893. }
  15894. if (useAutoColorCache) {
  15895. textStyle.textFill = autoColor;
  15896. }
  15897. }
  15898. // Always set `insideRollback`, so that the previous one can be cleared.
  15899. textStyle.insideRollback = insideRollback;
  15900. }
  15901. /**
  15902. * Consider the case: in a scatter,
  15903. * label: {
  15904. * normal: {position: 'inside'},
  15905. * emphasis: {position: 'top'}
  15906. * }
  15907. * In the normal state, the `textFill` will be set as '#fff' for pretty view (see
  15908. * `applyDefaultTextStyle`), but when switching to emphasis state, the `textFill`
  15909. * should be retured to 'autoColor', but not keep '#fff'.
  15910. */
  15911. function rollbackDefaultTextStyle(style) {
  15912. var insideRollback = style.insideRollback;
  15913. if (insideRollback) {
  15914. // Reset all of the props in `CACHED_LABEL_STYLE_PROPERTIES`.
  15915. style.textFill = insideRollback.textFill;
  15916. style.textStroke = insideRollback.textStroke;
  15917. style.textStrokeWidth = insideRollback.textStrokeWidth;
  15918. style.insideRollback = null;
  15919. }
  15920. }
  15921. function getFont(opt, ecModel) {
  15922. var gTextStyleModel = ecModel && ecModel.getModel('textStyle');
  15923. return trim([
  15924. // FIXME in node-canvas fontWeight is before fontStyle
  15925. opt.fontStyle || gTextStyleModel && gTextStyleModel.getShallow('fontStyle') || '',
  15926. opt.fontWeight || gTextStyleModel && gTextStyleModel.getShallow('fontWeight') || '',
  15927. (opt.fontSize || gTextStyleModel && gTextStyleModel.getShallow('fontSize') || 12) + 'px',
  15928. opt.fontFamily || gTextStyleModel && gTextStyleModel.getShallow('fontFamily') || 'sans-serif'
  15929. ].join(' '));
  15930. }
  15931. function animateOrSetProps(isUpdate, el, props, animatableModel, dataIndex, cb) {
  15932. if (typeof dataIndex === 'function') {
  15933. cb = dataIndex;
  15934. dataIndex = null;
  15935. }
  15936. // Do not check 'animation' property directly here. Consider this case:
  15937. // animation model is an `itemModel`, whose does not have `isAnimationEnabled`
  15938. // but its parent model (`seriesModel`) does.
  15939. var animationEnabled = animatableModel && animatableModel.isAnimationEnabled();
  15940. if (animationEnabled) {
  15941. var postfix = isUpdate ? 'Update' : '';
  15942. var duration = animatableModel.getShallow('animationDuration' + postfix);
  15943. var animationEasing = animatableModel.getShallow('animationEasing' + postfix);
  15944. var animationDelay = animatableModel.getShallow('animationDelay' + postfix);
  15945. if (typeof animationDelay === 'function') {
  15946. animationDelay = animationDelay(
  15947. dataIndex,
  15948. animatableModel.getAnimationDelayParams
  15949. ? animatableModel.getAnimationDelayParams(el, dataIndex)
  15950. : null
  15951. );
  15952. }
  15953. if (typeof duration === 'function') {
  15954. duration = duration(dataIndex);
  15955. }
  15956. duration > 0
  15957. ? el.animateTo(props, duration, animationDelay || 0, animationEasing, cb, !!cb)
  15958. : (el.stopAnimation(), el.attr(props), cb && cb());
  15959. }
  15960. else {
  15961. el.stopAnimation();
  15962. el.attr(props);
  15963. cb && cb();
  15964. }
  15965. }
  15966. /**
  15967. * Update graphic element properties with or without animation according to the
  15968. * configuration in series.
  15969. *
  15970. * Caution: this method will stop previous animation.
  15971. * So do not use this method to one element twice before
  15972. * animation starts, unless you know what you are doing.
  15973. *
  15974. * @param {module:zrender/Element} el
  15975. * @param {Object} props
  15976. * @param {module:echarts/model/Model} [animatableModel]
  15977. * @param {number} [dataIndex]
  15978. * @param {Function} [cb]
  15979. * @example
  15980. * graphic.updateProps(el, {
  15981. * position: [100, 100]
  15982. * }, seriesModel, dataIndex, function () { console.log('Animation done!'); });
  15983. * // Or
  15984. * graphic.updateProps(el, {
  15985. * position: [100, 100]
  15986. * }, seriesModel, function () { console.log('Animation done!'); });
  15987. */
  15988. function updateProps(el, props, animatableModel, dataIndex, cb) {
  15989. animateOrSetProps(true, el, props, animatableModel, dataIndex, cb);
  15990. }
  15991. /**
  15992. * Init graphic element properties with or without animation according to the
  15993. * configuration in series.
  15994. *
  15995. * Caution: this method will stop previous animation.
  15996. * So do not use this method to one element twice before
  15997. * animation starts, unless you know what you are doing.
  15998. *
  15999. * @param {module:zrender/Element} el
  16000. * @param {Object} props
  16001. * @param {module:echarts/model/Model} [animatableModel]
  16002. * @param {number} [dataIndex]
  16003. * @param {Function} cb
  16004. */
  16005. function initProps(el, props, animatableModel, dataIndex, cb) {
  16006. animateOrSetProps(false, el, props, animatableModel, dataIndex, cb);
  16007. }
  16008. /**
  16009. * Get transform matrix of target (param target),
  16010. * in coordinate of its ancestor (param ancestor)
  16011. *
  16012. * @param {module:zrender/mixin/Transformable} target
  16013. * @param {module:zrender/mixin/Transformable} [ancestor]
  16014. */
  16015. function getTransform(target, ancestor) {
  16016. var mat = identity([]);
  16017. while (target && target !== ancestor) {
  16018. mul$1(mat, target.getLocalTransform(), mat);
  16019. target = target.parent;
  16020. }
  16021. return mat;
  16022. }
  16023. /**
  16024. * Apply transform to an vertex.
  16025. * @param {Array.<number>} target [x, y]
  16026. * @param {Array.<number>|TypedArray.<number>|Object} transform Can be:
  16027. * + Transform matrix: like [1, 0, 0, 1, 0, 0]
  16028. * + {position, rotation, scale}, the same as `zrender/Transformable`.
  16029. * @param {boolean=} invert Whether use invert matrix.
  16030. * @return {Array.<number>} [x, y]
  16031. */
  16032. function applyTransform$1(target, transform, invert$$1) {
  16033. if (transform && !isArrayLike(transform)) {
  16034. transform = Transformable.getLocalTransform(transform);
  16035. }
  16036. if (invert$$1) {
  16037. transform = invert([], transform);
  16038. }
  16039. return applyTransform([], target, transform);
  16040. }
  16041. /**
  16042. * @param {string} direction 'left' 'right' 'top' 'bottom'
  16043. * @param {Array.<number>} transform Transform matrix: like [1, 0, 0, 1, 0, 0]
  16044. * @param {boolean=} invert Whether use invert matrix.
  16045. * @return {string} Transformed direction. 'left' 'right' 'top' 'bottom'
  16046. */
  16047. function transformDirection(direction, transform, invert$$1) {
  16048. // Pick a base, ensure that transform result will not be (0, 0).
  16049. var hBase = (transform[4] === 0 || transform[5] === 0 || transform[0] === 0)
  16050. ? 1 : Math.abs(2 * transform[4] / transform[0]);
  16051. var vBase = (transform[4] === 0 || transform[5] === 0 || transform[2] === 0)
  16052. ? 1 : Math.abs(2 * transform[4] / transform[2]);
  16053. var vertex = [
  16054. direction === 'left' ? -hBase : direction === 'right' ? hBase : 0,
  16055. direction === 'top' ? -vBase : direction === 'bottom' ? vBase : 0
  16056. ];
  16057. vertex = applyTransform$1(vertex, transform, invert$$1);
  16058. return Math.abs(vertex[0]) > Math.abs(vertex[1])
  16059. ? (vertex[0] > 0 ? 'right' : 'left')
  16060. : (vertex[1] > 0 ? 'bottom' : 'top');
  16061. }
  16062. /**
  16063. * Apply group transition animation from g1 to g2.
  16064. * If no animatableModel, no animation.
  16065. */
  16066. function groupTransition(g1, g2, animatableModel, cb) {
  16067. if (!g1 || !g2) {
  16068. return;
  16069. }
  16070. function getElMap(g) {
  16071. var elMap = {};
  16072. g.traverse(function (el) {
  16073. if (!el.isGroup && el.anid) {
  16074. elMap[el.anid] = el;
  16075. }
  16076. });
  16077. return elMap;
  16078. }
  16079. function getAnimatableProps(el) {
  16080. var obj = {
  16081. position: clone$1(el.position),
  16082. rotation: el.rotation
  16083. };
  16084. if (el.shape) {
  16085. obj.shape = extend({}, el.shape);
  16086. }
  16087. return obj;
  16088. }
  16089. var elMap1 = getElMap(g1);
  16090. g2.traverse(function (el) {
  16091. if (!el.isGroup && el.anid) {
  16092. var oldEl = elMap1[el.anid];
  16093. if (oldEl) {
  16094. var newProp = getAnimatableProps(el);
  16095. el.attr(getAnimatableProps(oldEl));
  16096. updateProps(el, newProp, animatableModel, el.dataIndex);
  16097. }
  16098. // else {
  16099. // if (el.previousProps) {
  16100. // graphic.updateProps
  16101. // }
  16102. // }
  16103. }
  16104. });
  16105. }
  16106. /**
  16107. * @param {Array.<Array.<number>>} points Like: [[23, 44], [53, 66], ...]
  16108. * @param {Object} rect {x, y, width, height}
  16109. * @return {Array.<Array.<number>>} A new clipped points.
  16110. */
  16111. function clipPointsByRect(points, rect) {
  16112. // FIXME: this way migth be incorrect when grpahic clipped by a corner.
  16113. // and when element have border.
  16114. return map(points, function (point) {
  16115. var x = point[0];
  16116. x = mathMax$1(x, rect.x);
  16117. x = mathMin$1(x, rect.x + rect.width);
  16118. var y = point[1];
  16119. y = mathMax$1(y, rect.y);
  16120. y = mathMin$1(y, rect.y + rect.height);
  16121. return [x, y];
  16122. });
  16123. }
  16124. /**
  16125. * @param {Object} targetRect {x, y, width, height}
  16126. * @param {Object} rect {x, y, width, height}
  16127. * @return {Object} A new clipped rect. If rect size are negative, return undefined.
  16128. */
  16129. function clipRectByRect(targetRect, rect) {
  16130. var x = mathMax$1(targetRect.x, rect.x);
  16131. var x2 = mathMin$1(targetRect.x + targetRect.width, rect.x + rect.width);
  16132. var y = mathMax$1(targetRect.y, rect.y);
  16133. var y2 = mathMin$1(targetRect.y + targetRect.height, rect.y + rect.height);
  16134. // If the total rect is cliped, nothing, including the border,
  16135. // should be painted. So return undefined.
  16136. if (x2 >= x && y2 >= y) {
  16137. return {
  16138. x: x,
  16139. y: y,
  16140. width: x2 - x,
  16141. height: y2 - y
  16142. };
  16143. }
  16144. }
  16145. /**
  16146. * @param {string} iconStr Support 'image://' or 'path://' or direct svg path.
  16147. * @param {Object} [opt] Properties of `module:zrender/Element`, except `style`.
  16148. * @param {Object} [rect] {x, y, width, height}
  16149. * @return {module:zrender/Element} Icon path or image element.
  16150. */
  16151. function createIcon(iconStr, opt, rect) {
  16152. opt = extend({rectHover: true}, opt);
  16153. var style = opt.style = {strokeNoScale: true};
  16154. rect = rect || {x: -1, y: -1, width: 2, height: 2};
  16155. if (iconStr) {
  16156. return iconStr.indexOf('image://') === 0
  16157. ? (
  16158. style.image = iconStr.slice(8),
  16159. defaults(style, rect),
  16160. new ZImage(opt)
  16161. )
  16162. : (
  16163. makePath(
  16164. iconStr.replace('path://', ''),
  16165. opt,
  16166. rect,
  16167. 'center'
  16168. )
  16169. );
  16170. }
  16171. }
  16172. /**
  16173. * Return `true` if the given line (line `a`) and the given polygon
  16174. * are intersect.
  16175. * Note that we do not count colinear as intersect here because no
  16176. * requirement for that. We could do that if required in future.
  16177. *
  16178. * @param {number} a1x
  16179. * @param {number} a1y
  16180. * @param {number} a2x
  16181. * @param {number} a2y
  16182. * @param {Array.<Array.<number>>} points Points of the polygon.
  16183. * @return {boolean}
  16184. */
  16185. function linePolygonIntersect(a1x, a1y, a2x, a2y, points) {
  16186. for (var i = 0, p2 = points[points.length - 1]; i < points.length; i++) {
  16187. var p = points[i];
  16188. if (lineLineIntersect(a1x, a1y, a2x, a2y, p[0], p[1], p2[0], p2[1])) {
  16189. return true;
  16190. }
  16191. p2 = p;
  16192. }
  16193. }
  16194. /**
  16195. * Return `true` if the given two lines (line `a` and line `b`)
  16196. * are intersect.
  16197. * Note that we do not count colinear as intersect here because no
  16198. * requirement for that. We could do that if required in future.
  16199. *
  16200. * @param {number} a1x
  16201. * @param {number} a1y
  16202. * @param {number} a2x
  16203. * @param {number} a2y
  16204. * @param {number} b1x
  16205. * @param {number} b1y
  16206. * @param {number} b2x
  16207. * @param {number} b2y
  16208. * @return {boolean}
  16209. */
  16210. function lineLineIntersect(a1x, a1y, a2x, a2y, b1x, b1y, b2x, b2y) {
  16211. // let `vec_m` to be `vec_a2 - vec_a1` and `vec_n` to be `vec_b2 - vec_b1`.
  16212. var mx = a2x - a1x;
  16213. var my = a2y - a1y;
  16214. var nx = b2x - b1x;
  16215. var ny = b2y - b1y;
  16216. // `vec_m` and `vec_n` are parallel iff
  16217. // exising `k` such that `vec_m = k · vec_n`, equivalent to `vec_m X vec_n = 0`.
  16218. var nmCrossProduct = crossProduct2d(nx, ny, mx, my);
  16219. if (nearZero(nmCrossProduct)) {
  16220. return false;
  16221. }
  16222. // `vec_m` and `vec_n` are intersect iff
  16223. // existing `p` and `q` in [0, 1] such that `vec_a1 + p * vec_m = vec_b1 + q * vec_n`,
  16224. // such that `q = ((vec_a1 - vec_b1) X vec_m) / (vec_n X vec_m)`
  16225. // and `p = ((vec_a1 - vec_b1) X vec_n) / (vec_n X vec_m)`.
  16226. var b1a1x = a1x - b1x;
  16227. var b1a1y = a1y - b1y;
  16228. var q = crossProduct2d(b1a1x, b1a1y, mx, my) / nmCrossProduct;
  16229. if (q < 0 || q > 1) {
  16230. return false;
  16231. }
  16232. var p = crossProduct2d(b1a1x, b1a1y, nx, ny) / nmCrossProduct;
  16233. if (p < 0 || p > 1) {
  16234. return false;
  16235. }
  16236. return true;
  16237. }
  16238. /**
  16239. * Cross product of 2-dimension vector.
  16240. */
  16241. function crossProduct2d(x1, y1, x2, y2) {
  16242. return x1 * y2 - x2 * y1;
  16243. }
  16244. function nearZero(val) {
  16245. return val <= (1e-6) && val >= -(1e-6);
  16246. }
  16247. // Register built-in shapes. These shapes might be overwirtten
  16248. // by users, although we do not recommend that.
  16249. registerShape('circle', Circle);
  16250. registerShape('sector', Sector);
  16251. registerShape('ring', Ring);
  16252. registerShape('polygon', Polygon);
  16253. registerShape('polyline', Polyline);
  16254. registerShape('rect', Rect);
  16255. registerShape('line', Line);
  16256. registerShape('bezierCurve', BezierCurve);
  16257. registerShape('arc', Arc);
  16258. var graphic = (Object.freeze || Object)({
  16259. Z2_EMPHASIS_LIFT: Z2_EMPHASIS_LIFT,
  16260. CACHED_LABEL_STYLE_PROPERTIES: CACHED_LABEL_STYLE_PROPERTIES,
  16261. extendShape: extendShape,
  16262. extendPath: extendPath,
  16263. registerShape: registerShape,
  16264. getShapeClass: getShapeClass,
  16265. makePath: makePath,
  16266. makeImage: makeImage,
  16267. mergePath: mergePath,
  16268. resizePath: resizePath,
  16269. subPixelOptimizeLine: subPixelOptimizeLine,
  16270. subPixelOptimizeRect: subPixelOptimizeRect,
  16271. subPixelOptimize: subPixelOptimize,
  16272. setElementHoverStyle: setElementHoverStyle,
  16273. setHoverStyle: setHoverStyle,
  16274. setAsHighDownDispatcher: setAsHighDownDispatcher,
  16275. isHighDownDispatcher: isHighDownDispatcher,
  16276. getHighlightDigit: getHighlightDigit,
  16277. setLabelStyle: setLabelStyle,
  16278. modifyLabelStyle: modifyLabelStyle,
  16279. setTextStyle: setTextStyle,
  16280. setText: setText,
  16281. getFont: getFont,
  16282. updateProps: updateProps,
  16283. initProps: initProps,
  16284. getTransform: getTransform,
  16285. applyTransform: applyTransform$1,
  16286. transformDirection: transformDirection,
  16287. groupTransition: groupTransition,
  16288. clipPointsByRect: clipPointsByRect,
  16289. clipRectByRect: clipRectByRect,
  16290. createIcon: createIcon,
  16291. linePolygonIntersect: linePolygonIntersect,
  16292. lineLineIntersect: lineLineIntersect,
  16293. Group: Group,
  16294. Image: ZImage,
  16295. Text: Text,
  16296. Circle: Circle,
  16297. Sector: Sector,
  16298. Ring: Ring,
  16299. Polygon: Polygon,
  16300. Polyline: Polyline,
  16301. Rect: Rect,
  16302. Line: Line,
  16303. BezierCurve: BezierCurve,
  16304. Arc: Arc,
  16305. IncrementalDisplayable: IncrementalDisplayble,
  16306. CompoundPath: CompoundPath,
  16307. LinearGradient: LinearGradient,
  16308. RadialGradient: RadialGradient,
  16309. BoundingRect: BoundingRect
  16310. });
  16311. /*
  16312. * Licensed to the Apache Software Foundation (ASF) under one
  16313. * or more contributor license agreements. See the NOTICE file
  16314. * distributed with this work for additional information
  16315. * regarding copyright ownership. The ASF licenses this file
  16316. * to you under the Apache License, Version 2.0 (the
  16317. * "License"); you may not use this file except in compliance
  16318. * with the License. You may obtain a copy of the License at
  16319. *
  16320. * http://www.apache.org/licenses/LICENSE-2.0
  16321. *
  16322. * Unless required by applicable law or agreed to in writing,
  16323. * software distributed under the License is distributed on an
  16324. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16325. * KIND, either express or implied. See the License for the
  16326. * specific language governing permissions and limitations
  16327. * under the License.
  16328. */
  16329. var PATH_COLOR = ['textStyle', 'color'];
  16330. var textStyleMixin = {
  16331. /**
  16332. * Get color property or get color from option.textStyle.color
  16333. * @param {boolean} [isEmphasis]
  16334. * @return {string}
  16335. */
  16336. getTextColor: function (isEmphasis) {
  16337. var ecModel = this.ecModel;
  16338. return this.getShallow('color')
  16339. || (
  16340. (!isEmphasis && ecModel) ? ecModel.get(PATH_COLOR) : null
  16341. );
  16342. },
  16343. /**
  16344. * Create font string from fontStyle, fontWeight, fontSize, fontFamily
  16345. * @return {string}
  16346. */
  16347. getFont: function () {
  16348. return getFont({
  16349. fontStyle: this.getShallow('fontStyle'),
  16350. fontWeight: this.getShallow('fontWeight'),
  16351. fontSize: this.getShallow('fontSize'),
  16352. fontFamily: this.getShallow('fontFamily')
  16353. }, this.ecModel);
  16354. },
  16355. getTextRect: function (text) {
  16356. return getBoundingRect(
  16357. text,
  16358. this.getFont(),
  16359. this.getShallow('align'),
  16360. this.getShallow('verticalAlign') || this.getShallow('baseline'),
  16361. this.getShallow('padding'),
  16362. this.getShallow('lineHeight'),
  16363. this.getShallow('rich'),
  16364. this.getShallow('truncateText')
  16365. );
  16366. }
  16367. };
  16368. /*
  16369. * Licensed to the Apache Software Foundation (ASF) under one
  16370. * or more contributor license agreements. See the NOTICE file
  16371. * distributed with this work for additional information
  16372. * regarding copyright ownership. The ASF licenses this file
  16373. * to you under the Apache License, Version 2.0 (the
  16374. * "License"); you may not use this file except in compliance
  16375. * with the License. You may obtain a copy of the License at
  16376. *
  16377. * http://www.apache.org/licenses/LICENSE-2.0
  16378. *
  16379. * Unless required by applicable law or agreed to in writing,
  16380. * software distributed under the License is distributed on an
  16381. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16382. * KIND, either express or implied. See the License for the
  16383. * specific language governing permissions and limitations
  16384. * under the License.
  16385. */
  16386. var getItemStyle = makeStyleMapper(
  16387. [
  16388. ['fill', 'color'],
  16389. ['stroke', 'borderColor'],
  16390. ['lineWidth', 'borderWidth'],
  16391. ['opacity'],
  16392. ['shadowBlur'],
  16393. ['shadowOffsetX'],
  16394. ['shadowOffsetY'],
  16395. ['shadowColor'],
  16396. ['textPosition'],
  16397. ['textAlign']
  16398. ]
  16399. );
  16400. var itemStyleMixin = {
  16401. getItemStyle: function (excludes, includes) {
  16402. var style = getItemStyle(this, excludes, includes);
  16403. var lineDash = this.getBorderLineDash();
  16404. lineDash && (style.lineDash = lineDash);
  16405. return style;
  16406. },
  16407. getBorderLineDash: function () {
  16408. var lineType = this.get('borderType');
  16409. return (lineType === 'solid' || lineType == null) ? null
  16410. : (lineType === 'dashed' ? [5, 5] : [1, 1]);
  16411. }
  16412. };
  16413. /*
  16414. * Licensed to the Apache Software Foundation (ASF) under one
  16415. * or more contributor license agreements. See the NOTICE file
  16416. * distributed with this work for additional information
  16417. * regarding copyright ownership. The ASF licenses this file
  16418. * to you under the Apache License, Version 2.0 (the
  16419. * "License"); you may not use this file except in compliance
  16420. * with the License. You may obtain a copy of the License at
  16421. *
  16422. * http://www.apache.org/licenses/LICENSE-2.0
  16423. *
  16424. * Unless required by applicable law or agreed to in writing,
  16425. * software distributed under the License is distributed on an
  16426. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16427. * KIND, either express or implied. See the License for the
  16428. * specific language governing permissions and limitations
  16429. * under the License.
  16430. */
  16431. /**
  16432. * @module echarts/model/Model
  16433. */
  16434. var mixin$1 = mixin;
  16435. var inner = makeInner();
  16436. /**
  16437. * @alias module:echarts/model/Model
  16438. * @constructor
  16439. * @param {Object} [option]
  16440. * @param {module:echarts/model/Model} [parentModel]
  16441. * @param {module:echarts/model/Global} [ecModel]
  16442. */
  16443. function Model(option, parentModel, ecModel) {
  16444. /**
  16445. * @type {module:echarts/model/Model}
  16446. * @readOnly
  16447. */
  16448. this.parentModel = parentModel;
  16449. /**
  16450. * @type {module:echarts/model/Global}
  16451. * @readOnly
  16452. */
  16453. this.ecModel = ecModel;
  16454. /**
  16455. * @type {Object}
  16456. * @protected
  16457. */
  16458. this.option = option;
  16459. // Simple optimization
  16460. // if (this.init) {
  16461. // if (arguments.length <= 4) {
  16462. // this.init(option, parentModel, ecModel, extraOpt);
  16463. // }
  16464. // else {
  16465. // this.init.apply(this, arguments);
  16466. // }
  16467. // }
  16468. }
  16469. Model.prototype = {
  16470. constructor: Model,
  16471. /**
  16472. * Model 的初始化函数
  16473. * @param {Object} option
  16474. */
  16475. init: null,
  16476. /**
  16477. * 从新的 Option merge
  16478. */
  16479. mergeOption: function (option) {
  16480. merge(this.option, option, true);
  16481. },
  16482. /**
  16483. * @param {string|Array.<string>} path
  16484. * @param {boolean} [ignoreParent=false]
  16485. * @return {*}
  16486. */
  16487. get: function (path, ignoreParent) {
  16488. if (path == null) {
  16489. return this.option;
  16490. }
  16491. return doGet(
  16492. this.option,
  16493. this.parsePath(path),
  16494. !ignoreParent && getParent(this, path)
  16495. );
  16496. },
  16497. /**
  16498. * @param {string} key
  16499. * @param {boolean} [ignoreParent=false]
  16500. * @return {*}
  16501. */
  16502. getShallow: function (key, ignoreParent) {
  16503. var option = this.option;
  16504. var val = option == null ? option : option[key];
  16505. var parentModel = !ignoreParent && getParent(this, key);
  16506. if (val == null && parentModel) {
  16507. val = parentModel.getShallow(key);
  16508. }
  16509. return val;
  16510. },
  16511. /**
  16512. * @param {string|Array.<string>} [path]
  16513. * @param {module:echarts/model/Model} [parentModel]
  16514. * @return {module:echarts/model/Model}
  16515. */
  16516. getModel: function (path, parentModel) {
  16517. var obj = path == null
  16518. ? this.option
  16519. : doGet(this.option, path = this.parsePath(path));
  16520. var thisParentModel;
  16521. parentModel = parentModel || (
  16522. (thisParentModel = getParent(this, path))
  16523. && thisParentModel.getModel(path)
  16524. );
  16525. return new Model(obj, parentModel, this.ecModel);
  16526. },
  16527. /**
  16528. * If model has option
  16529. */
  16530. isEmpty: function () {
  16531. return this.option == null;
  16532. },
  16533. restoreData: function () {},
  16534. // Pending
  16535. clone: function () {
  16536. var Ctor = this.constructor;
  16537. return new Ctor(clone(this.option));
  16538. },
  16539. setReadOnly: function (properties) {
  16540. // clazzUtil.setReadOnly(this, properties);
  16541. },
  16542. // If path is null/undefined, return null/undefined.
  16543. parsePath: function (path) {
  16544. if (typeof path === 'string') {
  16545. path = path.split('.');
  16546. }
  16547. return path;
  16548. },
  16549. /**
  16550. * @param {Function} getParentMethod
  16551. * param {Array.<string>|string} path
  16552. * return {module:echarts/model/Model}
  16553. */
  16554. customizeGetParent: function (getParentMethod) {
  16555. inner(this).getParent = getParentMethod;
  16556. },
  16557. isAnimationEnabled: function () {
  16558. if (!env$1.node) {
  16559. if (this.option.animation != null) {
  16560. return !!this.option.animation;
  16561. }
  16562. else if (this.parentModel) {
  16563. return this.parentModel.isAnimationEnabled();
  16564. }
  16565. }
  16566. }
  16567. };
  16568. function doGet(obj, pathArr, parentModel) {
  16569. for (var i = 0; i < pathArr.length; i++) {
  16570. // Ignore empty
  16571. if (!pathArr[i]) {
  16572. continue;
  16573. }
  16574. // obj could be number/string/... (like 0)
  16575. obj = (obj && typeof obj === 'object') ? obj[pathArr[i]] : null;
  16576. if (obj == null) {
  16577. break;
  16578. }
  16579. }
  16580. if (obj == null && parentModel) {
  16581. obj = parentModel.get(pathArr);
  16582. }
  16583. return obj;
  16584. }
  16585. // `path` can be null/undefined
  16586. function getParent(model, path) {
  16587. var getParentMethod = inner(model).getParent;
  16588. return getParentMethod ? getParentMethod.call(model, path) : model.parentModel;
  16589. }
  16590. // Enable Model.extend.
  16591. enableClassExtend(Model);
  16592. enableClassCheck(Model);
  16593. mixin$1(Model, lineStyleMixin);
  16594. mixin$1(Model, areaStyleMixin);
  16595. mixin$1(Model, textStyleMixin);
  16596. mixin$1(Model, itemStyleMixin);
  16597. /*
  16598. * Licensed to the Apache Software Foundation (ASF) under one
  16599. * or more contributor license agreements. See the NOTICE file
  16600. * distributed with this work for additional information
  16601. * regarding copyright ownership. The ASF licenses this file
  16602. * to you under the Apache License, Version 2.0 (the
  16603. * "License"); you may not use this file except in compliance
  16604. * with the License. You may obtain a copy of the License at
  16605. *
  16606. * http://www.apache.org/licenses/LICENSE-2.0
  16607. *
  16608. * Unless required by applicable law or agreed to in writing,
  16609. * software distributed under the License is distributed on an
  16610. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16611. * KIND, either express or implied. See the License for the
  16612. * specific language governing permissions and limitations
  16613. * under the License.
  16614. */
  16615. var base = 0;
  16616. /**
  16617. * @public
  16618. * @param {string} type
  16619. * @return {string}
  16620. */
  16621. function getUID(type) {
  16622. // Considering the case of crossing js context,
  16623. // use Math.random to make id as unique as possible.
  16624. return [(type || ''), base++, Math.random().toFixed(5)].join('_');
  16625. }
  16626. /**
  16627. * @inner
  16628. */
  16629. function enableSubTypeDefaulter(entity) {
  16630. var subTypeDefaulters = {};
  16631. entity.registerSubTypeDefaulter = function (componentType, defaulter) {
  16632. componentType = parseClassType$1(componentType);
  16633. subTypeDefaulters[componentType.main] = defaulter;
  16634. };
  16635. entity.determineSubType = function (componentType, option) {
  16636. var type = option.type;
  16637. if (!type) {
  16638. var componentTypeMain = parseClassType$1(componentType).main;
  16639. if (entity.hasSubTypes(componentType) && subTypeDefaulters[componentTypeMain]) {
  16640. type = subTypeDefaulters[componentTypeMain](option);
  16641. }
  16642. }
  16643. return type;
  16644. };
  16645. return entity;
  16646. }
  16647. /**
  16648. * Topological travel on Activity Network (Activity On Vertices).
  16649. * Dependencies is defined in Model.prototype.dependencies, like ['xAxis', 'yAxis'].
  16650. *
  16651. * If 'xAxis' or 'yAxis' is absent in componentTypeList, just ignore it in topology.
  16652. *
  16653. * If there is circle dependencey, Error will be thrown.
  16654. *
  16655. */
  16656. function enableTopologicalTravel(entity, dependencyGetter) {
  16657. /**
  16658. * @public
  16659. * @param {Array.<string>} targetNameList Target Component type list.
  16660. * Can be ['aa', 'bb', 'aa.xx']
  16661. * @param {Array.<string>} fullNameList By which we can build dependency graph.
  16662. * @param {Function} callback Params: componentType, dependencies.
  16663. * @param {Object} context Scope of callback.
  16664. */
  16665. entity.topologicalTravel = function (targetNameList, fullNameList, callback, context) {
  16666. if (!targetNameList.length) {
  16667. return;
  16668. }
  16669. var result = makeDepndencyGraph(fullNameList);
  16670. var graph = result.graph;
  16671. var stack = result.noEntryList;
  16672. var targetNameSet = {};
  16673. each$1(targetNameList, function (name) {
  16674. targetNameSet[name] = true;
  16675. });
  16676. while (stack.length) {
  16677. var currComponentType = stack.pop();
  16678. var currVertex = graph[currComponentType];
  16679. var isInTargetNameSet = !!targetNameSet[currComponentType];
  16680. if (isInTargetNameSet) {
  16681. callback.call(context, currComponentType, currVertex.originalDeps.slice());
  16682. delete targetNameSet[currComponentType];
  16683. }
  16684. each$1(
  16685. currVertex.successor,
  16686. isInTargetNameSet ? removeEdgeAndAdd : removeEdge
  16687. );
  16688. }
  16689. each$1(targetNameSet, function () {
  16690. throw new Error('Circle dependency may exists');
  16691. });
  16692. function removeEdge(succComponentType) {
  16693. graph[succComponentType].entryCount--;
  16694. if (graph[succComponentType].entryCount === 0) {
  16695. stack.push(succComponentType);
  16696. }
  16697. }
  16698. // Consider this case: legend depends on series, and we call
  16699. // chart.setOption({series: [...]}), where only series is in option.
  16700. // If we do not have 'removeEdgeAndAdd', legendModel.mergeOption will
  16701. // not be called, but only sereis.mergeOption is called. Thus legend
  16702. // have no chance to update its local record about series (like which
  16703. // name of series is available in legend).
  16704. function removeEdgeAndAdd(succComponentType) {
  16705. targetNameSet[succComponentType] = true;
  16706. removeEdge(succComponentType);
  16707. }
  16708. };
  16709. /**
  16710. * DepndencyGraph: {Object}
  16711. * key: conponentType,
  16712. * value: {
  16713. * successor: [conponentTypes...],
  16714. * originalDeps: [conponentTypes...],
  16715. * entryCount: {number}
  16716. * }
  16717. */
  16718. function makeDepndencyGraph(fullNameList) {
  16719. var graph = {};
  16720. var noEntryList = [];
  16721. each$1(fullNameList, function (name) {
  16722. var thisItem = createDependencyGraphItem(graph, name);
  16723. var originalDeps = thisItem.originalDeps = dependencyGetter(name);
  16724. var availableDeps = getAvailableDependencies(originalDeps, fullNameList);
  16725. thisItem.entryCount = availableDeps.length;
  16726. if (thisItem.entryCount === 0) {
  16727. noEntryList.push(name);
  16728. }
  16729. each$1(availableDeps, function (dependentName) {
  16730. if (indexOf(thisItem.predecessor, dependentName) < 0) {
  16731. thisItem.predecessor.push(dependentName);
  16732. }
  16733. var thatItem = createDependencyGraphItem(graph, dependentName);
  16734. if (indexOf(thatItem.successor, dependentName) < 0) {
  16735. thatItem.successor.push(name);
  16736. }
  16737. });
  16738. });
  16739. return {graph: graph, noEntryList: noEntryList};
  16740. }
  16741. function createDependencyGraphItem(graph, name) {
  16742. if (!graph[name]) {
  16743. graph[name] = {predecessor: [], successor: []};
  16744. }
  16745. return graph[name];
  16746. }
  16747. function getAvailableDependencies(originalDeps, fullNameList) {
  16748. var availableDeps = [];
  16749. each$1(originalDeps, function (dep) {
  16750. indexOf(fullNameList, dep) >= 0 && availableDeps.push(dep);
  16751. });
  16752. return availableDeps;
  16753. }
  16754. }
  16755. /*
  16756. * Licensed to the Apache Software Foundation (ASF) under one
  16757. * or more contributor license agreements. See the NOTICE file
  16758. * distributed with this work for additional information
  16759. * regarding copyright ownership. The ASF licenses this file
  16760. * to you under the Apache License, Version 2.0 (the
  16761. * "License"); you may not use this file except in compliance
  16762. * with the License. You may obtain a copy of the License at
  16763. *
  16764. * http://www.apache.org/licenses/LICENSE-2.0
  16765. *
  16766. * Unless required by applicable law or agreed to in writing,
  16767. * software distributed under the License is distributed on an
  16768. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16769. * KIND, either express or implied. See the License for the
  16770. * specific language governing permissions and limitations
  16771. * under the License.
  16772. */
  16773. /*
  16774. * A third-party license is embeded for some of the code in this file:
  16775. * The method "quantile" was copied from "d3.js".
  16776. * (See more details in the comment of the method below.)
  16777. * The use of the source code of this file is also subject to the terms
  16778. * and consitions of the license of "d3.js" (BSD-3Clause, see
  16779. * </licenses/LICENSE-d3>).
  16780. */
  16781. var RADIAN_EPSILON = 1e-4;
  16782. function _trim(str) {
  16783. return str.replace(/^\s+|\s+$/g, '');
  16784. }
  16785. /**
  16786. * Linear mapping a value from domain to range
  16787. * @memberOf module:echarts/util/number
  16788. * @param {(number|Array.<number>)} val
  16789. * @param {Array.<number>} domain Domain extent domain[0] can be bigger than domain[1]
  16790. * @param {Array.<number>} range Range extent range[0] can be bigger than range[1]
  16791. * @param {boolean} clamp
  16792. * @return {(number|Array.<number>}
  16793. */
  16794. function linearMap(val, domain, range, clamp) {
  16795. var subDomain = domain[1] - domain[0];
  16796. var subRange = range[1] - range[0];
  16797. if (subDomain === 0) {
  16798. return subRange === 0
  16799. ? range[0]
  16800. : (range[0] + range[1]) / 2;
  16801. }
  16802. // Avoid accuracy problem in edge, such as
  16803. // 146.39 - 62.83 === 83.55999999999999.
  16804. // See echarts/test/ut/spec/util/number.js#linearMap#accuracyError
  16805. // It is a little verbose for efficiency considering this method
  16806. // is a hotspot.
  16807. if (clamp) {
  16808. if (subDomain > 0) {
  16809. if (val <= domain[0]) {
  16810. return range[0];
  16811. }
  16812. else if (val >= domain[1]) {
  16813. return range[1];
  16814. }
  16815. }
  16816. else {
  16817. if (val >= domain[0]) {
  16818. return range[0];
  16819. }
  16820. else if (val <= domain[1]) {
  16821. return range[1];
  16822. }
  16823. }
  16824. }
  16825. else {
  16826. if (val === domain[0]) {
  16827. return range[0];
  16828. }
  16829. if (val === domain[1]) {
  16830. return range[1];
  16831. }
  16832. }
  16833. return (val - domain[0]) / subDomain * subRange + range[0];
  16834. }
  16835. /**
  16836. * Convert a percent string to absolute number.
  16837. * Returns NaN if percent is not a valid string or number
  16838. * @memberOf module:echarts/util/number
  16839. * @param {string|number} percent
  16840. * @param {number} all
  16841. * @return {number}
  16842. */
  16843. function parsePercent$1(percent, all) {
  16844. switch (percent) {
  16845. case 'center':
  16846. case 'middle':
  16847. percent = '50%';
  16848. break;
  16849. case 'left':
  16850. case 'top':
  16851. percent = '0%';
  16852. break;
  16853. case 'right':
  16854. case 'bottom':
  16855. percent = '100%';
  16856. break;
  16857. }
  16858. if (typeof percent === 'string') {
  16859. if (_trim(percent).match(/%$/)) {
  16860. return parseFloat(percent) / 100 * all;
  16861. }
  16862. return parseFloat(percent);
  16863. }
  16864. return percent == null ? NaN : +percent;
  16865. }
  16866. /**
  16867. * (1) Fix rounding error of float numbers.
  16868. * (2) Support return string to avoid scientific notation like '3.5e-7'.
  16869. *
  16870. * @param {number} x
  16871. * @param {number} [precision]
  16872. * @param {boolean} [returnStr]
  16873. * @return {number|string}
  16874. */
  16875. function round$1(x, precision, returnStr) {
  16876. if (precision == null) {
  16877. precision = 10;
  16878. }
  16879. // Avoid range error
  16880. precision = Math.min(Math.max(0, precision), 20);
  16881. x = (+x).toFixed(precision);
  16882. return returnStr ? x : +x;
  16883. }
  16884. /**
  16885. * asc sort arr.
  16886. * The input arr will be modified.
  16887. *
  16888. * @param {Array} arr
  16889. * @return {Array} The input arr.
  16890. */
  16891. function asc(arr) {
  16892. arr.sort(function (a, b) {
  16893. return a - b;
  16894. });
  16895. return arr;
  16896. }
  16897. /**
  16898. * Get precision
  16899. * @param {number} val
  16900. */
  16901. function getPrecision(val) {
  16902. val = +val;
  16903. if (isNaN(val)) {
  16904. return 0;
  16905. }
  16906. // It is much faster than methods converting number to string as follows
  16907. // var tmp = val.toString();
  16908. // return tmp.length - 1 - tmp.indexOf('.');
  16909. // especially when precision is low
  16910. var e = 1;
  16911. var count = 0;
  16912. while (Math.round(val * e) / e !== val) {
  16913. e *= 10;
  16914. count++;
  16915. }
  16916. return count;
  16917. }
  16918. /**
  16919. * @param {string|number} val
  16920. * @return {number}
  16921. */
  16922. function getPrecisionSafe(val) {
  16923. var str = val.toString();
  16924. // Consider scientific notation: '3.4e-12' '3.4e+12'
  16925. var eIndex = str.indexOf('e');
  16926. if (eIndex > 0) {
  16927. var precision = +str.slice(eIndex + 1);
  16928. return precision < 0 ? -precision : 0;
  16929. }
  16930. else {
  16931. var dotIndex = str.indexOf('.');
  16932. return dotIndex < 0 ? 0 : str.length - 1 - dotIndex;
  16933. }
  16934. }
  16935. /**
  16936. * Minimal dicernible data precisioin according to a single pixel.
  16937. *
  16938. * @param {Array.<number>} dataExtent
  16939. * @param {Array.<number>} pixelExtent
  16940. * @return {number} precision
  16941. */
  16942. function getPixelPrecision(dataExtent, pixelExtent) {
  16943. var log = Math.log;
  16944. var LN10 = Math.LN10;
  16945. var dataQuantity = Math.floor(log(dataExtent[1] - dataExtent[0]) / LN10);
  16946. var sizeQuantity = Math.round(log(Math.abs(pixelExtent[1] - pixelExtent[0])) / LN10);
  16947. // toFixed() digits argument must be between 0 and 20.
  16948. var precision = Math.min(Math.max(-dataQuantity + sizeQuantity, 0), 20);
  16949. return !isFinite(precision) ? 20 : precision;
  16950. }
  16951. /**
  16952. * Get a data of given precision, assuring the sum of percentages
  16953. * in valueList is 1.
  16954. * The largest remainer method is used.
  16955. * https://en.wikipedia.org/wiki/Largest_remainder_method
  16956. *
  16957. * @param {Array.<number>} valueList a list of all data
  16958. * @param {number} idx index of the data to be processed in valueList
  16959. * @param {number} precision integer number showing digits of precision
  16960. * @return {number} percent ranging from 0 to 100
  16961. */
  16962. function getPercentWithPrecision(valueList, idx, precision) {
  16963. if (!valueList[idx]) {
  16964. return 0;
  16965. }
  16966. var sum = reduce(valueList, function (acc, val) {
  16967. return acc + (isNaN(val) ? 0 : val);
  16968. }, 0);
  16969. if (sum === 0) {
  16970. return 0;
  16971. }
  16972. var digits = Math.pow(10, precision);
  16973. var votesPerQuota = map(valueList, function (val) {
  16974. return (isNaN(val) ? 0 : val) / sum * digits * 100;
  16975. });
  16976. var targetSeats = digits * 100;
  16977. var seats = map(votesPerQuota, function (votes) {
  16978. // Assign automatic seats.
  16979. return Math.floor(votes);
  16980. });
  16981. var currentSum = reduce(seats, function (acc, val) {
  16982. return acc + val;
  16983. }, 0);
  16984. var remainder = map(votesPerQuota, function (votes, idx) {
  16985. return votes - seats[idx];
  16986. });
  16987. // Has remainding votes.
  16988. while (currentSum < targetSeats) {
  16989. // Find next largest remainder.
  16990. var max = Number.NEGATIVE_INFINITY;
  16991. var maxId = null;
  16992. for (var i = 0, len = remainder.length; i < len; ++i) {
  16993. if (remainder[i] > max) {
  16994. max = remainder[i];
  16995. maxId = i;
  16996. }
  16997. }
  16998. // Add a vote to max remainder.
  16999. ++seats[maxId];
  17000. remainder[maxId] = 0;
  17001. ++currentSum;
  17002. }
  17003. return seats[idx] / digits;
  17004. }
  17005. // Number.MAX_SAFE_INTEGER, ie do not support.
  17006. var MAX_SAFE_INTEGER = 9007199254740991;
  17007. /**
  17008. * To 0 - 2 * PI, considering negative radian.
  17009. * @param {number} radian
  17010. * @return {number}
  17011. */
  17012. function remRadian(radian) {
  17013. var pi2 = Math.PI * 2;
  17014. return (radian % pi2 + pi2) % pi2;
  17015. }
  17016. /**
  17017. * @param {type} radian
  17018. * @return {boolean}
  17019. */
  17020. function isRadianAroundZero(val) {
  17021. return val > -RADIAN_EPSILON && val < RADIAN_EPSILON;
  17022. }
  17023. /* eslint-disable */
  17024. 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
  17025. /* eslint-enable */
  17026. /**
  17027. * @param {string|Date|number} value These values can be accepted:
  17028. * + An instance of Date, represent a time in its own time zone.
  17029. * + Or string in a subset of ISO 8601, only including:
  17030. * + only year, month, date: '2012-03', '2012-03-01', '2012-03-01 05', '2012-03-01 05:06',
  17031. * + separated with T or space: '2012-03-01T12:22:33.123', '2012-03-01 12:22:33.123',
  17032. * + time zone: '2012-03-01T12:22:33Z', '2012-03-01T12:22:33+8000', '2012-03-01T12:22:33-05:00',
  17033. * all of which will be treated as local time if time zone is not specified
  17034. * (see <https://momentjs.com/>).
  17035. * + Or other string format, including (all of which will be treated as loacal time):
  17036. * '2012', '2012-3-1', '2012/3/1', '2012/03/01',
  17037. * '2009/6/12 2:00', '2009/6/12 2:05:08', '2009/6/12 2:05:08.123'
  17038. * + a timestamp, which represent a time in UTC.
  17039. * @return {Date} date
  17040. */
  17041. function parseDate(value) {
  17042. if (value instanceof Date) {
  17043. return value;
  17044. }
  17045. else if (typeof value === 'string') {
  17046. // Different browsers parse date in different way, so we parse it manually.
  17047. // Some other issues:
  17048. // new Date('1970-01-01') is UTC,
  17049. // new Date('1970/01/01') and new Date('1970-1-01') is local.
  17050. // See issue #3623
  17051. var match = TIME_REG.exec(value);
  17052. if (!match) {
  17053. // return Invalid Date.
  17054. return new Date(NaN);
  17055. }
  17056. // Use local time when no timezone offset specifed.
  17057. if (!match[8]) {
  17058. // match[n] can only be string or undefined.
  17059. // But take care of '12' + 1 => '121'.
  17060. return new Date(
  17061. +match[1],
  17062. +(match[2] || 1) - 1,
  17063. +match[3] || 1,
  17064. +match[4] || 0,
  17065. +(match[5] || 0),
  17066. +match[6] || 0,
  17067. +match[7] || 0
  17068. );
  17069. }
  17070. // Timezoneoffset of Javascript Date has considered DST (Daylight Saving Time,
  17071. // https://tc39.github.io/ecma262/#sec-daylight-saving-time-adjustment).
  17072. // For example, system timezone is set as "Time Zone: America/Toronto",
  17073. // then these code will get different result:
  17074. // `new Date(1478411999999).getTimezoneOffset(); // get 240`
  17075. // `new Date(1478412000000).getTimezoneOffset(); // get 300`
  17076. // So we should not use `new Date`, but use `Date.UTC`.
  17077. else {
  17078. var hour = +match[4] || 0;
  17079. if (match[8].toUpperCase() !== 'Z') {
  17080. hour -= match[8].slice(0, 3);
  17081. }
  17082. return new Date(Date.UTC(
  17083. +match[1],
  17084. +(match[2] || 1) - 1,
  17085. +match[3] || 1,
  17086. hour,
  17087. +(match[5] || 0),
  17088. +match[6] || 0,
  17089. +match[7] || 0
  17090. ));
  17091. }
  17092. }
  17093. else if (value == null) {
  17094. return new Date(NaN);
  17095. }
  17096. return new Date(Math.round(value));
  17097. }
  17098. /**
  17099. * Quantity of a number. e.g. 0.1, 1, 10, 100
  17100. *
  17101. * @param {number} val
  17102. * @return {number}
  17103. */
  17104. function quantity(val) {
  17105. return Math.pow(10, quantityExponent(val));
  17106. }
  17107. /**
  17108. * Exponent of the quantity of a number
  17109. * e.g., 1234 equals to 1.234*10^3, so quantityExponent(1234) is 3
  17110. *
  17111. * @param {number} val non-negative value
  17112. * @return {number}
  17113. */
  17114. function quantityExponent(val) {
  17115. if (val === 0) {
  17116. return 0;
  17117. }
  17118. var exp = Math.floor(Math.log(val) / Math.LN10);
  17119. /**
  17120. * exp is expected to be the rounded-down result of the base-10 log of val.
  17121. * But due to the precision loss with Math.log(val), we need to restore it
  17122. * using 10^exp to make sure we can get val back from exp. #11249
  17123. */
  17124. if (val / Math.pow(10, exp) >= 10) {
  17125. exp++;
  17126. }
  17127. return exp;
  17128. }
  17129. /**
  17130. * find a “nice” number approximately equal to x. Round the number if round = true,
  17131. * take ceiling if round = false. The primary observation is that the “nicest”
  17132. * numbers in decimal are 1, 2, and 5, and all power-of-ten multiples of these numbers.
  17133. *
  17134. * See "Nice Numbers for Graph Labels" of Graphic Gems.
  17135. *
  17136. * @param {number} val Non-negative value.
  17137. * @param {boolean} round
  17138. * @return {number}
  17139. */
  17140. function nice(val, round) {
  17141. var exponent = quantityExponent(val);
  17142. var exp10 = Math.pow(10, exponent);
  17143. var f = val / exp10; // 1 <= f < 10
  17144. var nf;
  17145. if (round) {
  17146. if (f < 1.5) {
  17147. nf = 1;
  17148. }
  17149. else if (f < 2.5) {
  17150. nf = 2;
  17151. }
  17152. else if (f < 4) {
  17153. nf = 3;
  17154. }
  17155. else if (f < 7) {
  17156. nf = 5;
  17157. }
  17158. else {
  17159. nf = 10;
  17160. }
  17161. }
  17162. else {
  17163. if (f < 1) {
  17164. nf = 1;
  17165. }
  17166. else if (f < 2) {
  17167. nf = 2;
  17168. }
  17169. else if (f < 3) {
  17170. nf = 3;
  17171. }
  17172. else if (f < 5) {
  17173. nf = 5;
  17174. }
  17175. else {
  17176. nf = 10;
  17177. }
  17178. }
  17179. val = nf * exp10;
  17180. // Fix 3 * 0.1 === 0.30000000000000004 issue (see IEEE 754).
  17181. // 20 is the uppper bound of toFixed.
  17182. return exponent >= -20 ? +val.toFixed(exponent < 0 ? -exponent : 0) : val;
  17183. }
  17184. /**
  17185. * This code was copied from "d3.js"
  17186. * <https://github.com/d3/d3/blob/9cc9a875e636a1dcf36cc1e07bdf77e1ad6e2c74/src/arrays/quantile.js>.
  17187. * See the license statement at the head of this file.
  17188. * @param {Array.<number>} ascArr
  17189. */
  17190. function quantile(ascArr, p) {
  17191. var H = (ascArr.length - 1) * p + 1;
  17192. var h = Math.floor(H);
  17193. var v = +ascArr[h - 1];
  17194. var e = H - h;
  17195. return e ? v + e * (ascArr[h] - v) : v;
  17196. }
  17197. /**
  17198. * Order intervals asc, and split them when overlap.
  17199. * expect(numberUtil.reformIntervals([
  17200. * {interval: [18, 62], close: [1, 1]},
  17201. * {interval: [-Infinity, -70], close: [0, 0]},
  17202. * {interval: [-70, -26], close: [1, 1]},
  17203. * {interval: [-26, 18], close: [1, 1]},
  17204. * {interval: [62, 150], close: [1, 1]},
  17205. * {interval: [106, 150], close: [1, 1]},
  17206. * {interval: [150, Infinity], close: [0, 0]}
  17207. * ])).toEqual([
  17208. * {interval: [-Infinity, -70], close: [0, 0]},
  17209. * {interval: [-70, -26], close: [1, 1]},
  17210. * {interval: [-26, 18], close: [0, 1]},
  17211. * {interval: [18, 62], close: [0, 1]},
  17212. * {interval: [62, 150], close: [0, 1]},
  17213. * {interval: [150, Infinity], close: [0, 0]}
  17214. * ]);
  17215. * @param {Array.<Object>} list, where `close` mean open or close
  17216. * of the interval, and Infinity can be used.
  17217. * @return {Array.<Object>} The origin list, which has been reformed.
  17218. */
  17219. function reformIntervals(list) {
  17220. list.sort(function (a, b) {
  17221. return littleThan(a, b, 0) ? -1 : 1;
  17222. });
  17223. var curr = -Infinity;
  17224. var currClose = 1;
  17225. for (var i = 0; i < list.length;) {
  17226. var interval = list[i].interval;
  17227. var close = list[i].close;
  17228. for (var lg = 0; lg < 2; lg++) {
  17229. if (interval[lg] <= curr) {
  17230. interval[lg] = curr;
  17231. close[lg] = !lg ? 1 - currClose : 1;
  17232. }
  17233. curr = interval[lg];
  17234. currClose = close[lg];
  17235. }
  17236. if (interval[0] === interval[1] && close[0] * close[1] !== 1) {
  17237. list.splice(i, 1);
  17238. }
  17239. else {
  17240. i++;
  17241. }
  17242. }
  17243. return list;
  17244. function littleThan(a, b, lg) {
  17245. return a.interval[lg] < b.interval[lg]
  17246. || (
  17247. a.interval[lg] === b.interval[lg]
  17248. && (
  17249. (a.close[lg] - b.close[lg] === (!lg ? 1 : -1))
  17250. || (!lg && littleThan(a, b, 1))
  17251. )
  17252. );
  17253. }
  17254. }
  17255. /**
  17256. * parseFloat NaNs numeric-cast false positives (null|true|false|"")
  17257. * ...but misinterprets leading-number strings, particularly hex literals ("0x...")
  17258. * subtraction forces infinities to NaN
  17259. *
  17260. * @param {*} v
  17261. * @return {boolean}
  17262. */
  17263. function isNumeric(v) {
  17264. return v - parseFloat(v) >= 0;
  17265. }
  17266. var number = (Object.freeze || Object)({
  17267. linearMap: linearMap,
  17268. parsePercent: parsePercent$1,
  17269. round: round$1,
  17270. asc: asc,
  17271. getPrecision: getPrecision,
  17272. getPrecisionSafe: getPrecisionSafe,
  17273. getPixelPrecision: getPixelPrecision,
  17274. getPercentWithPrecision: getPercentWithPrecision,
  17275. MAX_SAFE_INTEGER: MAX_SAFE_INTEGER,
  17276. remRadian: remRadian,
  17277. isRadianAroundZero: isRadianAroundZero,
  17278. parseDate: parseDate,
  17279. quantity: quantity,
  17280. quantityExponent: quantityExponent,
  17281. nice: nice,
  17282. quantile: quantile,
  17283. reformIntervals: reformIntervals,
  17284. isNumeric: isNumeric
  17285. });
  17286. /*
  17287. * Licensed to the Apache Software Foundation (ASF) under one
  17288. * or more contributor license agreements. See the NOTICE file
  17289. * distributed with this work for additional information
  17290. * regarding copyright ownership. The ASF licenses this file
  17291. * to you under the Apache License, Version 2.0 (the
  17292. * "License"); you may not use this file except in compliance
  17293. * with the License. You may obtain a copy of the License at
  17294. *
  17295. * http://www.apache.org/licenses/LICENSE-2.0
  17296. *
  17297. * Unless required by applicable law or agreed to in writing,
  17298. * software distributed under the License is distributed on an
  17299. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17300. * KIND, either express or implied. See the License for the
  17301. * specific language governing permissions and limitations
  17302. * under the License.
  17303. */
  17304. // import Text from 'zrender/src/graphic/Text';
  17305. /**
  17306. * add commas after every three numbers
  17307. * @param {string|number} x
  17308. * @return {string}
  17309. */
  17310. function addCommas(x) {
  17311. if (isNaN(x)) {
  17312. return '-';
  17313. }
  17314. x = (x + '').split('.');
  17315. return x[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g, '$1,')
  17316. + (x.length > 1 ? ('.' + x[1]) : '');
  17317. }
  17318. /**
  17319. * @param {string} str
  17320. * @param {boolean} [upperCaseFirst=false]
  17321. * @return {string} str
  17322. */
  17323. function toCamelCase(str, upperCaseFirst) {
  17324. str = (str || '').toLowerCase().replace(/-(.)/g, function (match, group1) {
  17325. return group1.toUpperCase();
  17326. });
  17327. if (upperCaseFirst && str) {
  17328. str = str.charAt(0).toUpperCase() + str.slice(1);
  17329. }
  17330. return str;
  17331. }
  17332. var normalizeCssArray$1 = normalizeCssArray;
  17333. var replaceReg = /([&<>"'])/g;
  17334. var replaceMap = {
  17335. '&': '&amp;',
  17336. '<': '&lt;',
  17337. '>': '&gt;',
  17338. '"': '&quot;',
  17339. '\'': '&#39;'
  17340. };
  17341. function encodeHTML(source) {
  17342. return source == null
  17343. ? ''
  17344. : (source + '').replace(replaceReg, function (str, c) {
  17345. return replaceMap[c];
  17346. });
  17347. }
  17348. var TPL_VAR_ALIAS = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
  17349. var wrapVar = function (varName, seriesIdx) {
  17350. return '{' + varName + (seriesIdx == null ? '' : seriesIdx) + '}';
  17351. };
  17352. /**
  17353. * Template formatter
  17354. * @param {string} tpl
  17355. * @param {Array.<Object>|Object} paramsList
  17356. * @param {boolean} [encode=false]
  17357. * @return {string}
  17358. */
  17359. function formatTpl(tpl, paramsList, encode) {
  17360. if (!isArray(paramsList)) {
  17361. paramsList = [paramsList];
  17362. }
  17363. var seriesLen = paramsList.length;
  17364. if (!seriesLen) {
  17365. return '';
  17366. }
  17367. var $vars = paramsList[0].$vars || [];
  17368. for (var i = 0; i < $vars.length; i++) {
  17369. var alias = TPL_VAR_ALIAS[i];
  17370. tpl = tpl.replace(wrapVar(alias), wrapVar(alias, 0));
  17371. }
  17372. for (var seriesIdx = 0; seriesIdx < seriesLen; seriesIdx++) {
  17373. for (var k = 0; k < $vars.length; k++) {
  17374. var val = paramsList[seriesIdx][$vars[k]];
  17375. tpl = tpl.replace(
  17376. wrapVar(TPL_VAR_ALIAS[k], seriesIdx),
  17377. encode ? encodeHTML(val) : val
  17378. );
  17379. }
  17380. }
  17381. return tpl;
  17382. }
  17383. /**
  17384. * simple Template formatter
  17385. *
  17386. * @param {string} tpl
  17387. * @param {Object} param
  17388. * @param {boolean} [encode=false]
  17389. * @return {string}
  17390. */
  17391. function formatTplSimple(tpl, param, encode) {
  17392. each$1(param, function (value, key) {
  17393. tpl = tpl.replace(
  17394. '{' + key + '}',
  17395. encode ? encodeHTML(value) : value
  17396. );
  17397. });
  17398. return tpl;
  17399. }
  17400. /**
  17401. * @param {Object|string} [opt] If string, means color.
  17402. * @param {string} [opt.color]
  17403. * @param {string} [opt.extraCssText]
  17404. * @param {string} [opt.type='item'] 'item' or 'subItem'
  17405. * @param {string} [opt.renderMode='html'] render mode of tooltip, 'html' or 'richText'
  17406. * @param {string} [opt.markerId='X'] id name for marker. If only one marker is in a rich text, this can be omitted.
  17407. * @return {string}
  17408. */
  17409. function getTooltipMarker(opt, extraCssText) {
  17410. opt = isString(opt) ? {color: opt, extraCssText: extraCssText} : (opt || {});
  17411. var color = opt.color;
  17412. var type = opt.type;
  17413. var extraCssText = opt.extraCssText;
  17414. var renderMode = opt.renderMode || 'html';
  17415. var markerId = opt.markerId || 'X';
  17416. if (!color) {
  17417. return '';
  17418. }
  17419. if (renderMode === 'html') {
  17420. return type === 'subItem'
  17421. ? '<span style="display:inline-block;vertical-align:middle;margin-right:8px;margin-left:3px;'
  17422. + 'border-radius:4px;width:4px;height:4px;background-color:'
  17423. + encodeHTML(color) + ';' + (extraCssText || '') + '"></span>'
  17424. : '<span style="display:inline-block;margin-right:5px;'
  17425. + 'border-radius:10px;width:10px;height:10px;background-color:'
  17426. + encodeHTML(color) + ';' + (extraCssText || '') + '"></span>';
  17427. }
  17428. else {
  17429. // Space for rich element marker
  17430. return {
  17431. renderMode: renderMode,
  17432. content: '{marker' + markerId + '|} ',
  17433. style: {
  17434. color: color
  17435. }
  17436. };
  17437. }
  17438. }
  17439. function pad(str, len) {
  17440. str += '';
  17441. return '0000'.substr(0, len - str.length) + str;
  17442. }
  17443. /**
  17444. * ISO Date format
  17445. * @param {string} tpl
  17446. * @param {number} value
  17447. * @param {boolean} [isUTC=false] Default in local time.
  17448. * see `module:echarts/scale/Time`
  17449. * and `module:echarts/util/number#parseDate`.
  17450. * @inner
  17451. */
  17452. function formatTime(tpl, value, isUTC) {
  17453. if (tpl === 'week'
  17454. || tpl === 'month'
  17455. || tpl === 'quarter'
  17456. || tpl === 'half-year'
  17457. || tpl === 'year'
  17458. ) {
  17459. tpl = 'MM-dd\nyyyy';
  17460. }
  17461. var date = parseDate(value);
  17462. var utc = isUTC ? 'UTC' : '';
  17463. var y = date['get' + utc + 'FullYear']();
  17464. var M = date['get' + utc + 'Month']() + 1;
  17465. var d = date['get' + utc + 'Date']();
  17466. var h = date['get' + utc + 'Hours']();
  17467. var m = date['get' + utc + 'Minutes']();
  17468. var s = date['get' + utc + 'Seconds']();
  17469. var S = date['get' + utc + 'Milliseconds']();
  17470. tpl = tpl.replace('MM', pad(M, 2))
  17471. .replace('M', M)
  17472. .replace('yyyy', y)
  17473. .replace('yy', y % 100)
  17474. .replace('dd', pad(d, 2))
  17475. .replace('d', d)
  17476. .replace('hh', pad(h, 2))
  17477. .replace('h', h)
  17478. .replace('mm', pad(m, 2))
  17479. .replace('m', m)
  17480. .replace('ss', pad(s, 2))
  17481. .replace('s', s)
  17482. .replace('SSS', pad(S, 3));
  17483. return tpl;
  17484. }
  17485. /**
  17486. * Capital first
  17487. * @param {string} str
  17488. * @return {string}
  17489. */
  17490. function capitalFirst(str) {
  17491. return str ? str.charAt(0).toUpperCase() + str.substr(1) : str;
  17492. }
  17493. var truncateText$1 = truncateText;
  17494. /**
  17495. * @public
  17496. * @param {Object} opt
  17497. * @param {string} opt.text
  17498. * @param {string} opt.font
  17499. * @param {string} [opt.textAlign='left']
  17500. * @param {string} [opt.textVerticalAlign='top']
  17501. * @param {Array.<number>} [opt.textPadding]
  17502. * @param {number} [opt.textLineHeight]
  17503. * @param {Object} [opt.rich]
  17504. * @param {Object} [opt.truncate]
  17505. * @return {Object} {x, y, width, height, lineHeight}
  17506. */
  17507. function getTextBoundingRect(opt) {
  17508. return getBoundingRect(
  17509. opt.text,
  17510. opt.font,
  17511. opt.textAlign,
  17512. opt.textVerticalAlign,
  17513. opt.textPadding,
  17514. opt.textLineHeight,
  17515. opt.rich,
  17516. opt.truncate
  17517. );
  17518. }
  17519. /**
  17520. * @deprecated
  17521. * the `textLineHeight` was added later.
  17522. * For backward compatiblility, put it as the last parameter.
  17523. * But deprecated this interface. Please use `getTextBoundingRect` instead.
  17524. */
  17525. function getTextRect(
  17526. text, font, textAlign, textVerticalAlign, textPadding, rich, truncate, textLineHeight
  17527. ) {
  17528. return getBoundingRect(
  17529. text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, rich, truncate
  17530. );
  17531. }
  17532. /**
  17533. * open new tab
  17534. * @param {string} link url
  17535. * @param {string} target blank or self
  17536. */
  17537. function windowOpen(link, target) {
  17538. if (target === '_blank' || target === 'blank') {
  17539. var blank = window.open();
  17540. blank.opener = null;
  17541. blank.location = link;
  17542. }
  17543. else {
  17544. window.open(link, target);
  17545. }
  17546. }
  17547. var format = (Object.freeze || Object)({
  17548. addCommas: addCommas,
  17549. toCamelCase: toCamelCase,
  17550. normalizeCssArray: normalizeCssArray$1,
  17551. encodeHTML: encodeHTML,
  17552. formatTpl: formatTpl,
  17553. formatTplSimple: formatTplSimple,
  17554. getTooltipMarker: getTooltipMarker,
  17555. formatTime: formatTime,
  17556. capitalFirst: capitalFirst,
  17557. truncateText: truncateText$1,
  17558. getTextBoundingRect: getTextBoundingRect,
  17559. getTextRect: getTextRect,
  17560. windowOpen: windowOpen
  17561. });
  17562. /*
  17563. * Licensed to the Apache Software Foundation (ASF) under one
  17564. * or more contributor license agreements. See the NOTICE file
  17565. * distributed with this work for additional information
  17566. * regarding copyright ownership. The ASF licenses this file
  17567. * to you under the Apache License, Version 2.0 (the
  17568. * "License"); you may not use this file except in compliance
  17569. * with the License. You may obtain a copy of the License at
  17570. *
  17571. * http://www.apache.org/licenses/LICENSE-2.0
  17572. *
  17573. * Unless required by applicable law or agreed to in writing,
  17574. * software distributed under the License is distributed on an
  17575. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17576. * KIND, either express or implied. See the License for the
  17577. * specific language governing permissions and limitations
  17578. * under the License.
  17579. */
  17580. // Layout helpers for each component positioning
  17581. var each$3 = each$1;
  17582. /**
  17583. * @public
  17584. */
  17585. var LOCATION_PARAMS = [
  17586. 'left', 'right', 'top', 'bottom', 'width', 'height'
  17587. ];
  17588. /**
  17589. * @public
  17590. */
  17591. var HV_NAMES = [
  17592. ['width', 'left', 'right'],
  17593. ['height', 'top', 'bottom']
  17594. ];
  17595. function boxLayout(orient, group, gap, maxWidth, maxHeight) {
  17596. var x = 0;
  17597. var y = 0;
  17598. if (maxWidth == null) {
  17599. maxWidth = Infinity;
  17600. }
  17601. if (maxHeight == null) {
  17602. maxHeight = Infinity;
  17603. }
  17604. var currentLineMaxSize = 0;
  17605. group.eachChild(function (child, idx) {
  17606. var position = child.position;
  17607. var rect = child.getBoundingRect();
  17608. var nextChild = group.childAt(idx + 1);
  17609. var nextChildRect = nextChild && nextChild.getBoundingRect();
  17610. var nextX;
  17611. var nextY;
  17612. if (orient === 'horizontal') {
  17613. var moveX = rect.width + (nextChildRect ? (-nextChildRect.x + rect.x) : 0);
  17614. nextX = x + moveX;
  17615. // Wrap when width exceeds maxWidth or meet a `newline` group
  17616. // FIXME compare before adding gap?
  17617. if (nextX > maxWidth || child.newline) {
  17618. x = 0;
  17619. nextX = moveX;
  17620. y += currentLineMaxSize + gap;
  17621. currentLineMaxSize = rect.height;
  17622. }
  17623. else {
  17624. // FIXME: consider rect.y is not `0`?
  17625. currentLineMaxSize = Math.max(currentLineMaxSize, rect.height);
  17626. }
  17627. }
  17628. else {
  17629. var moveY = rect.height + (nextChildRect ? (-nextChildRect.y + rect.y) : 0);
  17630. nextY = y + moveY;
  17631. // Wrap when width exceeds maxHeight or meet a `newline` group
  17632. if (nextY > maxHeight || child.newline) {
  17633. x += currentLineMaxSize + gap;
  17634. y = 0;
  17635. nextY = moveY;
  17636. currentLineMaxSize = rect.width;
  17637. }
  17638. else {
  17639. currentLineMaxSize = Math.max(currentLineMaxSize, rect.width);
  17640. }
  17641. }
  17642. if (child.newline) {
  17643. return;
  17644. }
  17645. position[0] = x;
  17646. position[1] = y;
  17647. orient === 'horizontal'
  17648. ? (x = nextX + gap)
  17649. : (y = nextY + gap);
  17650. });
  17651. }
  17652. /**
  17653. * VBox or HBox layouting
  17654. * @param {string} orient
  17655. * @param {module:zrender/container/Group} group
  17656. * @param {number} gap
  17657. * @param {number} [width=Infinity]
  17658. * @param {number} [height=Infinity]
  17659. */
  17660. var box = boxLayout;
  17661. /**
  17662. * VBox layouting
  17663. * @param {module:zrender/container/Group} group
  17664. * @param {number} gap
  17665. * @param {number} [width=Infinity]
  17666. * @param {number} [height=Infinity]
  17667. */
  17668. var vbox = curry(boxLayout, 'vertical');
  17669. /**
  17670. * HBox layouting
  17671. * @param {module:zrender/container/Group} group
  17672. * @param {number} gap
  17673. * @param {number} [width=Infinity]
  17674. * @param {number} [height=Infinity]
  17675. */
  17676. var hbox = curry(boxLayout, 'horizontal');
  17677. /**
  17678. * If x or x2 is not specified or 'center' 'left' 'right',
  17679. * the width would be as long as possible.
  17680. * If y or y2 is not specified or 'middle' 'top' 'bottom',
  17681. * the height would be as long as possible.
  17682. *
  17683. * @param {Object} positionInfo
  17684. * @param {number|string} [positionInfo.x]
  17685. * @param {number|string} [positionInfo.y]
  17686. * @param {number|string} [positionInfo.x2]
  17687. * @param {number|string} [positionInfo.y2]
  17688. * @param {Object} containerRect {width, height}
  17689. * @param {string|number} margin
  17690. * @return {Object} {width, height}
  17691. */
  17692. function getAvailableSize(positionInfo, containerRect, margin) {
  17693. var containerWidth = containerRect.width;
  17694. var containerHeight = containerRect.height;
  17695. var x = parsePercent$1(positionInfo.x, containerWidth);
  17696. var y = parsePercent$1(positionInfo.y, containerHeight);
  17697. var x2 = parsePercent$1(positionInfo.x2, containerWidth);
  17698. var y2 = parsePercent$1(positionInfo.y2, containerHeight);
  17699. (isNaN(x) || isNaN(parseFloat(positionInfo.x))) && (x = 0);
  17700. (isNaN(x2) || isNaN(parseFloat(positionInfo.x2))) && (x2 = containerWidth);
  17701. (isNaN(y) || isNaN(parseFloat(positionInfo.y))) && (y = 0);
  17702. (isNaN(y2) || isNaN(parseFloat(positionInfo.y2))) && (y2 = containerHeight);
  17703. margin = normalizeCssArray$1(margin || 0);
  17704. return {
  17705. width: Math.max(x2 - x - margin[1] - margin[3], 0),
  17706. height: Math.max(y2 - y - margin[0] - margin[2], 0)
  17707. };
  17708. }
  17709. /**
  17710. * Parse position info.
  17711. *
  17712. * @param {Object} positionInfo
  17713. * @param {number|string} [positionInfo.left]
  17714. * @param {number|string} [positionInfo.top]
  17715. * @param {number|string} [positionInfo.right]
  17716. * @param {number|string} [positionInfo.bottom]
  17717. * @param {number|string} [positionInfo.width]
  17718. * @param {number|string} [positionInfo.height]
  17719. * @param {number|string} [positionInfo.aspect] Aspect is width / height
  17720. * @param {Object} containerRect
  17721. * @param {string|number} [margin]
  17722. *
  17723. * @return {module:zrender/core/BoundingRect}
  17724. */
  17725. function getLayoutRect(
  17726. positionInfo, containerRect, margin
  17727. ) {
  17728. margin = normalizeCssArray$1(margin || 0);
  17729. var containerWidth = containerRect.width;
  17730. var containerHeight = containerRect.height;
  17731. var left = parsePercent$1(positionInfo.left, containerWidth);
  17732. var top = parsePercent$1(positionInfo.top, containerHeight);
  17733. var right = parsePercent$1(positionInfo.right, containerWidth);
  17734. var bottom = parsePercent$1(positionInfo.bottom, containerHeight);
  17735. var width = parsePercent$1(positionInfo.width, containerWidth);
  17736. var height = parsePercent$1(positionInfo.height, containerHeight);
  17737. var verticalMargin = margin[2] + margin[0];
  17738. var horizontalMargin = margin[1] + margin[3];
  17739. var aspect = positionInfo.aspect;
  17740. // If width is not specified, calculate width from left and right
  17741. if (isNaN(width)) {
  17742. width = containerWidth - right - horizontalMargin - left;
  17743. }
  17744. if (isNaN(height)) {
  17745. height = containerHeight - bottom - verticalMargin - top;
  17746. }
  17747. if (aspect != null) {
  17748. // If width and height are not given
  17749. // 1. Graph should not exceeds the container
  17750. // 2. Aspect must be keeped
  17751. // 3. Graph should take the space as more as possible
  17752. // FIXME
  17753. // Margin is not considered, because there is no case that both
  17754. // using margin and aspect so far.
  17755. if (isNaN(width) && isNaN(height)) {
  17756. if (aspect > containerWidth / containerHeight) {
  17757. width = containerWidth * 0.8;
  17758. }
  17759. else {
  17760. height = containerHeight * 0.8;
  17761. }
  17762. }
  17763. // Calculate width or height with given aspect
  17764. if (isNaN(width)) {
  17765. width = aspect * height;
  17766. }
  17767. if (isNaN(height)) {
  17768. height = width / aspect;
  17769. }
  17770. }
  17771. // If left is not specified, calculate left from right and width
  17772. if (isNaN(left)) {
  17773. left = containerWidth - right - width - horizontalMargin;
  17774. }
  17775. if (isNaN(top)) {
  17776. top = containerHeight - bottom - height - verticalMargin;
  17777. }
  17778. // Align left and top
  17779. switch (positionInfo.left || positionInfo.right) {
  17780. case 'center':
  17781. left = containerWidth / 2 - width / 2 - margin[3];
  17782. break;
  17783. case 'right':
  17784. left = containerWidth - width - horizontalMargin;
  17785. break;
  17786. }
  17787. switch (positionInfo.top || positionInfo.bottom) {
  17788. case 'middle':
  17789. case 'center':
  17790. top = containerHeight / 2 - height / 2 - margin[0];
  17791. break;
  17792. case 'bottom':
  17793. top = containerHeight - height - verticalMargin;
  17794. break;
  17795. }
  17796. // If something is wrong and left, top, width, height are calculated as NaN
  17797. left = left || 0;
  17798. top = top || 0;
  17799. if (isNaN(width)) {
  17800. // Width may be NaN if only one value is given except width
  17801. width = containerWidth - horizontalMargin - left - (right || 0);
  17802. }
  17803. if (isNaN(height)) {
  17804. // Height may be NaN if only one value is given except height
  17805. height = containerHeight - verticalMargin - top - (bottom || 0);
  17806. }
  17807. var rect = new BoundingRect(left + margin[3], top + margin[0], width, height);
  17808. rect.margin = margin;
  17809. return rect;
  17810. }
  17811. /**
  17812. * Position a zr element in viewport
  17813. * Group position is specified by either
  17814. * {left, top}, {right, bottom}
  17815. * If all properties exists, right and bottom will be igonred.
  17816. *
  17817. * Logic:
  17818. * 1. Scale (against origin point in parent coord)
  17819. * 2. Rotate (against origin point in parent coord)
  17820. * 3. Traslate (with el.position by this method)
  17821. * So this method only fixes the last step 'Traslate', which does not affect
  17822. * scaling and rotating.
  17823. *
  17824. * If be called repeatly with the same input el, the same result will be gotten.
  17825. *
  17826. * @param {module:zrender/Element} el Should have `getBoundingRect` method.
  17827. * @param {Object} positionInfo
  17828. * @param {number|string} [positionInfo.left]
  17829. * @param {number|string} [positionInfo.top]
  17830. * @param {number|string} [positionInfo.right]
  17831. * @param {number|string} [positionInfo.bottom]
  17832. * @param {number|string} [positionInfo.width] Only for opt.boundingModel: 'raw'
  17833. * @param {number|string} [positionInfo.height] Only for opt.boundingModel: 'raw'
  17834. * @param {Object} containerRect
  17835. * @param {string|number} margin
  17836. * @param {Object} [opt]
  17837. * @param {Array.<number>} [opt.hv=[1,1]] Only horizontal or only vertical.
  17838. * @param {Array.<number>} [opt.boundingMode='all']
  17839. * Specify how to calculate boundingRect when locating.
  17840. * 'all': Position the boundingRect that is transformed and uioned
  17841. * both itself and its descendants.
  17842. * This mode simplies confine the elements in the bounding
  17843. * of their container (e.g., using 'right: 0').
  17844. * 'raw': Position the boundingRect that is not transformed and only itself.
  17845. * This mode is useful when you want a element can overflow its
  17846. * container. (Consider a rotated circle needs to be located in a corner.)
  17847. * In this mode positionInfo.width/height can only be number.
  17848. */
  17849. function positionElement(el, positionInfo, containerRect, margin, opt) {
  17850. var h = !opt || !opt.hv || opt.hv[0];
  17851. var v = !opt || !opt.hv || opt.hv[1];
  17852. var boundingMode = opt && opt.boundingMode || 'all';
  17853. if (!h && !v) {
  17854. return;
  17855. }
  17856. var rect;
  17857. if (boundingMode === 'raw') {
  17858. rect = el.type === 'group'
  17859. ? new BoundingRect(0, 0, +positionInfo.width || 0, +positionInfo.height || 0)
  17860. : el.getBoundingRect();
  17861. }
  17862. else {
  17863. rect = el.getBoundingRect();
  17864. if (el.needLocalTransform()) {
  17865. var transform = el.getLocalTransform();
  17866. // Notice: raw rect may be inner object of el,
  17867. // which should not be modified.
  17868. rect = rect.clone();
  17869. rect.applyTransform(transform);
  17870. }
  17871. }
  17872. // The real width and height can not be specified but calculated by the given el.
  17873. positionInfo = getLayoutRect(
  17874. defaults(
  17875. {width: rect.width, height: rect.height},
  17876. positionInfo
  17877. ),
  17878. containerRect,
  17879. margin
  17880. );
  17881. // Because 'tranlate' is the last step in transform
  17882. // (see zrender/core/Transformable#getLocalTransform),
  17883. // we can just only modify el.position to get final result.
  17884. var elPos = el.position;
  17885. var dx = h ? positionInfo.x - rect.x : 0;
  17886. var dy = v ? positionInfo.y - rect.y : 0;
  17887. el.attr('position', boundingMode === 'raw' ? [dx, dy] : [elPos[0] + dx, elPos[1] + dy]);
  17888. }
  17889. /**
  17890. * @param {Object} option Contains some of the properties in HV_NAMES.
  17891. * @param {number} hvIdx 0: horizontal; 1: vertical.
  17892. */
  17893. function sizeCalculable(option, hvIdx) {
  17894. return option[HV_NAMES[hvIdx][0]] != null
  17895. || (option[HV_NAMES[hvIdx][1]] != null && option[HV_NAMES[hvIdx][2]] != null);
  17896. }
  17897. /**
  17898. * Consider Case:
  17899. * When defulat option has {left: 0, width: 100}, and we set {right: 0}
  17900. * through setOption or media query, using normal zrUtil.merge will cause
  17901. * {right: 0} does not take effect.
  17902. *
  17903. * @example
  17904. * ComponentModel.extend({
  17905. * init: function () {
  17906. * ...
  17907. * var inputPositionParams = layout.getLayoutParams(option);
  17908. * this.mergeOption(inputPositionParams);
  17909. * },
  17910. * mergeOption: function (newOption) {
  17911. * newOption && zrUtil.merge(thisOption, newOption, true);
  17912. * layout.mergeLayoutParam(thisOption, newOption);
  17913. * }
  17914. * });
  17915. *
  17916. * @param {Object} targetOption
  17917. * @param {Object} newOption
  17918. * @param {Object|string} [opt]
  17919. * @param {boolean|Array.<boolean>} [opt.ignoreSize=false] Used for the components
  17920. * that width (or height) should not be calculated by left and right (or top and bottom).
  17921. */
  17922. function mergeLayoutParam(targetOption, newOption, opt) {
  17923. !isObject$1(opt) && (opt = {});
  17924. var ignoreSize = opt.ignoreSize;
  17925. !isArray(ignoreSize) && (ignoreSize = [ignoreSize, ignoreSize]);
  17926. var hResult = merge$$1(HV_NAMES[0], 0);
  17927. var vResult = merge$$1(HV_NAMES[1], 1);
  17928. copy(HV_NAMES[0], targetOption, hResult);
  17929. copy(HV_NAMES[1], targetOption, vResult);
  17930. function merge$$1(names, hvIdx) {
  17931. var newParams = {};
  17932. var newValueCount = 0;
  17933. var merged = {};
  17934. var mergedValueCount = 0;
  17935. var enoughParamNumber = 2;
  17936. each$3(names, function (name) {
  17937. merged[name] = targetOption[name];
  17938. });
  17939. each$3(names, function (name) {
  17940. // Consider case: newOption.width is null, which is
  17941. // set by user for removing width setting.
  17942. hasProp(newOption, name) && (newParams[name] = merged[name] = newOption[name]);
  17943. hasValue(newParams, name) && newValueCount++;
  17944. hasValue(merged, name) && mergedValueCount++;
  17945. });
  17946. if (ignoreSize[hvIdx]) {
  17947. // Only one of left/right is premitted to exist.
  17948. if (hasValue(newOption, names[1])) {
  17949. merged[names[2]] = null;
  17950. }
  17951. else if (hasValue(newOption, names[2])) {
  17952. merged[names[1]] = null;
  17953. }
  17954. return merged;
  17955. }
  17956. // Case: newOption: {width: ..., right: ...},
  17957. // or targetOption: {right: ...} and newOption: {width: ...},
  17958. // There is no conflict when merged only has params count
  17959. // little than enoughParamNumber.
  17960. if (mergedValueCount === enoughParamNumber || !newValueCount) {
  17961. return merged;
  17962. }
  17963. // Case: newOption: {width: ..., right: ...},
  17964. // Than we can make sure user only want those two, and ignore
  17965. // all origin params in targetOption.
  17966. else if (newValueCount >= enoughParamNumber) {
  17967. return newParams;
  17968. }
  17969. else {
  17970. // Chose another param from targetOption by priority.
  17971. for (var i = 0; i < names.length; i++) {
  17972. var name = names[i];
  17973. if (!hasProp(newParams, name) && hasProp(targetOption, name)) {
  17974. newParams[name] = targetOption[name];
  17975. break;
  17976. }
  17977. }
  17978. return newParams;
  17979. }
  17980. }
  17981. function hasProp(obj, name) {
  17982. return obj.hasOwnProperty(name);
  17983. }
  17984. function hasValue(obj, name) {
  17985. return obj[name] != null && obj[name] !== 'auto';
  17986. }
  17987. function copy(names, target, source) {
  17988. each$3(names, function (name) {
  17989. target[name] = source[name];
  17990. });
  17991. }
  17992. }
  17993. /**
  17994. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  17995. * @param {Object} source
  17996. * @return {Object} Result contains those props.
  17997. */
  17998. function getLayoutParams(source) {
  17999. return copyLayoutParams({}, source);
  18000. }
  18001. /**
  18002. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  18003. * @param {Object} source
  18004. * @return {Object} Result contains those props.
  18005. */
  18006. function copyLayoutParams(target, source) {
  18007. source && target && each$3(LOCATION_PARAMS, function (name) {
  18008. source.hasOwnProperty(name) && (target[name] = source[name]);
  18009. });
  18010. return target;
  18011. }
  18012. /*
  18013. * Licensed to the Apache Software Foundation (ASF) under one
  18014. * or more contributor license agreements. See the NOTICE file
  18015. * distributed with this work for additional information
  18016. * regarding copyright ownership. The ASF licenses this file
  18017. * to you under the Apache License, Version 2.0 (the
  18018. * "License"); you may not use this file except in compliance
  18019. * with the License. You may obtain a copy of the License at
  18020. *
  18021. * http://www.apache.org/licenses/LICENSE-2.0
  18022. *
  18023. * Unless required by applicable law or agreed to in writing,
  18024. * software distributed under the License is distributed on an
  18025. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18026. * KIND, either express or implied. See the License for the
  18027. * specific language governing permissions and limitations
  18028. * under the License.
  18029. */
  18030. var boxLayoutMixin = {
  18031. getBoxLayoutParams: function () {
  18032. return {
  18033. left: this.get('left'),
  18034. top: this.get('top'),
  18035. right: this.get('right'),
  18036. bottom: this.get('bottom'),
  18037. width: this.get('width'),
  18038. height: this.get('height')
  18039. };
  18040. }
  18041. };
  18042. /*
  18043. * Licensed to the Apache Software Foundation (ASF) under one
  18044. * or more contributor license agreements. See the NOTICE file
  18045. * distributed with this work for additional information
  18046. * regarding copyright ownership. The ASF licenses this file
  18047. * to you under the Apache License, Version 2.0 (the
  18048. * "License"); you may not use this file except in compliance
  18049. * with the License. You may obtain a copy of the License at
  18050. *
  18051. * http://www.apache.org/licenses/LICENSE-2.0
  18052. *
  18053. * Unless required by applicable law or agreed to in writing,
  18054. * software distributed under the License is distributed on an
  18055. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18056. * KIND, either express or implied. See the License for the
  18057. * specific language governing permissions and limitations
  18058. * under the License.
  18059. */
  18060. /**
  18061. * Component model
  18062. *
  18063. * @module echarts/model/Component
  18064. */
  18065. var inner$1 = makeInner();
  18066. /**
  18067. * @alias module:echarts/model/Component
  18068. * @constructor
  18069. * @param {Object} option
  18070. * @param {module:echarts/model/Model} parentModel
  18071. * @param {module:echarts/model/Model} ecModel
  18072. */
  18073. var ComponentModel = Model.extend({
  18074. type: 'component',
  18075. /**
  18076. * @readOnly
  18077. * @type {string}
  18078. */
  18079. id: '',
  18080. /**
  18081. * Because simplified concept is probably better, series.name (or component.name)
  18082. * has been having too many resposibilities:
  18083. * (1) Generating id (which requires name in option should not be modified).
  18084. * (2) As an index to mapping series when merging option or calling API (a name
  18085. * can refer to more then one components, which is convinient is some case).
  18086. * (3) Display.
  18087. * @readOnly
  18088. */
  18089. name: '',
  18090. /**
  18091. * @readOnly
  18092. * @type {string}
  18093. */
  18094. mainType: '',
  18095. /**
  18096. * @readOnly
  18097. * @type {string}
  18098. */
  18099. subType: '',
  18100. /**
  18101. * @readOnly
  18102. * @type {number}
  18103. */
  18104. componentIndex: 0,
  18105. /**
  18106. * @type {Object}
  18107. * @protected
  18108. */
  18109. defaultOption: null,
  18110. /**
  18111. * @type {module:echarts/model/Global}
  18112. * @readOnly
  18113. */
  18114. ecModel: null,
  18115. /**
  18116. * key: componentType
  18117. * value: Component model list, can not be null.
  18118. * @type {Object.<string, Array.<module:echarts/model/Model>>}
  18119. * @readOnly
  18120. */
  18121. dependentModels: [],
  18122. /**
  18123. * @type {string}
  18124. * @readOnly
  18125. */
  18126. uid: null,
  18127. /**
  18128. * Support merge layout params.
  18129. * Only support 'box' now (left/right/top/bottom/width/height).
  18130. * @type {string|Object} Object can be {ignoreSize: true}
  18131. * @readOnly
  18132. */
  18133. layoutMode: null,
  18134. $constructor: function (option, parentModel, ecModel, extraOpt) {
  18135. Model.call(this, option, parentModel, ecModel, extraOpt);
  18136. this.uid = getUID('ec_cpt_model');
  18137. },
  18138. init: function (option, parentModel, ecModel, extraOpt) {
  18139. this.mergeDefaultAndTheme(option, ecModel);
  18140. },
  18141. mergeDefaultAndTheme: function (option, ecModel) {
  18142. var layoutMode = this.layoutMode;
  18143. var inputPositionParams = layoutMode
  18144. ? getLayoutParams(option) : {};
  18145. var themeModel = ecModel.getTheme();
  18146. merge(option, themeModel.get(this.mainType));
  18147. merge(option, this.getDefaultOption());
  18148. if (layoutMode) {
  18149. mergeLayoutParam(option, inputPositionParams, layoutMode);
  18150. }
  18151. },
  18152. mergeOption: function (option, extraOpt) {
  18153. merge(this.option, option, true);
  18154. var layoutMode = this.layoutMode;
  18155. if (layoutMode) {
  18156. mergeLayoutParam(this.option, option, layoutMode);
  18157. }
  18158. },
  18159. // Hooker after init or mergeOption
  18160. optionUpdated: function (newCptOption, isInit) {},
  18161. getDefaultOption: function () {
  18162. var fields = inner$1(this);
  18163. if (!fields.defaultOption) {
  18164. var optList = [];
  18165. var Class = this.constructor;
  18166. while (Class) {
  18167. var opt = Class.prototype.defaultOption;
  18168. opt && optList.push(opt);
  18169. Class = Class.superClass;
  18170. }
  18171. var defaultOption = {};
  18172. for (var i = optList.length - 1; i >= 0; i--) {
  18173. defaultOption = merge(defaultOption, optList[i], true);
  18174. }
  18175. fields.defaultOption = defaultOption;
  18176. }
  18177. return fields.defaultOption;
  18178. },
  18179. getReferringComponents: function (mainType) {
  18180. return this.ecModel.queryComponents({
  18181. mainType: mainType,
  18182. index: this.get(mainType + 'Index', true),
  18183. id: this.get(mainType + 'Id', true)
  18184. });
  18185. }
  18186. });
  18187. // Reset ComponentModel.extend, add preConstruct.
  18188. // clazzUtil.enableClassExtend(
  18189. // ComponentModel,
  18190. // function (option, parentModel, ecModel, extraOpt) {
  18191. // // Set dependentModels, componentIndex, name, id, mainType, subType.
  18192. // zrUtil.extend(this, extraOpt);
  18193. // this.uid = componentUtil.getUID('componentModel');
  18194. // // this.setReadOnly([
  18195. // // 'type', 'id', 'uid', 'name', 'mainType', 'subType',
  18196. // // 'dependentModels', 'componentIndex'
  18197. // // ]);
  18198. // }
  18199. // );
  18200. // Add capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  18201. enableClassManagement(
  18202. ComponentModel, {registerWhenExtend: true}
  18203. );
  18204. enableSubTypeDefaulter(ComponentModel);
  18205. // Add capability of ComponentModel.topologicalTravel.
  18206. enableTopologicalTravel(ComponentModel, getDependencies);
  18207. function getDependencies(componentType) {
  18208. var deps = [];
  18209. each$1(ComponentModel.getClassesByMainType(componentType), function (Clazz) {
  18210. deps = deps.concat(Clazz.prototype.dependencies || []);
  18211. });
  18212. // Ensure main type.
  18213. deps = map(deps, function (type) {
  18214. return parseClassType$1(type).main;
  18215. });
  18216. // Hack dataset for convenience.
  18217. if (componentType !== 'dataset' && indexOf(deps, 'dataset') <= 0) {
  18218. deps.unshift('dataset');
  18219. }
  18220. return deps;
  18221. }
  18222. mixin(ComponentModel, boxLayoutMixin);
  18223. /*
  18224. * Licensed to the Apache Software Foundation (ASF) under one
  18225. * or more contributor license agreements. See the NOTICE file
  18226. * distributed with this work for additional information
  18227. * regarding copyright ownership. The ASF licenses this file
  18228. * to you under the Apache License, Version 2.0 (the
  18229. * "License"); you may not use this file except in compliance
  18230. * with the License. You may obtain a copy of the License at
  18231. *
  18232. * http://www.apache.org/licenses/LICENSE-2.0
  18233. *
  18234. * Unless required by applicable law or agreed to in writing,
  18235. * software distributed under the License is distributed on an
  18236. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18237. * KIND, either express or implied. See the License for the
  18238. * specific language governing permissions and limitations
  18239. * under the License.
  18240. */
  18241. var platform = '';
  18242. // Navigator not exists in node
  18243. if (typeof navigator !== 'undefined') {
  18244. platform = navigator.platform || '';
  18245. }
  18246. var globalDefault = {
  18247. // backgroundColor: 'rgba(0,0,0,0)',
  18248. // https://dribbble.com/shots/1065960-Infographic-Pie-chart-visualization
  18249. // color: ['#5793f3', '#d14a61', '#fd9c35', '#675bba', '#fec42c', '#dd4444', '#d4df5a', '#cd4870'],
  18250. // Light colors:
  18251. // color: ['#bcd3bb', '#e88f70', '#edc1a5', '#9dc5c8', '#e1e8c8', '#7b7c68', '#e5b5b5', '#f0b489', '#928ea8', '#bda29a'],
  18252. // color: ['#cc5664', '#9bd6ec', '#ea946e', '#8acaaa', '#f1ec64', '#ee8686', '#a48dc1', '#5da6bc', '#b9dcae'],
  18253. // Dark colors:
  18254. color: [
  18255. '#c23531', '#2f4554', '#61a0a8', '#d48265', '#91c7ae', '#749f83',
  18256. '#ca8622', '#bda29a', '#6e7074', '#546570', '#c4ccd3'
  18257. ],
  18258. gradientColor: ['#f6efa6', '#d88273', '#bf444c'],
  18259. // If xAxis and yAxis declared, grid is created by default.
  18260. // grid: {},
  18261. textStyle: {
  18262. // color: '#000',
  18263. // decoration: 'none',
  18264. // PENDING
  18265. fontFamily: platform.match(/^Win/) ? 'Microsoft YaHei' : 'sans-serif',
  18266. // fontFamily: 'Arial, Verdana, sans-serif',
  18267. fontSize: 12,
  18268. fontStyle: 'normal',
  18269. fontWeight: 'normal'
  18270. },
  18271. // http://blogs.adobe.com/webplatform/2014/02/24/using-blend-modes-in-html-canvas/
  18272. // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  18273. // Default is source-over
  18274. blendMode: null,
  18275. animation: 'auto',
  18276. animationDuration: 1000,
  18277. animationDurationUpdate: 300,
  18278. animationEasing: 'exponentialOut',
  18279. animationEasingUpdate: 'cubicOut',
  18280. animationThreshold: 2000,
  18281. // Configuration for progressive/incremental rendering
  18282. progressiveThreshold: 3000,
  18283. progressive: 400,
  18284. // Threshold of if use single hover layer to optimize.
  18285. // It is recommended that `hoverLayerThreshold` is equivalent to or less than
  18286. // `progressiveThreshold`, otherwise hover will cause restart of progressive,
  18287. // which is unexpected.
  18288. // see example <echarts/test/heatmap-large.html>.
  18289. hoverLayerThreshold: 3000,
  18290. // See: module:echarts/scale/Time
  18291. useUTC: false
  18292. };
  18293. /*
  18294. * Licensed to the Apache Software Foundation (ASF) under one
  18295. * or more contributor license agreements. See the NOTICE file
  18296. * distributed with this work for additional information
  18297. * regarding copyright ownership. The ASF licenses this file
  18298. * to you under the Apache License, Version 2.0 (the
  18299. * "License"); you may not use this file except in compliance
  18300. * with the License. You may obtain a copy of the License at
  18301. *
  18302. * http://www.apache.org/licenses/LICENSE-2.0
  18303. *
  18304. * Unless required by applicable law or agreed to in writing,
  18305. * software distributed under the License is distributed on an
  18306. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18307. * KIND, either express or implied. See the License for the
  18308. * specific language governing permissions and limitations
  18309. * under the License.
  18310. */
  18311. var inner$2 = makeInner();
  18312. function getNearestColorPalette(colors, requestColorNum) {
  18313. var paletteNum = colors.length;
  18314. // TODO colors must be in order
  18315. for (var i = 0; i < paletteNum; i++) {
  18316. if (colors[i].length > requestColorNum) {
  18317. return colors[i];
  18318. }
  18319. }
  18320. return colors[paletteNum - 1];
  18321. }
  18322. var colorPaletteMixin = {
  18323. clearColorPalette: function () {
  18324. inner$2(this).colorIdx = 0;
  18325. inner$2(this).colorNameMap = {};
  18326. },
  18327. /**
  18328. * @param {string} name MUST NOT be null/undefined. Otherwise call this function
  18329. * twise with the same parameters will get different result.
  18330. * @param {Object} [scope=this]
  18331. * @param {Object} [requestColorNum]
  18332. * @return {string} color string.
  18333. */
  18334. getColorFromPalette: function (name, scope, requestColorNum) {
  18335. scope = scope || this;
  18336. var scopeFields = inner$2(scope);
  18337. var colorIdx = scopeFields.colorIdx || 0;
  18338. var colorNameMap = scopeFields.colorNameMap = scopeFields.colorNameMap || {};
  18339. // Use `hasOwnProperty` to avoid conflict with Object.prototype.
  18340. if (colorNameMap.hasOwnProperty(name)) {
  18341. return colorNameMap[name];
  18342. }
  18343. var defaultColorPalette = normalizeToArray(this.get('color', true));
  18344. var layeredColorPalette = this.get('colorLayer', true);
  18345. var colorPalette = ((requestColorNum == null || !layeredColorPalette)
  18346. ? defaultColorPalette : getNearestColorPalette(layeredColorPalette, requestColorNum));
  18347. // In case can't find in layered color palette.
  18348. colorPalette = colorPalette || defaultColorPalette;
  18349. if (!colorPalette || !colorPalette.length) {
  18350. return;
  18351. }
  18352. var color = colorPalette[colorIdx];
  18353. if (name) {
  18354. colorNameMap[name] = color;
  18355. }
  18356. scopeFields.colorIdx = (colorIdx + 1) % colorPalette.length;
  18357. return color;
  18358. }
  18359. };
  18360. /*
  18361. * Licensed to the Apache Software Foundation (ASF) under one
  18362. * or more contributor license agreements. See the NOTICE file
  18363. * distributed with this work for additional information
  18364. * regarding copyright ownership. The ASF licenses this file
  18365. * to you under the Apache License, Version 2.0 (the
  18366. * "License"); you may not use this file except in compliance
  18367. * with the License. You may obtain a copy of the License at
  18368. *
  18369. * http://www.apache.org/licenses/LICENSE-2.0
  18370. *
  18371. * Unless required by applicable law or agreed to in writing,
  18372. * software distributed under the License is distributed on an
  18373. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18374. * KIND, either express or implied. See the License for the
  18375. * specific language governing permissions and limitations
  18376. * under the License.
  18377. */
  18378. // Avoid typo.
  18379. var SOURCE_FORMAT_ORIGINAL = 'original';
  18380. var SOURCE_FORMAT_ARRAY_ROWS = 'arrayRows';
  18381. var SOURCE_FORMAT_OBJECT_ROWS = 'objectRows';
  18382. var SOURCE_FORMAT_KEYED_COLUMNS = 'keyedColumns';
  18383. var SOURCE_FORMAT_UNKNOWN = 'unknown';
  18384. // ??? CHANGE A NAME
  18385. var SOURCE_FORMAT_TYPED_ARRAY = 'typedArray';
  18386. var SERIES_LAYOUT_BY_COLUMN = 'column';
  18387. var SERIES_LAYOUT_BY_ROW = 'row';
  18388. /*
  18389. * Licensed to the Apache Software Foundation (ASF) under one
  18390. * or more contributor license agreements. See the NOTICE file
  18391. * distributed with this work for additional information
  18392. * regarding copyright ownership. The ASF licenses this file
  18393. * to you under the Apache License, Version 2.0 (the
  18394. * "License"); you may not use this file except in compliance
  18395. * with the License. You may obtain a copy of the License at
  18396. *
  18397. * http://www.apache.org/licenses/LICENSE-2.0
  18398. *
  18399. * Unless required by applicable law or agreed to in writing,
  18400. * software distributed under the License is distributed on an
  18401. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18402. * KIND, either express or implied. See the License for the
  18403. * specific language governing permissions and limitations
  18404. * under the License.
  18405. */
  18406. /**
  18407. * [sourceFormat]
  18408. *
  18409. * + "original":
  18410. * This format is only used in series.data, where
  18411. * itemStyle can be specified in data item.
  18412. *
  18413. * + "arrayRows":
  18414. * [
  18415. * ['product', 'score', 'amount'],
  18416. * ['Matcha Latte', 89.3, 95.8],
  18417. * ['Milk Tea', 92.1, 89.4],
  18418. * ['Cheese Cocoa', 94.4, 91.2],
  18419. * ['Walnut Brownie', 85.4, 76.9]
  18420. * ]
  18421. *
  18422. * + "objectRows":
  18423. * [
  18424. * {product: 'Matcha Latte', score: 89.3, amount: 95.8},
  18425. * {product: 'Milk Tea', score: 92.1, amount: 89.4},
  18426. * {product: 'Cheese Cocoa', score: 94.4, amount: 91.2},
  18427. * {product: 'Walnut Brownie', score: 85.4, amount: 76.9}
  18428. * ]
  18429. *
  18430. * + "keyedColumns":
  18431. * {
  18432. * 'product': ['Matcha Latte', 'Milk Tea', 'Cheese Cocoa', 'Walnut Brownie'],
  18433. * 'count': [823, 235, 1042, 988],
  18434. * 'score': [95.8, 81.4, 91.2, 76.9]
  18435. * }
  18436. *
  18437. * + "typedArray"
  18438. *
  18439. * + "unknown"
  18440. */
  18441. /**
  18442. * @constructor
  18443. * @param {Object} fields
  18444. * @param {string} fields.sourceFormat
  18445. * @param {Array|Object} fields.fromDataset
  18446. * @param {Array|Object} [fields.data]
  18447. * @param {string} [seriesLayoutBy='column']
  18448. * @param {Array.<Object|string>} [dimensionsDefine]
  18449. * @param {Objet|HashMap} [encodeDefine]
  18450. * @param {number} [startIndex=0]
  18451. * @param {number} [dimensionsDetectCount]
  18452. */
  18453. function Source(fields) {
  18454. /**
  18455. * @type {boolean}
  18456. */
  18457. this.fromDataset = fields.fromDataset;
  18458. /**
  18459. * Not null/undefined.
  18460. * @type {Array|Object}
  18461. */
  18462. this.data = fields.data || (
  18463. fields.sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS ? {} : []
  18464. );
  18465. /**
  18466. * See also "detectSourceFormat".
  18467. * Not null/undefined.
  18468. * @type {string}
  18469. */
  18470. this.sourceFormat = fields.sourceFormat || SOURCE_FORMAT_UNKNOWN;
  18471. /**
  18472. * 'row' or 'column'
  18473. * Not null/undefined.
  18474. * @type {string} seriesLayoutBy
  18475. */
  18476. this.seriesLayoutBy = fields.seriesLayoutBy || SERIES_LAYOUT_BY_COLUMN;
  18477. /**
  18478. * dimensions definition in option.
  18479. * can be null/undefined.
  18480. * @type {Array.<Object|string>}
  18481. */
  18482. this.dimensionsDefine = fields.dimensionsDefine;
  18483. /**
  18484. * encode definition in option.
  18485. * can be null/undefined.
  18486. * @type {Objet|HashMap}
  18487. */
  18488. this.encodeDefine = fields.encodeDefine && createHashMap(fields.encodeDefine);
  18489. /**
  18490. * Not null/undefined, uint.
  18491. * @type {number}
  18492. */
  18493. this.startIndex = fields.startIndex || 0;
  18494. /**
  18495. * Can be null/undefined (when unknown), uint.
  18496. * @type {number}
  18497. */
  18498. this.dimensionsDetectCount = fields.dimensionsDetectCount;
  18499. }
  18500. /**
  18501. * Wrap original series data for some compatibility cases.
  18502. */
  18503. Source.seriesDataToSource = function (data) {
  18504. return new Source({
  18505. data: data,
  18506. sourceFormat: isTypedArray(data)
  18507. ? SOURCE_FORMAT_TYPED_ARRAY
  18508. : SOURCE_FORMAT_ORIGINAL,
  18509. fromDataset: false
  18510. });
  18511. };
  18512. enableClassCheck(Source);
  18513. /*
  18514. * Licensed to the Apache Software Foundation (ASF) under one
  18515. * or more contributor license agreements. See the NOTICE file
  18516. * distributed with this work for additional information
  18517. * regarding copyright ownership. The ASF licenses this file
  18518. * to you under the Apache License, Version 2.0 (the
  18519. * "License"); you may not use this file except in compliance
  18520. * with the License. You may obtain a copy of the License at
  18521. *
  18522. * http://www.apache.org/licenses/LICENSE-2.0
  18523. *
  18524. * Unless required by applicable law or agreed to in writing,
  18525. * software distributed under the License is distributed on an
  18526. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18527. * KIND, either express or implied. See the License for the
  18528. * specific language governing permissions and limitations
  18529. * under the License.
  18530. */
  18531. // The result of `guessOrdinal`.
  18532. var BE_ORDINAL = {
  18533. Must: 1, // Encounter string but not '-' and not number-like.
  18534. Might: 2, // Encounter string but number-like.
  18535. Not: 3 // Other cases
  18536. };
  18537. var inner$3 = makeInner();
  18538. /**
  18539. * @see {module:echarts/data/Source}
  18540. * @param {module:echarts/component/dataset/DatasetModel} datasetModel
  18541. * @return {string} sourceFormat
  18542. */
  18543. function detectSourceFormat(datasetModel) {
  18544. var data = datasetModel.option.source;
  18545. var sourceFormat = SOURCE_FORMAT_UNKNOWN;
  18546. if (isTypedArray(data)) {
  18547. sourceFormat = SOURCE_FORMAT_TYPED_ARRAY;
  18548. }
  18549. else if (isArray(data)) {
  18550. // FIXME Whether tolerate null in top level array?
  18551. if (data.length === 0) {
  18552. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  18553. }
  18554. for (var i = 0, len = data.length; i < len; i++) {
  18555. var item = data[i];
  18556. if (item == null) {
  18557. continue;
  18558. }
  18559. else if (isArray(item)) {
  18560. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  18561. break;
  18562. }
  18563. else if (isObject$1(item)) {
  18564. sourceFormat = SOURCE_FORMAT_OBJECT_ROWS;
  18565. break;
  18566. }
  18567. }
  18568. }
  18569. else if (isObject$1(data)) {
  18570. for (var key in data) {
  18571. if (data.hasOwnProperty(key) && isArrayLike(data[key])) {
  18572. sourceFormat = SOURCE_FORMAT_KEYED_COLUMNS;
  18573. break;
  18574. }
  18575. }
  18576. }
  18577. else if (data != null) {
  18578. throw new Error('Invalid data');
  18579. }
  18580. inner$3(datasetModel).sourceFormat = sourceFormat;
  18581. }
  18582. /**
  18583. * [Scenarios]:
  18584. * (1) Provide source data directly:
  18585. * series: {
  18586. * encode: {...},
  18587. * dimensions: [...]
  18588. * seriesLayoutBy: 'row',
  18589. * data: [[...]]
  18590. * }
  18591. * (2) Refer to datasetModel.
  18592. * series: [{
  18593. * encode: {...}
  18594. * // Ignore datasetIndex means `datasetIndex: 0`
  18595. * // and the dimensions defination in dataset is used
  18596. * }, {
  18597. * encode: {...},
  18598. * seriesLayoutBy: 'column',
  18599. * datasetIndex: 1
  18600. * }]
  18601. *
  18602. * Get data from series itself or datset.
  18603. * @return {module:echarts/data/Source} source
  18604. */
  18605. function getSource(seriesModel) {
  18606. return inner$3(seriesModel).source;
  18607. }
  18608. /**
  18609. * MUST be called before mergeOption of all series.
  18610. * @param {module:echarts/model/Global} ecModel
  18611. */
  18612. function resetSourceDefaulter(ecModel) {
  18613. // `datasetMap` is used to make default encode.
  18614. inner$3(ecModel).datasetMap = createHashMap();
  18615. }
  18616. /**
  18617. * [Caution]:
  18618. * MUST be called after series option merged and
  18619. * before "series.getInitailData()" called.
  18620. *
  18621. * [The rule of making default encode]:
  18622. * Category axis (if exists) alway map to the first dimension.
  18623. * Each other axis occupies a subsequent dimension.
  18624. *
  18625. * [Why make default encode]:
  18626. * Simplify the typing of encode in option, avoiding the case like that:
  18627. * series: [{encode: {x: 0, y: 1}}, {encode: {x: 0, y: 2}}, {encode: {x: 0, y: 3}}],
  18628. * where the "y" have to be manually typed as "1, 2, 3, ...".
  18629. *
  18630. * @param {module:echarts/model/Series} seriesModel
  18631. */
  18632. function prepareSource(seriesModel) {
  18633. var seriesOption = seriesModel.option;
  18634. var data = seriesOption.data;
  18635. var sourceFormat = isTypedArray(data)
  18636. ? SOURCE_FORMAT_TYPED_ARRAY : SOURCE_FORMAT_ORIGINAL;
  18637. var fromDataset = false;
  18638. var seriesLayoutBy = seriesOption.seriesLayoutBy;
  18639. var sourceHeader = seriesOption.sourceHeader;
  18640. var dimensionsDefine = seriesOption.dimensions;
  18641. var datasetModel = getDatasetModel(seriesModel);
  18642. if (datasetModel) {
  18643. var datasetOption = datasetModel.option;
  18644. data = datasetOption.source;
  18645. sourceFormat = inner$3(datasetModel).sourceFormat;
  18646. fromDataset = true;
  18647. // These settings from series has higher priority.
  18648. seriesLayoutBy = seriesLayoutBy || datasetOption.seriesLayoutBy;
  18649. sourceHeader == null && (sourceHeader = datasetOption.sourceHeader);
  18650. dimensionsDefine = dimensionsDefine || datasetOption.dimensions;
  18651. }
  18652. var completeResult = completeBySourceData(
  18653. data, sourceFormat, seriesLayoutBy, sourceHeader, dimensionsDefine
  18654. );
  18655. inner$3(seriesModel).source = new Source({
  18656. data: data,
  18657. fromDataset: fromDataset,
  18658. seriesLayoutBy: seriesLayoutBy,
  18659. sourceFormat: sourceFormat,
  18660. dimensionsDefine: completeResult.dimensionsDefine,
  18661. startIndex: completeResult.startIndex,
  18662. dimensionsDetectCount: completeResult.dimensionsDetectCount,
  18663. // Note: dataset option does not have `encode`.
  18664. encodeDefine: seriesOption.encode
  18665. });
  18666. }
  18667. // return {startIndex, dimensionsDefine, dimensionsCount}
  18668. function completeBySourceData(data, sourceFormat, seriesLayoutBy, sourceHeader, dimensionsDefine) {
  18669. if (!data) {
  18670. return {dimensionsDefine: normalizeDimensionsDefine(dimensionsDefine)};
  18671. }
  18672. var dimensionsDetectCount;
  18673. var startIndex;
  18674. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  18675. // Rule: Most of the first line are string: it is header.
  18676. // Caution: consider a line with 5 string and 1 number,
  18677. // it still can not be sure it is a head, because the
  18678. // 5 string may be 5 values of category columns.
  18679. if (sourceHeader === 'auto' || sourceHeader == null) {
  18680. arrayRowsTravelFirst(function (val) {
  18681. // '-' is regarded as null/undefined.
  18682. if (val != null && val !== '-') {
  18683. if (isString(val)) {
  18684. startIndex == null && (startIndex = 1);
  18685. }
  18686. else {
  18687. startIndex = 0;
  18688. }
  18689. }
  18690. // 10 is an experience number, avoid long loop.
  18691. }, seriesLayoutBy, data, 10);
  18692. }
  18693. else {
  18694. startIndex = sourceHeader ? 1 : 0;
  18695. }
  18696. if (!dimensionsDefine && startIndex === 1) {
  18697. dimensionsDefine = [];
  18698. arrayRowsTravelFirst(function (val, index) {
  18699. dimensionsDefine[index] = val != null ? val : '';
  18700. }, seriesLayoutBy, data);
  18701. }
  18702. dimensionsDetectCount = dimensionsDefine
  18703. ? dimensionsDefine.length
  18704. : seriesLayoutBy === SERIES_LAYOUT_BY_ROW
  18705. ? data.length
  18706. : data[0]
  18707. ? data[0].length
  18708. : null;
  18709. }
  18710. else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  18711. if (!dimensionsDefine) {
  18712. dimensionsDefine = objectRowsCollectDimensions(data);
  18713. }
  18714. }
  18715. else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  18716. if (!dimensionsDefine) {
  18717. dimensionsDefine = [];
  18718. each$1(data, function (colArr, key) {
  18719. dimensionsDefine.push(key);
  18720. });
  18721. }
  18722. }
  18723. else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  18724. var value0 = getDataItemValue(data[0]);
  18725. dimensionsDetectCount = isArray(value0) && value0.length || 1;
  18726. }
  18727. else if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  18728. if (__DEV__) {
  18729. assert$1(!!dimensionsDefine, 'dimensions must be given if data is TypedArray.');
  18730. }
  18731. }
  18732. return {
  18733. startIndex: startIndex,
  18734. dimensionsDefine: normalizeDimensionsDefine(dimensionsDefine),
  18735. dimensionsDetectCount: dimensionsDetectCount
  18736. };
  18737. }
  18738. // Consider dimensions defined like ['A', 'price', 'B', 'price', 'C', 'price'],
  18739. // which is reasonable. But dimension name is duplicated.
  18740. // Returns undefined or an array contains only object without null/undefiend or string.
  18741. function normalizeDimensionsDefine(dimensionsDefine) {
  18742. if (!dimensionsDefine) {
  18743. // The meaning of null/undefined is different from empty array.
  18744. return;
  18745. }
  18746. var nameMap = createHashMap();
  18747. return map(dimensionsDefine, function (item, index) {
  18748. item = extend({}, isObject$1(item) ? item : {name: item});
  18749. // User can set null in dimensions.
  18750. // We dont auto specify name, othewise a given name may
  18751. // cause it be refered unexpectedly.
  18752. if (item.name == null) {
  18753. return item;
  18754. }
  18755. // Also consider number form like 2012.
  18756. item.name += '';
  18757. // User may also specify displayName.
  18758. // displayName will always exists except user not
  18759. // specified or dim name is not specified or detected.
  18760. // (A auto generated dim name will not be used as
  18761. // displayName).
  18762. if (item.displayName == null) {
  18763. item.displayName = item.name;
  18764. }
  18765. var exist = nameMap.get(item.name);
  18766. if (!exist) {
  18767. nameMap.set(item.name, {count: 1});
  18768. }
  18769. else {
  18770. item.name += '-' + exist.count++;
  18771. }
  18772. return item;
  18773. });
  18774. }
  18775. function arrayRowsTravelFirst(cb, seriesLayoutBy, data, maxLoop) {
  18776. maxLoop == null && (maxLoop = Infinity);
  18777. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  18778. for (var i = 0; i < data.length && i < maxLoop; i++) {
  18779. cb(data[i] ? data[i][0] : null, i);
  18780. }
  18781. }
  18782. else {
  18783. var value0 = data[0] || [];
  18784. for (var i = 0; i < value0.length && i < maxLoop; i++) {
  18785. cb(value0[i], i);
  18786. }
  18787. }
  18788. }
  18789. function objectRowsCollectDimensions(data) {
  18790. var firstIndex = 0;
  18791. var obj;
  18792. while (firstIndex < data.length && !(obj = data[firstIndex++])) {} // jshint ignore: line
  18793. if (obj) {
  18794. var dimensions = [];
  18795. each$1(obj, function (value, key) {
  18796. dimensions.push(key);
  18797. });
  18798. return dimensions;
  18799. }
  18800. }
  18801. /**
  18802. * [The strategy of the arrengment of data dimensions for dataset]:
  18803. * "value way": all axes are non-category axes. So series one by one take
  18804. * several (the number is coordSysDims.length) dimensions from dataset.
  18805. * The result of data arrengment of data dimensions like:
  18806. * | ser0_x | ser0_y | ser1_x | ser1_y | ser2_x | ser2_y |
  18807. * "category way": at least one axis is category axis. So the the first data
  18808. * dimension is always mapped to the first category axis and shared by
  18809. * all of the series. The other data dimensions are taken by series like
  18810. * "value way" does.
  18811. * The result of data arrengment of data dimensions like:
  18812. * | ser_shared_x | ser0_y | ser1_y | ser2_y |
  18813. *
  18814. * @param {Array.<Object|string>} coordDimensions [{name: <string>, type: <string>, dimsDef: <Array>}, ...]
  18815. * @param {module:model/Series} seriesModel
  18816. * @param {module:data/Source} source
  18817. * @return {Object} encode Never be `null/undefined`.
  18818. */
  18819. function makeSeriesEncodeForAxisCoordSys(coordDimensions, seriesModel, source) {
  18820. var encode = {};
  18821. var datasetModel = getDatasetModel(seriesModel);
  18822. // Currently only make default when using dataset, util more reqirements occur.
  18823. if (!datasetModel || !coordDimensions) {
  18824. return encode;
  18825. }
  18826. var encodeItemName = [];
  18827. var encodeSeriesName = [];
  18828. var ecModel = seriesModel.ecModel;
  18829. var datasetMap = inner$3(ecModel).datasetMap;
  18830. var key = datasetModel.uid + '_' + source.seriesLayoutBy;
  18831. var baseCategoryDimIndex;
  18832. var categoryWayValueDimStart;
  18833. coordDimensions = coordDimensions.slice();
  18834. each$1(coordDimensions, function (coordDimInfo, coordDimIdx) {
  18835. !isObject$1(coordDimInfo) && (coordDimensions[coordDimIdx] = {name: coordDimInfo});
  18836. if (coordDimInfo.type === 'ordinal' && baseCategoryDimIndex == null) {
  18837. baseCategoryDimIndex = coordDimIdx;
  18838. categoryWayValueDimStart = getDataDimCountOnCoordDim(coordDimensions[coordDimIdx]);
  18839. }
  18840. encode[coordDimInfo.name] = [];
  18841. });
  18842. var datasetRecord = datasetMap.get(key)
  18843. || datasetMap.set(key, {categoryWayDim: categoryWayValueDimStart, valueWayDim: 0});
  18844. // TODO
  18845. // Auto detect first time axis and do arrangement.
  18846. each$1(coordDimensions, function (coordDimInfo, coordDimIdx) {
  18847. var coordDimName = coordDimInfo.name;
  18848. var count = getDataDimCountOnCoordDim(coordDimInfo);
  18849. // In value way.
  18850. if (baseCategoryDimIndex == null) {
  18851. var start = datasetRecord.valueWayDim;
  18852. pushDim(encode[coordDimName], start, count);
  18853. pushDim(encodeSeriesName, start, count);
  18854. datasetRecord.valueWayDim += count;
  18855. // ??? TODO give a better default series name rule?
  18856. // especially when encode x y specified.
  18857. // consider: when mutiple series share one dimension
  18858. // category axis, series name should better use
  18859. // the other dimsion name. On the other hand, use
  18860. // both dimensions name.
  18861. }
  18862. // In category way, the first category axis.
  18863. else if (baseCategoryDimIndex === coordDimIdx) {
  18864. pushDim(encode[coordDimName], 0, count);
  18865. pushDim(encodeItemName, 0, count);
  18866. }
  18867. // In category way, the other axis.
  18868. else {
  18869. var start = datasetRecord.categoryWayDim;
  18870. pushDim(encode[coordDimName], start, count);
  18871. pushDim(encodeSeriesName, start, count);
  18872. datasetRecord.categoryWayDim += count;
  18873. }
  18874. });
  18875. function pushDim(dimIdxArr, idxFrom, idxCount) {
  18876. for (var i = 0; i < idxCount; i++) {
  18877. dimIdxArr.push(idxFrom + i);
  18878. }
  18879. }
  18880. function getDataDimCountOnCoordDim(coordDimInfo) {
  18881. var dimsDef = coordDimInfo.dimsDef;
  18882. return dimsDef ? dimsDef.length : 1;
  18883. }
  18884. encodeItemName.length && (encode.itemName = encodeItemName);
  18885. encodeSeriesName.length && (encode.seriesName = encodeSeriesName);
  18886. return encode;
  18887. }
  18888. /**
  18889. * Work for data like [{name: ..., value: ...}, ...].
  18890. *
  18891. * @param {module:model/Series} seriesModel
  18892. * @param {module:data/Source} source
  18893. * @return {Object} encode Never be `null/undefined`.
  18894. */
  18895. function makeSeriesEncodeForNameBased(seriesModel, source, dimCount) {
  18896. var encode = {};
  18897. var datasetModel = getDatasetModel(seriesModel);
  18898. // Currently only make default when using dataset, util more reqirements occur.
  18899. if (!datasetModel) {
  18900. return encode;
  18901. }
  18902. var sourceFormat = source.sourceFormat;
  18903. var dimensionsDefine = source.dimensionsDefine;
  18904. var potentialNameDimIndex;
  18905. if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS || sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  18906. each$1(dimensionsDefine, function (dim, idx) {
  18907. if ((isObject$1(dim) ? dim.name : dim) === 'name') {
  18908. potentialNameDimIndex = idx;
  18909. }
  18910. });
  18911. }
  18912. // idxResult: {v, n}.
  18913. var idxResult = (function () {
  18914. var idxRes0 = {};
  18915. var idxRes1 = {};
  18916. var guessRecords = [];
  18917. // 5 is an experience value.
  18918. for (var i = 0, len = Math.min(5, dimCount); i < len; i++) {
  18919. var guessResult = doGuessOrdinal(
  18920. source.data, sourceFormat, source.seriesLayoutBy,
  18921. dimensionsDefine, source.startIndex, i
  18922. );
  18923. guessRecords.push(guessResult);
  18924. var isPureNumber = guessResult === BE_ORDINAL.Not;
  18925. // [Strategy of idxRes0]: find the first BE_ORDINAL.Not as the value dim,
  18926. // and then find a name dim with the priority:
  18927. // "BE_ORDINAL.Might|BE_ORDINAL.Must" > "other dim" > "the value dim itself".
  18928. if (isPureNumber && idxRes0.v == null && i !== potentialNameDimIndex) {
  18929. idxRes0.v = i;
  18930. }
  18931. if (idxRes0.n == null
  18932. || (idxRes0.n === idxRes0.v)
  18933. || (!isPureNumber && guessRecords[idxRes0.n] === BE_ORDINAL.Not)
  18934. ) {
  18935. idxRes0.n = i;
  18936. }
  18937. if (fulfilled(idxRes0) && guessRecords[idxRes0.n] !== BE_ORDINAL.Not) {
  18938. return idxRes0;
  18939. }
  18940. // [Strategy of idxRes1]: if idxRes0 not satisfied (that is, no BE_ORDINAL.Not),
  18941. // find the first BE_ORDINAL.Might as the value dim,
  18942. // and then find a name dim with the priority:
  18943. // "other dim" > "the value dim itself".
  18944. // That is for backward compat: number-like (e.g., `'3'`, `'55'`) can be
  18945. // treated as number.
  18946. if (!isPureNumber) {
  18947. if (guessResult === BE_ORDINAL.Might && idxRes1.v == null && i !== potentialNameDimIndex) {
  18948. idxRes1.v = i;
  18949. }
  18950. if (idxRes1.n == null || (idxRes1.n === idxRes1.v)) {
  18951. idxRes1.n = i;
  18952. }
  18953. }
  18954. }
  18955. function fulfilled(idxResult) {
  18956. return idxResult.v != null && idxResult.n != null;
  18957. }
  18958. return fulfilled(idxRes0) ? idxRes0 : fulfilled(idxRes1) ? idxRes1 : null;
  18959. })();
  18960. if (idxResult) {
  18961. encode.value = idxResult.v;
  18962. // `potentialNameDimIndex` has highest priority.
  18963. var nameDimIndex = potentialNameDimIndex != null ? potentialNameDimIndex : idxResult.n;
  18964. // By default, label use itemName in charts.
  18965. // So we dont set encodeLabel here.
  18966. encode.itemName = [nameDimIndex];
  18967. encode.seriesName = [nameDimIndex];
  18968. }
  18969. return encode;
  18970. }
  18971. /**
  18972. * If return null/undefined, indicate that should not use datasetModel.
  18973. */
  18974. function getDatasetModel(seriesModel) {
  18975. var option = seriesModel.option;
  18976. // Caution: consider the scenario:
  18977. // A dataset is declared and a series is not expected to use the dataset,
  18978. // and at the beginning `setOption({series: { noData })` (just prepare other
  18979. // option but no data), then `setOption({series: {data: [...]}); In this case,
  18980. // the user should set an empty array to avoid that dataset is used by default.
  18981. var thisData = option.data;
  18982. if (!thisData) {
  18983. return seriesModel.ecModel.getComponent('dataset', option.datasetIndex || 0);
  18984. }
  18985. }
  18986. /**
  18987. * The rule should not be complex, otherwise user might not
  18988. * be able to known where the data is wrong.
  18989. * The code is ugly, but how to make it neat?
  18990. *
  18991. * @param {module:echars/data/Source} source
  18992. * @param {number} dimIndex
  18993. * @return {BE_ORDINAL} guess result.
  18994. */
  18995. function guessOrdinal(source, dimIndex) {
  18996. return doGuessOrdinal(
  18997. source.data,
  18998. source.sourceFormat,
  18999. source.seriesLayoutBy,
  19000. source.dimensionsDefine,
  19001. source.startIndex,
  19002. dimIndex
  19003. );
  19004. }
  19005. // dimIndex may be overflow source data.
  19006. // return {BE_ORDINAL}
  19007. function doGuessOrdinal(
  19008. data, sourceFormat, seriesLayoutBy, dimensionsDefine, startIndex, dimIndex
  19009. ) {
  19010. var result;
  19011. // Experience value.
  19012. var maxLoop = 5;
  19013. if (isTypedArray(data)) {
  19014. return BE_ORDINAL.Not;
  19015. }
  19016. // When sourceType is 'objectRows' or 'keyedColumns', dimensionsDefine
  19017. // always exists in source.
  19018. var dimName;
  19019. var dimType;
  19020. if (dimensionsDefine) {
  19021. var dimDefItem = dimensionsDefine[dimIndex];
  19022. if (isObject$1(dimDefItem)) {
  19023. dimName = dimDefItem.name;
  19024. dimType = dimDefItem.type;
  19025. }
  19026. else if (isString(dimDefItem)) {
  19027. dimName = dimDefItem;
  19028. }
  19029. }
  19030. if (dimType != null) {
  19031. return dimType === 'ordinal' ? BE_ORDINAL.Must : BE_ORDINAL.Not;
  19032. }
  19033. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  19034. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  19035. var sample = data[dimIndex];
  19036. for (var i = 0; i < (sample || []).length && i < maxLoop; i++) {
  19037. if ((result = detectValue(sample[startIndex + i])) != null) {
  19038. return result;
  19039. }
  19040. }
  19041. }
  19042. else {
  19043. for (var i = 0; i < data.length && i < maxLoop; i++) {
  19044. var row = data[startIndex + i];
  19045. if (row && (result = detectValue(row[dimIndex])) != null) {
  19046. return result;
  19047. }
  19048. }
  19049. }
  19050. }
  19051. else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  19052. if (!dimName) {
  19053. return BE_ORDINAL.Not;
  19054. }
  19055. for (var i = 0; i < data.length && i < maxLoop; i++) {
  19056. var item = data[i];
  19057. if (item && (result = detectValue(item[dimName])) != null) {
  19058. return result;
  19059. }
  19060. }
  19061. }
  19062. else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  19063. if (!dimName) {
  19064. return BE_ORDINAL.Not;
  19065. }
  19066. var sample = data[dimName];
  19067. if (!sample || isTypedArray(sample)) {
  19068. return BE_ORDINAL.Not;
  19069. }
  19070. for (var i = 0; i < sample.length && i < maxLoop; i++) {
  19071. if ((result = detectValue(sample[i])) != null) {
  19072. return result;
  19073. }
  19074. }
  19075. }
  19076. else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  19077. for (var i = 0; i < data.length && i < maxLoop; i++) {
  19078. var item = data[i];
  19079. var val = getDataItemValue(item);
  19080. if (!isArray(val)) {
  19081. return BE_ORDINAL.Not;
  19082. }
  19083. if ((result = detectValue(val[dimIndex])) != null) {
  19084. return result;
  19085. }
  19086. }
  19087. }
  19088. function detectValue(val) {
  19089. var beStr = isString(val);
  19090. // Consider usage convenience, '1', '2' will be treated as "number".
  19091. // `isFinit('')` get `true`.
  19092. if (val != null && isFinite(val) && val !== '') {
  19093. return beStr ? BE_ORDINAL.Might : BE_ORDINAL.Not;
  19094. }
  19095. else if (beStr && val !== '-') {
  19096. return BE_ORDINAL.Must;
  19097. }
  19098. }
  19099. return BE_ORDINAL.Not;
  19100. }
  19101. /*
  19102. * Licensed to the Apache Software Foundation (ASF) under one
  19103. * or more contributor license agreements. See the NOTICE file
  19104. * distributed with this work for additional information
  19105. * regarding copyright ownership. The ASF licenses this file
  19106. * to you under the Apache License, Version 2.0 (the
  19107. * "License"); you may not use this file except in compliance
  19108. * with the License. You may obtain a copy of the License at
  19109. *
  19110. * http://www.apache.org/licenses/LICENSE-2.0
  19111. *
  19112. * Unless required by applicable law or agreed to in writing,
  19113. * software distributed under the License is distributed on an
  19114. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19115. * KIND, either express or implied. See the License for the
  19116. * specific language governing permissions and limitations
  19117. * under the License.
  19118. */
  19119. /**
  19120. * ECharts global model
  19121. *
  19122. * @module {echarts/model/Global}
  19123. */
  19124. /**
  19125. * Caution: If the mechanism should be changed some day, these cases
  19126. * should be considered:
  19127. *
  19128. * (1) In `merge option` mode, if using the same option to call `setOption`
  19129. * many times, the result should be the same (try our best to ensure that).
  19130. * (2) In `merge option` mode, if a component has no id/name specified, it
  19131. * will be merged by index, and the result sequence of the components is
  19132. * consistent to the original sequence.
  19133. * (3) `reset` feature (in toolbox). Find detailed info in comments about
  19134. * `mergeOption` in module:echarts/model/OptionManager.
  19135. */
  19136. var OPTION_INNER_KEY = '\0_ec_inner';
  19137. /**
  19138. * @alias module:echarts/model/Global
  19139. *
  19140. * @param {Object} option
  19141. * @param {module:echarts/model/Model} parentModel
  19142. * @param {Object} theme
  19143. */
  19144. var GlobalModel = Model.extend({
  19145. init: function (option, parentModel, theme, optionManager) {
  19146. theme = theme || {};
  19147. this.option = null; // Mark as not initialized.
  19148. /**
  19149. * @type {module:echarts/model/Model}
  19150. * @private
  19151. */
  19152. this._theme = new Model(theme);
  19153. /**
  19154. * @type {module:echarts/model/OptionManager}
  19155. */
  19156. this._optionManager = optionManager;
  19157. },
  19158. setOption: function (option, optionPreprocessorFuncs) {
  19159. assert$1(
  19160. !(OPTION_INNER_KEY in option),
  19161. 'please use chart.getOption()'
  19162. );
  19163. this._optionManager.setOption(option, optionPreprocessorFuncs);
  19164. this.resetOption(null);
  19165. },
  19166. /**
  19167. * @param {string} type null/undefined: reset all.
  19168. * 'recreate': force recreate all.
  19169. * 'timeline': only reset timeline option
  19170. * 'media': only reset media query option
  19171. * @return {boolean} Whether option changed.
  19172. */
  19173. resetOption: function (type) {
  19174. var optionChanged = false;
  19175. var optionManager = this._optionManager;
  19176. if (!type || type === 'recreate') {
  19177. var baseOption = optionManager.mountOption(type === 'recreate');
  19178. if (!this.option || type === 'recreate') {
  19179. initBase.call(this, baseOption);
  19180. }
  19181. else {
  19182. this.restoreData();
  19183. this.mergeOption(baseOption);
  19184. }
  19185. optionChanged = true;
  19186. }
  19187. if (type === 'timeline' || type === 'media') {
  19188. this.restoreData();
  19189. }
  19190. if (!type || type === 'recreate' || type === 'timeline') {
  19191. var timelineOption = optionManager.getTimelineOption(this);
  19192. timelineOption && (this.mergeOption(timelineOption), optionChanged = true);
  19193. }
  19194. if (!type || type === 'recreate' || type === 'media') {
  19195. var mediaOptions = optionManager.getMediaOption(this, this._api);
  19196. if (mediaOptions.length) {
  19197. each$1(mediaOptions, function (mediaOption) {
  19198. this.mergeOption(mediaOption, optionChanged = true);
  19199. }, this);
  19200. }
  19201. }
  19202. return optionChanged;
  19203. },
  19204. /**
  19205. * @protected
  19206. */
  19207. mergeOption: function (newOption) {
  19208. var option = this.option;
  19209. var componentsMap = this._componentsMap;
  19210. var newCptTypes = [];
  19211. resetSourceDefaulter(this);
  19212. // If no component class, merge directly.
  19213. // For example: color, animaiton options, etc.
  19214. each$1(newOption, function (componentOption, mainType) {
  19215. if (componentOption == null) {
  19216. return;
  19217. }
  19218. if (!ComponentModel.hasClass(mainType)) {
  19219. // globalSettingTask.dirty();
  19220. option[mainType] = option[mainType] == null
  19221. ? clone(componentOption)
  19222. : merge(option[mainType], componentOption, true);
  19223. }
  19224. else if (mainType) {
  19225. newCptTypes.push(mainType);
  19226. }
  19227. });
  19228. ComponentModel.topologicalTravel(
  19229. newCptTypes, ComponentModel.getAllClassMainTypes(), visitComponent, this
  19230. );
  19231. function visitComponent(mainType, dependencies) {
  19232. var newCptOptionList = normalizeToArray(newOption[mainType]);
  19233. var mapResult = mappingToExists(
  19234. componentsMap.get(mainType), newCptOptionList
  19235. );
  19236. makeIdAndName(mapResult);
  19237. // Set mainType and complete subType.
  19238. each$1(mapResult, function (item, index) {
  19239. var opt = item.option;
  19240. if (isObject$1(opt)) {
  19241. item.keyInfo.mainType = mainType;
  19242. item.keyInfo.subType = determineSubType(mainType, opt, item.exist);
  19243. }
  19244. });
  19245. var dependentModels = getComponentsByTypes(
  19246. componentsMap, dependencies
  19247. );
  19248. option[mainType] = [];
  19249. componentsMap.set(mainType, []);
  19250. each$1(mapResult, function (resultItem, index) {
  19251. var componentModel = resultItem.exist;
  19252. var newCptOption = resultItem.option;
  19253. assert$1(
  19254. isObject$1(newCptOption) || componentModel,
  19255. 'Empty component definition'
  19256. );
  19257. // Consider where is no new option and should be merged using {},
  19258. // see removeEdgeAndAdd in topologicalTravel and
  19259. // ComponentModel.getAllClassMainTypes.
  19260. if (!newCptOption) {
  19261. componentModel.mergeOption({}, this);
  19262. componentModel.optionUpdated({}, false);
  19263. }
  19264. else {
  19265. var ComponentModelClass = ComponentModel.getClass(
  19266. mainType, resultItem.keyInfo.subType, true
  19267. );
  19268. if (componentModel && componentModel.constructor === ComponentModelClass) {
  19269. componentModel.name = resultItem.keyInfo.name;
  19270. // componentModel.settingTask && componentModel.settingTask.dirty();
  19271. componentModel.mergeOption(newCptOption, this);
  19272. componentModel.optionUpdated(newCptOption, false);
  19273. }
  19274. else {
  19275. // PENDING Global as parent ?
  19276. var extraOpt = extend(
  19277. {
  19278. dependentModels: dependentModels,
  19279. componentIndex: index
  19280. },
  19281. resultItem.keyInfo
  19282. );
  19283. componentModel = new ComponentModelClass(
  19284. newCptOption, this, this, extraOpt
  19285. );
  19286. extend(componentModel, extraOpt);
  19287. componentModel.init(newCptOption, this, this, extraOpt);
  19288. // Call optionUpdated after init.
  19289. // newCptOption has been used as componentModel.option
  19290. // and may be merged with theme and default, so pass null
  19291. // to avoid confusion.
  19292. componentModel.optionUpdated(null, true);
  19293. }
  19294. }
  19295. componentsMap.get(mainType)[index] = componentModel;
  19296. option[mainType][index] = componentModel.option;
  19297. }, this);
  19298. // Backup series for filtering.
  19299. if (mainType === 'series') {
  19300. createSeriesIndices(this, componentsMap.get('series'));
  19301. }
  19302. }
  19303. this._seriesIndicesMap = createHashMap(
  19304. this._seriesIndices = this._seriesIndices || []
  19305. );
  19306. },
  19307. /**
  19308. * Get option for output (cloned option and inner info removed)
  19309. * @public
  19310. * @return {Object}
  19311. */
  19312. getOption: function () {
  19313. var option = clone(this.option);
  19314. each$1(option, function (opts, mainType) {
  19315. if (ComponentModel.hasClass(mainType)) {
  19316. var opts = normalizeToArray(opts);
  19317. for (var i = opts.length - 1; i >= 0; i--) {
  19318. // Remove options with inner id.
  19319. if (isIdInner(opts[i])) {
  19320. opts.splice(i, 1);
  19321. }
  19322. }
  19323. option[mainType] = opts;
  19324. }
  19325. });
  19326. delete option[OPTION_INNER_KEY];
  19327. return option;
  19328. },
  19329. /**
  19330. * @return {module:echarts/model/Model}
  19331. */
  19332. getTheme: function () {
  19333. return this._theme;
  19334. },
  19335. /**
  19336. * @param {string} mainType
  19337. * @param {number} [idx=0]
  19338. * @return {module:echarts/model/Component}
  19339. */
  19340. getComponent: function (mainType, idx) {
  19341. var list = this._componentsMap.get(mainType);
  19342. if (list) {
  19343. return list[idx || 0];
  19344. }
  19345. },
  19346. /**
  19347. * If none of index and id and name used, return all components with mainType.
  19348. * @param {Object} condition
  19349. * @param {string} condition.mainType
  19350. * @param {string} [condition.subType] If ignore, only query by mainType
  19351. * @param {number|Array.<number>} [condition.index] Either input index or id or name.
  19352. * @param {string|Array.<string>} [condition.id] Either input index or id or name.
  19353. * @param {string|Array.<string>} [condition.name] Either input index or id or name.
  19354. * @return {Array.<module:echarts/model/Component>}
  19355. */
  19356. queryComponents: function (condition) {
  19357. var mainType = condition.mainType;
  19358. if (!mainType) {
  19359. return [];
  19360. }
  19361. var index = condition.index;
  19362. var id = condition.id;
  19363. var name = condition.name;
  19364. var cpts = this._componentsMap.get(mainType);
  19365. if (!cpts || !cpts.length) {
  19366. return [];
  19367. }
  19368. var result;
  19369. if (index != null) {
  19370. if (!isArray(index)) {
  19371. index = [index];
  19372. }
  19373. result = filter(map(index, function (idx) {
  19374. return cpts[idx];
  19375. }), function (val) {
  19376. return !!val;
  19377. });
  19378. }
  19379. else if (id != null) {
  19380. var isIdArray = isArray(id);
  19381. result = filter(cpts, function (cpt) {
  19382. return (isIdArray && indexOf(id, cpt.id) >= 0)
  19383. || (!isIdArray && cpt.id === id);
  19384. });
  19385. }
  19386. else if (name != null) {
  19387. var isNameArray = isArray(name);
  19388. result = filter(cpts, function (cpt) {
  19389. return (isNameArray && indexOf(name, cpt.name) >= 0)
  19390. || (!isNameArray && cpt.name === name);
  19391. });
  19392. }
  19393. else {
  19394. // Return all components with mainType
  19395. result = cpts.slice();
  19396. }
  19397. return filterBySubType(result, condition);
  19398. },
  19399. /**
  19400. * The interface is different from queryComponents,
  19401. * which is convenient for inner usage.
  19402. *
  19403. * @usage
  19404. * var result = findComponents(
  19405. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}}
  19406. * );
  19407. * var result = findComponents(
  19408. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}}
  19409. * );
  19410. * var result = findComponents(
  19411. * {mainType: 'series',
  19412. * filter: function (model, index) {...}}
  19413. * );
  19414. * // result like [component0, componnet1, ...]
  19415. *
  19416. * @param {Object} condition
  19417. * @param {string} condition.mainType Mandatory.
  19418. * @param {string} [condition.subType] Optional.
  19419. * @param {Object} [condition.query] like {xxxIndex, xxxId, xxxName},
  19420. * where xxx is mainType.
  19421. * If query attribute is null/undefined or has no index/id/name,
  19422. * do not filtering by query conditions, which is convenient for
  19423. * no-payload situations or when target of action is global.
  19424. * @param {Function} [condition.filter] parameter: component, return boolean.
  19425. * @return {Array.<module:echarts/model/Component>}
  19426. */
  19427. findComponents: function (condition) {
  19428. var query = condition.query;
  19429. var mainType = condition.mainType;
  19430. var queryCond = getQueryCond(query);
  19431. var result = queryCond
  19432. ? this.queryComponents(queryCond)
  19433. : this._componentsMap.get(mainType);
  19434. return doFilter(filterBySubType(result, condition));
  19435. function getQueryCond(q) {
  19436. var indexAttr = mainType + 'Index';
  19437. var idAttr = mainType + 'Id';
  19438. var nameAttr = mainType + 'Name';
  19439. return q && (
  19440. q[indexAttr] != null
  19441. || q[idAttr] != null
  19442. || q[nameAttr] != null
  19443. )
  19444. ? {
  19445. mainType: mainType,
  19446. // subType will be filtered finally.
  19447. index: q[indexAttr],
  19448. id: q[idAttr],
  19449. name: q[nameAttr]
  19450. }
  19451. : null;
  19452. }
  19453. function doFilter(res) {
  19454. return condition.filter
  19455. ? filter(res, condition.filter)
  19456. : res;
  19457. }
  19458. },
  19459. /**
  19460. * @usage
  19461. * eachComponent('legend', function (legendModel, index) {
  19462. * ...
  19463. * });
  19464. * eachComponent(function (componentType, model, index) {
  19465. * // componentType does not include subType
  19466. * // (componentType is 'xxx' but not 'xxx.aa')
  19467. * });
  19468. * eachComponent(
  19469. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}},
  19470. * function (model, index) {...}
  19471. * );
  19472. * eachComponent(
  19473. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}},
  19474. * function (model, index) {...}
  19475. * );
  19476. *
  19477. * @param {string|Object=} mainType When mainType is object, the definition
  19478. * is the same as the method 'findComponents'.
  19479. * @param {Function} cb
  19480. * @param {*} context
  19481. */
  19482. eachComponent: function (mainType, cb, context) {
  19483. var componentsMap = this._componentsMap;
  19484. if (typeof mainType === 'function') {
  19485. context = cb;
  19486. cb = mainType;
  19487. componentsMap.each(function (components, componentType) {
  19488. each$1(components, function (component, index) {
  19489. cb.call(context, componentType, component, index);
  19490. });
  19491. });
  19492. }
  19493. else if (isString(mainType)) {
  19494. each$1(componentsMap.get(mainType), cb, context);
  19495. }
  19496. else if (isObject$1(mainType)) {
  19497. var queryResult = this.findComponents(mainType);
  19498. each$1(queryResult, cb, context);
  19499. }
  19500. },
  19501. /**
  19502. * @param {string} name
  19503. * @return {Array.<module:echarts/model/Series>}
  19504. */
  19505. getSeriesByName: function (name) {
  19506. var series = this._componentsMap.get('series');
  19507. return filter(series, function (oneSeries) {
  19508. return oneSeries.name === name;
  19509. });
  19510. },
  19511. /**
  19512. * @param {number} seriesIndex
  19513. * @return {module:echarts/model/Series}
  19514. */
  19515. getSeriesByIndex: function (seriesIndex) {
  19516. return this._componentsMap.get('series')[seriesIndex];
  19517. },
  19518. /**
  19519. * Get series list before filtered by type.
  19520. * FIXME: rename to getRawSeriesByType?
  19521. *
  19522. * @param {string} subType
  19523. * @return {Array.<module:echarts/model/Series>}
  19524. */
  19525. getSeriesByType: function (subType) {
  19526. var series = this._componentsMap.get('series');
  19527. return filter(series, function (oneSeries) {
  19528. return oneSeries.subType === subType;
  19529. });
  19530. },
  19531. /**
  19532. * @return {Array.<module:echarts/model/Series>}
  19533. */
  19534. getSeries: function () {
  19535. return this._componentsMap.get('series').slice();
  19536. },
  19537. /**
  19538. * @return {number}
  19539. */
  19540. getSeriesCount: function () {
  19541. return this._componentsMap.get('series').length;
  19542. },
  19543. /**
  19544. * After filtering, series may be different
  19545. * frome raw series.
  19546. *
  19547. * @param {Function} cb
  19548. * @param {*} context
  19549. */
  19550. eachSeries: function (cb, context) {
  19551. assertSeriesInitialized(this);
  19552. each$1(this._seriesIndices, function (rawSeriesIndex) {
  19553. var series = this._componentsMap.get('series')[rawSeriesIndex];
  19554. cb.call(context, series, rawSeriesIndex);
  19555. }, this);
  19556. },
  19557. /**
  19558. * Iterate raw series before filtered.
  19559. *
  19560. * @param {Function} cb
  19561. * @param {*} context
  19562. */
  19563. eachRawSeries: function (cb, context) {
  19564. each$1(this._componentsMap.get('series'), cb, context);
  19565. },
  19566. /**
  19567. * After filtering, series may be different.
  19568. * frome raw series.
  19569. *
  19570. * @param {string} subType.
  19571. * @param {Function} cb
  19572. * @param {*} context
  19573. */
  19574. eachSeriesByType: function (subType, cb, context) {
  19575. assertSeriesInitialized(this);
  19576. each$1(this._seriesIndices, function (rawSeriesIndex) {
  19577. var series = this._componentsMap.get('series')[rawSeriesIndex];
  19578. if (series.subType === subType) {
  19579. cb.call(context, series, rawSeriesIndex);
  19580. }
  19581. }, this);
  19582. },
  19583. /**
  19584. * Iterate raw series before filtered of given type.
  19585. *
  19586. * @parma {string} subType
  19587. * @param {Function} cb
  19588. * @param {*} context
  19589. */
  19590. eachRawSeriesByType: function (subType, cb, context) {
  19591. return each$1(this.getSeriesByType(subType), cb, context);
  19592. },
  19593. /**
  19594. * @param {module:echarts/model/Series} seriesModel
  19595. */
  19596. isSeriesFiltered: function (seriesModel) {
  19597. assertSeriesInitialized(this);
  19598. return this._seriesIndicesMap.get(seriesModel.componentIndex) == null;
  19599. },
  19600. /**
  19601. * @return {Array.<number>}
  19602. */
  19603. getCurrentSeriesIndices: function () {
  19604. return (this._seriesIndices || []).slice();
  19605. },
  19606. /**
  19607. * @param {Function} cb
  19608. * @param {*} context
  19609. */
  19610. filterSeries: function (cb, context) {
  19611. assertSeriesInitialized(this);
  19612. var filteredSeries = filter(
  19613. this._componentsMap.get('series'), cb, context
  19614. );
  19615. createSeriesIndices(this, filteredSeries);
  19616. },
  19617. restoreData: function (payload) {
  19618. var componentsMap = this._componentsMap;
  19619. createSeriesIndices(this, componentsMap.get('series'));
  19620. var componentTypes = [];
  19621. componentsMap.each(function (components, componentType) {
  19622. componentTypes.push(componentType);
  19623. });
  19624. ComponentModel.topologicalTravel(
  19625. componentTypes,
  19626. ComponentModel.getAllClassMainTypes(),
  19627. function (componentType, dependencies) {
  19628. each$1(componentsMap.get(componentType), function (component) {
  19629. (componentType !== 'series' || !isNotTargetSeries(component, payload))
  19630. && component.restoreData();
  19631. });
  19632. }
  19633. );
  19634. }
  19635. });
  19636. function isNotTargetSeries(seriesModel, payload) {
  19637. if (payload) {
  19638. var index = payload.seiresIndex;
  19639. var id = payload.seriesId;
  19640. var name = payload.seriesName;
  19641. return (index != null && seriesModel.componentIndex !== index)
  19642. || (id != null && seriesModel.id !== id)
  19643. || (name != null && seriesModel.name !== name);
  19644. }
  19645. }
  19646. /**
  19647. * @inner
  19648. */
  19649. function mergeTheme(option, theme) {
  19650. // PENDING
  19651. // NOT use `colorLayer` in theme if option has `color`
  19652. var notMergeColorLayer = option.color && !option.colorLayer;
  19653. each$1(theme, function (themeItem, name) {
  19654. if (name === 'colorLayer' && notMergeColorLayer) {
  19655. return;
  19656. }
  19657. // 如果有 component model 则把具体的 merge 逻辑交给该 model 处理
  19658. if (!ComponentModel.hasClass(name)) {
  19659. if (typeof themeItem === 'object') {
  19660. option[name] = !option[name]
  19661. ? clone(themeItem)
  19662. : merge(option[name], themeItem, false);
  19663. }
  19664. else {
  19665. if (option[name] == null) {
  19666. option[name] = themeItem;
  19667. }
  19668. }
  19669. }
  19670. });
  19671. }
  19672. function initBase(baseOption) {
  19673. baseOption = baseOption;
  19674. // Using OPTION_INNER_KEY to mark that this option can not be used outside,
  19675. // i.e. `chart.setOption(chart.getModel().option);` is forbiden.
  19676. this.option = {};
  19677. this.option[OPTION_INNER_KEY] = 1;
  19678. /**
  19679. * Init with series: [], in case of calling findSeries method
  19680. * before series initialized.
  19681. * @type {Object.<string, Array.<module:echarts/model/Model>>}
  19682. * @private
  19683. */
  19684. this._componentsMap = createHashMap({series: []});
  19685. /**
  19686. * Mapping between filtered series list and raw series list.
  19687. * key: filtered series indices, value: raw series indices.
  19688. * @type {Array.<nubmer>}
  19689. * @private
  19690. */
  19691. this._seriesIndices;
  19692. this._seriesIndicesMap;
  19693. mergeTheme(baseOption, this._theme.option);
  19694. // TODO Needs clone when merging to the unexisted property
  19695. merge(baseOption, globalDefault, false);
  19696. this.mergeOption(baseOption);
  19697. }
  19698. /**
  19699. * @inner
  19700. * @param {Array.<string>|string} types model types
  19701. * @return {Object} key: {string} type, value: {Array.<Object>} models
  19702. */
  19703. function getComponentsByTypes(componentsMap, types) {
  19704. if (!isArray(types)) {
  19705. types = types ? [types] : [];
  19706. }
  19707. var ret = {};
  19708. each$1(types, function (type) {
  19709. ret[type] = (componentsMap.get(type) || []).slice();
  19710. });
  19711. return ret;
  19712. }
  19713. /**
  19714. * @inner
  19715. */
  19716. function determineSubType(mainType, newCptOption, existComponent) {
  19717. var subType = newCptOption.type
  19718. ? newCptOption.type
  19719. : existComponent
  19720. ? existComponent.subType
  19721. // Use determineSubType only when there is no existComponent.
  19722. : ComponentModel.determineSubType(mainType, newCptOption);
  19723. // tooltip, markline, markpoint may always has no subType
  19724. return subType;
  19725. }
  19726. /**
  19727. * @inner
  19728. */
  19729. function createSeriesIndices(ecModel, seriesModels) {
  19730. ecModel._seriesIndicesMap = createHashMap(
  19731. ecModel._seriesIndices = map(seriesModels, function (series) {
  19732. return series.componentIndex;
  19733. }) || []
  19734. );
  19735. }
  19736. /**
  19737. * @inner
  19738. */
  19739. function filterBySubType(components, condition) {
  19740. // Using hasOwnProperty for restrict. Consider
  19741. // subType is undefined in user payload.
  19742. return condition.hasOwnProperty('subType')
  19743. ? filter(components, function (cpt) {
  19744. return cpt.subType === condition.subType;
  19745. })
  19746. : components;
  19747. }
  19748. /**
  19749. * @inner
  19750. */
  19751. function assertSeriesInitialized(ecModel) {
  19752. // Components that use _seriesIndices should depends on series component,
  19753. // which make sure that their initialization is after series.
  19754. if (__DEV__) {
  19755. if (!ecModel._seriesIndices) {
  19756. throw new Error('Option should contains series.');
  19757. }
  19758. }
  19759. }
  19760. mixin(GlobalModel, colorPaletteMixin);
  19761. /*
  19762. * Licensed to the Apache Software Foundation (ASF) under one
  19763. * or more contributor license agreements. See the NOTICE file
  19764. * distributed with this work for additional information
  19765. * regarding copyright ownership. The ASF licenses this file
  19766. * to you under the Apache License, Version 2.0 (the
  19767. * "License"); you may not use this file except in compliance
  19768. * with the License. You may obtain a copy of the License at
  19769. *
  19770. * http://www.apache.org/licenses/LICENSE-2.0
  19771. *
  19772. * Unless required by applicable law or agreed to in writing,
  19773. * software distributed under the License is distributed on an
  19774. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19775. * KIND, either express or implied. See the License for the
  19776. * specific language governing permissions and limitations
  19777. * under the License.
  19778. */
  19779. var echartsAPIList = [
  19780. 'getDom', 'getZr', 'getWidth', 'getHeight', 'getDevicePixelRatio', 'dispatchAction', 'isDisposed',
  19781. 'on', 'off', 'getDataURL', 'getConnectedDataURL', 'getModel', 'getOption',
  19782. 'getViewOfComponentModel', 'getViewOfSeriesModel'
  19783. ];
  19784. // And `getCoordinateSystems` and `getComponentByElement` will be injected in echarts.js
  19785. function ExtensionAPI(chartInstance) {
  19786. each$1(echartsAPIList, function (name) {
  19787. this[name] = bind(chartInstance[name], chartInstance);
  19788. }, this);
  19789. }
  19790. /*
  19791. * Licensed to the Apache Software Foundation (ASF) under one
  19792. * or more contributor license agreements. See the NOTICE file
  19793. * distributed with this work for additional information
  19794. * regarding copyright ownership. The ASF licenses this file
  19795. * to you under the Apache License, Version 2.0 (the
  19796. * "License"); you may not use this file except in compliance
  19797. * with the License. You may obtain a copy of the License at
  19798. *
  19799. * http://www.apache.org/licenses/LICENSE-2.0
  19800. *
  19801. * Unless required by applicable law or agreed to in writing,
  19802. * software distributed under the License is distributed on an
  19803. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19804. * KIND, either express or implied. See the License for the
  19805. * specific language governing permissions and limitations
  19806. * under the License.
  19807. */
  19808. var coordinateSystemCreators = {};
  19809. function CoordinateSystemManager() {
  19810. this._coordinateSystems = [];
  19811. }
  19812. CoordinateSystemManager.prototype = {
  19813. constructor: CoordinateSystemManager,
  19814. create: function (ecModel, api) {
  19815. var coordinateSystems = [];
  19816. each$1(coordinateSystemCreators, function (creater, type) {
  19817. var list = creater.create(ecModel, api);
  19818. coordinateSystems = coordinateSystems.concat(list || []);
  19819. });
  19820. this._coordinateSystems = coordinateSystems;
  19821. },
  19822. update: function (ecModel, api) {
  19823. each$1(this._coordinateSystems, function (coordSys) {
  19824. coordSys.update && coordSys.update(ecModel, api);
  19825. });
  19826. },
  19827. getCoordinateSystems: function () {
  19828. return this._coordinateSystems.slice();
  19829. }
  19830. };
  19831. CoordinateSystemManager.register = function (type, coordinateSystemCreator) {
  19832. coordinateSystemCreators[type] = coordinateSystemCreator;
  19833. };
  19834. CoordinateSystemManager.get = function (type) {
  19835. return coordinateSystemCreators[type];
  19836. };
  19837. /*
  19838. * Licensed to the Apache Software Foundation (ASF) under one
  19839. * or more contributor license agreements. See the NOTICE file
  19840. * distributed with this work for additional information
  19841. * regarding copyright ownership. The ASF licenses this file
  19842. * to you under the Apache License, Version 2.0 (the
  19843. * "License"); you may not use this file except in compliance
  19844. * with the License. You may obtain a copy of the License at
  19845. *
  19846. * http://www.apache.org/licenses/LICENSE-2.0
  19847. *
  19848. * Unless required by applicable law or agreed to in writing,
  19849. * software distributed under the License is distributed on an
  19850. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19851. * KIND, either express or implied. See the License for the
  19852. * specific language governing permissions and limitations
  19853. * under the License.
  19854. */
  19855. /**
  19856. * ECharts option manager
  19857. *
  19858. * @module {echarts/model/OptionManager}
  19859. */
  19860. var each$4 = each$1;
  19861. var clone$3 = clone;
  19862. var map$1 = map;
  19863. var merge$1 = merge;
  19864. var QUERY_REG = /^(min|max)?(.+)$/;
  19865. /**
  19866. * TERM EXPLANATIONS:
  19867. *
  19868. * [option]:
  19869. *
  19870. * An object that contains definitions of components. For example:
  19871. * var option = {
  19872. * title: {...},
  19873. * legend: {...},
  19874. * visualMap: {...},
  19875. * series: [
  19876. * {data: [...]},
  19877. * {data: [...]},
  19878. * ...
  19879. * ]
  19880. * };
  19881. *
  19882. * [rawOption]:
  19883. *
  19884. * An object input to echarts.setOption. 'rawOption' may be an
  19885. * 'option', or may be an object contains multi-options. For example:
  19886. * var option = {
  19887. * baseOption: {
  19888. * title: {...},
  19889. * legend: {...},
  19890. * series: [
  19891. * {data: [...]},
  19892. * {data: [...]},
  19893. * ...
  19894. * ]
  19895. * },
  19896. * timeline: {...},
  19897. * options: [
  19898. * {title: {...}, series: {data: [...]}},
  19899. * {title: {...}, series: {data: [...]}},
  19900. * ...
  19901. * ],
  19902. * media: [
  19903. * {
  19904. * query: {maxWidth: 320},
  19905. * option: {series: {x: 20}, visualMap: {show: false}}
  19906. * },
  19907. * {
  19908. * query: {minWidth: 320, maxWidth: 720},
  19909. * option: {series: {x: 500}, visualMap: {show: true}}
  19910. * },
  19911. * {
  19912. * option: {series: {x: 1200}, visualMap: {show: true}}
  19913. * }
  19914. * ]
  19915. * };
  19916. *
  19917. * @alias module:echarts/model/OptionManager
  19918. * @param {module:echarts/ExtensionAPI} api
  19919. */
  19920. function OptionManager(api) {
  19921. /**
  19922. * @private
  19923. * @type {module:echarts/ExtensionAPI}
  19924. */
  19925. this._api = api;
  19926. /**
  19927. * @private
  19928. * @type {Array.<number>}
  19929. */
  19930. this._timelineOptions = [];
  19931. /**
  19932. * @private
  19933. * @type {Array.<Object>}
  19934. */
  19935. this._mediaList = [];
  19936. /**
  19937. * @private
  19938. * @type {Object}
  19939. */
  19940. this._mediaDefault;
  19941. /**
  19942. * -1, means default.
  19943. * empty means no media.
  19944. * @private
  19945. * @type {Array.<number>}
  19946. */
  19947. this._currentMediaIndices = [];
  19948. /**
  19949. * @private
  19950. * @type {Object}
  19951. */
  19952. this._optionBackup;
  19953. /**
  19954. * @private
  19955. * @type {Object}
  19956. */
  19957. this._newBaseOption;
  19958. }
  19959. // timeline.notMerge is not supported in ec3. Firstly there is rearly
  19960. // case that notMerge is needed. Secondly supporting 'notMerge' requires
  19961. // rawOption cloned and backuped when timeline changed, which does no
  19962. // good to performance. What's more, that both timeline and setOption
  19963. // method supply 'notMerge' brings complex and some problems.
  19964. // Consider this case:
  19965. // (step1) chart.setOption({timeline: {notMerge: false}, ...}, false);
  19966. // (step2) chart.setOption({timeline: {notMerge: true}, ...}, false);
  19967. OptionManager.prototype = {
  19968. constructor: OptionManager,
  19969. /**
  19970. * @public
  19971. * @param {Object} rawOption Raw option.
  19972. * @param {module:echarts/model/Global} ecModel
  19973. * @param {Array.<Function>} optionPreprocessorFuncs
  19974. * @return {Object} Init option
  19975. */
  19976. setOption: function (rawOption, optionPreprocessorFuncs) {
  19977. if (rawOption) {
  19978. // That set dat primitive is dangerous if user reuse the data when setOption again.
  19979. each$1(normalizeToArray(rawOption.series), function (series) {
  19980. series && series.data && isTypedArray(series.data) && setAsPrimitive(series.data);
  19981. });
  19982. }
  19983. // Caution: some series modify option data, if do not clone,
  19984. // it should ensure that the repeat modify correctly
  19985. // (create a new object when modify itself).
  19986. rawOption = clone$3(rawOption);
  19987. // FIXME
  19988. // 如果 timeline options 或者 media 中设置了某个属性,而baseOption中没有设置,则进行警告。
  19989. var oldOptionBackup = this._optionBackup;
  19990. var newParsedOption = parseRawOption.call(
  19991. this, rawOption, optionPreprocessorFuncs, !oldOptionBackup
  19992. );
  19993. this._newBaseOption = newParsedOption.baseOption;
  19994. // For setOption at second time (using merge mode);
  19995. if (oldOptionBackup) {
  19996. // Only baseOption can be merged.
  19997. mergeOption(oldOptionBackup.baseOption, newParsedOption.baseOption);
  19998. // For simplicity, timeline options and media options do not support merge,
  19999. // that is, if you `setOption` twice and both has timeline options, the latter
  20000. // timeline opitons will not be merged to the formers, but just substitude them.
  20001. if (newParsedOption.timelineOptions.length) {
  20002. oldOptionBackup.timelineOptions = newParsedOption.timelineOptions;
  20003. }
  20004. if (newParsedOption.mediaList.length) {
  20005. oldOptionBackup.mediaList = newParsedOption.mediaList;
  20006. }
  20007. if (newParsedOption.mediaDefault) {
  20008. oldOptionBackup.mediaDefault = newParsedOption.mediaDefault;
  20009. }
  20010. }
  20011. else {
  20012. this._optionBackup = newParsedOption;
  20013. }
  20014. },
  20015. /**
  20016. * @param {boolean} isRecreate
  20017. * @return {Object}
  20018. */
  20019. mountOption: function (isRecreate) {
  20020. var optionBackup = this._optionBackup;
  20021. // TODO
  20022. // 如果没有reset功能则不clone。
  20023. this._timelineOptions = map$1(optionBackup.timelineOptions, clone$3);
  20024. this._mediaList = map$1(optionBackup.mediaList, clone$3);
  20025. this._mediaDefault = clone$3(optionBackup.mediaDefault);
  20026. this._currentMediaIndices = [];
  20027. return clone$3(isRecreate
  20028. // this._optionBackup.baseOption, which is created at the first `setOption`
  20029. // called, and is merged into every new option by inner method `mergeOption`
  20030. // each time `setOption` called, can be only used in `isRecreate`, because
  20031. // its reliability is under suspicion. In other cases option merge is
  20032. // performed by `model.mergeOption`.
  20033. ? optionBackup.baseOption : this._newBaseOption
  20034. );
  20035. },
  20036. /**
  20037. * @param {module:echarts/model/Global} ecModel
  20038. * @return {Object}
  20039. */
  20040. getTimelineOption: function (ecModel) {
  20041. var option;
  20042. var timelineOptions = this._timelineOptions;
  20043. if (timelineOptions.length) {
  20044. // getTimelineOption can only be called after ecModel inited,
  20045. // so we can get currentIndex from timelineModel.
  20046. var timelineModel = ecModel.getComponent('timeline');
  20047. if (timelineModel) {
  20048. option = clone$3(
  20049. timelineOptions[timelineModel.getCurrentIndex()],
  20050. true
  20051. );
  20052. }
  20053. }
  20054. return option;
  20055. },
  20056. /**
  20057. * @param {module:echarts/model/Global} ecModel
  20058. * @return {Array.<Object>}
  20059. */
  20060. getMediaOption: function (ecModel) {
  20061. var ecWidth = this._api.getWidth();
  20062. var ecHeight = this._api.getHeight();
  20063. var mediaList = this._mediaList;
  20064. var mediaDefault = this._mediaDefault;
  20065. var indices = [];
  20066. var result = [];
  20067. // No media defined.
  20068. if (!mediaList.length && !mediaDefault) {
  20069. return result;
  20070. }
  20071. // Multi media may be applied, the latter defined media has higher priority.
  20072. for (var i = 0, len = mediaList.length; i < len; i++) {
  20073. if (applyMediaQuery(mediaList[i].query, ecWidth, ecHeight)) {
  20074. indices.push(i);
  20075. }
  20076. }
  20077. // FIXME
  20078. // 是否mediaDefault应该强制用户设置,否则可能修改不能回归。
  20079. if (!indices.length && mediaDefault) {
  20080. indices = [-1];
  20081. }
  20082. if (indices.length && !indicesEquals(indices, this._currentMediaIndices)) {
  20083. result = map$1(indices, function (index) {
  20084. return clone$3(
  20085. index === -1 ? mediaDefault.option : mediaList[index].option
  20086. );
  20087. });
  20088. }
  20089. // Otherwise return nothing.
  20090. this._currentMediaIndices = indices;
  20091. return result;
  20092. }
  20093. };
  20094. function parseRawOption(rawOption, optionPreprocessorFuncs, isNew) {
  20095. var timelineOptions = [];
  20096. var mediaList = [];
  20097. var mediaDefault;
  20098. var baseOption;
  20099. // Compatible with ec2.
  20100. var timelineOpt = rawOption.timeline;
  20101. if (rawOption.baseOption) {
  20102. baseOption = rawOption.baseOption;
  20103. }
  20104. // For timeline
  20105. if (timelineOpt || rawOption.options) {
  20106. baseOption = baseOption || {};
  20107. timelineOptions = (rawOption.options || []).slice();
  20108. }
  20109. // For media query
  20110. if (rawOption.media) {
  20111. baseOption = baseOption || {};
  20112. var media = rawOption.media;
  20113. each$4(media, function (singleMedia) {
  20114. if (singleMedia && singleMedia.option) {
  20115. if (singleMedia.query) {
  20116. mediaList.push(singleMedia);
  20117. }
  20118. else if (!mediaDefault) {
  20119. // Use the first media default.
  20120. mediaDefault = singleMedia;
  20121. }
  20122. }
  20123. });
  20124. }
  20125. // For normal option
  20126. if (!baseOption) {
  20127. baseOption = rawOption;
  20128. }
  20129. // Set timelineOpt to baseOption in ec3,
  20130. // which is convenient for merge option.
  20131. if (!baseOption.timeline) {
  20132. baseOption.timeline = timelineOpt;
  20133. }
  20134. // Preprocess.
  20135. each$4([baseOption].concat(timelineOptions)
  20136. .concat(map(mediaList, function (media) {
  20137. return media.option;
  20138. })),
  20139. function (option) {
  20140. each$4(optionPreprocessorFuncs, function (preProcess) {
  20141. preProcess(option, isNew);
  20142. });
  20143. }
  20144. );
  20145. return {
  20146. baseOption: baseOption,
  20147. timelineOptions: timelineOptions,
  20148. mediaDefault: mediaDefault,
  20149. mediaList: mediaList
  20150. };
  20151. }
  20152. /**
  20153. * @see <http://www.w3.org/TR/css3-mediaqueries/#media1>
  20154. * Support: width, height, aspectRatio
  20155. * Can use max or min as prefix.
  20156. */
  20157. function applyMediaQuery(query, ecWidth, ecHeight) {
  20158. var realMap = {
  20159. width: ecWidth,
  20160. height: ecHeight,
  20161. aspectratio: ecWidth / ecHeight // lowser case for convenientce.
  20162. };
  20163. var applicatable = true;
  20164. each$1(query, function (value, attr) {
  20165. var matched = attr.match(QUERY_REG);
  20166. if (!matched || !matched[1] || !matched[2]) {
  20167. return;
  20168. }
  20169. var operator = matched[1];
  20170. var realAttr = matched[2].toLowerCase();
  20171. if (!compare(realMap[realAttr], value, operator)) {
  20172. applicatable = false;
  20173. }
  20174. });
  20175. return applicatable;
  20176. }
  20177. function compare(real, expect, operator) {
  20178. if (operator === 'min') {
  20179. return real >= expect;
  20180. }
  20181. else if (operator === 'max') {
  20182. return real <= expect;
  20183. }
  20184. else { // Equals
  20185. return real === expect;
  20186. }
  20187. }
  20188. function indicesEquals(indices1, indices2) {
  20189. // indices is always order by asc and has only finite number.
  20190. return indices1.join(',') === indices2.join(',');
  20191. }
  20192. /**
  20193. * Consider case:
  20194. * `chart.setOption(opt1);`
  20195. * Then user do some interaction like dataZoom, dataView changing.
  20196. * `chart.setOption(opt2);`
  20197. * Then user press 'reset button' in toolbox.
  20198. *
  20199. * After doing that all of the interaction effects should be reset, the
  20200. * chart should be the same as the result of invoke
  20201. * `chart.setOption(opt1); chart.setOption(opt2);`.
  20202. *
  20203. * Although it is not able ensure that
  20204. * `chart.setOption(opt1); chart.setOption(opt2);` is equivalents to
  20205. * `chart.setOption(merge(opt1, opt2));` exactly,
  20206. * this might be the only simple way to implement that feature.
  20207. *
  20208. * MEMO: We've considered some other approaches:
  20209. * 1. Each model handle its self restoration but not uniform treatment.
  20210. * (Too complex in logic and error-prone)
  20211. * 2. Use a shadow ecModel. (Performace expensive)
  20212. */
  20213. function mergeOption(oldOption, newOption) {
  20214. newOption = newOption || {};
  20215. each$4(newOption, function (newCptOpt, mainType) {
  20216. if (newCptOpt == null) {
  20217. return;
  20218. }
  20219. var oldCptOpt = oldOption[mainType];
  20220. if (!ComponentModel.hasClass(mainType)) {
  20221. oldOption[mainType] = merge$1(oldCptOpt, newCptOpt, true);
  20222. }
  20223. else {
  20224. newCptOpt = normalizeToArray(newCptOpt);
  20225. oldCptOpt = normalizeToArray(oldCptOpt);
  20226. var mapResult = mappingToExists(oldCptOpt, newCptOpt);
  20227. oldOption[mainType] = map$1(mapResult, function (item) {
  20228. return (item.option && item.exist)
  20229. ? merge$1(item.exist, item.option, true)
  20230. : (item.exist || item.option);
  20231. });
  20232. }
  20233. });
  20234. }
  20235. /*
  20236. * Licensed to the Apache Software Foundation (ASF) under one
  20237. * or more contributor license agreements. See the NOTICE file
  20238. * distributed with this work for additional information
  20239. * regarding copyright ownership. The ASF licenses this file
  20240. * to you under the Apache License, Version 2.0 (the
  20241. * "License"); you may not use this file except in compliance
  20242. * with the License. You may obtain a copy of the License at
  20243. *
  20244. * http://www.apache.org/licenses/LICENSE-2.0
  20245. *
  20246. * Unless required by applicable law or agreed to in writing,
  20247. * software distributed under the License is distributed on an
  20248. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20249. * KIND, either express or implied. See the License for the
  20250. * specific language governing permissions and limitations
  20251. * under the License.
  20252. */
  20253. var each$5 = each$1;
  20254. var isObject$3 = isObject$1;
  20255. var POSSIBLE_STYLES = [
  20256. 'areaStyle', 'lineStyle', 'nodeStyle', 'linkStyle',
  20257. 'chordStyle', 'label', 'labelLine'
  20258. ];
  20259. function compatEC2ItemStyle(opt) {
  20260. var itemStyleOpt = opt && opt.itemStyle;
  20261. if (!itemStyleOpt) {
  20262. return;
  20263. }
  20264. for (var i = 0, len = POSSIBLE_STYLES.length; i < len; i++) {
  20265. var styleName = POSSIBLE_STYLES[i];
  20266. var normalItemStyleOpt = itemStyleOpt.normal;
  20267. var emphasisItemStyleOpt = itemStyleOpt.emphasis;
  20268. if (normalItemStyleOpt && normalItemStyleOpt[styleName]) {
  20269. opt[styleName] = opt[styleName] || {};
  20270. if (!opt[styleName].normal) {
  20271. opt[styleName].normal = normalItemStyleOpt[styleName];
  20272. }
  20273. else {
  20274. merge(opt[styleName].normal, normalItemStyleOpt[styleName]);
  20275. }
  20276. normalItemStyleOpt[styleName] = null;
  20277. }
  20278. if (emphasisItemStyleOpt && emphasisItemStyleOpt[styleName]) {
  20279. opt[styleName] = opt[styleName] || {};
  20280. if (!opt[styleName].emphasis) {
  20281. opt[styleName].emphasis = emphasisItemStyleOpt[styleName];
  20282. }
  20283. else {
  20284. merge(opt[styleName].emphasis, emphasisItemStyleOpt[styleName]);
  20285. }
  20286. emphasisItemStyleOpt[styleName] = null;
  20287. }
  20288. }
  20289. }
  20290. function convertNormalEmphasis(opt, optType, useExtend) {
  20291. if (opt && opt[optType] && (opt[optType].normal || opt[optType].emphasis)) {
  20292. var normalOpt = opt[optType].normal;
  20293. var emphasisOpt = opt[optType].emphasis;
  20294. if (normalOpt) {
  20295. // Timeline controlStyle has other properties besides normal and emphasis
  20296. if (useExtend) {
  20297. opt[optType].normal = opt[optType].emphasis = null;
  20298. defaults(opt[optType], normalOpt);
  20299. }
  20300. else {
  20301. opt[optType] = normalOpt;
  20302. }
  20303. }
  20304. if (emphasisOpt) {
  20305. opt.emphasis = opt.emphasis || {};
  20306. opt.emphasis[optType] = emphasisOpt;
  20307. }
  20308. }
  20309. }
  20310. function removeEC3NormalStatus(opt) {
  20311. convertNormalEmphasis(opt, 'itemStyle');
  20312. convertNormalEmphasis(opt, 'lineStyle');
  20313. convertNormalEmphasis(opt, 'areaStyle');
  20314. convertNormalEmphasis(opt, 'label');
  20315. convertNormalEmphasis(opt, 'labelLine');
  20316. // treemap
  20317. convertNormalEmphasis(opt, 'upperLabel');
  20318. // graph
  20319. convertNormalEmphasis(opt, 'edgeLabel');
  20320. }
  20321. function compatTextStyle(opt, propName) {
  20322. // Check whether is not object (string\null\undefined ...)
  20323. var labelOptSingle = isObject$3(opt) && opt[propName];
  20324. var textStyle = isObject$3(labelOptSingle) && labelOptSingle.textStyle;
  20325. if (textStyle) {
  20326. for (var i = 0, len = TEXT_STYLE_OPTIONS.length; i < len; i++) {
  20327. var propName = TEXT_STYLE_OPTIONS[i];
  20328. if (textStyle.hasOwnProperty(propName)) {
  20329. labelOptSingle[propName] = textStyle[propName];
  20330. }
  20331. }
  20332. }
  20333. }
  20334. function compatEC3CommonStyles(opt) {
  20335. if (opt) {
  20336. removeEC3NormalStatus(opt);
  20337. compatTextStyle(opt, 'label');
  20338. opt.emphasis && compatTextStyle(opt.emphasis, 'label');
  20339. }
  20340. }
  20341. function processSeries(seriesOpt) {
  20342. if (!isObject$3(seriesOpt)) {
  20343. return;
  20344. }
  20345. compatEC2ItemStyle(seriesOpt);
  20346. removeEC3NormalStatus(seriesOpt);
  20347. compatTextStyle(seriesOpt, 'label');
  20348. // treemap
  20349. compatTextStyle(seriesOpt, 'upperLabel');
  20350. // graph
  20351. compatTextStyle(seriesOpt, 'edgeLabel');
  20352. if (seriesOpt.emphasis) {
  20353. compatTextStyle(seriesOpt.emphasis, 'label');
  20354. // treemap
  20355. compatTextStyle(seriesOpt.emphasis, 'upperLabel');
  20356. // graph
  20357. compatTextStyle(seriesOpt.emphasis, 'edgeLabel');
  20358. }
  20359. var markPoint = seriesOpt.markPoint;
  20360. if (markPoint) {
  20361. compatEC2ItemStyle(markPoint);
  20362. compatEC3CommonStyles(markPoint);
  20363. }
  20364. var markLine = seriesOpt.markLine;
  20365. if (markLine) {
  20366. compatEC2ItemStyle(markLine);
  20367. compatEC3CommonStyles(markLine);
  20368. }
  20369. var markArea = seriesOpt.markArea;
  20370. if (markArea) {
  20371. compatEC3CommonStyles(markArea);
  20372. }
  20373. var data = seriesOpt.data;
  20374. // Break with ec3: if `setOption` again, there may be no `type` in option,
  20375. // then the backward compat based on option type will not be performed.
  20376. if (seriesOpt.type === 'graph') {
  20377. data = data || seriesOpt.nodes;
  20378. var edgeData = seriesOpt.links || seriesOpt.edges;
  20379. if (edgeData && !isTypedArray(edgeData)) {
  20380. for (var i = 0; i < edgeData.length; i++) {
  20381. compatEC3CommonStyles(edgeData[i]);
  20382. }
  20383. }
  20384. each$1(seriesOpt.categories, function (opt) {
  20385. removeEC3NormalStatus(opt);
  20386. });
  20387. }
  20388. if (data && !isTypedArray(data)) {
  20389. for (var i = 0; i < data.length; i++) {
  20390. compatEC3CommonStyles(data[i]);
  20391. }
  20392. }
  20393. // mark point data
  20394. var markPoint = seriesOpt.markPoint;
  20395. if (markPoint && markPoint.data) {
  20396. var mpData = markPoint.data;
  20397. for (var i = 0; i < mpData.length; i++) {
  20398. compatEC3CommonStyles(mpData[i]);
  20399. }
  20400. }
  20401. // mark line data
  20402. var markLine = seriesOpt.markLine;
  20403. if (markLine && markLine.data) {
  20404. var mlData = markLine.data;
  20405. for (var i = 0; i < mlData.length; i++) {
  20406. if (isArray(mlData[i])) {
  20407. compatEC3CommonStyles(mlData[i][0]);
  20408. compatEC3CommonStyles(mlData[i][1]);
  20409. }
  20410. else {
  20411. compatEC3CommonStyles(mlData[i]);
  20412. }
  20413. }
  20414. }
  20415. // Series
  20416. if (seriesOpt.type === 'gauge') {
  20417. compatTextStyle(seriesOpt, 'axisLabel');
  20418. compatTextStyle(seriesOpt, 'title');
  20419. compatTextStyle(seriesOpt, 'detail');
  20420. }
  20421. else if (seriesOpt.type === 'treemap') {
  20422. convertNormalEmphasis(seriesOpt.breadcrumb, 'itemStyle');
  20423. each$1(seriesOpt.levels, function (opt) {
  20424. removeEC3NormalStatus(opt);
  20425. });
  20426. }
  20427. else if (seriesOpt.type === 'tree') {
  20428. removeEC3NormalStatus(seriesOpt.leaves);
  20429. }
  20430. // sunburst starts from ec4, so it does not need to compat levels.
  20431. }
  20432. function toArr(o) {
  20433. return isArray(o) ? o : o ? [o] : [];
  20434. }
  20435. function toObj(o) {
  20436. return (isArray(o) ? o[0] : o) || {};
  20437. }
  20438. var compatStyle = function (option, isTheme) {
  20439. each$5(toArr(option.series), function (seriesOpt) {
  20440. isObject$3(seriesOpt) && processSeries(seriesOpt);
  20441. });
  20442. var axes = ['xAxis', 'yAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'parallelAxis', 'radar'];
  20443. isTheme && axes.push('valueAxis', 'categoryAxis', 'logAxis', 'timeAxis');
  20444. each$5(
  20445. axes,
  20446. function (axisName) {
  20447. each$5(toArr(option[axisName]), function (axisOpt) {
  20448. if (axisOpt) {
  20449. compatTextStyle(axisOpt, 'axisLabel');
  20450. compatTextStyle(axisOpt.axisPointer, 'label');
  20451. }
  20452. });
  20453. }
  20454. );
  20455. each$5(toArr(option.parallel), function (parallelOpt) {
  20456. var parallelAxisDefault = parallelOpt && parallelOpt.parallelAxisDefault;
  20457. compatTextStyle(parallelAxisDefault, 'axisLabel');
  20458. compatTextStyle(parallelAxisDefault && parallelAxisDefault.axisPointer, 'label');
  20459. });
  20460. each$5(toArr(option.calendar), function (calendarOpt) {
  20461. convertNormalEmphasis(calendarOpt, 'itemStyle');
  20462. compatTextStyle(calendarOpt, 'dayLabel');
  20463. compatTextStyle(calendarOpt, 'monthLabel');
  20464. compatTextStyle(calendarOpt, 'yearLabel');
  20465. });
  20466. // radar.name.textStyle
  20467. each$5(toArr(option.radar), function (radarOpt) {
  20468. compatTextStyle(radarOpt, 'name');
  20469. });
  20470. each$5(toArr(option.geo), function (geoOpt) {
  20471. if (isObject$3(geoOpt)) {
  20472. compatEC3CommonStyles(geoOpt);
  20473. each$5(toArr(geoOpt.regions), function (regionObj) {
  20474. compatEC3CommonStyles(regionObj);
  20475. });
  20476. }
  20477. });
  20478. each$5(toArr(option.timeline), function (timelineOpt) {
  20479. compatEC3CommonStyles(timelineOpt);
  20480. convertNormalEmphasis(timelineOpt, 'label');
  20481. convertNormalEmphasis(timelineOpt, 'itemStyle');
  20482. convertNormalEmphasis(timelineOpt, 'controlStyle', true);
  20483. var data = timelineOpt.data;
  20484. isArray(data) && each$1(data, function (item) {
  20485. if (isObject$1(item)) {
  20486. convertNormalEmphasis(item, 'label');
  20487. convertNormalEmphasis(item, 'itemStyle');
  20488. }
  20489. });
  20490. });
  20491. each$5(toArr(option.toolbox), function (toolboxOpt) {
  20492. convertNormalEmphasis(toolboxOpt, 'iconStyle');
  20493. each$5(toolboxOpt.feature, function (featureOpt) {
  20494. convertNormalEmphasis(featureOpt, 'iconStyle');
  20495. });
  20496. });
  20497. compatTextStyle(toObj(option.axisPointer), 'label');
  20498. compatTextStyle(toObj(option.tooltip).axisPointer, 'label');
  20499. };
  20500. /*
  20501. * Licensed to the Apache Software Foundation (ASF) under one
  20502. * or more contributor license agreements. See the NOTICE file
  20503. * distributed with this work for additional information
  20504. * regarding copyright ownership. The ASF licenses this file
  20505. * to you under the Apache License, Version 2.0 (the
  20506. * "License"); you may not use this file except in compliance
  20507. * with the License. You may obtain a copy of the License at
  20508. *
  20509. * http://www.apache.org/licenses/LICENSE-2.0
  20510. *
  20511. * Unless required by applicable law or agreed to in writing,
  20512. * software distributed under the License is distributed on an
  20513. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20514. * KIND, either express or implied. See the License for the
  20515. * specific language governing permissions and limitations
  20516. * under the License.
  20517. */
  20518. // Compatitable with 2.0
  20519. function get(opt, path) {
  20520. path = path.split(',');
  20521. var obj = opt;
  20522. for (var i = 0; i < path.length; i++) {
  20523. obj = obj && obj[path[i]];
  20524. if (obj == null) {
  20525. break;
  20526. }
  20527. }
  20528. return obj;
  20529. }
  20530. function set$1(opt, path, val, overwrite) {
  20531. path = path.split(',');
  20532. var obj = opt;
  20533. var key;
  20534. for (var i = 0; i < path.length - 1; i++) {
  20535. key = path[i];
  20536. if (obj[key] == null) {
  20537. obj[key] = {};
  20538. }
  20539. obj = obj[key];
  20540. }
  20541. if (overwrite || obj[path[i]] == null) {
  20542. obj[path[i]] = val;
  20543. }
  20544. }
  20545. function compatLayoutProperties(option) {
  20546. each$1(LAYOUT_PROPERTIES, function (prop) {
  20547. if (prop[0] in option && !(prop[1] in option)) {
  20548. option[prop[1]] = option[prop[0]];
  20549. }
  20550. });
  20551. }
  20552. var LAYOUT_PROPERTIES = [
  20553. ['x', 'left'], ['y', 'top'], ['x2', 'right'], ['y2', 'bottom']
  20554. ];
  20555. var COMPATITABLE_COMPONENTS = [
  20556. 'grid', 'geo', 'parallel', 'legend', 'toolbox', 'title', 'visualMap', 'dataZoom', 'timeline'
  20557. ];
  20558. var backwardCompat = function (option, isTheme) {
  20559. compatStyle(option, isTheme);
  20560. // Make sure series array for model initialization.
  20561. option.series = normalizeToArray(option.series);
  20562. each$1(option.series, function (seriesOpt) {
  20563. if (!isObject$1(seriesOpt)) {
  20564. return;
  20565. }
  20566. var seriesType = seriesOpt.type;
  20567. if (seriesType === 'line') {
  20568. if (seriesOpt.clipOverflow != null) {
  20569. seriesOpt.clip = seriesOpt.clipOverflow;
  20570. }
  20571. }
  20572. else if (seriesType === 'pie' || seriesType === 'gauge') {
  20573. if (seriesOpt.clockWise != null) {
  20574. seriesOpt.clockwise = seriesOpt.clockWise;
  20575. }
  20576. }
  20577. else if (seriesType === 'gauge') {
  20578. var pointerColor = get(seriesOpt, 'pointer.color');
  20579. pointerColor != null
  20580. && set$1(seriesOpt, 'itemStyle.color', pointerColor);
  20581. }
  20582. compatLayoutProperties(seriesOpt);
  20583. });
  20584. // dataRange has changed to visualMap
  20585. if (option.dataRange) {
  20586. option.visualMap = option.dataRange;
  20587. }
  20588. each$1(COMPATITABLE_COMPONENTS, function (componentName) {
  20589. var options = option[componentName];
  20590. if (options) {
  20591. if (!isArray(options)) {
  20592. options = [options];
  20593. }
  20594. each$1(options, function (option) {
  20595. compatLayoutProperties(option);
  20596. });
  20597. }
  20598. });
  20599. };
  20600. /*
  20601. * Licensed to the Apache Software Foundation (ASF) under one
  20602. * or more contributor license agreements. See the NOTICE file
  20603. * distributed with this work for additional information
  20604. * regarding copyright ownership. The ASF licenses this file
  20605. * to you under the Apache License, Version 2.0 (the
  20606. * "License"); you may not use this file except in compliance
  20607. * with the License. You may obtain a copy of the License at
  20608. *
  20609. * http://www.apache.org/licenses/LICENSE-2.0
  20610. *
  20611. * Unless required by applicable law or agreed to in writing,
  20612. * software distributed under the License is distributed on an
  20613. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20614. * KIND, either express or implied. See the License for the
  20615. * specific language governing permissions and limitations
  20616. * under the License.
  20617. */
  20618. // (1) [Caution]: the logic is correct based on the premises:
  20619. // data processing stage is blocked in stream.
  20620. // See <module:echarts/stream/Scheduler#performDataProcessorTasks>
  20621. // (2) Only register once when import repeatly.
  20622. // Should be executed after series filtered and before stack calculation.
  20623. var dataStack = function (ecModel) {
  20624. var stackInfoMap = createHashMap();
  20625. ecModel.eachSeries(function (seriesModel) {
  20626. var stack = seriesModel.get('stack');
  20627. // Compatibal: when `stack` is set as '', do not stack.
  20628. if (stack) {
  20629. var stackInfoList = stackInfoMap.get(stack) || stackInfoMap.set(stack, []);
  20630. var data = seriesModel.getData();
  20631. var stackInfo = {
  20632. // Used for calculate axis extent automatically.
  20633. stackResultDimension: data.getCalculationInfo('stackResultDimension'),
  20634. stackedOverDimension: data.getCalculationInfo('stackedOverDimension'),
  20635. stackedDimension: data.getCalculationInfo('stackedDimension'),
  20636. stackedByDimension: data.getCalculationInfo('stackedByDimension'),
  20637. isStackedByIndex: data.getCalculationInfo('isStackedByIndex'),
  20638. data: data,
  20639. seriesModel: seriesModel
  20640. };
  20641. // If stacked on axis that do not support data stack.
  20642. if (!stackInfo.stackedDimension
  20643. || !(stackInfo.isStackedByIndex || stackInfo.stackedByDimension)
  20644. ) {
  20645. return;
  20646. }
  20647. stackInfoList.length && data.setCalculationInfo(
  20648. 'stackedOnSeries', stackInfoList[stackInfoList.length - 1].seriesModel
  20649. );
  20650. stackInfoList.push(stackInfo);
  20651. }
  20652. });
  20653. stackInfoMap.each(calculateStack);
  20654. };
  20655. function calculateStack(stackInfoList) {
  20656. each$1(stackInfoList, function (targetStackInfo, idxInStack) {
  20657. var resultVal = [];
  20658. var resultNaN = [NaN, NaN];
  20659. var dims = [targetStackInfo.stackResultDimension, targetStackInfo.stackedOverDimension];
  20660. var targetData = targetStackInfo.data;
  20661. var isStackedByIndex = targetStackInfo.isStackedByIndex;
  20662. // Should not write on raw data, because stack series model list changes
  20663. // depending on legend selection.
  20664. var newData = targetData.map(dims, function (v0, v1, dataIndex) {
  20665. var sum = targetData.get(targetStackInfo.stackedDimension, dataIndex);
  20666. // Consider `connectNulls` of line area, if value is NaN, stackedOver
  20667. // should also be NaN, to draw a appropriate belt area.
  20668. if (isNaN(sum)) {
  20669. return resultNaN;
  20670. }
  20671. var byValue;
  20672. var stackedDataRawIndex;
  20673. if (isStackedByIndex) {
  20674. stackedDataRawIndex = targetData.getRawIndex(dataIndex);
  20675. }
  20676. else {
  20677. byValue = targetData.get(targetStackInfo.stackedByDimension, dataIndex);
  20678. }
  20679. // If stackOver is NaN, chart view will render point on value start.
  20680. var stackedOver = NaN;
  20681. for (var j = idxInStack - 1; j >= 0; j--) {
  20682. var stackInfo = stackInfoList[j];
  20683. // Has been optimized by inverted indices on `stackedByDimension`.
  20684. if (!isStackedByIndex) {
  20685. stackedDataRawIndex = stackInfo.data.rawIndexOf(stackInfo.stackedByDimension, byValue);
  20686. }
  20687. if (stackedDataRawIndex >= 0) {
  20688. var val = stackInfo.data.getByRawIndex(stackInfo.stackResultDimension, stackedDataRawIndex);
  20689. // Considering positive stack, negative stack and empty data
  20690. if ((sum >= 0 && val > 0) // Positive stack
  20691. || (sum <= 0 && val < 0) // Negative stack
  20692. ) {
  20693. sum += val;
  20694. stackedOver = val;
  20695. break;
  20696. }
  20697. }
  20698. }
  20699. resultVal[0] = sum;
  20700. resultVal[1] = stackedOver;
  20701. return resultVal;
  20702. });
  20703. targetData.hostModel.setData(newData);
  20704. // Update for consequent calculation
  20705. targetStackInfo.data = newData;
  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. // TODO
  20727. // ??? refactor? check the outer usage of data provider.
  20728. // merge with defaultDimValueGetter?
  20729. /**
  20730. * If normal array used, mutable chunk size is supported.
  20731. * If typed array used, chunk size must be fixed.
  20732. */
  20733. function DefaultDataProvider(source, dimSize) {
  20734. if (!Source.isInstance(source)) {
  20735. source = Source.seriesDataToSource(source);
  20736. }
  20737. this._source = source;
  20738. var data = this._data = source.data;
  20739. var sourceFormat = source.sourceFormat;
  20740. // Typed array. TODO IE10+?
  20741. if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  20742. if (__DEV__) {
  20743. if (dimSize == null) {
  20744. throw new Error('Typed array data must specify dimension size');
  20745. }
  20746. }
  20747. this._offset = 0;
  20748. this._dimSize = dimSize;
  20749. this._data = data;
  20750. }
  20751. var methods = providerMethods[
  20752. sourceFormat === SOURCE_FORMAT_ARRAY_ROWS
  20753. ? sourceFormat + '_' + source.seriesLayoutBy
  20754. : sourceFormat
  20755. ];
  20756. if (__DEV__) {
  20757. assert$1(methods, 'Invalide sourceFormat: ' + sourceFormat);
  20758. }
  20759. extend(this, methods);
  20760. }
  20761. var providerProto = DefaultDataProvider.prototype;
  20762. // If data is pure without style configuration
  20763. providerProto.pure = false;
  20764. // If data is persistent and will not be released after use.
  20765. providerProto.persistent = true;
  20766. // ???! FIXME legacy data provider do not has method getSource
  20767. providerProto.getSource = function () {
  20768. return this._source;
  20769. };
  20770. var providerMethods = {
  20771. 'arrayRows_column': {
  20772. pure: true,
  20773. count: function () {
  20774. return Math.max(0, this._data.length - this._source.startIndex);
  20775. },
  20776. getItem: function (idx) {
  20777. return this._data[idx + this._source.startIndex];
  20778. },
  20779. appendData: appendDataSimply
  20780. },
  20781. 'arrayRows_row': {
  20782. pure: true,
  20783. count: function () {
  20784. var row = this._data[0];
  20785. return row ? Math.max(0, row.length - this._source.startIndex) : 0;
  20786. },
  20787. getItem: function (idx) {
  20788. idx += this._source.startIndex;
  20789. var item = [];
  20790. var data = this._data;
  20791. for (var i = 0; i < data.length; i++) {
  20792. var row = data[i];
  20793. item.push(row ? row[idx] : null);
  20794. }
  20795. return item;
  20796. },
  20797. appendData: function () {
  20798. throw new Error('Do not support appendData when set seriesLayoutBy: "row".');
  20799. }
  20800. },
  20801. 'objectRows': {
  20802. pure: true,
  20803. count: countSimply,
  20804. getItem: getItemSimply,
  20805. appendData: appendDataSimply
  20806. },
  20807. 'keyedColumns': {
  20808. pure: true,
  20809. count: function () {
  20810. var dimName = this._source.dimensionsDefine[0].name;
  20811. var col = this._data[dimName];
  20812. return col ? col.length : 0;
  20813. },
  20814. getItem: function (idx) {
  20815. var item = [];
  20816. var dims = this._source.dimensionsDefine;
  20817. for (var i = 0; i < dims.length; i++) {
  20818. var col = this._data[dims[i].name];
  20819. item.push(col ? col[idx] : null);
  20820. }
  20821. return item;
  20822. },
  20823. appendData: function (newData) {
  20824. var data = this._data;
  20825. each$1(newData, function (newCol, key) {
  20826. var oldCol = data[key] || (data[key] = []);
  20827. for (var i = 0; i < (newCol || []).length; i++) {
  20828. oldCol.push(newCol[i]);
  20829. }
  20830. });
  20831. }
  20832. },
  20833. 'original': {
  20834. count: countSimply,
  20835. getItem: getItemSimply,
  20836. appendData: appendDataSimply
  20837. },
  20838. 'typedArray': {
  20839. persistent: false,
  20840. pure: true,
  20841. count: function () {
  20842. return this._data ? (this._data.length / this._dimSize) : 0;
  20843. },
  20844. getItem: function (idx, out) {
  20845. idx = idx - this._offset;
  20846. out = out || [];
  20847. var offset = this._dimSize * idx;
  20848. for (var i = 0; i < this._dimSize; i++) {
  20849. out[i] = this._data[offset + i];
  20850. }
  20851. return out;
  20852. },
  20853. appendData: function (newData) {
  20854. if (__DEV__) {
  20855. assert$1(
  20856. isTypedArray(newData),
  20857. 'Added data must be TypedArray if data in initialization is TypedArray'
  20858. );
  20859. }
  20860. this._data = newData;
  20861. },
  20862. // Clean self if data is already used.
  20863. clean: function () {
  20864. // PENDING
  20865. this._offset += this.count();
  20866. this._data = null;
  20867. }
  20868. }
  20869. };
  20870. function countSimply() {
  20871. return this._data.length;
  20872. }
  20873. function getItemSimply(idx) {
  20874. return this._data[idx];
  20875. }
  20876. function appendDataSimply(newData) {
  20877. for (var i = 0; i < newData.length; i++) {
  20878. this._data.push(newData[i]);
  20879. }
  20880. }
  20881. var rawValueGetters = {
  20882. arrayRows: getRawValueSimply,
  20883. objectRows: function (dataItem, dataIndex, dimIndex, dimName) {
  20884. return dimIndex != null ? dataItem[dimName] : dataItem;
  20885. },
  20886. keyedColumns: getRawValueSimply,
  20887. original: function (dataItem, dataIndex, dimIndex, dimName) {
  20888. // FIXME
  20889. // In some case (markpoint in geo (geo-map.html)), dataItem
  20890. // is {coord: [...]}
  20891. var value = getDataItemValue(dataItem);
  20892. return (dimIndex == null || !(value instanceof Array))
  20893. ? value
  20894. : value[dimIndex];
  20895. },
  20896. typedArray: getRawValueSimply
  20897. };
  20898. function getRawValueSimply(dataItem, dataIndex, dimIndex, dimName) {
  20899. return dimIndex != null ? dataItem[dimIndex] : dataItem;
  20900. }
  20901. var defaultDimValueGetters = {
  20902. arrayRows: getDimValueSimply,
  20903. objectRows: function (dataItem, dimName, dataIndex, dimIndex) {
  20904. return converDataValue(dataItem[dimName], this._dimensionInfos[dimName]);
  20905. },
  20906. keyedColumns: getDimValueSimply,
  20907. original: function (dataItem, dimName, dataIndex, dimIndex) {
  20908. // Performance sensitive, do not use modelUtil.getDataItemValue.
  20909. // If dataItem is an plain object with no value field, the var `value`
  20910. // will be assigned with the object, but it will be tread correctly
  20911. // in the `convertDataValue`.
  20912. var value = dataItem && (dataItem.value == null ? dataItem : dataItem.value);
  20913. // If any dataItem is like { value: 10 }
  20914. if (!this._rawData.pure && isDataItemOption(dataItem)) {
  20915. this.hasItemOption = true;
  20916. }
  20917. return converDataValue(
  20918. (value instanceof Array)
  20919. ? value[dimIndex]
  20920. // If value is a single number or something else not array.
  20921. : value,
  20922. this._dimensionInfos[dimName]
  20923. );
  20924. },
  20925. typedArray: function (dataItem, dimName, dataIndex, dimIndex) {
  20926. return dataItem[dimIndex];
  20927. }
  20928. };
  20929. function getDimValueSimply(dataItem, dimName, dataIndex, dimIndex) {
  20930. return converDataValue(dataItem[dimIndex], this._dimensionInfos[dimName]);
  20931. }
  20932. /**
  20933. * This helper method convert value in data.
  20934. * @param {string|number|Date} value
  20935. * @param {Object|string} [dimInfo] If string (like 'x'), dimType defaults 'number'.
  20936. * If "dimInfo.ordinalParseAndSave", ordinal value can be parsed.
  20937. */
  20938. function converDataValue(value, dimInfo) {
  20939. // Performance sensitive.
  20940. var dimType = dimInfo && dimInfo.type;
  20941. if (dimType === 'ordinal') {
  20942. // If given value is a category string
  20943. var ordinalMeta = dimInfo && dimInfo.ordinalMeta;
  20944. return ordinalMeta
  20945. ? ordinalMeta.parseAndCollect(value)
  20946. : value;
  20947. }
  20948. if (dimType === 'time'
  20949. // spead up when using timestamp
  20950. && typeof value !== 'number'
  20951. && value != null
  20952. && value !== '-'
  20953. ) {
  20954. value = +parseDate(value);
  20955. }
  20956. // dimType defaults 'number'.
  20957. // If dimType is not ordinal and value is null or undefined or NaN or '-',
  20958. // parse to NaN.
  20959. return (value == null || value === '')
  20960. ? NaN
  20961. // If string (like '-'), using '+' parse to NaN
  20962. // If object, also parse to NaN
  20963. : +value;
  20964. }
  20965. // ??? FIXME can these logic be more neat: getRawValue, getRawDataItem,
  20966. // Consider persistent.
  20967. // Caution: why use raw value to display on label or tooltip?
  20968. // A reason is to avoid format. For example time value we do not know
  20969. // how to format is expected. More over, if stack is used, calculated
  20970. // value may be 0.91000000001, which have brings trouble to display.
  20971. // TODO: consider how to treat null/undefined/NaN when display?
  20972. /**
  20973. * @param {module:echarts/data/List} data
  20974. * @param {number} dataIndex
  20975. * @param {string|number} [dim] dimName or dimIndex
  20976. * @return {Array.<number>|string|number} can be null/undefined.
  20977. */
  20978. function retrieveRawValue(data, dataIndex, dim) {
  20979. if (!data) {
  20980. return;
  20981. }
  20982. // Consider data may be not persistent.
  20983. var dataItem = data.getRawDataItem(dataIndex);
  20984. if (dataItem == null) {
  20985. return;
  20986. }
  20987. var sourceFormat = data.getProvider().getSource().sourceFormat;
  20988. var dimName;
  20989. var dimIndex;
  20990. var dimInfo = data.getDimensionInfo(dim);
  20991. if (dimInfo) {
  20992. dimName = dimInfo.name;
  20993. dimIndex = dimInfo.index;
  20994. }
  20995. return rawValueGetters[sourceFormat](dataItem, dataIndex, dimIndex, dimName);
  20996. }
  20997. /**
  20998. * Compatible with some cases (in pie, map) like:
  20999. * data: [{name: 'xx', value: 5, selected: true}, ...]
  21000. * where only sourceFormat is 'original' and 'objectRows' supported.
  21001. *
  21002. * ??? TODO
  21003. * Supported detail options in data item when using 'arrayRows'.
  21004. *
  21005. * @param {module:echarts/data/List} data
  21006. * @param {number} dataIndex
  21007. * @param {string} attr like 'selected'
  21008. */
  21009. function retrieveRawAttr(data, dataIndex, attr) {
  21010. if (!data) {
  21011. return;
  21012. }
  21013. var sourceFormat = data.getProvider().getSource().sourceFormat;
  21014. if (sourceFormat !== SOURCE_FORMAT_ORIGINAL
  21015. && sourceFormat !== SOURCE_FORMAT_OBJECT_ROWS
  21016. ) {
  21017. return;
  21018. }
  21019. var dataItem = data.getRawDataItem(dataIndex);
  21020. if (sourceFormat === SOURCE_FORMAT_ORIGINAL && !isObject$1(dataItem)) {
  21021. dataItem = null;
  21022. }
  21023. if (dataItem) {
  21024. return dataItem[attr];
  21025. }
  21026. }
  21027. /*
  21028. * Licensed to the Apache Software Foundation (ASF) under one
  21029. * or more contributor license agreements. See the NOTICE file
  21030. * distributed with this work for additional information
  21031. * regarding copyright ownership. The ASF licenses this file
  21032. * to you under the Apache License, Version 2.0 (the
  21033. * "License"); you may not use this file except in compliance
  21034. * with the License. You may obtain a copy of the License at
  21035. *
  21036. * http://www.apache.org/licenses/LICENSE-2.0
  21037. *
  21038. * Unless required by applicable law or agreed to in writing,
  21039. * software distributed under the License is distributed on an
  21040. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21041. * KIND, either express or implied. See the License for the
  21042. * specific language governing permissions and limitations
  21043. * under the License.
  21044. */
  21045. var DIMENSION_LABEL_REG = /\{@(.+?)\}/g;
  21046. // PENDING A little ugly
  21047. var dataFormatMixin = {
  21048. /**
  21049. * Get params for formatter
  21050. * @param {number} dataIndex
  21051. * @param {string} [dataType]
  21052. * @return {Object}
  21053. */
  21054. getDataParams: function (dataIndex, dataType) {
  21055. var data = this.getData(dataType);
  21056. var rawValue = this.getRawValue(dataIndex, dataType);
  21057. var rawDataIndex = data.getRawIndex(dataIndex);
  21058. var name = data.getName(dataIndex);
  21059. var itemOpt = data.getRawDataItem(dataIndex);
  21060. var color = data.getItemVisual(dataIndex, 'color');
  21061. var borderColor = data.getItemVisual(dataIndex, 'borderColor');
  21062. var tooltipModel = this.ecModel.getComponent('tooltip');
  21063. var renderModeOption = tooltipModel && tooltipModel.get('renderMode');
  21064. var renderMode = getTooltipRenderMode(renderModeOption);
  21065. var mainType = this.mainType;
  21066. var isSeries = mainType === 'series';
  21067. var userOutput = data.userOutput;
  21068. return {
  21069. componentType: mainType,
  21070. componentSubType: this.subType,
  21071. componentIndex: this.componentIndex,
  21072. seriesType: isSeries ? this.subType : null,
  21073. seriesIndex: this.seriesIndex,
  21074. seriesId: isSeries ? this.id : null,
  21075. seriesName: isSeries ? this.name : null,
  21076. name: name,
  21077. dataIndex: rawDataIndex,
  21078. data: itemOpt,
  21079. dataType: dataType,
  21080. value: rawValue,
  21081. color: color,
  21082. borderColor: borderColor,
  21083. dimensionNames: userOutput ? userOutput.dimensionNames : null,
  21084. encode: userOutput ? userOutput.encode : null,
  21085. marker: getTooltipMarker({
  21086. color: color,
  21087. renderMode: renderMode
  21088. }),
  21089. // Param name list for mapping `a`, `b`, `c`, `d`, `e`
  21090. $vars: ['seriesName', 'name', 'value']
  21091. };
  21092. },
  21093. /**
  21094. * Format label
  21095. * @param {number} dataIndex
  21096. * @param {string} [status='normal'] 'normal' or 'emphasis'
  21097. * @param {string} [dataType]
  21098. * @param {number} [dimIndex] Only used in some chart that
  21099. * use formatter in different dimensions, like radar.
  21100. * @param {string} [labelProp='label']
  21101. * @return {string} If not formatter, return null/undefined
  21102. */
  21103. getFormattedLabel: function (dataIndex, status, dataType, dimIndex, labelProp) {
  21104. status = status || 'normal';
  21105. var data = this.getData(dataType);
  21106. var itemModel = data.getItemModel(dataIndex);
  21107. var params = this.getDataParams(dataIndex, dataType);
  21108. if (dimIndex != null && (params.value instanceof Array)) {
  21109. params.value = params.value[dimIndex];
  21110. }
  21111. var formatter = itemModel.get(
  21112. status === 'normal'
  21113. ? [labelProp || 'label', 'formatter']
  21114. : [status, labelProp || 'label', 'formatter']
  21115. );
  21116. if (typeof formatter === 'function') {
  21117. params.status = status;
  21118. params.dimensionIndex = dimIndex;
  21119. return formatter(params);
  21120. }
  21121. else if (typeof formatter === 'string') {
  21122. var str = formatTpl(formatter, params);
  21123. // Support 'aaa{@[3]}bbb{@product}ccc'.
  21124. // Do not support '}' in dim name util have to.
  21125. return str.replace(DIMENSION_LABEL_REG, function (origin, dim) {
  21126. var len = dim.length;
  21127. if (dim.charAt(0) === '[' && dim.charAt(len - 1) === ']') {
  21128. dim = +dim.slice(1, len - 1); // Also: '[]' => 0
  21129. }
  21130. return retrieveRawValue(data, dataIndex, dim);
  21131. });
  21132. }
  21133. },
  21134. /**
  21135. * Get raw value in option
  21136. * @param {number} idx
  21137. * @param {string} [dataType]
  21138. * @return {Array|number|string}
  21139. */
  21140. getRawValue: function (idx, dataType) {
  21141. return retrieveRawValue(this.getData(dataType), idx);
  21142. },
  21143. /**
  21144. * Should be implemented.
  21145. * @param {number} dataIndex
  21146. * @param {boolean} [multipleSeries=false]
  21147. * @param {number} [dataType]
  21148. * @return {string} tooltip string
  21149. */
  21150. formatTooltip: function () {
  21151. // Empty function
  21152. }
  21153. };
  21154. /*
  21155. * Licensed to the Apache Software Foundation (ASF) under one
  21156. * or more contributor license agreements. See the NOTICE file
  21157. * distributed with this work for additional information
  21158. * regarding copyright ownership. The ASF licenses this file
  21159. * to you under the Apache License, Version 2.0 (the
  21160. * "License"); you may not use this file except in compliance
  21161. * with the License. You may obtain a copy of the License at
  21162. *
  21163. * http://www.apache.org/licenses/LICENSE-2.0
  21164. *
  21165. * Unless required by applicable law or agreed to in writing,
  21166. * software distributed under the License is distributed on an
  21167. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21168. * KIND, either express or implied. See the License for the
  21169. * specific language governing permissions and limitations
  21170. * under the License.
  21171. */
  21172. /**
  21173. * @param {Object} define
  21174. * @return See the return of `createTask`.
  21175. */
  21176. function createTask(define) {
  21177. return new Task(define);
  21178. }
  21179. /**
  21180. * @constructor
  21181. * @param {Object} define
  21182. * @param {Function} define.reset Custom reset
  21183. * @param {Function} [define.plan] Returns 'reset' indicate reset immediately.
  21184. * @param {Function} [define.count] count is used to determin data task.
  21185. * @param {Function} [define.onDirty] count is used to determin data task.
  21186. */
  21187. function Task(define) {
  21188. define = define || {};
  21189. this._reset = define.reset;
  21190. this._plan = define.plan;
  21191. this._count = define.count;
  21192. this._onDirty = define.onDirty;
  21193. this._dirty = true;
  21194. // Context must be specified implicitly, to
  21195. // avoid miss update context when model changed.
  21196. this.context;
  21197. }
  21198. var taskProto = Task.prototype;
  21199. /**
  21200. * @param {Object} performArgs
  21201. * @param {number} [performArgs.step] Specified step.
  21202. * @param {number} [performArgs.skip] Skip customer perform call.
  21203. * @param {number} [performArgs.modBy] Sampling window size.
  21204. * @param {number} [performArgs.modDataCount] Sampling count.
  21205. */
  21206. taskProto.perform = function (performArgs) {
  21207. var upTask = this._upstream;
  21208. var skip = performArgs && performArgs.skip;
  21209. // TODO some refactor.
  21210. // Pull data. Must pull data each time, because context.data
  21211. // may be updated by Series.setData.
  21212. if (this._dirty && upTask) {
  21213. var context = this.context;
  21214. context.data = context.outputData = upTask.context.outputData;
  21215. }
  21216. if (this.__pipeline) {
  21217. this.__pipeline.currentTask = this;
  21218. }
  21219. var planResult;
  21220. if (this._plan && !skip) {
  21221. planResult = this._plan(this.context);
  21222. }
  21223. // Support sharding by mod, which changes the render sequence and makes the rendered graphic
  21224. // elements uniformed distributed when progress, especially when moving or zooming.
  21225. var lastModBy = normalizeModBy(this._modBy);
  21226. var lastModDataCount = this._modDataCount || 0;
  21227. var modBy = normalizeModBy(performArgs && performArgs.modBy);
  21228. var modDataCount = performArgs && performArgs.modDataCount || 0;
  21229. if (lastModBy !== modBy || lastModDataCount !== modDataCount) {
  21230. planResult = 'reset';
  21231. }
  21232. function normalizeModBy(val) {
  21233. !(val >= 1) && (val = 1); // jshint ignore:line
  21234. return val;
  21235. }
  21236. var forceFirstProgress;
  21237. if (this._dirty || planResult === 'reset') {
  21238. this._dirty = false;
  21239. forceFirstProgress = reset(this, skip);
  21240. }
  21241. this._modBy = modBy;
  21242. this._modDataCount = modDataCount;
  21243. var step = performArgs && performArgs.step;
  21244. if (upTask) {
  21245. if (__DEV__) {
  21246. assert$1(upTask._outputDueEnd != null);
  21247. }
  21248. this._dueEnd = upTask._outputDueEnd;
  21249. }
  21250. // DataTask or overallTask
  21251. else {
  21252. if (__DEV__) {
  21253. assert$1(!this._progress || this._count);
  21254. }
  21255. this._dueEnd = this._count ? this._count(this.context) : Infinity;
  21256. }
  21257. // Note: Stubs, that its host overall task let it has progress, has progress.
  21258. // If no progress, pass index from upstream to downstream each time plan called.
  21259. if (this._progress) {
  21260. var start = this._dueIndex;
  21261. var end = Math.min(
  21262. step != null ? this._dueIndex + step : Infinity,
  21263. this._dueEnd
  21264. );
  21265. if (!skip && (forceFirstProgress || start < end)) {
  21266. var progress = this._progress;
  21267. if (isArray(progress)) {
  21268. for (var i = 0; i < progress.length; i++) {
  21269. doProgress(this, progress[i], start, end, modBy, modDataCount);
  21270. }
  21271. }
  21272. else {
  21273. doProgress(this, progress, start, end, modBy, modDataCount);
  21274. }
  21275. }
  21276. this._dueIndex = end;
  21277. // If no `outputDueEnd`, assume that output data and
  21278. // input data is the same, so use `dueIndex` as `outputDueEnd`.
  21279. var outputDueEnd = this._settedOutputEnd != null
  21280. ? this._settedOutputEnd : end;
  21281. if (__DEV__) {
  21282. // ??? Can not rollback.
  21283. assert$1(outputDueEnd >= this._outputDueEnd);
  21284. }
  21285. this._outputDueEnd = outputDueEnd;
  21286. }
  21287. else {
  21288. // (1) Some overall task has no progress.
  21289. // (2) Stubs, that its host overall task do not let it has progress, has no progress.
  21290. // This should always be performed so it can be passed to downstream.
  21291. this._dueIndex = this._outputDueEnd = this._settedOutputEnd != null
  21292. ? this._settedOutputEnd : this._dueEnd;
  21293. }
  21294. return this.unfinished();
  21295. };
  21296. var iterator = (function () {
  21297. var end;
  21298. var current;
  21299. var modBy;
  21300. var modDataCount;
  21301. var winCount;
  21302. var it = {
  21303. reset: function (s, e, sStep, sCount) {
  21304. current = s;
  21305. end = e;
  21306. modBy = sStep;
  21307. modDataCount = sCount;
  21308. winCount = Math.ceil(modDataCount / modBy);
  21309. it.next = (modBy > 1 && modDataCount > 0) ? modNext : sequentialNext;
  21310. }
  21311. };
  21312. return it;
  21313. function sequentialNext() {
  21314. return current < end ? current++ : null;
  21315. }
  21316. function modNext() {
  21317. var dataIndex = (current % winCount) * modBy + Math.ceil(current / winCount);
  21318. var result = current >= end
  21319. ? null
  21320. : dataIndex < modDataCount
  21321. ? dataIndex
  21322. // If modDataCount is smaller than data.count() (consider `appendData` case),
  21323. // Use normal linear rendering mode.
  21324. : current;
  21325. current++;
  21326. return result;
  21327. }
  21328. })();
  21329. taskProto.dirty = function () {
  21330. this._dirty = true;
  21331. this._onDirty && this._onDirty(this.context);
  21332. };
  21333. function doProgress(taskIns, progress, start, end, modBy, modDataCount) {
  21334. iterator.reset(start, end, modBy, modDataCount);
  21335. taskIns._callingProgress = progress;
  21336. taskIns._callingProgress({
  21337. start: start, end: end, count: end - start, next: iterator.next
  21338. }, taskIns.context);
  21339. }
  21340. function reset(taskIns, skip) {
  21341. taskIns._dueIndex = taskIns._outputDueEnd = taskIns._dueEnd = 0;
  21342. taskIns._settedOutputEnd = null;
  21343. var progress;
  21344. var forceFirstProgress;
  21345. if (!skip && taskIns._reset) {
  21346. progress = taskIns._reset(taskIns.context);
  21347. if (progress && progress.progress) {
  21348. forceFirstProgress = progress.forceFirstProgress;
  21349. progress = progress.progress;
  21350. }
  21351. // To simplify no progress checking, array must has item.
  21352. if (isArray(progress) && !progress.length) {
  21353. progress = null;
  21354. }
  21355. }
  21356. taskIns._progress = progress;
  21357. taskIns._modBy = taskIns._modDataCount = null;
  21358. var downstream = taskIns._downstream;
  21359. downstream && downstream.dirty();
  21360. return forceFirstProgress;
  21361. }
  21362. /**
  21363. * @return {boolean}
  21364. */
  21365. taskProto.unfinished = function () {
  21366. return this._progress && this._dueIndex < this._dueEnd;
  21367. };
  21368. /**
  21369. * @param {Object} downTask The downstream task.
  21370. * @return {Object} The downstream task.
  21371. */
  21372. taskProto.pipe = function (downTask) {
  21373. if (__DEV__) {
  21374. assert$1(downTask && !downTask._disposed && downTask !== this);
  21375. }
  21376. // If already downstream, do not dirty downTask.
  21377. if (this._downstream !== downTask || this._dirty) {
  21378. this._downstream = downTask;
  21379. downTask._upstream = this;
  21380. downTask.dirty();
  21381. }
  21382. };
  21383. taskProto.dispose = function () {
  21384. if (this._disposed) {
  21385. return;
  21386. }
  21387. this._upstream && (this._upstream._downstream = null);
  21388. this._downstream && (this._downstream._upstream = null);
  21389. this._dirty = false;
  21390. this._disposed = true;
  21391. };
  21392. taskProto.getUpstream = function () {
  21393. return this._upstream;
  21394. };
  21395. taskProto.getDownstream = function () {
  21396. return this._downstream;
  21397. };
  21398. taskProto.setOutputEnd = function (end) {
  21399. // This only happend in dataTask, dataZoom, map, currently.
  21400. // where dataZoom do not set end each time, but only set
  21401. // when reset. So we should record the setted end, in case
  21402. // that the stub of dataZoom perform again and earse the
  21403. // setted end by upstream.
  21404. this._outputDueEnd = this._settedOutputEnd = end;
  21405. };
  21406. ///////////////////////////////////////////////////////////
  21407. // For stream debug (Should be commented out after used!)
  21408. // Usage: printTask(this, 'begin');
  21409. // Usage: printTask(this, null, {someExtraProp});
  21410. // function printTask(task, prefix, extra) {
  21411. // window.ecTaskUID == null && (window.ecTaskUID = 0);
  21412. // task.uidDebug == null && (task.uidDebug = `task_${window.ecTaskUID++}`);
  21413. // task.agent && task.agent.uidDebug == null && (task.agent.uidDebug = `task_${window.ecTaskUID++}`);
  21414. // var props = [];
  21415. // if (task.__pipeline) {
  21416. // var val = `${task.__idxInPipeline}/${task.__pipeline.tail.__idxInPipeline} ${task.agent ? '(stub)' : ''}`;
  21417. // props.push({text: 'idx', value: val});
  21418. // } else {
  21419. // var stubCount = 0;
  21420. // task.agentStubMap.each(() => stubCount++);
  21421. // props.push({text: 'idx', value: `overall (stubs: ${stubCount})`});
  21422. // }
  21423. // props.push({text: 'uid', value: task.uidDebug});
  21424. // if (task.__pipeline) {
  21425. // props.push({text: 'pid', value: task.__pipeline.id});
  21426. // task.agent && props.push(
  21427. // {text: 'stubFor', value: task.agent.uidDebug}
  21428. // );
  21429. // }
  21430. // props.push(
  21431. // {text: 'dirty', value: task._dirty},
  21432. // {text: 'dueIndex', value: task._dueIndex},
  21433. // {text: 'dueEnd', value: task._dueEnd},
  21434. // {text: 'outputDueEnd', value: task._outputDueEnd}
  21435. // );
  21436. // if (extra) {
  21437. // Object.keys(extra).forEach(key => {
  21438. // props.push({text: key, value: extra[key]});
  21439. // });
  21440. // }
  21441. // var args = ['color: blue'];
  21442. // var msg = `%c[${prefix || 'T'}] %c` + props.map(item => (
  21443. // args.push('color: black', 'color: red'),
  21444. // `${item.text}: %c${item.value}`
  21445. // )).join('%c, ');
  21446. // console.log.apply(console, [msg].concat(args));
  21447. // // console.log(this);
  21448. // }
  21449. /*
  21450. * Licensed to the Apache Software Foundation (ASF) under one
  21451. * or more contributor license agreements. See the NOTICE file
  21452. * distributed with this work for additional information
  21453. * regarding copyright ownership. The ASF licenses this file
  21454. * to you under the Apache License, Version 2.0 (the
  21455. * "License"); you may not use this file except in compliance
  21456. * with the License. You may obtain a copy of the License at
  21457. *
  21458. * http://www.apache.org/licenses/LICENSE-2.0
  21459. *
  21460. * Unless required by applicable law or agreed to in writing,
  21461. * software distributed under the License is distributed on an
  21462. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21463. * KIND, either express or implied. See the License for the
  21464. * specific language governing permissions and limitations
  21465. * under the License.
  21466. */
  21467. var inner$4 = makeInner();
  21468. var SeriesModel = ComponentModel.extend({
  21469. type: 'series.__base__',
  21470. /**
  21471. * @readOnly
  21472. */
  21473. seriesIndex: 0,
  21474. // coodinateSystem will be injected in the echarts/CoordinateSystem
  21475. coordinateSystem: null,
  21476. /**
  21477. * @type {Object}
  21478. * @protected
  21479. */
  21480. defaultOption: null,
  21481. /**
  21482. * legend visual provider to the legend component
  21483. * @type {Object}
  21484. */
  21485. // PENDING
  21486. legendVisualProvider: null,
  21487. /**
  21488. * Access path of color for visual
  21489. */
  21490. visualColorAccessPath: 'itemStyle.color',
  21491. /**
  21492. * Access path of borderColor for visual
  21493. */
  21494. visualBorderColorAccessPath: 'itemStyle.borderColor',
  21495. /**
  21496. * Support merge layout params.
  21497. * Only support 'box' now (left/right/top/bottom/width/height).
  21498. * @type {string|Object} Object can be {ignoreSize: true}
  21499. * @readOnly
  21500. */
  21501. layoutMode: null,
  21502. init: function (option, parentModel, ecModel, extraOpt) {
  21503. /**
  21504. * @type {number}
  21505. * @readOnly
  21506. */
  21507. this.seriesIndex = this.componentIndex;
  21508. this.dataTask = createTask({
  21509. count: dataTaskCount,
  21510. reset: dataTaskReset
  21511. });
  21512. this.dataTask.context = {model: this};
  21513. this.mergeDefaultAndTheme(option, ecModel);
  21514. prepareSource(this);
  21515. var data = this.getInitialData(option, ecModel);
  21516. wrapData(data, this);
  21517. this.dataTask.context.data = data;
  21518. if (__DEV__) {
  21519. assert$1(data, 'getInitialData returned invalid data.');
  21520. }
  21521. /**
  21522. * @type {module:echarts/data/List|module:echarts/data/Tree|module:echarts/data/Graph}
  21523. * @private
  21524. */
  21525. inner$4(this).dataBeforeProcessed = data;
  21526. // If we reverse the order (make data firstly, and then make
  21527. // dataBeforeProcessed by cloneShallow), cloneShallow will
  21528. // cause data.graph.data !== data when using
  21529. // module:echarts/data/Graph or module:echarts/data/Tree.
  21530. // See module:echarts/data/helper/linkList
  21531. // Theoretically, it is unreasonable to call `seriesModel.getData()` in the model
  21532. // init or merge stage, because the data can be restored. So we do not `restoreData`
  21533. // and `setData` here, which forbids calling `seriesModel.getData()` in this stage.
  21534. // Call `seriesModel.getRawData()` instead.
  21535. // this.restoreData();
  21536. autoSeriesName(this);
  21537. },
  21538. /**
  21539. * Util for merge default and theme to option
  21540. * @param {Object} option
  21541. * @param {module:echarts/model/Global} ecModel
  21542. */
  21543. mergeDefaultAndTheme: function (option, ecModel) {
  21544. var layoutMode = this.layoutMode;
  21545. var inputPositionParams = layoutMode
  21546. ? getLayoutParams(option) : {};
  21547. // Backward compat: using subType on theme.
  21548. // But if name duplicate between series subType
  21549. // (for example: parallel) add component mainType,
  21550. // add suffix 'Series'.
  21551. var themeSubType = this.subType;
  21552. if (ComponentModel.hasClass(themeSubType)) {
  21553. themeSubType += 'Series';
  21554. }
  21555. merge(
  21556. option,
  21557. ecModel.getTheme().get(this.subType)
  21558. );
  21559. merge(option, this.getDefaultOption());
  21560. // Default label emphasis `show`
  21561. defaultEmphasis(option, 'label', ['show']);
  21562. this.fillDataTextStyle(option.data);
  21563. if (layoutMode) {
  21564. mergeLayoutParam(option, inputPositionParams, layoutMode);
  21565. }
  21566. },
  21567. mergeOption: function (newSeriesOption, ecModel) {
  21568. // this.settingTask.dirty();
  21569. newSeriesOption = merge(this.option, newSeriesOption, true);
  21570. this.fillDataTextStyle(newSeriesOption.data);
  21571. var layoutMode = this.layoutMode;
  21572. if (layoutMode) {
  21573. mergeLayoutParam(this.option, newSeriesOption, layoutMode);
  21574. }
  21575. prepareSource(this);
  21576. var data = this.getInitialData(newSeriesOption, ecModel);
  21577. wrapData(data, this);
  21578. this.dataTask.dirty();
  21579. this.dataTask.context.data = data;
  21580. inner$4(this).dataBeforeProcessed = data;
  21581. autoSeriesName(this);
  21582. },
  21583. fillDataTextStyle: function (data) {
  21584. // Default data label emphasis `show`
  21585. // FIXME Tree structure data ?
  21586. // FIXME Performance ?
  21587. if (data && !isTypedArray(data)) {
  21588. var props = ['show'];
  21589. for (var i = 0; i < data.length; i++) {
  21590. if (data[i] && data[i].label) {
  21591. defaultEmphasis(data[i], 'label', props);
  21592. }
  21593. }
  21594. }
  21595. },
  21596. /**
  21597. * Init a data structure from data related option in series
  21598. * Must be overwritten
  21599. */
  21600. getInitialData: function () {},
  21601. /**
  21602. * Append data to list
  21603. * @param {Object} params
  21604. * @param {Array|TypedArray} params.data
  21605. */
  21606. appendData: function (params) {
  21607. // FIXME ???
  21608. // (1) If data from dataset, forbidden append.
  21609. // (2) support append data of dataset.
  21610. var data = this.getRawData();
  21611. data.appendData(params.data);
  21612. },
  21613. /**
  21614. * Consider some method like `filter`, `map` need make new data,
  21615. * We should make sure that `seriesModel.getData()` get correct
  21616. * data in the stream procedure. So we fetch data from upstream
  21617. * each time `task.perform` called.
  21618. * @param {string} [dataType]
  21619. * @return {module:echarts/data/List}
  21620. */
  21621. getData: function (dataType) {
  21622. var task = getCurrentTask(this);
  21623. if (task) {
  21624. var data = task.context.data;
  21625. return dataType == null ? data : data.getLinkedData(dataType);
  21626. }
  21627. else {
  21628. // When series is not alive (that may happen when click toolbox
  21629. // restore or setOption with not merge mode), series data may
  21630. // be still need to judge animation or something when graphic
  21631. // elements want to know whether fade out.
  21632. return inner$4(this).data;
  21633. }
  21634. },
  21635. /**
  21636. * @param {module:echarts/data/List} data
  21637. */
  21638. setData: function (data) {
  21639. var task = getCurrentTask(this);
  21640. if (task) {
  21641. var context = task.context;
  21642. // Consider case: filter, data sample.
  21643. if (context.data !== data && task.modifyOutputEnd) {
  21644. task.setOutputEnd(data.count());
  21645. }
  21646. context.outputData = data;
  21647. // Caution: setData should update context.data,
  21648. // Because getData may be called multiply in a
  21649. // single stage and expect to get the data just
  21650. // set. (For example, AxisProxy, x y both call
  21651. // getData and setDate sequentially).
  21652. // So the context.data should be fetched from
  21653. // upstream each time when a stage starts to be
  21654. // performed.
  21655. if (task !== this.dataTask) {
  21656. context.data = data;
  21657. }
  21658. }
  21659. inner$4(this).data = data;
  21660. },
  21661. /**
  21662. * @see {module:echarts/data/helper/sourceHelper#getSource}
  21663. * @return {module:echarts/data/Source} source
  21664. */
  21665. getSource: function () {
  21666. return getSource(this);
  21667. },
  21668. /**
  21669. * Get data before processed
  21670. * @return {module:echarts/data/List}
  21671. */
  21672. getRawData: function () {
  21673. return inner$4(this).dataBeforeProcessed;
  21674. },
  21675. /**
  21676. * Get base axis if has coordinate system and has axis.
  21677. * By default use coordSys.getBaseAxis();
  21678. * Can be overrided for some chart.
  21679. * @return {type} description
  21680. */
  21681. getBaseAxis: function () {
  21682. var coordSys = this.coordinateSystem;
  21683. return coordSys && coordSys.getBaseAxis && coordSys.getBaseAxis();
  21684. },
  21685. // FIXME
  21686. /**
  21687. * Default tooltip formatter
  21688. *
  21689. * @param {number} dataIndex
  21690. * @param {boolean} [multipleSeries=false]
  21691. * @param {number} [dataType]
  21692. * @param {string} [renderMode='html'] valid values: 'html' and 'richText'.
  21693. * 'html' is used for rendering tooltip in extra DOM form, and the result
  21694. * string is used as DOM HTML content.
  21695. * 'richText' is used for rendering tooltip in rich text form, for those where
  21696. * DOM operation is not supported.
  21697. * @return {Object} formatted tooltip with `html` and `markers`
  21698. */
  21699. formatTooltip: function (dataIndex, multipleSeries, dataType, renderMode) {
  21700. var series = this;
  21701. renderMode = renderMode || 'html';
  21702. var newLine = renderMode === 'html' ? '<br/>' : '\n';
  21703. var isRichText = renderMode === 'richText';
  21704. var markers = {};
  21705. var markerId = 0;
  21706. function formatArrayValue(value) {
  21707. // ??? TODO refactor these logic.
  21708. // check: category-no-encode-has-axis-data in dataset.html
  21709. var vertially = reduce(value, function (vertially, val, idx) {
  21710. var dimItem = data.getDimensionInfo(idx);
  21711. return vertially |= dimItem && dimItem.tooltip !== false && dimItem.displayName != null;
  21712. }, 0);
  21713. var result = [];
  21714. tooltipDims.length
  21715. ? each$1(tooltipDims, function (dim) {
  21716. setEachItem(retrieveRawValue(data, dataIndex, dim), dim);
  21717. })
  21718. // By default, all dims is used on tooltip.
  21719. : each$1(value, setEachItem);
  21720. function setEachItem(val, dim) {
  21721. var dimInfo = data.getDimensionInfo(dim);
  21722. // If `dimInfo.tooltip` is not set, show tooltip.
  21723. if (!dimInfo || dimInfo.otherDims.tooltip === false) {
  21724. return;
  21725. }
  21726. var dimType = dimInfo.type;
  21727. var markName = 'sub' + series.seriesIndex + 'at' + markerId;
  21728. var dimHead = getTooltipMarker({
  21729. color: color,
  21730. type: 'subItem',
  21731. renderMode: renderMode,
  21732. markerId: markName
  21733. });
  21734. var dimHeadStr = typeof dimHead === 'string' ? dimHead : dimHead.content;
  21735. var valStr = (vertially
  21736. ? dimHeadStr + encodeHTML(dimInfo.displayName || '-') + ': '
  21737. : ''
  21738. )
  21739. // FIXME should not format time for raw data?
  21740. + encodeHTML(dimType === 'ordinal'
  21741. ? val + ''
  21742. : dimType === 'time'
  21743. ? (multipleSeries ? '' : formatTime('yyyy/MM/dd hh:mm:ss', val))
  21744. : addCommas(val)
  21745. );
  21746. valStr && result.push(valStr);
  21747. if (isRichText) {
  21748. markers[markName] = color;
  21749. ++markerId;
  21750. }
  21751. }
  21752. var newLine = vertially ? (isRichText ? '\n' : '<br/>') : '';
  21753. var content = newLine + result.join(newLine || ', ');
  21754. return {
  21755. renderMode: renderMode,
  21756. content: content,
  21757. style: markers
  21758. };
  21759. }
  21760. function formatSingleValue(val) {
  21761. // return encodeHTML(addCommas(val));
  21762. return {
  21763. renderMode: renderMode,
  21764. content: encodeHTML(addCommas(val)),
  21765. style: markers
  21766. };
  21767. }
  21768. var data = this.getData();
  21769. var tooltipDims = data.mapDimension('defaultedTooltip', true);
  21770. var tooltipDimLen = tooltipDims.length;
  21771. var value = this.getRawValue(dataIndex);
  21772. var isValueArr = isArray(value);
  21773. var color = data.getItemVisual(dataIndex, 'color');
  21774. if (isObject$1(color) && color.colorStops) {
  21775. color = (color.colorStops[0] || {}).color;
  21776. }
  21777. color = color || 'transparent';
  21778. // Complicated rule for pretty tooltip.
  21779. var formattedValue = (tooltipDimLen > 1 || (isValueArr && !tooltipDimLen))
  21780. ? formatArrayValue(value)
  21781. : tooltipDimLen
  21782. ? formatSingleValue(retrieveRawValue(data, dataIndex, tooltipDims[0]))
  21783. : formatSingleValue(isValueArr ? value[0] : value);
  21784. var content = formattedValue.content;
  21785. var markName = series.seriesIndex + 'at' + markerId;
  21786. var colorEl = getTooltipMarker({
  21787. color: color,
  21788. type: 'item',
  21789. renderMode: renderMode,
  21790. markerId: markName
  21791. });
  21792. markers[markName] = color;
  21793. ++markerId;
  21794. var name = data.getName(dataIndex);
  21795. var seriesName = this.name;
  21796. if (!isNameSpecified(this)) {
  21797. seriesName = '';
  21798. }
  21799. seriesName = seriesName
  21800. ? encodeHTML(seriesName) + (!multipleSeries ? newLine : ': ')
  21801. : '';
  21802. var colorStr = typeof colorEl === 'string' ? colorEl : colorEl.content;
  21803. var html = !multipleSeries
  21804. ? seriesName + colorStr
  21805. + (name
  21806. ? encodeHTML(name) + ': ' + content
  21807. : content
  21808. )
  21809. : colorStr + seriesName + content;
  21810. return {
  21811. html: html,
  21812. markers: markers
  21813. };
  21814. },
  21815. /**
  21816. * @return {boolean}
  21817. */
  21818. isAnimationEnabled: function () {
  21819. if (env$1.node) {
  21820. return false;
  21821. }
  21822. var animationEnabled = this.getShallow('animation');
  21823. if (animationEnabled) {
  21824. if (this.getData().count() > this.getShallow('animationThreshold')) {
  21825. animationEnabled = false;
  21826. }
  21827. }
  21828. return animationEnabled;
  21829. },
  21830. restoreData: function () {
  21831. this.dataTask.dirty();
  21832. },
  21833. getColorFromPalette: function (name, scope, requestColorNum) {
  21834. var ecModel = this.ecModel;
  21835. // PENDING
  21836. var color = colorPaletteMixin.getColorFromPalette.call(this, name, scope, requestColorNum);
  21837. if (!color) {
  21838. color = ecModel.getColorFromPalette(name, scope, requestColorNum);
  21839. }
  21840. return color;
  21841. },
  21842. /**
  21843. * Use `data.mapDimension(coordDim, true)` instead.
  21844. * @deprecated
  21845. */
  21846. coordDimToDataDim: function (coordDim) {
  21847. return this.getRawData().mapDimension(coordDim, true);
  21848. },
  21849. /**
  21850. * Get progressive rendering count each step
  21851. * @return {number}
  21852. */
  21853. getProgressive: function () {
  21854. return this.get('progressive');
  21855. },
  21856. /**
  21857. * Get progressive rendering count each step
  21858. * @return {number}
  21859. */
  21860. getProgressiveThreshold: function () {
  21861. return this.get('progressiveThreshold');
  21862. },
  21863. /**
  21864. * Get data indices for show tooltip content. See tooltip.
  21865. * @abstract
  21866. * @param {Array.<string>|string} dim
  21867. * @param {Array.<number>} value
  21868. * @param {module:echarts/coord/single/SingleAxis} baseAxis
  21869. * @return {Object} {dataIndices, nestestValue}.
  21870. */
  21871. getAxisTooltipData: null,
  21872. /**
  21873. * See tooltip.
  21874. * @abstract
  21875. * @param {number} dataIndex
  21876. * @return {Array.<number>} Point of tooltip. null/undefined can be returned.
  21877. */
  21878. getTooltipPosition: null,
  21879. /**
  21880. * @see {module:echarts/stream/Scheduler}
  21881. */
  21882. pipeTask: null,
  21883. /**
  21884. * Convinient for override in extended class.
  21885. * @protected
  21886. * @type {Function}
  21887. */
  21888. preventIncremental: null,
  21889. /**
  21890. * @public
  21891. * @readOnly
  21892. * @type {Object}
  21893. */
  21894. pipelineContext: null
  21895. });
  21896. mixin(SeriesModel, dataFormatMixin);
  21897. mixin(SeriesModel, colorPaletteMixin);
  21898. /**
  21899. * MUST be called after `prepareSource` called
  21900. * Here we need to make auto series, especially for auto legend. But we
  21901. * do not modify series.name in option to avoid side effects.
  21902. */
  21903. function autoSeriesName(seriesModel) {
  21904. // User specified name has higher priority, otherwise it may cause
  21905. // series can not be queried unexpectedly.
  21906. var name = seriesModel.name;
  21907. if (!isNameSpecified(seriesModel)) {
  21908. seriesModel.name = getSeriesAutoName(seriesModel) || name;
  21909. }
  21910. }
  21911. function getSeriesAutoName(seriesModel) {
  21912. var data = seriesModel.getRawData();
  21913. var dataDims = data.mapDimension('seriesName', true);
  21914. var nameArr = [];
  21915. each$1(dataDims, function (dataDim) {
  21916. var dimInfo = data.getDimensionInfo(dataDim);
  21917. dimInfo.displayName && nameArr.push(dimInfo.displayName);
  21918. });
  21919. return nameArr.join(' ');
  21920. }
  21921. function dataTaskCount(context) {
  21922. return context.model.getRawData().count();
  21923. }
  21924. function dataTaskReset(context) {
  21925. var seriesModel = context.model;
  21926. seriesModel.setData(seriesModel.getRawData().cloneShallow());
  21927. return dataTaskProgress;
  21928. }
  21929. function dataTaskProgress(param, context) {
  21930. // Avoid repead cloneShallow when data just created in reset.
  21931. if (context.outputData && param.end > context.outputData.count()) {
  21932. context.model.getRawData().cloneShallow(context.outputData);
  21933. }
  21934. }
  21935. // TODO refactor
  21936. function wrapData(data, seriesModel) {
  21937. each$1(data.CHANGABLE_METHODS, function (methodName) {
  21938. data.wrapMethod(methodName, curry(onDataSelfChange, seriesModel));
  21939. });
  21940. }
  21941. function onDataSelfChange(seriesModel) {
  21942. var task = getCurrentTask(seriesModel);
  21943. if (task) {
  21944. // Consider case: filter, selectRange
  21945. task.setOutputEnd(this.count());
  21946. }
  21947. }
  21948. function getCurrentTask(seriesModel) {
  21949. var scheduler = (seriesModel.ecModel || {}).scheduler;
  21950. var pipeline = scheduler && scheduler.getPipeline(seriesModel.uid);
  21951. if (pipeline) {
  21952. // When pipline finished, the currrentTask keep the last
  21953. // task (renderTask).
  21954. var task = pipeline.currentTask;
  21955. if (task) {
  21956. var agentStubMap = task.agentStubMap;
  21957. if (agentStubMap) {
  21958. task = agentStubMap.get(seriesModel.uid);
  21959. }
  21960. }
  21961. return task;
  21962. }
  21963. }
  21964. /*
  21965. * Licensed to the Apache Software Foundation (ASF) under one
  21966. * or more contributor license agreements. See the NOTICE file
  21967. * distributed with this work for additional information
  21968. * regarding copyright ownership. The ASF licenses this file
  21969. * to you under the Apache License, Version 2.0 (the
  21970. * "License"); you may not use this file except in compliance
  21971. * with the License. You may obtain a copy of the License at
  21972. *
  21973. * http://www.apache.org/licenses/LICENSE-2.0
  21974. *
  21975. * Unless required by applicable law or agreed to in writing,
  21976. * software distributed under the License is distributed on an
  21977. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21978. * KIND, either express or implied. See the License for the
  21979. * specific language governing permissions and limitations
  21980. * under the License.
  21981. */
  21982. var Component$1 = function () {
  21983. /**
  21984. * @type {module:zrender/container/Group}
  21985. * @readOnly
  21986. */
  21987. this.group = new Group();
  21988. /**
  21989. * @type {string}
  21990. * @readOnly
  21991. */
  21992. this.uid = getUID('viewComponent');
  21993. };
  21994. Component$1.prototype = {
  21995. constructor: Component$1,
  21996. init: function (ecModel, api) {},
  21997. render: function (componentModel, ecModel, api, payload) {},
  21998. dispose: function () {},
  21999. /**
  22000. * @param {string} eventType
  22001. * @param {Object} query
  22002. * @param {module:zrender/Element} targetEl
  22003. * @param {Object} packedEvent
  22004. * @return {boolen} Pass only when return `true`.
  22005. */
  22006. filterForExposedEvent: null
  22007. };
  22008. var componentProto = Component$1.prototype;
  22009. componentProto.updateView =
  22010. componentProto.updateLayout =
  22011. componentProto.updateVisual =
  22012. function (seriesModel, ecModel, api, payload) {
  22013. // Do nothing;
  22014. };
  22015. // Enable Component.extend.
  22016. enableClassExtend(Component$1);
  22017. // Enable capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  22018. enableClassManagement(Component$1, {registerWhenExtend: true});
  22019. /*
  22020. * Licensed to the Apache Software Foundation (ASF) under one
  22021. * or more contributor license agreements. See the NOTICE file
  22022. * distributed with this work for additional information
  22023. * regarding copyright ownership. The ASF licenses this file
  22024. * to you under the Apache License, Version 2.0 (the
  22025. * "License"); you may not use this file except in compliance
  22026. * with the License. You may obtain a copy of the License at
  22027. *
  22028. * http://www.apache.org/licenses/LICENSE-2.0
  22029. *
  22030. * Unless required by applicable law or agreed to in writing,
  22031. * software distributed under the License is distributed on an
  22032. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22033. * KIND, either express or implied. See the License for the
  22034. * specific language governing permissions and limitations
  22035. * under the License.
  22036. */
  22037. /**
  22038. * @return {string} If large mode changed, return string 'reset';
  22039. */
  22040. var createRenderPlanner = function () {
  22041. var inner = makeInner();
  22042. return function (seriesModel) {
  22043. var fields = inner(seriesModel);
  22044. var pipelineContext = seriesModel.pipelineContext;
  22045. var originalLarge = fields.large;
  22046. var originalProgressive = fields.progressiveRender;
  22047. // FIXME: if the planner works on a filtered series, `pipelineContext` does not
  22048. // exists. See #11611 . Probably we need to modify this structure, see the comment
  22049. // on `performRawSeries` in `Schedular.js`.
  22050. var large = fields.large = pipelineContext && pipelineContext.large;
  22051. var progressive = fields.progressiveRender = pipelineContext && pipelineContext.progressiveRender;
  22052. return !!((originalLarge ^ large) || (originalProgressive ^ progressive)) && 'reset';
  22053. };
  22054. };
  22055. /*
  22056. * Licensed to the Apache Software Foundation (ASF) under one
  22057. * or more contributor license agreements. See the NOTICE file
  22058. * distributed with this work for additional information
  22059. * regarding copyright ownership. The ASF licenses this file
  22060. * to you under the Apache License, Version 2.0 (the
  22061. * "License"); you may not use this file except in compliance
  22062. * with the License. You may obtain a copy of the License at
  22063. *
  22064. * http://www.apache.org/licenses/LICENSE-2.0
  22065. *
  22066. * Unless required by applicable law or agreed to in writing,
  22067. * software distributed under the License is distributed on an
  22068. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22069. * KIND, either express or implied. See the License for the
  22070. * specific language governing permissions and limitations
  22071. * under the License.
  22072. */
  22073. var inner$5 = makeInner();
  22074. var renderPlanner = createRenderPlanner();
  22075. function Chart() {
  22076. /**
  22077. * @type {module:zrender/container/Group}
  22078. * @readOnly
  22079. */
  22080. this.group = new Group();
  22081. /**
  22082. * @type {string}
  22083. * @readOnly
  22084. */
  22085. this.uid = getUID('viewChart');
  22086. this.renderTask = createTask({
  22087. plan: renderTaskPlan,
  22088. reset: renderTaskReset
  22089. });
  22090. this.renderTask.context = {view: this};
  22091. }
  22092. Chart.prototype = {
  22093. type: 'chart',
  22094. /**
  22095. * Init the chart.
  22096. * @param {module:echarts/model/Global} ecModel
  22097. * @param {module:echarts/ExtensionAPI} api
  22098. */
  22099. init: function (ecModel, api) {},
  22100. /**
  22101. * Render the chart.
  22102. * @param {module:echarts/model/Series} seriesModel
  22103. * @param {module:echarts/model/Global} ecModel
  22104. * @param {module:echarts/ExtensionAPI} api
  22105. * @param {Object} payload
  22106. */
  22107. render: function (seriesModel, ecModel, api, payload) {},
  22108. /**
  22109. * Highlight series or specified data item.
  22110. * @param {module:echarts/model/Series} seriesModel
  22111. * @param {module:echarts/model/Global} ecModel
  22112. * @param {module:echarts/ExtensionAPI} api
  22113. * @param {Object} payload
  22114. */
  22115. highlight: function (seriesModel, ecModel, api, payload) {
  22116. toggleHighlight(seriesModel.getData(), payload, 'emphasis');
  22117. },
  22118. /**
  22119. * Downplay series or specified data item.
  22120. * @param {module:echarts/model/Series} seriesModel
  22121. * @param {module:echarts/model/Global} ecModel
  22122. * @param {module:echarts/ExtensionAPI} api
  22123. * @param {Object} payload
  22124. */
  22125. downplay: function (seriesModel, ecModel, api, payload) {
  22126. toggleHighlight(seriesModel.getData(), payload, 'normal');
  22127. },
  22128. /**
  22129. * Remove self.
  22130. * @param {module:echarts/model/Global} ecModel
  22131. * @param {module:echarts/ExtensionAPI} api
  22132. */
  22133. remove: function (ecModel, api) {
  22134. this.group.removeAll();
  22135. },
  22136. /**
  22137. * Dispose self.
  22138. * @param {module:echarts/model/Global} ecModel
  22139. * @param {module:echarts/ExtensionAPI} api
  22140. */
  22141. dispose: function () {},
  22142. /**
  22143. * Rendering preparation in progressive mode.
  22144. * @param {module:echarts/model/Series} seriesModel
  22145. * @param {module:echarts/model/Global} ecModel
  22146. * @param {module:echarts/ExtensionAPI} api
  22147. * @param {Object} payload
  22148. */
  22149. incrementalPrepareRender: null,
  22150. /**
  22151. * Render in progressive mode.
  22152. * @param {Object} params See taskParams in `stream/task.js`
  22153. * @param {module:echarts/model/Series} seriesModel
  22154. * @param {module:echarts/model/Global} ecModel
  22155. * @param {module:echarts/ExtensionAPI} api
  22156. * @param {Object} payload
  22157. */
  22158. incrementalRender: null,
  22159. /**
  22160. * Update transform directly.
  22161. * @param {module:echarts/model/Series} seriesModel
  22162. * @param {module:echarts/model/Global} ecModel
  22163. * @param {module:echarts/ExtensionAPI} api
  22164. * @param {Object} payload
  22165. * @return {Object} {update: true}
  22166. */
  22167. updateTransform: null,
  22168. /**
  22169. * The view contains the given point.
  22170. * @interface
  22171. * @param {Array.<number>} point
  22172. * @return {boolean}
  22173. */
  22174. // containPoint: function () {}
  22175. /**
  22176. * @param {string} eventType
  22177. * @param {Object} query
  22178. * @param {module:zrender/Element} targetEl
  22179. * @param {Object} packedEvent
  22180. * @return {boolen} Pass only when return `true`.
  22181. */
  22182. filterForExposedEvent: null
  22183. };
  22184. var chartProto = Chart.prototype;
  22185. chartProto.updateView =
  22186. chartProto.updateLayout =
  22187. chartProto.updateVisual =
  22188. function (seriesModel, ecModel, api, payload) {
  22189. this.render(seriesModel, ecModel, api, payload);
  22190. };
  22191. /**
  22192. * Set state of single element
  22193. * @param {module:zrender/Element} el
  22194. * @param {string} state 'normal'|'emphasis'
  22195. * @param {number} highlightDigit
  22196. */
  22197. function elSetState(el, state, highlightDigit) {
  22198. if (el) {
  22199. el.trigger(state, highlightDigit);
  22200. if (el.isGroup
  22201. // Simple optimize.
  22202. && !isHighDownDispatcher(el)
  22203. ) {
  22204. for (var i = 0, len = el.childCount(); i < len; i++) {
  22205. elSetState(el.childAt(i), state, highlightDigit);
  22206. }
  22207. }
  22208. }
  22209. }
  22210. /**
  22211. * @param {module:echarts/data/List} data
  22212. * @param {Object} payload
  22213. * @param {string} state 'normal'|'emphasis'
  22214. */
  22215. function toggleHighlight(data, payload, state) {
  22216. var dataIndex = queryDataIndex(data, payload);
  22217. var highlightDigit = (payload && payload.highlightKey != null)
  22218. ? getHighlightDigit(payload.highlightKey)
  22219. : null;
  22220. if (dataIndex != null) {
  22221. each$1(normalizeToArray(dataIndex), function (dataIdx) {
  22222. elSetState(data.getItemGraphicEl(dataIdx), state, highlightDigit);
  22223. });
  22224. }
  22225. else {
  22226. data.eachItemGraphicEl(function (el) {
  22227. elSetState(el, state, highlightDigit);
  22228. });
  22229. }
  22230. }
  22231. // Enable Chart.extend.
  22232. enableClassExtend(Chart, ['dispose']);
  22233. // Add capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  22234. enableClassManagement(Chart, {registerWhenExtend: true});
  22235. Chart.markUpdateMethod = function (payload, methodName) {
  22236. inner$5(payload).updateMethod = methodName;
  22237. };
  22238. function renderTaskPlan(context) {
  22239. return renderPlanner(context.model);
  22240. }
  22241. function renderTaskReset(context) {
  22242. var seriesModel = context.model;
  22243. var ecModel = context.ecModel;
  22244. var api = context.api;
  22245. var payload = context.payload;
  22246. // ???! remove updateView updateVisual
  22247. var progressiveRender = seriesModel.pipelineContext.progressiveRender;
  22248. var view = context.view;
  22249. var updateMethod = payload && inner$5(payload).updateMethod;
  22250. var methodName = progressiveRender
  22251. ? 'incrementalPrepareRender'
  22252. : (updateMethod && view[updateMethod])
  22253. ? updateMethod
  22254. // `appendData` is also supported when data amount
  22255. // is less than progressive threshold.
  22256. : 'render';
  22257. if (methodName !== 'render') {
  22258. view[methodName](seriesModel, ecModel, api, payload);
  22259. }
  22260. return progressMethodMap[methodName];
  22261. }
  22262. var progressMethodMap = {
  22263. incrementalPrepareRender: {
  22264. progress: function (params, context) {
  22265. context.view.incrementalRender(
  22266. params, context.model, context.ecModel, context.api, context.payload
  22267. );
  22268. }
  22269. },
  22270. render: {
  22271. // Put view.render in `progress` to support appendData. But in this case
  22272. // view.render should not be called in reset, otherwise it will be called
  22273. // twise. Use `forceFirstProgress` to make sure that view.render is called
  22274. // in any cases.
  22275. forceFirstProgress: true,
  22276. progress: function (params, context) {
  22277. context.view.render(
  22278. context.model, context.ecModel, context.api, context.payload
  22279. );
  22280. }
  22281. }
  22282. };
  22283. /*
  22284. * Licensed to the Apache Software Foundation (ASF) under one
  22285. * or more contributor license agreements. See the NOTICE file
  22286. * distributed with this work for additional information
  22287. * regarding copyright ownership. The ASF licenses this file
  22288. * to you under the Apache License, Version 2.0 (the
  22289. * "License"); you may not use this file except in compliance
  22290. * with the License. You may obtain a copy of the License at
  22291. *
  22292. * http://www.apache.org/licenses/LICENSE-2.0
  22293. *
  22294. * Unless required by applicable law or agreed to in writing,
  22295. * software distributed under the License is distributed on an
  22296. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22297. * KIND, either express or implied. See the License for the
  22298. * specific language governing permissions and limitations
  22299. * under the License.
  22300. */
  22301. var ORIGIN_METHOD = '\0__throttleOriginMethod';
  22302. var RATE = '\0__throttleRate';
  22303. var THROTTLE_TYPE = '\0__throttleType';
  22304. /**
  22305. * @public
  22306. * @param {(Function)} fn
  22307. * @param {number} [delay=0] Unit: ms.
  22308. * @param {boolean} [debounce=false]
  22309. * true: If call interval less than `delay`, only the last call works.
  22310. * false: If call interval less than `delay, call works on fixed rate.
  22311. * @return {(Function)} throttled fn.
  22312. */
  22313. function throttle(fn, delay, debounce) {
  22314. var currCall;
  22315. var lastCall = 0;
  22316. var lastExec = 0;
  22317. var timer = null;
  22318. var diff;
  22319. var scope;
  22320. var args;
  22321. var debounceNextCall;
  22322. delay = delay || 0;
  22323. function exec() {
  22324. lastExec = (new Date()).getTime();
  22325. timer = null;
  22326. fn.apply(scope, args || []);
  22327. }
  22328. var cb = function () {
  22329. currCall = (new Date()).getTime();
  22330. scope = this;
  22331. args = arguments;
  22332. var thisDelay = debounceNextCall || delay;
  22333. var thisDebounce = debounceNextCall || debounce;
  22334. debounceNextCall = null;
  22335. diff = currCall - (thisDebounce ? lastCall : lastExec) - thisDelay;
  22336. clearTimeout(timer);
  22337. // Here we should make sure that: the `exec` SHOULD NOT be called later
  22338. // than a new call of `cb`, that is, preserving the command order. Consider
  22339. // calculating "scale rate" when roaming as an example. When a call of `cb`
  22340. // happens, either the `exec` is called dierectly, or the call is delayed.
  22341. // But the delayed call should never be later than next call of `cb`. Under
  22342. // this assurance, we can simply update view state each time `dispatchAction`
  22343. // triggered by user roaming, but not need to add extra code to avoid the
  22344. // state being "rolled-back".
  22345. if (thisDebounce) {
  22346. timer = setTimeout(exec, thisDelay);
  22347. }
  22348. else {
  22349. if (diff >= 0) {
  22350. exec();
  22351. }
  22352. else {
  22353. timer = setTimeout(exec, -diff);
  22354. }
  22355. }
  22356. lastCall = currCall;
  22357. };
  22358. /**
  22359. * Clear throttle.
  22360. * @public
  22361. */
  22362. cb.clear = function () {
  22363. if (timer) {
  22364. clearTimeout(timer);
  22365. timer = null;
  22366. }
  22367. };
  22368. /**
  22369. * Enable debounce once.
  22370. */
  22371. cb.debounceNextCall = function (debounceDelay) {
  22372. debounceNextCall = debounceDelay;
  22373. };
  22374. return cb;
  22375. }
  22376. /**
  22377. * Create throttle method or update throttle rate.
  22378. *
  22379. * @example
  22380. * ComponentView.prototype.render = function () {
  22381. * ...
  22382. * throttle.createOrUpdate(
  22383. * this,
  22384. * '_dispatchAction',
  22385. * this.model.get('throttle'),
  22386. * 'fixRate'
  22387. * );
  22388. * };
  22389. * ComponentView.prototype.remove = function () {
  22390. * throttle.clear(this, '_dispatchAction');
  22391. * };
  22392. * ComponentView.prototype.dispose = function () {
  22393. * throttle.clear(this, '_dispatchAction');
  22394. * };
  22395. *
  22396. * @public
  22397. * @param {Object} obj
  22398. * @param {string} fnAttr
  22399. * @param {number} [rate]
  22400. * @param {string} [throttleType='fixRate'] 'fixRate' or 'debounce'
  22401. * @return {Function} throttled function.
  22402. */
  22403. function createOrUpdate(obj, fnAttr, rate, throttleType) {
  22404. var fn = obj[fnAttr];
  22405. if (!fn) {
  22406. return;
  22407. }
  22408. var originFn = fn[ORIGIN_METHOD] || fn;
  22409. var lastThrottleType = fn[THROTTLE_TYPE];
  22410. var lastRate = fn[RATE];
  22411. if (lastRate !== rate || lastThrottleType !== throttleType) {
  22412. if (rate == null || !throttleType) {
  22413. return (obj[fnAttr] = originFn);
  22414. }
  22415. fn = obj[fnAttr] = throttle(
  22416. originFn, rate, throttleType === 'debounce'
  22417. );
  22418. fn[ORIGIN_METHOD] = originFn;
  22419. fn[THROTTLE_TYPE] = throttleType;
  22420. fn[RATE] = rate;
  22421. }
  22422. return fn;
  22423. }
  22424. /**
  22425. * Clear throttle. Example see throttle.createOrUpdate.
  22426. *
  22427. * @public
  22428. * @param {Object} obj
  22429. * @param {string} fnAttr
  22430. */
  22431. function clear(obj, fnAttr) {
  22432. var fn = obj[fnAttr];
  22433. if (fn && fn[ORIGIN_METHOD]) {
  22434. obj[fnAttr] = fn[ORIGIN_METHOD];
  22435. }
  22436. }
  22437. /*
  22438. * Licensed to the Apache Software Foundation (ASF) under one
  22439. * or more contributor license agreements. See the NOTICE file
  22440. * distributed with this work for additional information
  22441. * regarding copyright ownership. The ASF licenses this file
  22442. * to you under the Apache License, Version 2.0 (the
  22443. * "License"); you may not use this file except in compliance
  22444. * with the License. You may obtain a copy of the License at
  22445. *
  22446. * http://www.apache.org/licenses/LICENSE-2.0
  22447. *
  22448. * Unless required by applicable law or agreed to in writing,
  22449. * software distributed under the License is distributed on an
  22450. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22451. * KIND, either express or implied. See the License for the
  22452. * specific language governing permissions and limitations
  22453. * under the License.
  22454. */
  22455. var seriesColor = {
  22456. createOnAllSeries: true,
  22457. performRawSeries: true,
  22458. reset: function (seriesModel, ecModel) {
  22459. var data = seriesModel.getData();
  22460. var colorAccessPath = (seriesModel.visualColorAccessPath || 'itemStyle.color').split('.');
  22461. // Set in itemStyle
  22462. var color = seriesModel.get(colorAccessPath);
  22463. var colorCallback = (isFunction$1(color) && !(color instanceof Gradient))
  22464. ? color : null;
  22465. // Default color
  22466. if (!color || colorCallback) {
  22467. color = seriesModel.getColorFromPalette(
  22468. // TODO series count changed.
  22469. seriesModel.name, null, ecModel.getSeriesCount()
  22470. );
  22471. }
  22472. data.setVisual('color', color);
  22473. var borderColorAccessPath = (seriesModel.visualBorderColorAccessPath || 'itemStyle.borderColor').split('.');
  22474. var borderColor = seriesModel.get(borderColorAccessPath);
  22475. data.setVisual('borderColor', borderColor);
  22476. // Only visible series has each data be visual encoded
  22477. if (!ecModel.isSeriesFiltered(seriesModel)) {
  22478. if (colorCallback) {
  22479. data.each(function (idx) {
  22480. data.setItemVisual(
  22481. idx, 'color', colorCallback(seriesModel.getDataParams(idx))
  22482. );
  22483. });
  22484. }
  22485. // itemStyle in each data item
  22486. var dataEach = function (data, idx) {
  22487. var itemModel = data.getItemModel(idx);
  22488. var color = itemModel.get(colorAccessPath, true);
  22489. var borderColor = itemModel.get(borderColorAccessPath, true);
  22490. if (color != null) {
  22491. data.setItemVisual(idx, 'color', color);
  22492. }
  22493. if (borderColor != null) {
  22494. data.setItemVisual(idx, 'borderColor', borderColor);
  22495. }
  22496. };
  22497. return { dataEach: data.hasItemOption ? dataEach : null };
  22498. }
  22499. }
  22500. };
  22501. /*
  22502. * Licensed to the Apache Software Foundation (ASF) under one
  22503. * or more contributor license agreements. See the NOTICE file
  22504. * distributed with this work for additional information
  22505. * regarding copyright ownership. The ASF licenses this file
  22506. * to you under the Apache License, Version 2.0 (the
  22507. * "License"); you may not use this file except in compliance
  22508. * with the License. You may obtain a copy of the License at
  22509. *
  22510. * http://www.apache.org/licenses/LICENSE-2.0
  22511. *
  22512. * Unless required by applicable law or agreed to in writing,
  22513. * software distributed under the License is distributed on an
  22514. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22515. * KIND, either express or implied. See the License for the
  22516. * specific language governing permissions and limitations
  22517. * under the License.
  22518. */
  22519. /**
  22520. * Language: (Simplified) Chinese.
  22521. */
  22522. var lang = {
  22523. legend: {
  22524. selector: {
  22525. all: '全选',
  22526. inverse: '反选'
  22527. }
  22528. },
  22529. toolbox: {
  22530. brush: {
  22531. title: {
  22532. rect: '矩形选择',
  22533. polygon: '圈选',
  22534. lineX: '横向选择',
  22535. lineY: '纵向选择',
  22536. keep: '保持选择',
  22537. clear: '清除选择'
  22538. }
  22539. },
  22540. dataView: {
  22541. title: '数据视图',
  22542. lang: ['数据视图', '关闭', '刷新']
  22543. },
  22544. dataZoom: {
  22545. title: {
  22546. zoom: '区域缩放',
  22547. back: '区域缩放还原'
  22548. }
  22549. },
  22550. magicType: {
  22551. title: {
  22552. line: '切换为折线图',
  22553. bar: '切换为柱状图',
  22554. stack: '切换为堆叠',
  22555. tiled: '切换为平铺'
  22556. }
  22557. },
  22558. restore: {
  22559. title: '还原'
  22560. },
  22561. saveAsImage: {
  22562. title: '保存为图片',
  22563. lang: ['右键另存为图片']
  22564. }
  22565. },
  22566. series: {
  22567. typeNames: {
  22568. pie: '饼图',
  22569. bar: '柱状图',
  22570. line: '折线图',
  22571. scatter: '散点图',
  22572. effectScatter: '涟漪散点图',
  22573. radar: '雷达图',
  22574. tree: '树图',
  22575. treemap: '矩形树图',
  22576. boxplot: '箱型图',
  22577. candlestick: 'K线图',
  22578. k: 'K线图',
  22579. heatmap: '热力图',
  22580. map: '地图',
  22581. parallel: '平行坐标图',
  22582. lines: '线图',
  22583. graph: '关系图',
  22584. sankey: '桑基图',
  22585. funnel: '漏斗图',
  22586. gauge: '仪表盘图',
  22587. pictorialBar: '象形柱图',
  22588. themeRiver: '主题河流图',
  22589. sunburst: '旭日图'
  22590. }
  22591. },
  22592. aria: {
  22593. general: {
  22594. withTitle: '这是一个关于“{title}”的图表。',
  22595. withoutTitle: '这是一个图表,'
  22596. },
  22597. series: {
  22598. single: {
  22599. prefix: '',
  22600. withName: '图表类型是{seriesType},表示{seriesName}。',
  22601. withoutName: '图表类型是{seriesType}。'
  22602. },
  22603. multiple: {
  22604. prefix: '它由{seriesCount}个图表系列组成。',
  22605. withName: '第{seriesId}个系列是一个表示{seriesName}的{seriesType},',
  22606. withoutName: '第{seriesId}个系列是一个{seriesType},',
  22607. separator: {
  22608. middle: ';',
  22609. end: '。'
  22610. }
  22611. }
  22612. },
  22613. data: {
  22614. allData: '其数据是——',
  22615. partialData: '其中,前{displayCnt}项是——',
  22616. withName: '{name}的数据是{value}',
  22617. withoutName: '{value}',
  22618. separator: {
  22619. middle: ',',
  22620. end: ''
  22621. }
  22622. }
  22623. }
  22624. };
  22625. /*
  22626. * Licensed to the Apache Software Foundation (ASF) under one
  22627. * or more contributor license agreements. See the NOTICE file
  22628. * distributed with this work for additional information
  22629. * regarding copyright ownership. The ASF licenses this file
  22630. * to you under the Apache License, Version 2.0 (the
  22631. * "License"); you may not use this file except in compliance
  22632. * with the License. You may obtain a copy of the License at
  22633. *
  22634. * http://www.apache.org/licenses/LICENSE-2.0
  22635. *
  22636. * Unless required by applicable law or agreed to in writing,
  22637. * software distributed under the License is distributed on an
  22638. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22639. * KIND, either express or implied. See the License for the
  22640. * specific language governing permissions and limitations
  22641. * under the License.
  22642. */
  22643. var aria = function (dom, ecModel) {
  22644. var ariaModel = ecModel.getModel('aria');
  22645. if (!ariaModel.get('show')) {
  22646. return;
  22647. }
  22648. else if (ariaModel.get('description')) {
  22649. dom.setAttribute('aria-label', ariaModel.get('description'));
  22650. return;
  22651. }
  22652. var seriesCnt = 0;
  22653. ecModel.eachSeries(function (seriesModel, idx) {
  22654. ++seriesCnt;
  22655. }, this);
  22656. var maxDataCnt = ariaModel.get('data.maxCount') || 10;
  22657. var maxSeriesCnt = ariaModel.get('series.maxCount') || 10;
  22658. var displaySeriesCnt = Math.min(seriesCnt, maxSeriesCnt);
  22659. var ariaLabel;
  22660. if (seriesCnt < 1) {
  22661. // No series, no aria label
  22662. return;
  22663. }
  22664. else {
  22665. var title = getTitle();
  22666. if (title) {
  22667. ariaLabel = replace(getConfig('general.withTitle'), {
  22668. title: title
  22669. });
  22670. }
  22671. else {
  22672. ariaLabel = getConfig('general.withoutTitle');
  22673. }
  22674. var seriesLabels = [];
  22675. var prefix = seriesCnt > 1
  22676. ? 'series.multiple.prefix'
  22677. : 'series.single.prefix';
  22678. ariaLabel += replace(getConfig(prefix), { seriesCount: seriesCnt });
  22679. ecModel.eachSeries(function (seriesModel, idx) {
  22680. if (idx < displaySeriesCnt) {
  22681. var seriesLabel;
  22682. var seriesName = seriesModel.get('name');
  22683. var seriesTpl = 'series.'
  22684. + (seriesCnt > 1 ? 'multiple' : 'single') + '.';
  22685. seriesLabel = getConfig(seriesName
  22686. ? seriesTpl + 'withName'
  22687. : seriesTpl + 'withoutName');
  22688. seriesLabel = replace(seriesLabel, {
  22689. seriesId: seriesModel.seriesIndex,
  22690. seriesName: seriesModel.get('name'),
  22691. seriesType: getSeriesTypeName(seriesModel.subType)
  22692. });
  22693. var data = seriesModel.getData();
  22694. window.data = data;
  22695. if (data.count() > maxDataCnt) {
  22696. // Show part of data
  22697. seriesLabel += replace(getConfig('data.partialData'), {
  22698. displayCnt: maxDataCnt
  22699. });
  22700. }
  22701. else {
  22702. seriesLabel += getConfig('data.allData');
  22703. }
  22704. var dataLabels = [];
  22705. for (var i = 0; i < data.count(); i++) {
  22706. if (i < maxDataCnt) {
  22707. var name = data.getName(i);
  22708. var value = retrieveRawValue(data, i);
  22709. dataLabels.push(
  22710. replace(
  22711. name
  22712. ? getConfig('data.withName')
  22713. : getConfig('data.withoutName'),
  22714. {
  22715. name: name,
  22716. value: value
  22717. }
  22718. )
  22719. );
  22720. }
  22721. }
  22722. seriesLabel += dataLabels
  22723. .join(getConfig('data.separator.middle'))
  22724. + getConfig('data.separator.end');
  22725. seriesLabels.push(seriesLabel);
  22726. }
  22727. });
  22728. ariaLabel += seriesLabels
  22729. .join(getConfig('series.multiple.separator.middle'))
  22730. + getConfig('series.multiple.separator.end');
  22731. dom.setAttribute('aria-label', ariaLabel);
  22732. }
  22733. function replace(str, keyValues) {
  22734. if (typeof str !== 'string') {
  22735. return str;
  22736. }
  22737. var result = str;
  22738. each$1(keyValues, function (value, key) {
  22739. result = result.replace(
  22740. new RegExp('\\{\\s*' + key + '\\s*\\}', 'g'),
  22741. value
  22742. );
  22743. });
  22744. return result;
  22745. }
  22746. function getConfig(path) {
  22747. var userConfig = ariaModel.get(path);
  22748. if (userConfig == null) {
  22749. var pathArr = path.split('.');
  22750. var result = lang.aria;
  22751. for (var i = 0; i < pathArr.length; ++i) {
  22752. result = result[pathArr[i]];
  22753. }
  22754. return result;
  22755. }
  22756. else {
  22757. return userConfig;
  22758. }
  22759. }
  22760. function getTitle() {
  22761. var title = ecModel.getModel('title').option;
  22762. if (title && title.length) {
  22763. title = title[0];
  22764. }
  22765. return title && title.text;
  22766. }
  22767. function getSeriesTypeName(type) {
  22768. return lang.series.typeNames[type] || '自定义图';
  22769. }
  22770. };
  22771. /*
  22772. * Licensed to the Apache Software Foundation (ASF) under one
  22773. * or more contributor license agreements. See the NOTICE file
  22774. * distributed with this work for additional information
  22775. * regarding copyright ownership. The ASF licenses this file
  22776. * to you under the Apache License, Version 2.0 (the
  22777. * "License"); you may not use this file except in compliance
  22778. * with the License. You may obtain a copy of the License at
  22779. *
  22780. * http://www.apache.org/licenses/LICENSE-2.0
  22781. *
  22782. * Unless required by applicable law or agreed to in writing,
  22783. * software distributed under the License is distributed on an
  22784. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22785. * KIND, either express or implied. See the License for the
  22786. * specific language governing permissions and limitations
  22787. * under the License.
  22788. */
  22789. var PI$1 = Math.PI;
  22790. /**
  22791. * @param {module:echarts/ExtensionAPI} api
  22792. * @param {Object} [opts]
  22793. * @param {string} [opts.text]
  22794. * @param {string} [opts.color]
  22795. * @param {string} [opts.textColor]
  22796. * @return {module:zrender/Element}
  22797. */
  22798. var loadingDefault = function (api, opts) {
  22799. opts = opts || {};
  22800. defaults(opts, {
  22801. text: 'loading',
  22802. textColor: '#000',
  22803. fontSize: '12px',
  22804. maskColor: 'rgba(255, 255, 255, 0.8)',
  22805. showSpinner: true,
  22806. color: '#c23531',
  22807. spinnerRadius: 10,
  22808. lineWidth: 5,
  22809. zlevel: 0
  22810. });
  22811. var group = new Group();
  22812. var mask = new Rect({
  22813. style: {
  22814. fill: opts.maskColor
  22815. },
  22816. zlevel: opts.zlevel,
  22817. z: 10000
  22818. });
  22819. group.add(mask);
  22820. var font = opts.fontSize + ' sans-serif';
  22821. var labelRect = new Rect({
  22822. style: {
  22823. fill: 'none',
  22824. text: opts.text,
  22825. font: font,
  22826. textPosition: 'right',
  22827. textDistance: 10,
  22828. textFill: opts.textColor
  22829. },
  22830. zlevel: opts.zlevel,
  22831. z: 10001
  22832. });
  22833. group.add(labelRect);
  22834. if (opts.showSpinner) {
  22835. var arc = new Arc({
  22836. shape: {
  22837. startAngle: -PI$1 / 2,
  22838. endAngle: -PI$1 / 2 + 0.1,
  22839. r: opts.spinnerRadius
  22840. },
  22841. style: {
  22842. stroke: opts.color,
  22843. lineCap: 'round',
  22844. lineWidth: opts.lineWidth
  22845. },
  22846. zlevel: opts.zlevel,
  22847. z: 10001
  22848. });
  22849. arc.animateShape(true)
  22850. .when(1000, {
  22851. endAngle: PI$1 * 3 / 2
  22852. })
  22853. .start('circularInOut');
  22854. arc.animateShape(true)
  22855. .when(1000, {
  22856. startAngle: PI$1 * 3 / 2
  22857. })
  22858. .delay(300)
  22859. .start('circularInOut');
  22860. group.add(arc);
  22861. }
  22862. // Inject resize
  22863. group.resize = function () {
  22864. var textWidth = getWidth(opts.text, font);
  22865. var r = opts.showSpinner ? opts.spinnerRadius : 0;
  22866. // cx = (containerWidth - arcDiameter - textDistance - textWidth) / 2
  22867. // textDistance needs to be calculated when both animation and text exist
  22868. var cx = (api.getWidth() - r * 2 - (opts.showSpinner && textWidth ? 10 : 0) - textWidth) / 2
  22869. // only show the text
  22870. - (opts.showSpinner ? 0 : textWidth / 2);
  22871. var cy = api.getHeight() / 2;
  22872. opts.showSpinner && arc.setShape({
  22873. cx: cx,
  22874. cy: cy
  22875. });
  22876. labelRect.setShape({
  22877. x: cx - r,
  22878. y: cy - r,
  22879. width: r * 2,
  22880. height: r * 2
  22881. });
  22882. mask.setShape({
  22883. x: 0,
  22884. y: 0,
  22885. width: api.getWidth(),
  22886. height: api.getHeight()
  22887. });
  22888. };
  22889. group.resize();
  22890. return group;
  22891. };
  22892. /*
  22893. * Licensed to the Apache Software Foundation (ASF) under one
  22894. * or more contributor license agreements. See the NOTICE file
  22895. * distributed with this work for additional information
  22896. * regarding copyright ownership. The ASF licenses this file
  22897. * to you under the Apache License, Version 2.0 (the
  22898. * "License"); you may not use this file except in compliance
  22899. * with the License. You may obtain a copy of the License at
  22900. *
  22901. * http://www.apache.org/licenses/LICENSE-2.0
  22902. *
  22903. * Unless required by applicable law or agreed to in writing,
  22904. * software distributed under the License is distributed on an
  22905. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22906. * KIND, either express or implied. See the License for the
  22907. * specific language governing permissions and limitations
  22908. * under the License.
  22909. */
  22910. /**
  22911. * @module echarts/stream/Scheduler
  22912. */
  22913. /**
  22914. * @constructor
  22915. */
  22916. function Scheduler(ecInstance, api, dataProcessorHandlers, visualHandlers) {
  22917. this.ecInstance = ecInstance;
  22918. this.api = api;
  22919. this.unfinished;
  22920. // Fix current processors in case that in some rear cases that
  22921. // processors might be registered after echarts instance created.
  22922. // Register processors incrementally for a echarts instance is
  22923. // not supported by this stream architecture.
  22924. var dataProcessorHandlers = this._dataProcessorHandlers = dataProcessorHandlers.slice();
  22925. var visualHandlers = this._visualHandlers = visualHandlers.slice();
  22926. this._allHandlers = dataProcessorHandlers.concat(visualHandlers);
  22927. /**
  22928. * @private
  22929. * @type {
  22930. * [handlerUID: string]: {
  22931. * seriesTaskMap?: {
  22932. * [seriesUID: string]: Task
  22933. * },
  22934. * overallTask?: Task
  22935. * }
  22936. * }
  22937. */
  22938. this._stageTaskMap = createHashMap();
  22939. }
  22940. var proto = Scheduler.prototype;
  22941. /**
  22942. * @param {module:echarts/model/Global} ecModel
  22943. * @param {Object} payload
  22944. */
  22945. proto.restoreData = function (ecModel, payload) {
  22946. // TODO: Only restroe needed series and components, but not all components.
  22947. // Currently `restoreData` of all of the series and component will be called.
  22948. // But some independent components like `title`, `legend`, `graphic`, `toolbox`,
  22949. // `tooltip`, `axisPointer`, etc, do not need series refresh when `setOption`,
  22950. // and some components like coordinate system, axes, dataZoom, visualMap only
  22951. // need their target series refresh.
  22952. // (1) If we are implementing this feature some day, we should consider these cases:
  22953. // if a data processor depends on a component (e.g., dataZoomProcessor depends
  22954. // on the settings of `dataZoom`), it should be re-performed if the component
  22955. // is modified by `setOption`.
  22956. // (2) If a processor depends on sevral series, speicified by its `getTargetSeries`,
  22957. // it should be re-performed when the result array of `getTargetSeries` changed.
  22958. // We use `dependencies` to cover these issues.
  22959. // (3) How to update target series when coordinate system related components modified.
  22960. // TODO: simply the dirty mechanism? Check whether only the case here can set tasks dirty,
  22961. // and this case all of the tasks will be set as dirty.
  22962. ecModel.restoreData(payload);
  22963. // Theoretically an overall task not only depends on each of its target series, but also
  22964. // depends on all of the series.
  22965. // The overall task is not in pipeline, and `ecModel.restoreData` only set pipeline tasks
  22966. // dirty. If `getTargetSeries` of an overall task returns nothing, we should also ensure
  22967. // that the overall task is set as dirty and to be performed, otherwise it probably cause
  22968. // state chaos. So we have to set dirty of all of the overall tasks manually, otherwise it
  22969. // probably cause state chaos (consider `dataZoomProcessor`).
  22970. this._stageTaskMap.each(function (taskRecord) {
  22971. var overallTask = taskRecord.overallTask;
  22972. overallTask && overallTask.dirty();
  22973. });
  22974. };
  22975. // If seriesModel provided, incremental threshold is check by series data.
  22976. proto.getPerformArgs = function (task, isBlock) {
  22977. // For overall task
  22978. if (!task.__pipeline) {
  22979. return;
  22980. }
  22981. var pipeline = this._pipelineMap.get(task.__pipeline.id);
  22982. var pCtx = pipeline.context;
  22983. var incremental = !isBlock
  22984. && pipeline.progressiveEnabled
  22985. && (!pCtx || pCtx.progressiveRender)
  22986. && task.__idxInPipeline > pipeline.blockIndex;
  22987. var step = incremental ? pipeline.step : null;
  22988. var modDataCount = pCtx && pCtx.modDataCount;
  22989. var modBy = modDataCount != null ? Math.ceil(modDataCount / step) : null;
  22990. return {step: step, modBy: modBy, modDataCount: modDataCount};
  22991. };
  22992. proto.getPipeline = function (pipelineId) {
  22993. return this._pipelineMap.get(pipelineId);
  22994. };
  22995. /**
  22996. * Current, progressive rendering starts from visual and layout.
  22997. * Always detect render mode in the same stage, avoiding that incorrect
  22998. * detection caused by data filtering.
  22999. * Caution:
  23000. * `updateStreamModes` use `seriesModel.getData()`.
  23001. */
  23002. proto.updateStreamModes = function (seriesModel, view) {
  23003. var pipeline = this._pipelineMap.get(seriesModel.uid);
  23004. var data = seriesModel.getData();
  23005. var dataLen = data.count();
  23006. // `progressiveRender` means that can render progressively in each
  23007. // animation frame. Note that some types of series do not provide
  23008. // `view.incrementalPrepareRender` but support `chart.appendData`. We
  23009. // use the term `incremental` but not `progressive` to describe the
  23010. // case that `chart.appendData`.
  23011. var progressiveRender = pipeline.progressiveEnabled
  23012. && view.incrementalPrepareRender
  23013. && dataLen >= pipeline.threshold;
  23014. var large = seriesModel.get('large') && dataLen >= seriesModel.get('largeThreshold');
  23015. // TODO: modDataCount should not updated if `appendData`, otherwise cause whole repaint.
  23016. // see `test/candlestick-large3.html`
  23017. var modDataCount = seriesModel.get('progressiveChunkMode') === 'mod' ? dataLen : null;
  23018. seriesModel.pipelineContext = pipeline.context = {
  23019. progressiveRender: progressiveRender,
  23020. modDataCount: modDataCount,
  23021. large: large
  23022. };
  23023. };
  23024. proto.restorePipelines = function (ecModel) {
  23025. var scheduler = this;
  23026. var pipelineMap = scheduler._pipelineMap = createHashMap();
  23027. ecModel.eachSeries(function (seriesModel) {
  23028. var progressive = seriesModel.getProgressive();
  23029. var pipelineId = seriesModel.uid;
  23030. pipelineMap.set(pipelineId, {
  23031. id: pipelineId,
  23032. head: null,
  23033. tail: null,
  23034. threshold: seriesModel.getProgressiveThreshold(),
  23035. progressiveEnabled: progressive
  23036. && !(seriesModel.preventIncremental && seriesModel.preventIncremental()),
  23037. blockIndex: -1,
  23038. step: Math.round(progressive || 700),
  23039. count: 0
  23040. });
  23041. pipe(scheduler, seriesModel, seriesModel.dataTask);
  23042. });
  23043. };
  23044. proto.prepareStageTasks = function () {
  23045. var stageTaskMap = this._stageTaskMap;
  23046. var ecModel = this.ecInstance.getModel();
  23047. var api = this.api;
  23048. each$1(this._allHandlers, function (handler) {
  23049. var record = stageTaskMap.get(handler.uid) || stageTaskMap.set(handler.uid, []);
  23050. handler.reset && createSeriesStageTask(this, handler, record, ecModel, api);
  23051. handler.overallReset && createOverallStageTask(this, handler, record, ecModel, api);
  23052. }, this);
  23053. };
  23054. proto.prepareView = function (view, model, ecModel, api) {
  23055. var renderTask = view.renderTask;
  23056. var context = renderTask.context;
  23057. context.model = model;
  23058. context.ecModel = ecModel;
  23059. context.api = api;
  23060. renderTask.__block = !view.incrementalPrepareRender;
  23061. pipe(this, model, renderTask);
  23062. };
  23063. proto.performDataProcessorTasks = function (ecModel, payload) {
  23064. // If we do not use `block` here, it should be considered when to update modes.
  23065. performStageTasks(this, this._dataProcessorHandlers, ecModel, payload, {block: true});
  23066. };
  23067. // opt
  23068. // opt.visualType: 'visual' or 'layout'
  23069. // opt.setDirty
  23070. proto.performVisualTasks = function (ecModel, payload, opt) {
  23071. performStageTasks(this, this._visualHandlers, ecModel, payload, opt);
  23072. };
  23073. function performStageTasks(scheduler, stageHandlers, ecModel, payload, opt) {
  23074. opt = opt || {};
  23075. var unfinished;
  23076. each$1(stageHandlers, function (stageHandler, idx) {
  23077. if (opt.visualType && opt.visualType !== stageHandler.visualType) {
  23078. return;
  23079. }
  23080. var stageHandlerRecord = scheduler._stageTaskMap.get(stageHandler.uid);
  23081. var seriesTaskMap = stageHandlerRecord.seriesTaskMap;
  23082. var overallTask = stageHandlerRecord.overallTask;
  23083. if (overallTask) {
  23084. var overallNeedDirty;
  23085. var agentStubMap = overallTask.agentStubMap;
  23086. agentStubMap.each(function (stub) {
  23087. if (needSetDirty(opt, stub)) {
  23088. stub.dirty();
  23089. overallNeedDirty = true;
  23090. }
  23091. });
  23092. overallNeedDirty && overallTask.dirty();
  23093. updatePayload(overallTask, payload);
  23094. var performArgs = scheduler.getPerformArgs(overallTask, opt.block);
  23095. // Execute stubs firstly, which may set the overall task dirty,
  23096. // then execute the overall task. And stub will call seriesModel.setData,
  23097. // which ensures that in the overallTask seriesModel.getData() will not
  23098. // return incorrect data.
  23099. agentStubMap.each(function (stub) {
  23100. stub.perform(performArgs);
  23101. });
  23102. unfinished |= overallTask.perform(performArgs);
  23103. }
  23104. else if (seriesTaskMap) {
  23105. seriesTaskMap.each(function (task, pipelineId) {
  23106. if (needSetDirty(opt, task)) {
  23107. task.dirty();
  23108. }
  23109. var performArgs = scheduler.getPerformArgs(task, opt.block);
  23110. // FIXME
  23111. // if intending to decalare `performRawSeries` in handlers, only
  23112. // stream-independent (specifically, data item independent) operations can be
  23113. // performed. Because is a series is filtered, most of the tasks will not
  23114. // be performed. A stream-dependent operation probably cause wrong biz logic.
  23115. // Perhaps we should not provide a separate callback for this case instead
  23116. // of providing the config `performRawSeries`. The stream-dependent operaions
  23117. // and stream-independent operations should better not be mixed.
  23118. performArgs.skip = !stageHandler.performRawSeries
  23119. && ecModel.isSeriesFiltered(task.context.model);
  23120. updatePayload(task, payload);
  23121. unfinished |= task.perform(performArgs);
  23122. });
  23123. }
  23124. });
  23125. function needSetDirty(opt, task) {
  23126. return opt.setDirty && (!opt.dirtyMap || opt.dirtyMap.get(task.__pipeline.id));
  23127. }
  23128. scheduler.unfinished |= unfinished;
  23129. }
  23130. proto.performSeriesTasks = function (ecModel) {
  23131. var unfinished;
  23132. ecModel.eachSeries(function (seriesModel) {
  23133. // Progress to the end for dataInit and dataRestore.
  23134. unfinished |= seriesModel.dataTask.perform();
  23135. });
  23136. this.unfinished |= unfinished;
  23137. };
  23138. proto.plan = function () {
  23139. // Travel pipelines, check block.
  23140. this._pipelineMap.each(function (pipeline) {
  23141. var task = pipeline.tail;
  23142. do {
  23143. if (task.__block) {
  23144. pipeline.blockIndex = task.__idxInPipeline;
  23145. break;
  23146. }
  23147. task = task.getUpstream();
  23148. }
  23149. while (task);
  23150. });
  23151. };
  23152. var updatePayload = proto.updatePayload = function (task, payload) {
  23153. payload !== 'remain' && (task.context.payload = payload);
  23154. };
  23155. function createSeriesStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) {
  23156. var seriesTaskMap = stageHandlerRecord.seriesTaskMap
  23157. || (stageHandlerRecord.seriesTaskMap = createHashMap());
  23158. var seriesType = stageHandler.seriesType;
  23159. var getTargetSeries = stageHandler.getTargetSeries;
  23160. // If a stageHandler should cover all series, `createOnAllSeries` should be declared mandatorily,
  23161. // to avoid some typo or abuse. Otherwise if an extension do not specify a `seriesType`,
  23162. // it works but it may cause other irrelevant charts blocked.
  23163. if (stageHandler.createOnAllSeries) {
  23164. ecModel.eachRawSeries(create);
  23165. }
  23166. else if (seriesType) {
  23167. ecModel.eachRawSeriesByType(seriesType, create);
  23168. }
  23169. else if (getTargetSeries) {
  23170. getTargetSeries(ecModel, api).each(create);
  23171. }
  23172. function create(seriesModel) {
  23173. var pipelineId = seriesModel.uid;
  23174. // Init tasks for each seriesModel only once.
  23175. // Reuse original task instance.
  23176. var task = seriesTaskMap.get(pipelineId)
  23177. || seriesTaskMap.set(pipelineId, createTask({
  23178. plan: seriesTaskPlan,
  23179. reset: seriesTaskReset,
  23180. count: seriesTaskCount
  23181. }));
  23182. task.context = {
  23183. model: seriesModel,
  23184. ecModel: ecModel,
  23185. api: api,
  23186. useClearVisual: stageHandler.isVisual && !stageHandler.isLayout,
  23187. plan: stageHandler.plan,
  23188. reset: stageHandler.reset,
  23189. scheduler: scheduler
  23190. };
  23191. pipe(scheduler, seriesModel, task);
  23192. }
  23193. // Clear unused series tasks.
  23194. var pipelineMap = scheduler._pipelineMap;
  23195. seriesTaskMap.each(function (task, pipelineId) {
  23196. if (!pipelineMap.get(pipelineId)) {
  23197. task.dispose();
  23198. seriesTaskMap.removeKey(pipelineId);
  23199. }
  23200. });
  23201. }
  23202. function createOverallStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) {
  23203. var overallTask = stageHandlerRecord.overallTask = stageHandlerRecord.overallTask
  23204. // For overall task, the function only be called on reset stage.
  23205. || createTask({reset: overallTaskReset});
  23206. overallTask.context = {
  23207. ecModel: ecModel,
  23208. api: api,
  23209. overallReset: stageHandler.overallReset,
  23210. scheduler: scheduler
  23211. };
  23212. // Reuse orignal stubs.
  23213. var agentStubMap = overallTask.agentStubMap = overallTask.agentStubMap || createHashMap();
  23214. var seriesType = stageHandler.seriesType;
  23215. var getTargetSeries = stageHandler.getTargetSeries;
  23216. var overallProgress = true;
  23217. var modifyOutputEnd = stageHandler.modifyOutputEnd;
  23218. // An overall task with seriesType detected or has `getTargetSeries`, we add
  23219. // stub in each pipelines, it will set the overall task dirty when the pipeline
  23220. // progress. Moreover, to avoid call the overall task each frame (too frequent),
  23221. // we set the pipeline block.
  23222. if (seriesType) {
  23223. ecModel.eachRawSeriesByType(seriesType, createStub);
  23224. }
  23225. else if (getTargetSeries) {
  23226. getTargetSeries(ecModel, api).each(createStub);
  23227. }
  23228. // Otherwise, (usually it is legancy case), the overall task will only be
  23229. // executed when upstream dirty. Otherwise the progressive rendering of all
  23230. // pipelines will be disabled unexpectedly. But it still needs stubs to receive
  23231. // dirty info from upsteam.
  23232. else {
  23233. overallProgress = false;
  23234. each$1(ecModel.getSeries(), createStub);
  23235. }
  23236. function createStub(seriesModel) {
  23237. var pipelineId = seriesModel.uid;
  23238. var stub = agentStubMap.get(pipelineId);
  23239. if (!stub) {
  23240. stub = agentStubMap.set(pipelineId, createTask(
  23241. {reset: stubReset, onDirty: stubOnDirty}
  23242. ));
  23243. // When the result of `getTargetSeries` changed, the overallTask
  23244. // should be set as dirty and re-performed.
  23245. overallTask.dirty();
  23246. }
  23247. stub.context = {
  23248. model: seriesModel,
  23249. overallProgress: overallProgress,
  23250. modifyOutputEnd: modifyOutputEnd
  23251. };
  23252. stub.agent = overallTask;
  23253. stub.__block = overallProgress;
  23254. pipe(scheduler, seriesModel, stub);
  23255. }
  23256. // Clear unused stubs.
  23257. var pipelineMap = scheduler._pipelineMap;
  23258. agentStubMap.each(function (stub, pipelineId) {
  23259. if (!pipelineMap.get(pipelineId)) {
  23260. stub.dispose();
  23261. // When the result of `getTargetSeries` changed, the overallTask
  23262. // should be set as dirty and re-performed.
  23263. overallTask.dirty();
  23264. agentStubMap.removeKey(pipelineId);
  23265. }
  23266. });
  23267. }
  23268. function overallTaskReset(context) {
  23269. context.overallReset(
  23270. context.ecModel, context.api, context.payload
  23271. );
  23272. }
  23273. function stubReset(context, upstreamContext) {
  23274. return context.overallProgress && stubProgress;
  23275. }
  23276. function stubProgress() {
  23277. this.agent.dirty();
  23278. this.getDownstream().dirty();
  23279. }
  23280. function stubOnDirty() {
  23281. this.agent && this.agent.dirty();
  23282. }
  23283. function seriesTaskPlan(context) {
  23284. return context.plan && context.plan(
  23285. context.model, context.ecModel, context.api, context.payload
  23286. );
  23287. }
  23288. function seriesTaskReset(context) {
  23289. if (context.useClearVisual) {
  23290. context.data.clearAllVisual();
  23291. }
  23292. var resetDefines = context.resetDefines = normalizeToArray(context.reset(
  23293. context.model, context.ecModel, context.api, context.payload
  23294. ));
  23295. return resetDefines.length > 1
  23296. ? map(resetDefines, function (v, idx) {
  23297. return makeSeriesTaskProgress(idx);
  23298. })
  23299. : singleSeriesTaskProgress;
  23300. }
  23301. var singleSeriesTaskProgress = makeSeriesTaskProgress(0);
  23302. function makeSeriesTaskProgress(resetDefineIdx) {
  23303. return function (params, context) {
  23304. var data = context.data;
  23305. var resetDefine = context.resetDefines[resetDefineIdx];
  23306. if (resetDefine && resetDefine.dataEach) {
  23307. for (var i = params.start; i < params.end; i++) {
  23308. resetDefine.dataEach(data, i);
  23309. }
  23310. }
  23311. else if (resetDefine && resetDefine.progress) {
  23312. resetDefine.progress(params, data);
  23313. }
  23314. };
  23315. }
  23316. function seriesTaskCount(context) {
  23317. return context.data.count();
  23318. }
  23319. function pipe(scheduler, seriesModel, task) {
  23320. var pipelineId = seriesModel.uid;
  23321. var pipeline = scheduler._pipelineMap.get(pipelineId);
  23322. !pipeline.head && (pipeline.head = task);
  23323. pipeline.tail && pipeline.tail.pipe(task);
  23324. pipeline.tail = task;
  23325. task.__idxInPipeline = pipeline.count++;
  23326. task.__pipeline = pipeline;
  23327. }
  23328. Scheduler.wrapStageHandler = function (stageHandler, visualType) {
  23329. if (isFunction$1(stageHandler)) {
  23330. stageHandler = {
  23331. overallReset: stageHandler,
  23332. seriesType: detectSeriseType(stageHandler)
  23333. };
  23334. }
  23335. stageHandler.uid = getUID('stageHandler');
  23336. visualType && (stageHandler.visualType = visualType);
  23337. return stageHandler;
  23338. };
  23339. /**
  23340. * Only some legacy stage handlers (usually in echarts extensions) are pure function.
  23341. * To ensure that they can work normally, they should work in block mode, that is,
  23342. * they should not be started util the previous tasks finished. So they cause the
  23343. * progressive rendering disabled. We try to detect the series type, to narrow down
  23344. * the block range to only the series type they concern, but not all series.
  23345. */
  23346. function detectSeriseType(legacyFunc) {
  23347. seriesType = null;
  23348. try {
  23349. // Assume there is no async when calling `eachSeriesByType`.
  23350. legacyFunc(ecModelMock, apiMock);
  23351. }
  23352. catch (e) {
  23353. }
  23354. return seriesType;
  23355. }
  23356. var ecModelMock = {};
  23357. var apiMock = {};
  23358. var seriesType;
  23359. mockMethods(ecModelMock, GlobalModel);
  23360. mockMethods(apiMock, ExtensionAPI);
  23361. ecModelMock.eachSeriesByType = ecModelMock.eachRawSeriesByType = function (type) {
  23362. seriesType = type;
  23363. };
  23364. ecModelMock.eachComponent = function (cond) {
  23365. if (cond.mainType === 'series' && cond.subType) {
  23366. seriesType = cond.subType;
  23367. }
  23368. };
  23369. function mockMethods(target, Clz) {
  23370. /* eslint-disable */
  23371. for (var name in Clz.prototype) {
  23372. // Do not use hasOwnProperty
  23373. target[name] = noop;
  23374. }
  23375. /* eslint-enable */
  23376. }
  23377. /*
  23378. * Licensed to the Apache Software Foundation (ASF) under one
  23379. * or more contributor license agreements. See the NOTICE file
  23380. * distributed with this work for additional information
  23381. * regarding copyright ownership. The ASF licenses this file
  23382. * to you under the Apache License, Version 2.0 (the
  23383. * "License"); you may not use this file except in compliance
  23384. * with the License. You may obtain a copy of the License at
  23385. *
  23386. * http://www.apache.org/licenses/LICENSE-2.0
  23387. *
  23388. * Unless required by applicable law or agreed to in writing,
  23389. * software distributed under the License is distributed on an
  23390. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23391. * KIND, either express or implied. See the License for the
  23392. * specific language governing permissions and limitations
  23393. * under the License.
  23394. */
  23395. var colorAll = [
  23396. '#37A2DA', '#32C5E9', '#67E0E3', '#9FE6B8', '#FFDB5C', '#ff9f7f',
  23397. '#fb7293', '#E062AE', '#E690D1', '#e7bcf3', '#9d96f5', '#8378EA', '#96BFFF'
  23398. ];
  23399. var lightTheme = {
  23400. color: colorAll,
  23401. colorLayer: [
  23402. ['#37A2DA', '#ffd85c', '#fd7b5f'],
  23403. ['#37A2DA', '#67E0E3', '#FFDB5C', '#ff9f7f', '#E062AE', '#9d96f5'],
  23404. ['#37A2DA', '#32C5E9', '#9FE6B8', '#FFDB5C', '#ff9f7f', '#fb7293', '#e7bcf3', '#8378EA', '#96BFFF'],
  23405. colorAll
  23406. ]
  23407. };
  23408. /*
  23409. * Licensed to the Apache Software Foundation (ASF) under one
  23410. * or more contributor license agreements. See the NOTICE file
  23411. * distributed with this work for additional information
  23412. * regarding copyright ownership. The ASF licenses this file
  23413. * to you under the Apache License, Version 2.0 (the
  23414. * "License"); you may not use this file except in compliance
  23415. * with the License. You may obtain a copy of the License at
  23416. *
  23417. * http://www.apache.org/licenses/LICENSE-2.0
  23418. *
  23419. * Unless required by applicable law or agreed to in writing,
  23420. * software distributed under the License is distributed on an
  23421. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23422. * KIND, either express or implied. See the License for the
  23423. * specific language governing permissions and limitations
  23424. * under the License.
  23425. */
  23426. var contrastColor = '#eee';
  23427. var axisCommon = function () {
  23428. return {
  23429. axisLine: {
  23430. lineStyle: {
  23431. color: contrastColor
  23432. }
  23433. },
  23434. axisTick: {
  23435. lineStyle: {
  23436. color: contrastColor
  23437. }
  23438. },
  23439. axisLabel: {
  23440. textStyle: {
  23441. color: contrastColor
  23442. }
  23443. },
  23444. splitLine: {
  23445. lineStyle: {
  23446. type: 'dashed',
  23447. color: '#aaa'
  23448. }
  23449. },
  23450. splitArea: {
  23451. areaStyle: {
  23452. color: contrastColor
  23453. }
  23454. }
  23455. };
  23456. };
  23457. var colorPalette = [
  23458. '#dd6b66', '#759aa0', '#e69d87', '#8dc1a9', '#ea7e53',
  23459. '#eedd78', '#73a373', '#73b9bc', '#7289ab', '#91ca8c', '#f49f42'
  23460. ];
  23461. var theme = {
  23462. color: colorPalette,
  23463. backgroundColor: '#333',
  23464. tooltip: {
  23465. axisPointer: {
  23466. lineStyle: {
  23467. color: contrastColor
  23468. },
  23469. crossStyle: {
  23470. color: contrastColor
  23471. },
  23472. label: {
  23473. color: '#000'
  23474. }
  23475. }
  23476. },
  23477. legend: {
  23478. textStyle: {
  23479. color: contrastColor
  23480. }
  23481. },
  23482. textStyle: {
  23483. color: contrastColor
  23484. },
  23485. title: {
  23486. textStyle: {
  23487. color: contrastColor
  23488. }
  23489. },
  23490. toolbox: {
  23491. iconStyle: {
  23492. normal: {
  23493. borderColor: contrastColor
  23494. }
  23495. }
  23496. },
  23497. dataZoom: {
  23498. textStyle: {
  23499. color: contrastColor
  23500. }
  23501. },
  23502. visualMap: {
  23503. textStyle: {
  23504. color: contrastColor
  23505. }
  23506. },
  23507. timeline: {
  23508. lineStyle: {
  23509. color: contrastColor
  23510. },
  23511. itemStyle: {
  23512. normal: {
  23513. color: colorPalette[1]
  23514. }
  23515. },
  23516. label: {
  23517. normal: {
  23518. textStyle: {
  23519. color: contrastColor
  23520. }
  23521. }
  23522. },
  23523. controlStyle: {
  23524. normal: {
  23525. color: contrastColor,
  23526. borderColor: contrastColor
  23527. }
  23528. }
  23529. },
  23530. timeAxis: axisCommon(),
  23531. logAxis: axisCommon(),
  23532. valueAxis: axisCommon(),
  23533. categoryAxis: axisCommon(),
  23534. line: {
  23535. symbol: 'circle'
  23536. },
  23537. graph: {
  23538. color: colorPalette
  23539. },
  23540. gauge: {
  23541. title: {
  23542. textStyle: {
  23543. color: contrastColor
  23544. }
  23545. }
  23546. },
  23547. candlestick: {
  23548. itemStyle: {
  23549. normal: {
  23550. color: '#FD1050',
  23551. color0: '#0CF49B',
  23552. borderColor: '#FD1050',
  23553. borderColor0: '#0CF49B'
  23554. }
  23555. }
  23556. }
  23557. };
  23558. theme.categoryAxis.splitLine.show = false;
  23559. /*
  23560. * Licensed to the Apache Software Foundation (ASF) under one
  23561. * or more contributor license agreements. See the NOTICE file
  23562. * distributed with this work for additional information
  23563. * regarding copyright ownership. The ASF licenses this file
  23564. * to you under the Apache License, Version 2.0 (the
  23565. * "License"); you may not use this file except in compliance
  23566. * with the License. You may obtain a copy of the License at
  23567. *
  23568. * http://www.apache.org/licenses/LICENSE-2.0
  23569. *
  23570. * Unless required by applicable law or agreed to in writing,
  23571. * software distributed under the License is distributed on an
  23572. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23573. * KIND, either express or implied. See the License for the
  23574. * specific language governing permissions and limitations
  23575. * under the License.
  23576. */
  23577. /**
  23578. * This module is imported by echarts directly.
  23579. *
  23580. * Notice:
  23581. * Always keep this file exists for backward compatibility.
  23582. * Because before 4.1.0, dataset is an optional component,
  23583. * some users may import this module manually.
  23584. */
  23585. ComponentModel.extend({
  23586. type: 'dataset',
  23587. /**
  23588. * @protected
  23589. */
  23590. defaultOption: {
  23591. // 'row', 'column'
  23592. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN,
  23593. // null/'auto': auto detect header, see "module:echarts/data/helper/sourceHelper"
  23594. sourceHeader: null,
  23595. dimensions: null,
  23596. source: null
  23597. },
  23598. optionUpdated: function () {
  23599. detectSourceFormat(this);
  23600. }
  23601. });
  23602. Component$1.extend({
  23603. type: 'dataset'
  23604. });
  23605. /**
  23606. * 椭圆形状
  23607. * @module zrender/graphic/shape/Ellipse
  23608. */
  23609. var Ellipse = Path.extend({
  23610. type: 'ellipse',
  23611. shape: {
  23612. cx: 0, cy: 0,
  23613. rx: 0, ry: 0
  23614. },
  23615. buildPath: function (ctx, shape) {
  23616. var k = 0.5522848;
  23617. var x = shape.cx;
  23618. var y = shape.cy;
  23619. var a = shape.rx;
  23620. var b = shape.ry;
  23621. var ox = a * k; // 水平控制点偏移量
  23622. var oy = b * k; // 垂直控制点偏移量
  23623. // 从椭圆的左端点开始顺时针绘制四条三次贝塞尔曲线
  23624. ctx.moveTo(x - a, y);
  23625. ctx.bezierCurveTo(x - a, y - oy, x - ox, y - b, x, y - b);
  23626. ctx.bezierCurveTo(x + ox, y - b, x + a, y - oy, x + a, y);
  23627. ctx.bezierCurveTo(x + a, y + oy, x + ox, y + b, x, y + b);
  23628. ctx.bezierCurveTo(x - ox, y + b, x - a, y + oy, x - a, y);
  23629. ctx.closePath();
  23630. }
  23631. });
  23632. // import RadialGradient from '../graphic/RadialGradient';
  23633. // import Pattern from '../graphic/Pattern';
  23634. // import * as vector from '../core/vector';
  23635. // Most of the values can be separated by comma and/or white space.
  23636. var DILIMITER_REG = /[\s,]+/;
  23637. /**
  23638. * For big svg string, this method might be time consuming.
  23639. *
  23640. * @param {string} svg xml string
  23641. * @return {Object} xml root.
  23642. */
  23643. function parseXML(svg) {
  23644. if (isString(svg)) {
  23645. var parser = new DOMParser();
  23646. svg = parser.parseFromString(svg, 'text/xml');
  23647. }
  23648. // Document node. If using $.get, doc node may be input.
  23649. if (svg.nodeType === 9) {
  23650. svg = svg.firstChild;
  23651. }
  23652. // nodeName of <!DOCTYPE svg> is also 'svg'.
  23653. while (svg.nodeName.toLowerCase() !== 'svg' || svg.nodeType !== 1) {
  23654. svg = svg.nextSibling;
  23655. }
  23656. return svg;
  23657. }
  23658. function SVGParser() {
  23659. this._defs = {};
  23660. this._root = null;
  23661. this._isDefine = false;
  23662. this._isText = false;
  23663. }
  23664. SVGParser.prototype.parse = function (xml, opt) {
  23665. opt = opt || {};
  23666. var svg = parseXML(xml);
  23667. if (!svg) {
  23668. throw new Error('Illegal svg');
  23669. }
  23670. var root = new Group();
  23671. this._root = root;
  23672. // parse view port
  23673. var viewBox = svg.getAttribute('viewBox') || '';
  23674. // If width/height not specified, means "100%" of `opt.width/height`.
  23675. // TODO: Other percent value not supported yet.
  23676. var width = parseFloat(svg.getAttribute('width') || opt.width);
  23677. var height = parseFloat(svg.getAttribute('height') || opt.height);
  23678. // If width/height not specified, set as null for output.
  23679. isNaN(width) && (width = null);
  23680. isNaN(height) && (height = null);
  23681. // Apply inline style on svg element.
  23682. parseAttributes(svg, root, null, true);
  23683. var child = svg.firstChild;
  23684. while (child) {
  23685. this._parseNode(child, root);
  23686. child = child.nextSibling;
  23687. }
  23688. var viewBoxRect;
  23689. var viewBoxTransform;
  23690. if (viewBox) {
  23691. var viewBoxArr = trim(viewBox).split(DILIMITER_REG);
  23692. // Some invalid case like viewBox: 'none'.
  23693. if (viewBoxArr.length >= 4) {
  23694. viewBoxRect = {
  23695. x: parseFloat(viewBoxArr[0] || 0),
  23696. y: parseFloat(viewBoxArr[1] || 0),
  23697. width: parseFloat(viewBoxArr[2]),
  23698. height: parseFloat(viewBoxArr[3])
  23699. };
  23700. }
  23701. }
  23702. if (viewBoxRect && width != null && height != null) {
  23703. viewBoxTransform = makeViewBoxTransform(viewBoxRect, width, height);
  23704. if (!opt.ignoreViewBox) {
  23705. // If set transform on the output group, it probably bring trouble when
  23706. // some users only intend to show the clipped content inside the viewBox,
  23707. // but not intend to transform the output group. So we keep the output
  23708. // group no transform. If the user intend to use the viewBox as a
  23709. // camera, just set `opt.ignoreViewBox` as `true` and set transfrom
  23710. // manually according to the viewBox info in the output of this method.
  23711. var elRoot = root;
  23712. root = new Group();
  23713. root.add(elRoot);
  23714. elRoot.scale = viewBoxTransform.scale.slice();
  23715. elRoot.position = viewBoxTransform.position.slice();
  23716. }
  23717. }
  23718. // Some shapes might be overflow the viewport, which should be
  23719. // clipped despite whether the viewBox is used, as the SVG does.
  23720. if (!opt.ignoreRootClip && width != null && height != null) {
  23721. root.setClipPath(new Rect({
  23722. shape: {x: 0, y: 0, width: width, height: height}
  23723. }));
  23724. }
  23725. // Set width/height on group just for output the viewport size.
  23726. return {
  23727. root: root,
  23728. width: width,
  23729. height: height,
  23730. viewBoxRect: viewBoxRect,
  23731. viewBoxTransform: viewBoxTransform
  23732. };
  23733. };
  23734. SVGParser.prototype._parseNode = function (xmlNode, parentGroup) {
  23735. var nodeName = xmlNode.nodeName.toLowerCase();
  23736. // TODO
  23737. // support <style>...</style> in svg, where nodeName is 'style',
  23738. // CSS classes is defined globally wherever the style tags are declared.
  23739. if (nodeName === 'defs') {
  23740. // define flag
  23741. this._isDefine = true;
  23742. }
  23743. else if (nodeName === 'text') {
  23744. this._isText = true;
  23745. }
  23746. var el;
  23747. if (this._isDefine) {
  23748. var parser = defineParsers[nodeName];
  23749. if (parser) {
  23750. var def = parser.call(this, xmlNode);
  23751. var id = xmlNode.getAttribute('id');
  23752. if (id) {
  23753. this._defs[id] = def;
  23754. }
  23755. }
  23756. }
  23757. else {
  23758. var parser = nodeParsers[nodeName];
  23759. if (parser) {
  23760. el = parser.call(this, xmlNode, parentGroup);
  23761. parentGroup.add(el);
  23762. }
  23763. }
  23764. var child = xmlNode.firstChild;
  23765. while (child) {
  23766. if (child.nodeType === 1) {
  23767. this._parseNode(child, el);
  23768. }
  23769. // Is text
  23770. if (child.nodeType === 3 && this._isText) {
  23771. this._parseText(child, el);
  23772. }
  23773. child = child.nextSibling;
  23774. }
  23775. // Quit define
  23776. if (nodeName === 'defs') {
  23777. this._isDefine = false;
  23778. }
  23779. else if (nodeName === 'text') {
  23780. this._isText = false;
  23781. }
  23782. };
  23783. SVGParser.prototype._parseText = function (xmlNode, parentGroup) {
  23784. if (xmlNode.nodeType === 1) {
  23785. var dx = xmlNode.getAttribute('dx') || 0;
  23786. var dy = xmlNode.getAttribute('dy') || 0;
  23787. this._textX += parseFloat(dx);
  23788. this._textY += parseFloat(dy);
  23789. }
  23790. var text = new Text({
  23791. style: {
  23792. text: xmlNode.textContent,
  23793. transformText: true
  23794. },
  23795. position: [this._textX || 0, this._textY || 0]
  23796. });
  23797. inheritStyle(parentGroup, text);
  23798. parseAttributes(xmlNode, text, this._defs);
  23799. var fontSize = text.style.fontSize;
  23800. if (fontSize && fontSize < 9) {
  23801. // PENDING
  23802. text.style.fontSize = 9;
  23803. text.scale = text.scale || [1, 1];
  23804. text.scale[0] *= fontSize / 9;
  23805. text.scale[1] *= fontSize / 9;
  23806. }
  23807. var rect = text.getBoundingRect();
  23808. this._textX += rect.width;
  23809. parentGroup.add(text);
  23810. return text;
  23811. };
  23812. var nodeParsers = {
  23813. 'g': function (xmlNode, parentGroup) {
  23814. var g = new Group();
  23815. inheritStyle(parentGroup, g);
  23816. parseAttributes(xmlNode, g, this._defs);
  23817. return g;
  23818. },
  23819. 'rect': function (xmlNode, parentGroup) {
  23820. var rect = new Rect();
  23821. inheritStyle(parentGroup, rect);
  23822. parseAttributes(xmlNode, rect, this._defs);
  23823. rect.setShape({
  23824. x: parseFloat(xmlNode.getAttribute('x') || 0),
  23825. y: parseFloat(xmlNode.getAttribute('y') || 0),
  23826. width: parseFloat(xmlNode.getAttribute('width') || 0),
  23827. height: parseFloat(xmlNode.getAttribute('height') || 0)
  23828. });
  23829. // console.log(xmlNode.getAttribute('transform'));
  23830. // console.log(rect.transform);
  23831. return rect;
  23832. },
  23833. 'circle': function (xmlNode, parentGroup) {
  23834. var circle = new Circle();
  23835. inheritStyle(parentGroup, circle);
  23836. parseAttributes(xmlNode, circle, this._defs);
  23837. circle.setShape({
  23838. cx: parseFloat(xmlNode.getAttribute('cx') || 0),
  23839. cy: parseFloat(xmlNode.getAttribute('cy') || 0),
  23840. r: parseFloat(xmlNode.getAttribute('r') || 0)
  23841. });
  23842. return circle;
  23843. },
  23844. 'line': function (xmlNode, parentGroup) {
  23845. var line = new Line();
  23846. inheritStyle(parentGroup, line);
  23847. parseAttributes(xmlNode, line, this._defs);
  23848. line.setShape({
  23849. x1: parseFloat(xmlNode.getAttribute('x1') || 0),
  23850. y1: parseFloat(xmlNode.getAttribute('y1') || 0),
  23851. x2: parseFloat(xmlNode.getAttribute('x2') || 0),
  23852. y2: parseFloat(xmlNode.getAttribute('y2') || 0)
  23853. });
  23854. return line;
  23855. },
  23856. 'ellipse': function (xmlNode, parentGroup) {
  23857. var ellipse = new Ellipse();
  23858. inheritStyle(parentGroup, ellipse);
  23859. parseAttributes(xmlNode, ellipse, this._defs);
  23860. ellipse.setShape({
  23861. cx: parseFloat(xmlNode.getAttribute('cx') || 0),
  23862. cy: parseFloat(xmlNode.getAttribute('cy') || 0),
  23863. rx: parseFloat(xmlNode.getAttribute('rx') || 0),
  23864. ry: parseFloat(xmlNode.getAttribute('ry') || 0)
  23865. });
  23866. return ellipse;
  23867. },
  23868. 'polygon': function (xmlNode, parentGroup) {
  23869. var points = xmlNode.getAttribute('points');
  23870. if (points) {
  23871. points = parsePoints(points);
  23872. }
  23873. var polygon = new Polygon({
  23874. shape: {
  23875. points: points || []
  23876. }
  23877. });
  23878. inheritStyle(parentGroup, polygon);
  23879. parseAttributes(xmlNode, polygon, this._defs);
  23880. return polygon;
  23881. },
  23882. 'polyline': function (xmlNode, parentGroup) {
  23883. var path = new Path();
  23884. inheritStyle(parentGroup, path);
  23885. parseAttributes(xmlNode, path, this._defs);
  23886. var points = xmlNode.getAttribute('points');
  23887. if (points) {
  23888. points = parsePoints(points);
  23889. }
  23890. var polyline = new Polyline({
  23891. shape: {
  23892. points: points || []
  23893. }
  23894. });
  23895. return polyline;
  23896. },
  23897. 'image': function (xmlNode, parentGroup) {
  23898. var img = new ZImage();
  23899. inheritStyle(parentGroup, img);
  23900. parseAttributes(xmlNode, img, this._defs);
  23901. img.setStyle({
  23902. image: xmlNode.getAttribute('xlink:href'),
  23903. x: xmlNode.getAttribute('x'),
  23904. y: xmlNode.getAttribute('y'),
  23905. width: xmlNode.getAttribute('width'),
  23906. height: xmlNode.getAttribute('height')
  23907. });
  23908. return img;
  23909. },
  23910. 'text': function (xmlNode, parentGroup) {
  23911. var x = xmlNode.getAttribute('x') || 0;
  23912. var y = xmlNode.getAttribute('y') || 0;
  23913. var dx = xmlNode.getAttribute('dx') || 0;
  23914. var dy = xmlNode.getAttribute('dy') || 0;
  23915. this._textX = parseFloat(x) + parseFloat(dx);
  23916. this._textY = parseFloat(y) + parseFloat(dy);
  23917. var g = new Group();
  23918. inheritStyle(parentGroup, g);
  23919. parseAttributes(xmlNode, g, this._defs);
  23920. return g;
  23921. },
  23922. 'tspan': function (xmlNode, parentGroup) {
  23923. var x = xmlNode.getAttribute('x');
  23924. var y = xmlNode.getAttribute('y');
  23925. if (x != null) {
  23926. // new offset x
  23927. this._textX = parseFloat(x);
  23928. }
  23929. if (y != null) {
  23930. // new offset y
  23931. this._textY = parseFloat(y);
  23932. }
  23933. var dx = xmlNode.getAttribute('dx') || 0;
  23934. var dy = xmlNode.getAttribute('dy') || 0;
  23935. var g = new Group();
  23936. inheritStyle(parentGroup, g);
  23937. parseAttributes(xmlNode, g, this._defs);
  23938. this._textX += dx;
  23939. this._textY += dy;
  23940. return g;
  23941. },
  23942. 'path': function (xmlNode, parentGroup) {
  23943. // TODO svg fill rule
  23944. // https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/fill-rule
  23945. // path.style.globalCompositeOperation = 'xor';
  23946. var d = xmlNode.getAttribute('d') || '';
  23947. // Performance sensitive.
  23948. var path = createFromString(d);
  23949. inheritStyle(parentGroup, path);
  23950. parseAttributes(xmlNode, path, this._defs);
  23951. return path;
  23952. }
  23953. };
  23954. var defineParsers = {
  23955. 'lineargradient': function (xmlNode) {
  23956. var x1 = parseInt(xmlNode.getAttribute('x1') || 0, 10);
  23957. var y1 = parseInt(xmlNode.getAttribute('y1') || 0, 10);
  23958. var x2 = parseInt(xmlNode.getAttribute('x2') || 10, 10);
  23959. var y2 = parseInt(xmlNode.getAttribute('y2') || 0, 10);
  23960. var gradient = new LinearGradient(x1, y1, x2, y2);
  23961. _parseGradientColorStops(xmlNode, gradient);
  23962. return gradient;
  23963. },
  23964. 'radialgradient': function (xmlNode) {
  23965. }
  23966. };
  23967. function _parseGradientColorStops(xmlNode, gradient) {
  23968. var stop = xmlNode.firstChild;
  23969. while (stop) {
  23970. if (stop.nodeType === 1) {
  23971. var offset = stop.getAttribute('offset');
  23972. if (offset.indexOf('%') > 0) { // percentage
  23973. offset = parseInt(offset, 10) / 100;
  23974. }
  23975. else if (offset) { // number from 0 to 1
  23976. offset = parseFloat(offset);
  23977. }
  23978. else {
  23979. offset = 0;
  23980. }
  23981. var stopColor = stop.getAttribute('stop-color') || '#000000';
  23982. gradient.addColorStop(offset, stopColor);
  23983. }
  23984. stop = stop.nextSibling;
  23985. }
  23986. }
  23987. function inheritStyle(parent, child) {
  23988. if (parent && parent.__inheritedStyle) {
  23989. if (!child.__inheritedStyle) {
  23990. child.__inheritedStyle = {};
  23991. }
  23992. defaults(child.__inheritedStyle, parent.__inheritedStyle);
  23993. }
  23994. }
  23995. function parsePoints(pointsString) {
  23996. var list = trim(pointsString).split(DILIMITER_REG);
  23997. var points = [];
  23998. for (var i = 0; i < list.length; i += 2) {
  23999. var x = parseFloat(list[i]);
  24000. var y = parseFloat(list[i + 1]);
  24001. points.push([x, y]);
  24002. }
  24003. return points;
  24004. }
  24005. var attributesMap = {
  24006. 'fill': 'fill',
  24007. 'stroke': 'stroke',
  24008. 'stroke-width': 'lineWidth',
  24009. 'opacity': 'opacity',
  24010. 'fill-opacity': 'fillOpacity',
  24011. 'stroke-opacity': 'strokeOpacity',
  24012. 'stroke-dasharray': 'lineDash',
  24013. 'stroke-dashoffset': 'lineDashOffset',
  24014. 'stroke-linecap': 'lineCap',
  24015. 'stroke-linejoin': 'lineJoin',
  24016. 'stroke-miterlimit': 'miterLimit',
  24017. 'font-family': 'fontFamily',
  24018. 'font-size': 'fontSize',
  24019. 'font-style': 'fontStyle',
  24020. 'font-weight': 'fontWeight',
  24021. 'text-align': 'textAlign',
  24022. 'alignment-baseline': 'textBaseline'
  24023. };
  24024. function parseAttributes(xmlNode, el, defs, onlyInlineStyle) {
  24025. var zrStyle = el.__inheritedStyle || {};
  24026. var isTextEl = el.type === 'text';
  24027. // TODO Shadow
  24028. if (xmlNode.nodeType === 1) {
  24029. parseTransformAttribute(xmlNode, el);
  24030. extend(zrStyle, parseStyleAttribute(xmlNode));
  24031. if (!onlyInlineStyle) {
  24032. for (var svgAttrName in attributesMap) {
  24033. if (attributesMap.hasOwnProperty(svgAttrName)) {
  24034. var attrValue = xmlNode.getAttribute(svgAttrName);
  24035. if (attrValue != null) {
  24036. zrStyle[attributesMap[svgAttrName]] = attrValue;
  24037. }
  24038. }
  24039. }
  24040. }
  24041. }
  24042. var elFillProp = isTextEl ? 'textFill' : 'fill';
  24043. var elStrokeProp = isTextEl ? 'textStroke' : 'stroke';
  24044. el.style = el.style || new Style();
  24045. var elStyle = el.style;
  24046. zrStyle.fill != null && elStyle.set(elFillProp, getPaint(zrStyle.fill, defs));
  24047. zrStyle.stroke != null && elStyle.set(elStrokeProp, getPaint(zrStyle.stroke, defs));
  24048. each$1([
  24049. 'lineWidth', 'opacity', 'fillOpacity', 'strokeOpacity', 'miterLimit', 'fontSize'
  24050. ], function (propName) {
  24051. var elPropName = (propName === 'lineWidth' && isTextEl) ? 'textStrokeWidth' : propName;
  24052. zrStyle[propName] != null && elStyle.set(elPropName, parseFloat(zrStyle[propName]));
  24053. });
  24054. if (!zrStyle.textBaseline || zrStyle.textBaseline === 'auto') {
  24055. zrStyle.textBaseline = 'alphabetic';
  24056. }
  24057. if (zrStyle.textBaseline === 'alphabetic') {
  24058. zrStyle.textBaseline = 'bottom';
  24059. }
  24060. if (zrStyle.textAlign === 'start') {
  24061. zrStyle.textAlign = 'left';
  24062. }
  24063. if (zrStyle.textAlign === 'end') {
  24064. zrStyle.textAlign = 'right';
  24065. }
  24066. each$1(['lineDashOffset', 'lineCap', 'lineJoin',
  24067. 'fontWeight', 'fontFamily', 'fontStyle', 'textAlign', 'textBaseline'
  24068. ], function (propName) {
  24069. zrStyle[propName] != null && elStyle.set(propName, zrStyle[propName]);
  24070. });
  24071. if (zrStyle.lineDash) {
  24072. el.style.lineDash = trim(zrStyle.lineDash).split(DILIMITER_REG);
  24073. }
  24074. if (elStyle[elStrokeProp] && elStyle[elStrokeProp] !== 'none') {
  24075. // enable stroke
  24076. el[elStrokeProp] = true;
  24077. }
  24078. el.__inheritedStyle = zrStyle;
  24079. }
  24080. var urlRegex = /url\(\s*#(.*?)\)/;
  24081. function getPaint(str, defs) {
  24082. // if (str === 'none') {
  24083. // return;
  24084. // }
  24085. var urlMatch = defs && str && str.match(urlRegex);
  24086. if (urlMatch) {
  24087. var url = trim(urlMatch[1]);
  24088. var def = defs[url];
  24089. return def;
  24090. }
  24091. return str;
  24092. }
  24093. var transformRegex = /(translate|scale|rotate|skewX|skewY|matrix)\(([\-\s0-9\.e,]*)\)/g;
  24094. function parseTransformAttribute(xmlNode, node) {
  24095. var transform = xmlNode.getAttribute('transform');
  24096. if (transform) {
  24097. transform = transform.replace(/,/g, ' ');
  24098. var m = null;
  24099. var transformOps = [];
  24100. transform.replace(transformRegex, function (str, type, value) {
  24101. transformOps.push(type, value);
  24102. });
  24103. for (var i = transformOps.length - 1; i > 0; i -= 2) {
  24104. var value = transformOps[i];
  24105. var type = transformOps[i - 1];
  24106. m = m || create$1();
  24107. switch (type) {
  24108. case 'translate':
  24109. value = trim(value).split(DILIMITER_REG);
  24110. translate(m, m, [parseFloat(value[0]), parseFloat(value[1] || 0)]);
  24111. break;
  24112. case 'scale':
  24113. value = trim(value).split(DILIMITER_REG);
  24114. scale$1(m, m, [parseFloat(value[0]), parseFloat(value[1] || value[0])]);
  24115. break;
  24116. case 'rotate':
  24117. value = trim(value).split(DILIMITER_REG);
  24118. rotate(m, m, parseFloat(value[0]));
  24119. break;
  24120. case 'skew':
  24121. value = trim(value).split(DILIMITER_REG);
  24122. console.warn('Skew transform is not supported yet');
  24123. break;
  24124. case 'matrix':
  24125. var value = trim(value).split(DILIMITER_REG);
  24126. m[0] = parseFloat(value[0]);
  24127. m[1] = parseFloat(value[1]);
  24128. m[2] = parseFloat(value[2]);
  24129. m[3] = parseFloat(value[3]);
  24130. m[4] = parseFloat(value[4]);
  24131. m[5] = parseFloat(value[5]);
  24132. break;
  24133. }
  24134. }
  24135. node.setLocalTransform(m);
  24136. }
  24137. }
  24138. // Value may contain space.
  24139. var styleRegex = /([^\s:;]+)\s*:\s*([^:;]+)/g;
  24140. function parseStyleAttribute(xmlNode) {
  24141. var style = xmlNode.getAttribute('style');
  24142. var result = {};
  24143. if (!style) {
  24144. return result;
  24145. }
  24146. var styleList = {};
  24147. styleRegex.lastIndex = 0;
  24148. var styleRegResult;
  24149. while ((styleRegResult = styleRegex.exec(style)) != null) {
  24150. styleList[styleRegResult[1]] = styleRegResult[2];
  24151. }
  24152. for (var svgAttrName in attributesMap) {
  24153. if (attributesMap.hasOwnProperty(svgAttrName) && styleList[svgAttrName] != null) {
  24154. result[attributesMap[svgAttrName]] = styleList[svgAttrName];
  24155. }
  24156. }
  24157. return result;
  24158. }
  24159. /**
  24160. * @param {Array.<number>} viewBoxRect
  24161. * @param {number} width
  24162. * @param {number} height
  24163. * @return {Object} {scale, position}
  24164. */
  24165. function makeViewBoxTransform(viewBoxRect, width, height) {
  24166. var scaleX = width / viewBoxRect.width;
  24167. var scaleY = height / viewBoxRect.height;
  24168. var scale = Math.min(scaleX, scaleY);
  24169. // preserveAspectRatio 'xMidYMid'
  24170. var viewBoxScale = [scale, scale];
  24171. var viewBoxPosition = [
  24172. -(viewBoxRect.x + viewBoxRect.width / 2) * scale + width / 2,
  24173. -(viewBoxRect.y + viewBoxRect.height / 2) * scale + height / 2
  24174. ];
  24175. return {
  24176. scale: viewBoxScale,
  24177. position: viewBoxPosition
  24178. };
  24179. }
  24180. /**
  24181. * @param {string|XMLElement} xml
  24182. * @param {Object} [opt]
  24183. * @param {number} [opt.width] Default width if svg width not specified or is a percent value.
  24184. * @param {number} [opt.height] Default height if svg height not specified or is a percent value.
  24185. * @param {boolean} [opt.ignoreViewBox]
  24186. * @param {boolean} [opt.ignoreRootClip]
  24187. * @return {Object} result:
  24188. * {
  24189. * root: Group, The root of the the result tree of zrender shapes,
  24190. * width: number, the viewport width of the SVG,
  24191. * height: number, the viewport height of the SVG,
  24192. * viewBoxRect: {x, y, width, height}, the declared viewBox rect of the SVG, if exists,
  24193. * viewBoxTransform: the {scale, position} calculated by viewBox and viewport, is exists.
  24194. * }
  24195. */
  24196. function parseSVG(xml, opt) {
  24197. var parser = new SVGParser();
  24198. return parser.parse(xml, opt);
  24199. }
  24200. /*
  24201. * Licensed to the Apache Software Foundation (ASF) under one
  24202. * or more contributor license agreements. See the NOTICE file
  24203. * distributed with this work for additional information
  24204. * regarding copyright ownership. The ASF licenses this file
  24205. * to you under the Apache License, Version 2.0 (the
  24206. * "License"); you may not use this file except in compliance
  24207. * with the License. You may obtain a copy of the License at
  24208. *
  24209. * http://www.apache.org/licenses/LICENSE-2.0
  24210. *
  24211. * Unless required by applicable law or agreed to in writing,
  24212. * software distributed under the License is distributed on an
  24213. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  24214. * KIND, either express or implied. See the License for the
  24215. * specific language governing permissions and limitations
  24216. * under the License.
  24217. */
  24218. var storage = createHashMap();
  24219. // For minimize the code size of common echarts package,
  24220. // do not put too much logic in this module.
  24221. var mapDataStorage = {
  24222. // The format of record: see `echarts.registerMap`.
  24223. // Compatible with previous `echarts.registerMap`.
  24224. registerMap: function (mapName, rawGeoJson, rawSpecialAreas) {
  24225. var records;
  24226. if (isArray(rawGeoJson)) {
  24227. records = rawGeoJson;
  24228. }
  24229. else if (rawGeoJson.svg) {
  24230. records = [{
  24231. type: 'svg',
  24232. source: rawGeoJson.svg,
  24233. specialAreas: rawGeoJson.specialAreas
  24234. }];
  24235. }
  24236. else {
  24237. // Backward compatibility.
  24238. if (rawGeoJson.geoJson && !rawGeoJson.features) {
  24239. rawSpecialAreas = rawGeoJson.specialAreas;
  24240. rawGeoJson = rawGeoJson.geoJson;
  24241. }
  24242. records = [{
  24243. type: 'geoJSON',
  24244. source: rawGeoJson,
  24245. specialAreas: rawSpecialAreas
  24246. }];
  24247. }
  24248. each$1(records, function (record) {
  24249. var type = record.type;
  24250. type === 'geoJson' && (type = record.type = 'geoJSON');
  24251. var parse = parsers[type];
  24252. if (__DEV__) {
  24253. assert$1(parse, 'Illegal map type: ' + type);
  24254. }
  24255. parse(record);
  24256. });
  24257. return storage.set(mapName, records);
  24258. },
  24259. retrieveMap: function (mapName) {
  24260. return storage.get(mapName);
  24261. }
  24262. };
  24263. var parsers = {
  24264. geoJSON: function (record) {
  24265. var source = record.source;
  24266. record.geoJSON = !isString(source)
  24267. ? source
  24268. : (typeof JSON !== 'undefined' && JSON.parse)
  24269. ? JSON.parse(source)
  24270. : (new Function('return (' + source + ');'))();
  24271. },
  24272. // Only perform parse to XML object here, which might be time
  24273. // consiming for large SVG.
  24274. // Although convert XML to zrender element is also time consiming,
  24275. // if we do it here, the clone of zrender elements has to be
  24276. // required. So we do it once for each geo instance, util real
  24277. // performance issues call for optimizing it.
  24278. svg: function (record) {
  24279. record.svgXML = parseXML(record.source);
  24280. }
  24281. };
  24282. /*
  24283. * Licensed to the Apache Software Foundation (ASF) under one
  24284. * or more contributor license agreements. See the NOTICE file
  24285. * distributed with this work for additional information
  24286. * regarding copyright ownership. The ASF licenses this file
  24287. * to you under the Apache License, Version 2.0 (the
  24288. * "License"); you may not use this file except in compliance
  24289. * with the License. You may obtain a copy of the License at
  24290. *
  24291. * http://www.apache.org/licenses/LICENSE-2.0
  24292. *
  24293. * Unless required by applicable law or agreed to in writing,
  24294. * software distributed under the License is distributed on an
  24295. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  24296. * KIND, either express or implied. See the License for the
  24297. * specific language governing permissions and limitations
  24298. * under the License.
  24299. */
  24300. var assert = assert$1;
  24301. var each = each$1;
  24302. var isFunction = isFunction$1;
  24303. var isObject = isObject$1;
  24304. var parseClassType = ComponentModel.parseClassType;
  24305. var version = '4.8.0';
  24306. var dependencies = {
  24307. zrender: '4.3.1'
  24308. };
  24309. var TEST_FRAME_REMAIN_TIME = 1;
  24310. var PRIORITY_PROCESSOR_FILTER = 1000;
  24311. var PRIORITY_PROCESSOR_SERIES_FILTER = 800;
  24312. var PRIORITY_PROCESSOR_DATASTACK = 900;
  24313. var PRIORITY_PROCESSOR_STATISTIC = 5000;
  24314. var PRIORITY_VISUAL_LAYOUT = 1000;
  24315. var PRIORITY_VISUAL_PROGRESSIVE_LAYOUT = 1100;
  24316. var PRIORITY_VISUAL_GLOBAL = 2000;
  24317. var PRIORITY_VISUAL_CHART = 3000;
  24318. var PRIORITY_VISUAL_POST_CHART_LAYOUT = 3500;
  24319. var PRIORITY_VISUAL_COMPONENT = 4000;
  24320. // FIXME
  24321. // necessary?
  24322. var PRIORITY_VISUAL_BRUSH = 5000;
  24323. var PRIORITY = {
  24324. PROCESSOR: {
  24325. FILTER: PRIORITY_PROCESSOR_FILTER,
  24326. SERIES_FILTER: PRIORITY_PROCESSOR_SERIES_FILTER,
  24327. STATISTIC: PRIORITY_PROCESSOR_STATISTIC
  24328. },
  24329. VISUAL: {
  24330. LAYOUT: PRIORITY_VISUAL_LAYOUT,
  24331. PROGRESSIVE_LAYOUT: PRIORITY_VISUAL_PROGRESSIVE_LAYOUT,
  24332. GLOBAL: PRIORITY_VISUAL_GLOBAL,
  24333. CHART: PRIORITY_VISUAL_CHART,
  24334. POST_CHART_LAYOUT: PRIORITY_VISUAL_POST_CHART_LAYOUT,
  24335. COMPONENT: PRIORITY_VISUAL_COMPONENT,
  24336. BRUSH: PRIORITY_VISUAL_BRUSH
  24337. }
  24338. };
  24339. // Main process have three entries: `setOption`, `dispatchAction` and `resize`,
  24340. // where they must not be invoked nestedly, except the only case: invoke
  24341. // dispatchAction with updateMethod "none" in main process.
  24342. // This flag is used to carry out this rule.
  24343. // All events will be triggered out side main process (i.e. when !this[IN_MAIN_PROCESS]).
  24344. var IN_MAIN_PROCESS = '__flagInMainProcess';
  24345. var OPTION_UPDATED = '__optionUpdated';
  24346. var ACTION_REG = /^[a-zA-Z0-9_]+$/;
  24347. function createRegisterEventWithLowercaseName(method, ignoreDisposed) {
  24348. return function (eventName, handler, context) {
  24349. if (!ignoreDisposed && this._disposed) {
  24350. disposedWarning(this.id);
  24351. return;
  24352. }
  24353. // Event name is all lowercase
  24354. eventName = eventName && eventName.toLowerCase();
  24355. Eventful.prototype[method].call(this, eventName, handler, context);
  24356. };
  24357. }
  24358. /**
  24359. * @module echarts~MessageCenter
  24360. */
  24361. function MessageCenter() {
  24362. Eventful.call(this);
  24363. }
  24364. MessageCenter.prototype.on = createRegisterEventWithLowercaseName('on', true);
  24365. MessageCenter.prototype.off = createRegisterEventWithLowercaseName('off', true);
  24366. MessageCenter.prototype.one = createRegisterEventWithLowercaseName('one', true);
  24367. mixin(MessageCenter, Eventful);
  24368. /**
  24369. * @module echarts~ECharts
  24370. */
  24371. function ECharts(dom, theme$$1, opts) {
  24372. opts = opts || {};
  24373. // Get theme by name
  24374. if (typeof theme$$1 === 'string') {
  24375. theme$$1 = themeStorage[theme$$1];
  24376. }
  24377. /**
  24378. * @type {string}
  24379. */
  24380. this.id;
  24381. /**
  24382. * Group id
  24383. * @type {string}
  24384. */
  24385. this.group;
  24386. /**
  24387. * @type {HTMLElement}
  24388. * @private
  24389. */
  24390. this._dom = dom;
  24391. var defaultRenderer = 'canvas';
  24392. if (__DEV__) {
  24393. defaultRenderer = (
  24394. typeof window === 'undefined' ? global : window
  24395. ).__ECHARTS__DEFAULT__RENDERER__ || defaultRenderer;
  24396. }
  24397. /**
  24398. * @type {module:zrender/ZRender}
  24399. * @private
  24400. */
  24401. var zr = this._zr = init$1(dom, {
  24402. renderer: opts.renderer || defaultRenderer,
  24403. devicePixelRatio: opts.devicePixelRatio,
  24404. width: opts.width,
  24405. height: opts.height
  24406. });
  24407. /**
  24408. * Expect 60 fps.
  24409. * @type {Function}
  24410. * @private
  24411. */
  24412. this._throttledZrFlush = throttle(bind(zr.flush, zr), 17);
  24413. var theme$$1 = clone(theme$$1);
  24414. theme$$1 && backwardCompat(theme$$1, true);
  24415. /**
  24416. * @type {Object}
  24417. * @private
  24418. */
  24419. this._theme = theme$$1;
  24420. /**
  24421. * @type {Array.<module:echarts/view/Chart>}
  24422. * @private
  24423. */
  24424. this._chartsViews = [];
  24425. /**
  24426. * @type {Object.<string, module:echarts/view/Chart>}
  24427. * @private
  24428. */
  24429. this._chartsMap = {};
  24430. /**
  24431. * @type {Array.<module:echarts/view/Component>}
  24432. * @private
  24433. */
  24434. this._componentsViews = [];
  24435. /**
  24436. * @type {Object.<string, module:echarts/view/Component>}
  24437. * @private
  24438. */
  24439. this._componentsMap = {};
  24440. /**
  24441. * @type {module:echarts/CoordinateSystem}
  24442. * @private
  24443. */
  24444. this._coordSysMgr = new CoordinateSystemManager();
  24445. /**
  24446. * @type {module:echarts/ExtensionAPI}
  24447. * @private
  24448. */
  24449. var api = this._api = createExtensionAPI(this);
  24450. // Sort on demand
  24451. function prioritySortFunc(a, b) {
  24452. return a.__prio - b.__prio;
  24453. }
  24454. sort(visualFuncs, prioritySortFunc);
  24455. sort(dataProcessorFuncs, prioritySortFunc);
  24456. /**
  24457. * @type {module:echarts/stream/Scheduler}
  24458. */
  24459. this._scheduler = new Scheduler(this, api, dataProcessorFuncs, visualFuncs);
  24460. Eventful.call(this, this._ecEventProcessor = new EventProcessor());
  24461. /**
  24462. * @type {module:echarts~MessageCenter}
  24463. * @private
  24464. */
  24465. this._messageCenter = new MessageCenter();
  24466. // Init mouse events
  24467. this._initEvents();
  24468. // In case some people write `window.onresize = chart.resize`
  24469. this.resize = bind(this.resize, this);
  24470. // Can't dispatch action during rendering procedure
  24471. this._pendingActions = [];
  24472. zr.animation.on('frame', this._onframe, this);
  24473. bindRenderedEvent(zr, this);
  24474. // ECharts instance can be used as value.
  24475. setAsPrimitive(this);
  24476. }
  24477. var echartsProto = ECharts.prototype;
  24478. echartsProto._onframe = function () {
  24479. if (this._disposed) {
  24480. return;
  24481. }
  24482. var scheduler = this._scheduler;
  24483. // Lazy update
  24484. if (this[OPTION_UPDATED]) {
  24485. var silent = this[OPTION_UPDATED].silent;
  24486. this[IN_MAIN_PROCESS] = true;
  24487. prepare(this);
  24488. updateMethods.update.call(this);
  24489. this[IN_MAIN_PROCESS] = false;
  24490. this[OPTION_UPDATED] = false;
  24491. flushPendingActions.call(this, silent);
  24492. triggerUpdatedEvent.call(this, silent);
  24493. }
  24494. // Avoid do both lazy update and progress in one frame.
  24495. else if (scheduler.unfinished) {
  24496. // Stream progress.
  24497. var remainTime = TEST_FRAME_REMAIN_TIME;
  24498. var ecModel = this._model;
  24499. var api = this._api;
  24500. scheduler.unfinished = false;
  24501. do {
  24502. var startTime = +new Date();
  24503. scheduler.performSeriesTasks(ecModel);
  24504. // Currently dataProcessorFuncs do not check threshold.
  24505. scheduler.performDataProcessorTasks(ecModel);
  24506. updateStreamModes(this, ecModel);
  24507. // Do not update coordinate system here. Because that coord system update in
  24508. // each frame is not a good user experience. So we follow the rule that
  24509. // the extent of the coordinate system is determin in the first frame (the
  24510. // frame is executed immedietely after task reset.
  24511. // this._coordSysMgr.update(ecModel, api);
  24512. // console.log('--- ec frame visual ---', remainTime);
  24513. scheduler.performVisualTasks(ecModel);
  24514. renderSeries(this, this._model, api, 'remain');
  24515. remainTime -= (+new Date() - startTime);
  24516. }
  24517. while (remainTime > 0 && scheduler.unfinished);
  24518. // Call flush explicitly for trigger finished event.
  24519. if (!scheduler.unfinished) {
  24520. this._zr.flush();
  24521. }
  24522. // Else, zr flushing be ensue within the same frame,
  24523. // because zr flushing is after onframe event.
  24524. }
  24525. };
  24526. /**
  24527. * @return {HTMLElement}
  24528. */
  24529. echartsProto.getDom = function () {
  24530. return this._dom;
  24531. };
  24532. /**
  24533. * @return {module:zrender~ZRender}
  24534. */
  24535. echartsProto.getZr = function () {
  24536. return this._zr;
  24537. };
  24538. /**
  24539. * Usage:
  24540. * chart.setOption(option, notMerge, lazyUpdate);
  24541. * chart.setOption(option, {
  24542. * notMerge: ...,
  24543. * lazyUpdate: ...,
  24544. * silent: ...
  24545. * });
  24546. *
  24547. * @param {Object} option
  24548. * @param {Object|boolean} [opts] opts or notMerge.
  24549. * @param {boolean} [opts.notMerge=false]
  24550. * @param {boolean} [opts.lazyUpdate=false] Useful when setOption frequently.
  24551. */
  24552. echartsProto.setOption = function (option, notMerge, lazyUpdate) {
  24553. if (__DEV__) {
  24554. assert(!this[IN_MAIN_PROCESS], '`setOption` should not be called during main process.');
  24555. }
  24556. if (this._disposed) {
  24557. disposedWarning(this.id);
  24558. return;
  24559. }
  24560. var silent;
  24561. if (isObject(notMerge)) {
  24562. lazyUpdate = notMerge.lazyUpdate;
  24563. silent = notMerge.silent;
  24564. notMerge = notMerge.notMerge;
  24565. }
  24566. this[IN_MAIN_PROCESS] = true;
  24567. if (!this._model || notMerge) {
  24568. var optionManager = new OptionManager(this._api);
  24569. var theme$$1 = this._theme;
  24570. var ecModel = this._model = new GlobalModel();
  24571. ecModel.scheduler = this._scheduler;
  24572. ecModel.init(null, null, theme$$1, optionManager);
  24573. }
  24574. this._model.setOption(option, optionPreprocessorFuncs);
  24575. if (lazyUpdate) {
  24576. this[OPTION_UPDATED] = {silent: silent};
  24577. this[IN_MAIN_PROCESS] = false;
  24578. }
  24579. else {
  24580. prepare(this);
  24581. updateMethods.update.call(this);
  24582. // Ensure zr refresh sychronously, and then pixel in canvas can be
  24583. // fetched after `setOption`.
  24584. this._zr.flush();
  24585. this[OPTION_UPDATED] = false;
  24586. this[IN_MAIN_PROCESS] = false;
  24587. flushPendingActions.call(this, silent);
  24588. triggerUpdatedEvent.call(this, silent);
  24589. }
  24590. };
  24591. /**
  24592. * @DEPRECATED
  24593. */
  24594. echartsProto.setTheme = function () {
  24595. console.error('ECharts#setTheme() is DEPRECATED in ECharts 3.0');
  24596. };
  24597. /**
  24598. * @return {module:echarts/model/Global}
  24599. */
  24600. echartsProto.getModel = function () {
  24601. return this._model;
  24602. };
  24603. /**
  24604. * @return {Object}
  24605. */
  24606. echartsProto.getOption = function () {
  24607. return this._model && this._model.getOption();
  24608. };
  24609. /**
  24610. * @return {number}
  24611. */
  24612. echartsProto.getWidth = function () {
  24613. return this._zr.getWidth();
  24614. };
  24615. /**
  24616. * @return {number}
  24617. */
  24618. echartsProto.getHeight = function () {
  24619. return this._zr.getHeight();
  24620. };
  24621. /**
  24622. * @return {number}
  24623. */
  24624. echartsProto.getDevicePixelRatio = function () {
  24625. return this._zr.painter.dpr || window.devicePixelRatio || 1;
  24626. };
  24627. /**
  24628. * Get canvas which has all thing rendered
  24629. * @param {Object} opts
  24630. * @param {string} [opts.backgroundColor]
  24631. * @return {string}
  24632. */
  24633. echartsProto.getRenderedCanvas = function (opts) {
  24634. if (!env$1.canvasSupported) {
  24635. return;
  24636. }
  24637. opts = opts || {};
  24638. opts.pixelRatio = opts.pixelRatio || 1;
  24639. opts.backgroundColor = opts.backgroundColor
  24640. || this._model.get('backgroundColor');
  24641. var zr = this._zr;
  24642. // var list = zr.storage.getDisplayList();
  24643. // Stop animations
  24644. // Never works before in init animation, so remove it.
  24645. // zrUtil.each(list, function (el) {
  24646. // el.stopAnimation(true);
  24647. // });
  24648. return zr.painter.getRenderedCanvas(opts);
  24649. };
  24650. /**
  24651. * Get svg data url
  24652. * @return {string}
  24653. */
  24654. echartsProto.getSvgDataURL = function () {
  24655. if (!env$1.svgSupported) {
  24656. return;
  24657. }
  24658. var zr = this._zr;
  24659. var list = zr.storage.getDisplayList();
  24660. // Stop animations
  24661. each$1(list, function (el) {
  24662. el.stopAnimation(true);
  24663. });
  24664. return zr.painter.toDataURL();
  24665. };
  24666. /**
  24667. * @return {string}
  24668. * @param {Object} opts
  24669. * @param {string} [opts.type='png']
  24670. * @param {string} [opts.pixelRatio=1]
  24671. * @param {string} [opts.backgroundColor]
  24672. * @param {string} [opts.excludeComponents]
  24673. */
  24674. echartsProto.getDataURL = function (opts) {
  24675. if (this._disposed) {
  24676. disposedWarning(this.id);
  24677. return;
  24678. }
  24679. opts = opts || {};
  24680. var excludeComponents = opts.excludeComponents;
  24681. var ecModel = this._model;
  24682. var excludesComponentViews = [];
  24683. var self = this;
  24684. each(excludeComponents, function (componentType) {
  24685. ecModel.eachComponent({
  24686. mainType: componentType
  24687. }, function (component) {
  24688. var view = self._componentsMap[component.__viewId];
  24689. if (!view.group.ignore) {
  24690. excludesComponentViews.push(view);
  24691. view.group.ignore = true;
  24692. }
  24693. });
  24694. });
  24695. var url = this._zr.painter.getType() === 'svg'
  24696. ? this.getSvgDataURL()
  24697. : this.getRenderedCanvas(opts).toDataURL(
  24698. 'image/' + (opts && opts.type || 'png')
  24699. );
  24700. each(excludesComponentViews, function (view) {
  24701. view.group.ignore = false;
  24702. });
  24703. return url;
  24704. };
  24705. /**
  24706. * @return {string}
  24707. * @param {Object} opts
  24708. * @param {string} [opts.type='png']
  24709. * @param {string} [opts.pixelRatio=1]
  24710. * @param {string} [opts.backgroundColor]
  24711. */
  24712. echartsProto.getConnectedDataURL = function (opts) {
  24713. if (this._disposed) {
  24714. disposedWarning(this.id);
  24715. return;
  24716. }
  24717. if (!env$1.canvasSupported) {
  24718. return;
  24719. }
  24720. var isSvg = opts.type === 'svg';
  24721. var groupId = this.group;
  24722. var mathMin = Math.min;
  24723. var mathMax = Math.max;
  24724. var MAX_NUMBER = Infinity;
  24725. if (connectedGroups[groupId]) {
  24726. var left = MAX_NUMBER;
  24727. var top = MAX_NUMBER;
  24728. var right = -MAX_NUMBER;
  24729. var bottom = -MAX_NUMBER;
  24730. var canvasList = [];
  24731. var dpr = (opts && opts.pixelRatio) || 1;
  24732. each$1(instances, function (chart, id) {
  24733. if (chart.group === groupId) {
  24734. var canvas = isSvg
  24735. ? chart.getZr().painter.getSvgDom().innerHTML
  24736. : chart.getRenderedCanvas(clone(opts));
  24737. var boundingRect = chart.getDom().getBoundingClientRect();
  24738. left = mathMin(boundingRect.left, left);
  24739. top = mathMin(boundingRect.top, top);
  24740. right = mathMax(boundingRect.right, right);
  24741. bottom = mathMax(boundingRect.bottom, bottom);
  24742. canvasList.push({
  24743. dom: canvas,
  24744. left: boundingRect.left,
  24745. top: boundingRect.top
  24746. });
  24747. }
  24748. });
  24749. left *= dpr;
  24750. top *= dpr;
  24751. right *= dpr;
  24752. bottom *= dpr;
  24753. var width = right - left;
  24754. var height = bottom - top;
  24755. var targetCanvas = createCanvas();
  24756. var zr = init$1(targetCanvas, {
  24757. renderer: isSvg ? 'svg' : 'canvas'
  24758. });
  24759. zr.resize({
  24760. width: width,
  24761. height: height
  24762. });
  24763. if (isSvg) {
  24764. var content = '';
  24765. each(canvasList, function (item) {
  24766. var x = item.left - left;
  24767. var y = item.top - top;
  24768. content += '<g transform="translate(' + x + ','
  24769. + y + ')">' + item.dom + '</g>';
  24770. });
  24771. zr.painter.getSvgRoot().innerHTML = content;
  24772. if (opts.connectedBackgroundColor) {
  24773. zr.painter.setBackgroundColor(opts.connectedBackgroundColor);
  24774. }
  24775. zr.refreshImmediately();
  24776. return zr.painter.toDataURL();
  24777. }
  24778. else {
  24779. // Background between the charts
  24780. if (opts.connectedBackgroundColor) {
  24781. zr.add(new Rect({
  24782. shape: {
  24783. x: 0,
  24784. y: 0,
  24785. width: width,
  24786. height: height
  24787. },
  24788. style: {
  24789. fill: opts.connectedBackgroundColor
  24790. }
  24791. }));
  24792. }
  24793. each(canvasList, function (item) {
  24794. var img = new ZImage({
  24795. style: {
  24796. x: item.left * dpr - left,
  24797. y: item.top * dpr - top,
  24798. image: item.dom
  24799. }
  24800. });
  24801. zr.add(img);
  24802. });
  24803. zr.refreshImmediately();
  24804. return targetCanvas.toDataURL('image/' + (opts && opts.type || 'png'));
  24805. }
  24806. }
  24807. else {
  24808. return this.getDataURL(opts);
  24809. }
  24810. };
  24811. /**
  24812. * Convert from logical coordinate system to pixel coordinate system.
  24813. * See CoordinateSystem#convertToPixel.
  24814. * @param {string|Object} finder
  24815. * If string, e.g., 'geo', means {geoIndex: 0}.
  24816. * If Object, could contain some of these properties below:
  24817. * {
  24818. * seriesIndex / seriesId / seriesName,
  24819. * geoIndex / geoId, geoName,
  24820. * bmapIndex / bmapId / bmapName,
  24821. * xAxisIndex / xAxisId / xAxisName,
  24822. * yAxisIndex / yAxisId / yAxisName,
  24823. * gridIndex / gridId / gridName,
  24824. * ... (can be extended)
  24825. * }
  24826. * @param {Array|number} value
  24827. * @return {Array|number} result
  24828. */
  24829. echartsProto.convertToPixel = curry(doConvertPixel, 'convertToPixel');
  24830. /**
  24831. * Convert from pixel coordinate system to logical coordinate system.
  24832. * See CoordinateSystem#convertFromPixel.
  24833. * @param {string|Object} finder
  24834. * If string, e.g., 'geo', means {geoIndex: 0}.
  24835. * If Object, could contain some of these properties below:
  24836. * {
  24837. * seriesIndex / seriesId / seriesName,
  24838. * geoIndex / geoId / geoName,
  24839. * bmapIndex / bmapId / bmapName,
  24840. * xAxisIndex / xAxisId / xAxisName,
  24841. * yAxisIndex / yAxisId / yAxisName
  24842. * gridIndex / gridId / gridName,
  24843. * ... (can be extended)
  24844. * }
  24845. * @param {Array|number} value
  24846. * @return {Array|number} result
  24847. */
  24848. echartsProto.convertFromPixel = curry(doConvertPixel, 'convertFromPixel');
  24849. function doConvertPixel(methodName, finder, value) {
  24850. if (this._disposed) {
  24851. disposedWarning(this.id);
  24852. return;
  24853. }
  24854. var ecModel = this._model;
  24855. var coordSysList = this._coordSysMgr.getCoordinateSystems();
  24856. var result;
  24857. finder = parseFinder(ecModel, finder);
  24858. for (var i = 0; i < coordSysList.length; i++) {
  24859. var coordSys = coordSysList[i];
  24860. if (coordSys[methodName]
  24861. && (result = coordSys[methodName](ecModel, finder, value)) != null
  24862. ) {
  24863. return result;
  24864. }
  24865. }
  24866. if (__DEV__) {
  24867. console.warn(
  24868. 'No coordinate system that supports ' + methodName + ' found by the given finder.'
  24869. );
  24870. }
  24871. }
  24872. /**
  24873. * Is the specified coordinate systems or components contain the given pixel point.
  24874. * @param {string|Object} finder
  24875. * If string, e.g., 'geo', means {geoIndex: 0}.
  24876. * If Object, could contain some of these properties below:
  24877. * {
  24878. * seriesIndex / seriesId / seriesName,
  24879. * geoIndex / geoId / geoName,
  24880. * bmapIndex / bmapId / bmapName,
  24881. * xAxisIndex / xAxisId / xAxisName,
  24882. * yAxisIndex / yAxisId / yAxisName,
  24883. * gridIndex / gridId / gridName,
  24884. * ... (can be extended)
  24885. * }
  24886. * @param {Array|number} value
  24887. * @return {boolean} result
  24888. */
  24889. echartsProto.containPixel = function (finder, value) {
  24890. if (this._disposed) {
  24891. disposedWarning(this.id);
  24892. return;
  24893. }
  24894. var ecModel = this._model;
  24895. var result;
  24896. finder = parseFinder(ecModel, finder);
  24897. each$1(finder, function (models, key) {
  24898. key.indexOf('Models') >= 0 && each$1(models, function (model) {
  24899. var coordSys = model.coordinateSystem;
  24900. if (coordSys && coordSys.containPoint) {
  24901. result |= !!coordSys.containPoint(value);
  24902. }
  24903. else if (key === 'seriesModels') {
  24904. var view = this._chartsMap[model.__viewId];
  24905. if (view && view.containPoint) {
  24906. result |= view.containPoint(value, model);
  24907. }
  24908. else {
  24909. if (__DEV__) {
  24910. console.warn(key + ': ' + (view
  24911. ? 'The found component do not support containPoint.'
  24912. : 'No view mapping to the found component.'
  24913. ));
  24914. }
  24915. }
  24916. }
  24917. else {
  24918. if (__DEV__) {
  24919. console.warn(key + ': containPoint is not supported');
  24920. }
  24921. }
  24922. }, this);
  24923. }, this);
  24924. return !!result;
  24925. };
  24926. /**
  24927. * Get visual from series or data.
  24928. * @param {string|Object} finder
  24929. * If string, e.g., 'series', means {seriesIndex: 0}.
  24930. * If Object, could contain some of these properties below:
  24931. * {
  24932. * seriesIndex / seriesId / seriesName,
  24933. * dataIndex / dataIndexInside
  24934. * }
  24935. * If dataIndex is not specified, series visual will be fetched,
  24936. * but not data item visual.
  24937. * If all of seriesIndex, seriesId, seriesName are not specified,
  24938. * visual will be fetched from first series.
  24939. * @param {string} visualType 'color', 'symbol', 'symbolSize'
  24940. */
  24941. echartsProto.getVisual = function (finder, visualType) {
  24942. var ecModel = this._model;
  24943. finder = parseFinder(ecModel, finder, {defaultMainType: 'series'});
  24944. var seriesModel = finder.seriesModel;
  24945. if (__DEV__) {
  24946. if (!seriesModel) {
  24947. console.warn('There is no specified seires model');
  24948. }
  24949. }
  24950. var data = seriesModel.getData();
  24951. var dataIndexInside = finder.hasOwnProperty('dataIndexInside')
  24952. ? finder.dataIndexInside
  24953. : finder.hasOwnProperty('dataIndex')
  24954. ? data.indexOfRawIndex(finder.dataIndex)
  24955. : null;
  24956. return dataIndexInside != null
  24957. ? data.getItemVisual(dataIndexInside, visualType)
  24958. : data.getVisual(visualType);
  24959. };
  24960. /**
  24961. * Get view of corresponding component model
  24962. * @param {module:echarts/model/Component} componentModel
  24963. * @return {module:echarts/view/Component}
  24964. */
  24965. echartsProto.getViewOfComponentModel = function (componentModel) {
  24966. return this._componentsMap[componentModel.__viewId];
  24967. };
  24968. /**
  24969. * Get view of corresponding series model
  24970. * @param {module:echarts/model/Series} seriesModel
  24971. * @return {module:echarts/view/Chart}
  24972. */
  24973. echartsProto.getViewOfSeriesModel = function (seriesModel) {
  24974. return this._chartsMap[seriesModel.__viewId];
  24975. };
  24976. var updateMethods = {
  24977. prepareAndUpdate: function (payload) {
  24978. prepare(this);
  24979. updateMethods.update.call(this, payload);
  24980. },
  24981. /**
  24982. * @param {Object} payload
  24983. * @private
  24984. */
  24985. update: function (payload) {
  24986. // console.profile && console.profile('update');
  24987. var ecModel = this._model;
  24988. var api = this._api;
  24989. var zr = this._zr;
  24990. var coordSysMgr = this._coordSysMgr;
  24991. var scheduler = this._scheduler;
  24992. // update before setOption
  24993. if (!ecModel) {
  24994. return;
  24995. }
  24996. scheduler.restoreData(ecModel, payload);
  24997. scheduler.performSeriesTasks(ecModel);
  24998. // TODO
  24999. // Save total ecModel here for undo/redo (after restoring data and before processing data).
  25000. // Undo (restoration of total ecModel) can be carried out in 'action' or outside API call.
  25001. // Create new coordinate system each update
  25002. // In LineView may save the old coordinate system and use it to get the orignal point
  25003. coordSysMgr.create(ecModel, api);
  25004. scheduler.performDataProcessorTasks(ecModel, payload);
  25005. // Current stream render is not supported in data process. So we can update
  25006. // stream modes after data processing, where the filtered data is used to
  25007. // deteming whether use progressive rendering.
  25008. updateStreamModes(this, ecModel);
  25009. // We update stream modes before coordinate system updated, then the modes info
  25010. // can be fetched when coord sys updating (consider the barGrid extent fix). But
  25011. // the drawback is the full coord info can not be fetched. Fortunately this full
  25012. // coord is not requied in stream mode updater currently.
  25013. coordSysMgr.update(ecModel, api);
  25014. clearColorPalette(ecModel);
  25015. scheduler.performVisualTasks(ecModel, payload);
  25016. render(this, ecModel, api, payload);
  25017. // Set background
  25018. var backgroundColor = ecModel.get('backgroundColor') || 'transparent';
  25019. // In IE8
  25020. if (!env$1.canvasSupported) {
  25021. var colorArr = parse(backgroundColor);
  25022. backgroundColor = stringify(colorArr, 'rgb');
  25023. if (colorArr[3] === 0) {
  25024. backgroundColor = 'transparent';
  25025. }
  25026. }
  25027. else {
  25028. zr.setBackgroundColor(backgroundColor);
  25029. }
  25030. performPostUpdateFuncs(ecModel, api);
  25031. // console.profile && console.profileEnd('update');
  25032. },
  25033. /**
  25034. * @param {Object} payload
  25035. * @private
  25036. */
  25037. updateTransform: function (payload) {
  25038. var ecModel = this._model;
  25039. var ecIns = this;
  25040. var api = this._api;
  25041. // update before setOption
  25042. if (!ecModel) {
  25043. return;
  25044. }
  25045. // ChartView.markUpdateMethod(payload, 'updateTransform');
  25046. var componentDirtyList = [];
  25047. ecModel.eachComponent(function (componentType, componentModel) {
  25048. var componentView = ecIns.getViewOfComponentModel(componentModel);
  25049. if (componentView && componentView.__alive) {
  25050. if (componentView.updateTransform) {
  25051. var result = componentView.updateTransform(componentModel, ecModel, api, payload);
  25052. result && result.update && componentDirtyList.push(componentView);
  25053. }
  25054. else {
  25055. componentDirtyList.push(componentView);
  25056. }
  25057. }
  25058. });
  25059. var seriesDirtyMap = createHashMap();
  25060. ecModel.eachSeries(function (seriesModel) {
  25061. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  25062. if (chartView.updateTransform) {
  25063. var result = chartView.updateTransform(seriesModel, ecModel, api, payload);
  25064. result && result.update && seriesDirtyMap.set(seriesModel.uid, 1);
  25065. }
  25066. else {
  25067. seriesDirtyMap.set(seriesModel.uid, 1);
  25068. }
  25069. });
  25070. clearColorPalette(ecModel);
  25071. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  25072. // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  25073. this._scheduler.performVisualTasks(
  25074. ecModel, payload, {setDirty: true, dirtyMap: seriesDirtyMap}
  25075. );
  25076. // Currently, not call render of components. Geo render cost a lot.
  25077. // renderComponents(ecIns, ecModel, api, payload, componentDirtyList);
  25078. renderSeries(ecIns, ecModel, api, payload, seriesDirtyMap);
  25079. performPostUpdateFuncs(ecModel, this._api);
  25080. },
  25081. /**
  25082. * @param {Object} payload
  25083. * @private
  25084. */
  25085. updateView: function (payload) {
  25086. var ecModel = this._model;
  25087. // update before setOption
  25088. if (!ecModel) {
  25089. return;
  25090. }
  25091. Chart.markUpdateMethod(payload, 'updateView');
  25092. clearColorPalette(ecModel);
  25093. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  25094. this._scheduler.performVisualTasks(ecModel, payload, {setDirty: true});
  25095. render(this, this._model, this._api, payload);
  25096. performPostUpdateFuncs(ecModel, this._api);
  25097. },
  25098. /**
  25099. * @param {Object} payload
  25100. * @private
  25101. */
  25102. updateVisual: function (payload) {
  25103. updateMethods.update.call(this, payload);
  25104. // var ecModel = this._model;
  25105. // // update before setOption
  25106. // if (!ecModel) {
  25107. // return;
  25108. // }
  25109. // ChartView.markUpdateMethod(payload, 'updateVisual');
  25110. // clearColorPalette(ecModel);
  25111. // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  25112. // this._scheduler.performVisualTasks(ecModel, payload, {visualType: 'visual', setDirty: true});
  25113. // render(this, this._model, this._api, payload);
  25114. // performPostUpdateFuncs(ecModel, this._api);
  25115. },
  25116. /**
  25117. * @param {Object} payload
  25118. * @private
  25119. */
  25120. updateLayout: function (payload) {
  25121. updateMethods.update.call(this, payload);
  25122. // var ecModel = this._model;
  25123. // // update before setOption
  25124. // if (!ecModel) {
  25125. // return;
  25126. // }
  25127. // ChartView.markUpdateMethod(payload, 'updateLayout');
  25128. // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  25129. // // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  25130. // this._scheduler.performVisualTasks(ecModel, payload, {setDirty: true});
  25131. // render(this, this._model, this._api, payload);
  25132. // performPostUpdateFuncs(ecModel, this._api);
  25133. }
  25134. };
  25135. function prepare(ecIns) {
  25136. var ecModel = ecIns._model;
  25137. var scheduler = ecIns._scheduler;
  25138. scheduler.restorePipelines(ecModel);
  25139. scheduler.prepareStageTasks();
  25140. prepareView(ecIns, 'component', ecModel, scheduler);
  25141. prepareView(ecIns, 'chart', ecModel, scheduler);
  25142. scheduler.plan();
  25143. }
  25144. /**
  25145. * @private
  25146. */
  25147. function updateDirectly(ecIns, method, payload, mainType, subType) {
  25148. var ecModel = ecIns._model;
  25149. // broadcast
  25150. if (!mainType) {
  25151. // FIXME
  25152. // Chart will not be update directly here, except set dirty.
  25153. // But there is no such scenario now.
  25154. each(ecIns._componentsViews.concat(ecIns._chartsViews), callView);
  25155. return;
  25156. }
  25157. var query = {};
  25158. query[mainType + 'Id'] = payload[mainType + 'Id'];
  25159. query[mainType + 'Index'] = payload[mainType + 'Index'];
  25160. query[mainType + 'Name'] = payload[mainType + 'Name'];
  25161. var condition = {mainType: mainType, query: query};
  25162. subType && (condition.subType = subType); // subType may be '' by parseClassType;
  25163. var excludeSeriesId = payload.excludeSeriesId;
  25164. if (excludeSeriesId != null) {
  25165. excludeSeriesId = createHashMap(normalizeToArray(excludeSeriesId));
  25166. }
  25167. // If dispatchAction before setOption, do nothing.
  25168. ecModel && ecModel.eachComponent(condition, function (model) {
  25169. if (!excludeSeriesId || excludeSeriesId.get(model.id) == null) {
  25170. callView(ecIns[
  25171. mainType === 'series' ? '_chartsMap' : '_componentsMap'
  25172. ][model.__viewId]);
  25173. }
  25174. }, ecIns);
  25175. function callView(view) {
  25176. view && view.__alive && view[method] && view[method](
  25177. view.__model, ecModel, ecIns._api, payload
  25178. );
  25179. }
  25180. }
  25181. /**
  25182. * Resize the chart
  25183. * @param {Object} opts
  25184. * @param {number} [opts.width] Can be 'auto' (the same as null/undefined)
  25185. * @param {number} [opts.height] Can be 'auto' (the same as null/undefined)
  25186. * @param {boolean} [opts.silent=false]
  25187. */
  25188. echartsProto.resize = function (opts) {
  25189. if (__DEV__) {
  25190. assert(!this[IN_MAIN_PROCESS], '`resize` should not be called during main process.');
  25191. }
  25192. if (this._disposed) {
  25193. disposedWarning(this.id);
  25194. return;
  25195. }
  25196. this._zr.resize(opts);
  25197. var ecModel = this._model;
  25198. // Resize loading effect
  25199. this._loadingFX && this._loadingFX.resize();
  25200. if (!ecModel) {
  25201. return;
  25202. }
  25203. var optionChanged = ecModel.resetOption('media');
  25204. var silent = opts && opts.silent;
  25205. this[IN_MAIN_PROCESS] = true;
  25206. optionChanged && prepare(this);
  25207. updateMethods.update.call(this);
  25208. this[IN_MAIN_PROCESS] = false;
  25209. flushPendingActions.call(this, silent);
  25210. triggerUpdatedEvent.call(this, silent);
  25211. };
  25212. function updateStreamModes(ecIns, ecModel) {
  25213. var chartsMap = ecIns._chartsMap;
  25214. var scheduler = ecIns._scheduler;
  25215. ecModel.eachSeries(function (seriesModel) {
  25216. scheduler.updateStreamModes(seriesModel, chartsMap[seriesModel.__viewId]);
  25217. });
  25218. }
  25219. /**
  25220. * Show loading effect
  25221. * @param {string} [name='default']
  25222. * @param {Object} [cfg]
  25223. */
  25224. echartsProto.showLoading = function (name, cfg) {
  25225. if (this._disposed) {
  25226. disposedWarning(this.id);
  25227. return;
  25228. }
  25229. if (isObject(name)) {
  25230. cfg = name;
  25231. name = '';
  25232. }
  25233. name = name || 'default';
  25234. this.hideLoading();
  25235. if (!loadingEffects[name]) {
  25236. if (__DEV__) {
  25237. console.warn('Loading effects ' + name + ' not exists.');
  25238. }
  25239. return;
  25240. }
  25241. var el = loadingEffects[name](this._api, cfg);
  25242. var zr = this._zr;
  25243. this._loadingFX = el;
  25244. zr.add(el);
  25245. };
  25246. /**
  25247. * Hide loading effect
  25248. */
  25249. echartsProto.hideLoading = function () {
  25250. if (this._disposed) {
  25251. disposedWarning(this.id);
  25252. return;
  25253. }
  25254. this._loadingFX && this._zr.remove(this._loadingFX);
  25255. this._loadingFX = null;
  25256. };
  25257. /**
  25258. * @param {Object} eventObj
  25259. * @return {Object}
  25260. */
  25261. echartsProto.makeActionFromEvent = function (eventObj) {
  25262. var payload = extend({}, eventObj);
  25263. payload.type = eventActionMap[eventObj.type];
  25264. return payload;
  25265. };
  25266. /**
  25267. * @pubilc
  25268. * @param {Object} payload
  25269. * @param {string} [payload.type] Action type
  25270. * @param {Object|boolean} [opt] If pass boolean, means opt.silent
  25271. * @param {boolean} [opt.silent=false] Whether trigger events.
  25272. * @param {boolean} [opt.flush=undefined]
  25273. * true: Flush immediately, and then pixel in canvas can be fetched
  25274. * immediately. Caution: it might affect performance.
  25275. * false: Not flush.
  25276. * undefined: Auto decide whether perform flush.
  25277. */
  25278. echartsProto.dispatchAction = function (payload, opt) {
  25279. if (this._disposed) {
  25280. disposedWarning(this.id);
  25281. return;
  25282. }
  25283. if (!isObject(opt)) {
  25284. opt = {silent: !!opt};
  25285. }
  25286. if (!actions[payload.type]) {
  25287. return;
  25288. }
  25289. // Avoid dispatch action before setOption. Especially in `connect`.
  25290. if (!this._model) {
  25291. return;
  25292. }
  25293. // May dispatchAction in rendering procedure
  25294. if (this[IN_MAIN_PROCESS]) {
  25295. this._pendingActions.push(payload);
  25296. return;
  25297. }
  25298. doDispatchAction.call(this, payload, opt.silent);
  25299. if (opt.flush) {
  25300. this._zr.flush(true);
  25301. }
  25302. else if (opt.flush !== false && env$1.browser.weChat) {
  25303. // In WeChat embeded browser, `requestAnimationFrame` and `setInterval`
  25304. // hang when sliding page (on touch event), which cause that zr does not
  25305. // refresh util user interaction finished, which is not expected.
  25306. // But `dispatchAction` may be called too frequently when pan on touch
  25307. // screen, which impacts performance if do not throttle them.
  25308. this._throttledZrFlush();
  25309. }
  25310. flushPendingActions.call(this, opt.silent);
  25311. triggerUpdatedEvent.call(this, opt.silent);
  25312. };
  25313. function doDispatchAction(payload, silent) {
  25314. var payloadType = payload.type;
  25315. var escapeConnect = payload.escapeConnect;
  25316. var actionWrap = actions[payloadType];
  25317. var actionInfo = actionWrap.actionInfo;
  25318. var cptType = (actionInfo.update || 'update').split(':');
  25319. var updateMethod = cptType.pop();
  25320. cptType = cptType[0] != null && parseClassType(cptType[0]);
  25321. this[IN_MAIN_PROCESS] = true;
  25322. var payloads = [payload];
  25323. var batched = false;
  25324. // Batch action
  25325. if (payload.batch) {
  25326. batched = true;
  25327. payloads = map(payload.batch, function (item) {
  25328. item = defaults(extend({}, item), payload);
  25329. item.batch = null;
  25330. return item;
  25331. });
  25332. }
  25333. var eventObjBatch = [];
  25334. var eventObj;
  25335. var isHighDown = payloadType === 'highlight' || payloadType === 'downplay';
  25336. each(payloads, function (batchItem) {
  25337. // Action can specify the event by return it.
  25338. eventObj = actionWrap.action(batchItem, this._model, this._api);
  25339. // Emit event outside
  25340. eventObj = eventObj || extend({}, batchItem);
  25341. // Convert type to eventType
  25342. eventObj.type = actionInfo.event || eventObj.type;
  25343. eventObjBatch.push(eventObj);
  25344. // light update does not perform data process, layout and visual.
  25345. if (isHighDown) {
  25346. // method, payload, mainType, subType
  25347. updateDirectly(this, updateMethod, batchItem, 'series');
  25348. }
  25349. else if (cptType) {
  25350. updateDirectly(this, updateMethod, batchItem, cptType.main, cptType.sub);
  25351. }
  25352. }, this);
  25353. if (updateMethod !== 'none' && !isHighDown && !cptType) {
  25354. // Still dirty
  25355. if (this[OPTION_UPDATED]) {
  25356. // FIXME Pass payload ?
  25357. prepare(this);
  25358. updateMethods.update.call(this, payload);
  25359. this[OPTION_UPDATED] = false;
  25360. }
  25361. else {
  25362. updateMethods[updateMethod].call(this, payload);
  25363. }
  25364. }
  25365. // Follow the rule of action batch
  25366. if (batched) {
  25367. eventObj = {
  25368. type: actionInfo.event || payloadType,
  25369. escapeConnect: escapeConnect,
  25370. batch: eventObjBatch
  25371. };
  25372. }
  25373. else {
  25374. eventObj = eventObjBatch[0];
  25375. }
  25376. this[IN_MAIN_PROCESS] = false;
  25377. !silent && this._messageCenter.trigger(eventObj.type, eventObj);
  25378. }
  25379. function flushPendingActions(silent) {
  25380. var pendingActions = this._pendingActions;
  25381. while (pendingActions.length) {
  25382. var payload = pendingActions.shift();
  25383. doDispatchAction.call(this, payload, silent);
  25384. }
  25385. }
  25386. function triggerUpdatedEvent(silent) {
  25387. !silent && this.trigger('updated');
  25388. }
  25389. /**
  25390. * Event `rendered` is triggered when zr
  25391. * rendered. It is useful for realtime
  25392. * snapshot (reflect animation).
  25393. *
  25394. * Event `finished` is triggered when:
  25395. * (1) zrender rendering finished.
  25396. * (2) initial animation finished.
  25397. * (3) progressive rendering finished.
  25398. * (4) no pending action.
  25399. * (5) no delayed setOption needs to be processed.
  25400. */
  25401. function bindRenderedEvent(zr, ecIns) {
  25402. zr.on('rendered', function () {
  25403. ecIns.trigger('rendered');
  25404. // The `finished` event should not be triggered repeatly,
  25405. // so it should only be triggered when rendering indeed happend
  25406. // in zrender. (Consider the case that dipatchAction is keep
  25407. // triggering when mouse move).
  25408. if (
  25409. // Although zr is dirty if initial animation is not finished
  25410. // and this checking is called on frame, we also check
  25411. // animation finished for robustness.
  25412. zr.animation.isFinished()
  25413. && !ecIns[OPTION_UPDATED]
  25414. && !ecIns._scheduler.unfinished
  25415. && !ecIns._pendingActions.length
  25416. ) {
  25417. ecIns.trigger('finished');
  25418. }
  25419. });
  25420. }
  25421. /**
  25422. * @param {Object} params
  25423. * @param {number} params.seriesIndex
  25424. * @param {Array|TypedArray} params.data
  25425. */
  25426. echartsProto.appendData = function (params) {
  25427. if (this._disposed) {
  25428. disposedWarning(this.id);
  25429. return;
  25430. }
  25431. var seriesIndex = params.seriesIndex;
  25432. var ecModel = this.getModel();
  25433. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  25434. if (__DEV__) {
  25435. assert(params.data && seriesModel);
  25436. }
  25437. seriesModel.appendData(params);
  25438. // Note: `appendData` does not support that update extent of coordinate
  25439. // system, util some scenario require that. In the expected usage of
  25440. // `appendData`, the initial extent of coordinate system should better
  25441. // be fixed by axis `min`/`max` setting or initial data, otherwise if
  25442. // the extent changed while `appendData`, the location of the painted
  25443. // graphic elements have to be changed, which make the usage of
  25444. // `appendData` meaningless.
  25445. this._scheduler.unfinished = true;
  25446. };
  25447. /**
  25448. * Register event
  25449. * @method
  25450. */
  25451. echartsProto.on = createRegisterEventWithLowercaseName('on', false);
  25452. echartsProto.off = createRegisterEventWithLowercaseName('off', false);
  25453. echartsProto.one = createRegisterEventWithLowercaseName('one', false);
  25454. /**
  25455. * Prepare view instances of charts and components
  25456. * @param {module:echarts/model/Global} ecModel
  25457. * @private
  25458. */
  25459. function prepareView(ecIns, type, ecModel, scheduler) {
  25460. var isComponent = type === 'component';
  25461. var viewList = isComponent ? ecIns._componentsViews : ecIns._chartsViews;
  25462. var viewMap = isComponent ? ecIns._componentsMap : ecIns._chartsMap;
  25463. var zr = ecIns._zr;
  25464. var api = ecIns._api;
  25465. for (var i = 0; i < viewList.length; i++) {
  25466. viewList[i].__alive = false;
  25467. }
  25468. isComponent
  25469. ? ecModel.eachComponent(function (componentType, model) {
  25470. componentType !== 'series' && doPrepare(model);
  25471. })
  25472. : ecModel.eachSeries(doPrepare);
  25473. function doPrepare(model) {
  25474. // Consider: id same and type changed.
  25475. var viewId = '_ec_' + model.id + '_' + model.type;
  25476. var view = viewMap[viewId];
  25477. if (!view) {
  25478. var classType = parseClassType(model.type);
  25479. var Clazz = isComponent
  25480. ? Component$1.getClass(classType.main, classType.sub)
  25481. : Chart.getClass(classType.sub);
  25482. if (__DEV__) {
  25483. assert(Clazz, classType.sub + ' does not exist.');
  25484. }
  25485. view = new Clazz();
  25486. view.init(ecModel, api);
  25487. viewMap[viewId] = view;
  25488. viewList.push(view);
  25489. zr.add(view.group);
  25490. }
  25491. model.__viewId = view.__id = viewId;
  25492. view.__alive = true;
  25493. view.__model = model;
  25494. view.group.__ecComponentInfo = {
  25495. mainType: model.mainType,
  25496. index: model.componentIndex
  25497. };
  25498. !isComponent && scheduler.prepareView(view, model, ecModel, api);
  25499. }
  25500. for (var i = 0; i < viewList.length;) {
  25501. var view = viewList[i];
  25502. if (!view.__alive) {
  25503. !isComponent && view.renderTask.dispose();
  25504. zr.remove(view.group);
  25505. view.dispose(ecModel, api);
  25506. viewList.splice(i, 1);
  25507. delete viewMap[view.__id];
  25508. view.__id = view.group.__ecComponentInfo = null;
  25509. }
  25510. else {
  25511. i++;
  25512. }
  25513. }
  25514. }
  25515. // /**
  25516. // * Encode visual infomation from data after data processing
  25517. // *
  25518. // * @param {module:echarts/model/Global} ecModel
  25519. // * @param {object} layout
  25520. // * @param {boolean} [layoutFilter] `true`: only layout,
  25521. // * `false`: only not layout,
  25522. // * `null`/`undefined`: all.
  25523. // * @param {string} taskBaseTag
  25524. // * @private
  25525. // */
  25526. // function startVisualEncoding(ecIns, ecModel, api, payload, layoutFilter) {
  25527. // each(visualFuncs, function (visual, index) {
  25528. // var isLayout = visual.isLayout;
  25529. // if (layoutFilter == null
  25530. // || (layoutFilter === false && !isLayout)
  25531. // || (layoutFilter === true && isLayout)
  25532. // ) {
  25533. // visual.func(ecModel, api, payload);
  25534. // }
  25535. // });
  25536. // }
  25537. function clearColorPalette(ecModel) {
  25538. ecModel.clearColorPalette();
  25539. ecModel.eachSeries(function (seriesModel) {
  25540. seriesModel.clearColorPalette();
  25541. });
  25542. }
  25543. function render(ecIns, ecModel, api, payload) {
  25544. renderComponents(ecIns, ecModel, api, payload);
  25545. each(ecIns._chartsViews, function (chart) {
  25546. chart.__alive = false;
  25547. });
  25548. renderSeries(ecIns, ecModel, api, payload);
  25549. // Remove groups of unrendered charts
  25550. each(ecIns._chartsViews, function (chart) {
  25551. if (!chart.__alive) {
  25552. chart.remove(ecModel, api);
  25553. }
  25554. });
  25555. }
  25556. function renderComponents(ecIns, ecModel, api, payload, dirtyList) {
  25557. each(dirtyList || ecIns._componentsViews, function (componentView) {
  25558. var componentModel = componentView.__model;
  25559. componentView.render(componentModel, ecModel, api, payload);
  25560. updateZ(componentModel, componentView);
  25561. });
  25562. }
  25563. /**
  25564. * Render each chart and component
  25565. * @private
  25566. */
  25567. function renderSeries(ecIns, ecModel, api, payload, dirtyMap) {
  25568. // Render all charts
  25569. var scheduler = ecIns._scheduler;
  25570. var unfinished;
  25571. ecModel.eachSeries(function (seriesModel) {
  25572. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  25573. chartView.__alive = true;
  25574. var renderTask = chartView.renderTask;
  25575. scheduler.updatePayload(renderTask, payload);
  25576. if (dirtyMap && dirtyMap.get(seriesModel.uid)) {
  25577. renderTask.dirty();
  25578. }
  25579. unfinished |= renderTask.perform(scheduler.getPerformArgs(renderTask));
  25580. chartView.group.silent = !!seriesModel.get('silent');
  25581. updateZ(seriesModel, chartView);
  25582. updateBlend(seriesModel, chartView);
  25583. });
  25584. scheduler.unfinished |= unfinished;
  25585. // If use hover layer
  25586. updateHoverLayerStatus(ecIns, ecModel);
  25587. // Add aria
  25588. aria(ecIns._zr.dom, ecModel);
  25589. }
  25590. function performPostUpdateFuncs(ecModel, api) {
  25591. each(postUpdateFuncs, function (func) {
  25592. func(ecModel, api);
  25593. });
  25594. }
  25595. var MOUSE_EVENT_NAMES = [
  25596. 'click', 'dblclick', 'mouseover', 'mouseout', 'mousemove',
  25597. 'mousedown', 'mouseup', 'globalout', 'contextmenu'
  25598. ];
  25599. /**
  25600. * @private
  25601. */
  25602. echartsProto._initEvents = function () {
  25603. each(MOUSE_EVENT_NAMES, function (eveName) {
  25604. var handler = function (e) {
  25605. var ecModel = this.getModel();
  25606. var el = e.target;
  25607. var params;
  25608. var isGlobalOut = eveName === 'globalout';
  25609. // no e.target when 'globalout'.
  25610. if (isGlobalOut) {
  25611. params = {};
  25612. }
  25613. else if (el && el.dataIndex != null) {
  25614. var dataModel = el.dataModel || ecModel.getSeriesByIndex(el.seriesIndex);
  25615. params = dataModel && dataModel.getDataParams(el.dataIndex, el.dataType, el) || {};
  25616. }
  25617. // If element has custom eventData of components
  25618. else if (el && el.eventData) {
  25619. params = extend({}, el.eventData);
  25620. }
  25621. // Contract: if params prepared in mouse event,
  25622. // these properties must be specified:
  25623. // {
  25624. // componentType: string (component main type)
  25625. // componentIndex: number
  25626. // }
  25627. // Otherwise event query can not work.
  25628. if (params) {
  25629. var componentType = params.componentType;
  25630. var componentIndex = params.componentIndex;
  25631. // Special handling for historic reason: when trigger by
  25632. // markLine/markPoint/markArea, the componentType is
  25633. // 'markLine'/'markPoint'/'markArea', but we should better
  25634. // enable them to be queried by seriesIndex, since their
  25635. // option is set in each series.
  25636. if (componentType === 'markLine'
  25637. || componentType === 'markPoint'
  25638. || componentType === 'markArea'
  25639. ) {
  25640. componentType = 'series';
  25641. componentIndex = params.seriesIndex;
  25642. }
  25643. var model = componentType && componentIndex != null
  25644. && ecModel.getComponent(componentType, componentIndex);
  25645. var view = model && this[
  25646. model.mainType === 'series' ? '_chartsMap' : '_componentsMap'
  25647. ][model.__viewId];
  25648. if (__DEV__) {
  25649. // `event.componentType` and `event[componentTpype + 'Index']` must not
  25650. // be missed, otherwise there is no way to distinguish source component.
  25651. // See `dataFormat.getDataParams`.
  25652. if (!isGlobalOut && !(model && view)) {
  25653. console.warn('model or view can not be found by params');
  25654. }
  25655. }
  25656. params.event = e;
  25657. params.type = eveName;
  25658. this._ecEventProcessor.eventInfo = {
  25659. targetEl: el,
  25660. packedEvent: params,
  25661. model: model,
  25662. view: view
  25663. };
  25664. this.trigger(eveName, params);
  25665. }
  25666. };
  25667. // Consider that some component (like tooltip, brush, ...)
  25668. // register zr event handler, but user event handler might
  25669. // do anything, such as call `setOption` or `dispatchAction`,
  25670. // which probably update any of the content and probably
  25671. // cause problem if it is called previous other inner handlers.
  25672. handler.zrEventfulCallAtLast = true;
  25673. this._zr.on(eveName, handler, this);
  25674. }, this);
  25675. each(eventActionMap, function (actionType, eventType) {
  25676. this._messageCenter.on(eventType, function (event) {
  25677. this.trigger(eventType, event);
  25678. }, this);
  25679. }, this);
  25680. };
  25681. /**
  25682. * @return {boolean}
  25683. */
  25684. echartsProto.isDisposed = function () {
  25685. return this._disposed;
  25686. };
  25687. /**
  25688. * Clear
  25689. */
  25690. echartsProto.clear = function () {
  25691. if (this._disposed) {
  25692. disposedWarning(this.id);
  25693. return;
  25694. }
  25695. this.setOption({ series: [] }, true);
  25696. };
  25697. /**
  25698. * Dispose instance
  25699. */
  25700. echartsProto.dispose = function () {
  25701. if (this._disposed) {
  25702. disposedWarning(this.id);
  25703. return;
  25704. }
  25705. this._disposed = true;
  25706. setAttribute(this.getDom(), DOM_ATTRIBUTE_KEY, '');
  25707. var api = this._api;
  25708. var ecModel = this._model;
  25709. each(this._componentsViews, function (component) {
  25710. component.dispose(ecModel, api);
  25711. });
  25712. each(this._chartsViews, function (chart) {
  25713. chart.dispose(ecModel, api);
  25714. });
  25715. // Dispose after all views disposed
  25716. this._zr.dispose();
  25717. delete instances[this.id];
  25718. };
  25719. mixin(ECharts, Eventful);
  25720. function disposedWarning(id) {
  25721. if (__DEV__) {
  25722. console.warn('Instance ' + id + ' has been disposed');
  25723. }
  25724. }
  25725. function updateHoverLayerStatus(ecIns, ecModel) {
  25726. var zr = ecIns._zr;
  25727. var storage = zr.storage;
  25728. var elCount = 0;
  25729. storage.traverse(function (el) {
  25730. elCount++;
  25731. });
  25732. if (elCount > ecModel.get('hoverLayerThreshold') && !env$1.node) {
  25733. ecModel.eachSeries(function (seriesModel) {
  25734. if (seriesModel.preventUsingHoverLayer) {
  25735. return;
  25736. }
  25737. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  25738. if (chartView.__alive) {
  25739. chartView.group.traverse(function (el) {
  25740. // Don't switch back.
  25741. el.useHoverLayer = true;
  25742. });
  25743. }
  25744. });
  25745. }
  25746. }
  25747. /**
  25748. * Update chart progressive and blend.
  25749. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  25750. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  25751. */
  25752. function updateBlend(seriesModel, chartView) {
  25753. var blendMode = seriesModel.get('blendMode') || null;
  25754. if (__DEV__) {
  25755. if (!env$1.canvasSupported && blendMode && blendMode !== 'source-over') {
  25756. console.warn('Only canvas support blendMode');
  25757. }
  25758. }
  25759. chartView.group.traverse(function (el) {
  25760. // FIXME marker and other components
  25761. if (!el.isGroup) {
  25762. // Only set if blendMode is changed. In case element is incremental and don't wan't to rerender.
  25763. if (el.style.blend !== blendMode) {
  25764. el.setStyle('blend', blendMode);
  25765. }
  25766. }
  25767. if (el.eachPendingDisplayable) {
  25768. el.eachPendingDisplayable(function (displayable) {
  25769. displayable.setStyle('blend', blendMode);
  25770. });
  25771. }
  25772. });
  25773. }
  25774. /**
  25775. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  25776. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  25777. */
  25778. function updateZ(model, view) {
  25779. var z = model.get('z');
  25780. var zlevel = model.get('zlevel');
  25781. // Set z and zlevel
  25782. view.group.traverse(function (el) {
  25783. if (el.type !== 'group') {
  25784. z != null && (el.z = z);
  25785. zlevel != null && (el.zlevel = zlevel);
  25786. }
  25787. });
  25788. }
  25789. function createExtensionAPI(ecInstance) {
  25790. var coordSysMgr = ecInstance._coordSysMgr;
  25791. return extend(new ExtensionAPI(ecInstance), {
  25792. // Inject methods
  25793. getCoordinateSystems: bind(
  25794. coordSysMgr.getCoordinateSystems, coordSysMgr
  25795. ),
  25796. getComponentByElement: function (el) {
  25797. while (el) {
  25798. var modelInfo = el.__ecComponentInfo;
  25799. if (modelInfo != null) {
  25800. return ecInstance._model.getComponent(modelInfo.mainType, modelInfo.index);
  25801. }
  25802. el = el.parent;
  25803. }
  25804. }
  25805. });
  25806. }
  25807. /**
  25808. * @class
  25809. * Usage of query:
  25810. * `chart.on('click', query, handler);`
  25811. * The `query` can be:
  25812. * + The component type query string, only `mainType` or `mainType.subType`,
  25813. * like: 'xAxis', 'series', 'xAxis.category' or 'series.line'.
  25814. * + The component query object, like:
  25815. * `{seriesIndex: 2}`, `{seriesName: 'xx'}`, `{seriesId: 'some'}`,
  25816. * `{xAxisIndex: 2}`, `{xAxisName: 'xx'}`, `{xAxisId: 'some'}`.
  25817. * + The data query object, like:
  25818. * `{dataIndex: 123}`, `{dataType: 'link'}`, `{name: 'some'}`.
  25819. * + The other query object (cmponent customized query), like:
  25820. * `{element: 'some'}` (only available in custom series).
  25821. *
  25822. * Caveat: If a prop in the `query` object is `null/undefined`, it is the
  25823. * same as there is no such prop in the `query` object.
  25824. */
  25825. function EventProcessor() {
  25826. // These info required: targetEl, packedEvent, model, view
  25827. this.eventInfo;
  25828. }
  25829. EventProcessor.prototype = {
  25830. constructor: EventProcessor,
  25831. normalizeQuery: function (query) {
  25832. var cptQuery = {};
  25833. var dataQuery = {};
  25834. var otherQuery = {};
  25835. // `query` is `mainType` or `mainType.subType` of component.
  25836. if (isString(query)) {
  25837. var condCptType = parseClassType(query);
  25838. // `.main` and `.sub` may be ''.
  25839. cptQuery.mainType = condCptType.main || null;
  25840. cptQuery.subType = condCptType.sub || null;
  25841. }
  25842. // `query` is an object, convert to {mainType, index, name, id}.
  25843. else {
  25844. // `xxxIndex`, `xxxName`, `xxxId`, `name`, `dataIndex`, `dataType` is reserved,
  25845. // can not be used in `compomentModel.filterForExposedEvent`.
  25846. var suffixes = ['Index', 'Name', 'Id'];
  25847. var dataKeys = {name: 1, dataIndex: 1, dataType: 1};
  25848. each$1(query, function (val, key) {
  25849. var reserved = false;
  25850. for (var i = 0; i < suffixes.length; i++) {
  25851. var propSuffix = suffixes[i];
  25852. var suffixPos = key.lastIndexOf(propSuffix);
  25853. if (suffixPos > 0 && suffixPos === key.length - propSuffix.length) {
  25854. var mainType = key.slice(0, suffixPos);
  25855. // Consider `dataIndex`.
  25856. if (mainType !== 'data') {
  25857. cptQuery.mainType = mainType;
  25858. cptQuery[propSuffix.toLowerCase()] = val;
  25859. reserved = true;
  25860. }
  25861. }
  25862. }
  25863. if (dataKeys.hasOwnProperty(key)) {
  25864. dataQuery[key] = val;
  25865. reserved = true;
  25866. }
  25867. if (!reserved) {
  25868. otherQuery[key] = val;
  25869. }
  25870. });
  25871. }
  25872. return {
  25873. cptQuery: cptQuery,
  25874. dataQuery: dataQuery,
  25875. otherQuery: otherQuery
  25876. };
  25877. },
  25878. filter: function (eventType, query, args) {
  25879. // They should be assigned before each trigger call.
  25880. var eventInfo = this.eventInfo;
  25881. if (!eventInfo) {
  25882. return true;
  25883. }
  25884. var targetEl = eventInfo.targetEl;
  25885. var packedEvent = eventInfo.packedEvent;
  25886. var model = eventInfo.model;
  25887. var view = eventInfo.view;
  25888. // For event like 'globalout'.
  25889. if (!model || !view) {
  25890. return true;
  25891. }
  25892. var cptQuery = query.cptQuery;
  25893. var dataQuery = query.dataQuery;
  25894. return check(cptQuery, model, 'mainType')
  25895. && check(cptQuery, model, 'subType')
  25896. && check(cptQuery, model, 'index', 'componentIndex')
  25897. && check(cptQuery, model, 'name')
  25898. && check(cptQuery, model, 'id')
  25899. && check(dataQuery, packedEvent, 'name')
  25900. && check(dataQuery, packedEvent, 'dataIndex')
  25901. && check(dataQuery, packedEvent, 'dataType')
  25902. && (!view.filterForExposedEvent || view.filterForExposedEvent(
  25903. eventType, query.otherQuery, targetEl, packedEvent
  25904. ));
  25905. function check(query, host, prop, propOnHost) {
  25906. return query[prop] == null || host[propOnHost || prop] === query[prop];
  25907. }
  25908. },
  25909. afterTrigger: function () {
  25910. // Make sure the eventInfo wont be used in next trigger.
  25911. this.eventInfo = null;
  25912. }
  25913. };
  25914. /**
  25915. * @type {Object} key: actionType.
  25916. * @inner
  25917. */
  25918. var actions = {};
  25919. /**
  25920. * Map eventType to actionType
  25921. * @type {Object}
  25922. */
  25923. var eventActionMap = {};
  25924. /**
  25925. * Data processor functions of each stage
  25926. * @type {Array.<Object.<string, Function>>}
  25927. * @inner
  25928. */
  25929. var dataProcessorFuncs = [];
  25930. /**
  25931. * @type {Array.<Function>}
  25932. * @inner
  25933. */
  25934. var optionPreprocessorFuncs = [];
  25935. /**
  25936. * @type {Array.<Function>}
  25937. * @inner
  25938. */
  25939. var postUpdateFuncs = [];
  25940. /**
  25941. * Visual encoding functions of each stage
  25942. * @type {Array.<Object.<string, Function>>}
  25943. */
  25944. var visualFuncs = [];
  25945. /**
  25946. * Theme storage
  25947. * @type {Object.<key, Object>}
  25948. */
  25949. var themeStorage = {};
  25950. /**
  25951. * Loading effects
  25952. */
  25953. var loadingEffects = {};
  25954. var instances = {};
  25955. var connectedGroups = {};
  25956. var idBase = new Date() - 0;
  25957. var groupIdBase = new Date() - 0;
  25958. var DOM_ATTRIBUTE_KEY = '_echarts_instance_';
  25959. function enableConnect(chart) {
  25960. var STATUS_PENDING = 0;
  25961. var STATUS_UPDATING = 1;
  25962. var STATUS_UPDATED = 2;
  25963. var STATUS_KEY = '__connectUpdateStatus';
  25964. function updateConnectedChartsStatus(charts, status) {
  25965. for (var i = 0; i < charts.length; i++) {
  25966. var otherChart = charts[i];
  25967. otherChart[STATUS_KEY] = status;
  25968. }
  25969. }
  25970. each(eventActionMap, function (actionType, eventType) {
  25971. chart._messageCenter.on(eventType, function (event) {
  25972. if (connectedGroups[chart.group] && chart[STATUS_KEY] !== STATUS_PENDING) {
  25973. if (event && event.escapeConnect) {
  25974. return;
  25975. }
  25976. var action = chart.makeActionFromEvent(event);
  25977. var otherCharts = [];
  25978. each(instances, function (otherChart) {
  25979. if (otherChart !== chart && otherChart.group === chart.group) {
  25980. otherCharts.push(otherChart);
  25981. }
  25982. });
  25983. updateConnectedChartsStatus(otherCharts, STATUS_PENDING);
  25984. each(otherCharts, function (otherChart) {
  25985. if (otherChart[STATUS_KEY] !== STATUS_UPDATING) {
  25986. otherChart.dispatchAction(action);
  25987. }
  25988. });
  25989. updateConnectedChartsStatus(otherCharts, STATUS_UPDATED);
  25990. }
  25991. });
  25992. });
  25993. }
  25994. /**
  25995. * @param {HTMLElement} dom
  25996. * @param {Object} [theme]
  25997. * @param {Object} opts
  25998. * @param {number} [opts.devicePixelRatio] Use window.devicePixelRatio by default
  25999. * @param {string} [opts.renderer] Can choose 'canvas' or 'svg' to render the chart.
  26000. * @param {number} [opts.width] Use clientWidth of the input `dom` by default.
  26001. * Can be 'auto' (the same as null/undefined)
  26002. * @param {number} [opts.height] Use clientHeight of the input `dom` by default.
  26003. * Can be 'auto' (the same as null/undefined)
  26004. */
  26005. function init(dom, theme$$1, opts) {
  26006. if (__DEV__) {
  26007. // Check version
  26008. if ((version$1.replace('.', '') - 0) < (dependencies.zrender.replace('.', '') - 0)) {
  26009. throw new Error(
  26010. 'zrender/src ' + version$1
  26011. + ' is too old for ECharts ' + version
  26012. + '. Current version need ZRender '
  26013. + dependencies.zrender + '+'
  26014. );
  26015. }
  26016. if (!dom) {
  26017. throw new Error('Initialize failed: invalid dom.');
  26018. }
  26019. }
  26020. var existInstance = getInstanceByDom(dom);
  26021. if (existInstance) {
  26022. if (__DEV__) {
  26023. console.warn('There is a chart instance already initialized on the dom.');
  26024. }
  26025. return existInstance;
  26026. }
  26027. if (__DEV__) {
  26028. if (isDom(dom)
  26029. && dom.nodeName.toUpperCase() !== 'CANVAS'
  26030. && (
  26031. (!dom.clientWidth && (!opts || opts.width == null))
  26032. || (!dom.clientHeight && (!opts || opts.height == null))
  26033. )
  26034. ) {
  26035. console.warn('Can\'t get DOM width or height. Please check '
  26036. + 'dom.clientWidth and dom.clientHeight. They should not be 0.'
  26037. + 'For example, you may need to call this in the callback '
  26038. + 'of window.onload.');
  26039. }
  26040. }
  26041. var chart = new ECharts(dom, theme$$1, opts);
  26042. chart.id = 'ec_' + idBase++;
  26043. instances[chart.id] = chart;
  26044. setAttribute(dom, DOM_ATTRIBUTE_KEY, chart.id);
  26045. enableConnect(chart);
  26046. return chart;
  26047. }
  26048. /**
  26049. * @return {string|Array.<module:echarts~ECharts>} groupId
  26050. */
  26051. function connect(groupId) {
  26052. // Is array of charts
  26053. if (isArray(groupId)) {
  26054. var charts = groupId;
  26055. groupId = null;
  26056. // If any chart has group
  26057. each(charts, function (chart) {
  26058. if (chart.group != null) {
  26059. groupId = chart.group;
  26060. }
  26061. });
  26062. groupId = groupId || ('g_' + groupIdBase++);
  26063. each(charts, function (chart) {
  26064. chart.group = groupId;
  26065. });
  26066. }
  26067. connectedGroups[groupId] = true;
  26068. return groupId;
  26069. }
  26070. /**
  26071. * @DEPRECATED
  26072. * @return {string} groupId
  26073. */
  26074. function disConnect(groupId) {
  26075. connectedGroups[groupId] = false;
  26076. }
  26077. /**
  26078. * @return {string} groupId
  26079. */
  26080. var disconnect = disConnect;
  26081. /**
  26082. * Dispose a chart instance
  26083. * @param {module:echarts~ECharts|HTMLDomElement|string} chart
  26084. */
  26085. function dispose(chart) {
  26086. if (typeof chart === 'string') {
  26087. chart = instances[chart];
  26088. }
  26089. else if (!(chart instanceof ECharts)) {
  26090. // Try to treat as dom
  26091. chart = getInstanceByDom(chart);
  26092. }
  26093. if ((chart instanceof ECharts) && !chart.isDisposed()) {
  26094. chart.dispose();
  26095. }
  26096. }
  26097. /**
  26098. * @param {HTMLElement} dom
  26099. * @return {echarts~ECharts}
  26100. */
  26101. function getInstanceByDom(dom) {
  26102. return instances[getAttribute(dom, DOM_ATTRIBUTE_KEY)];
  26103. }
  26104. /**
  26105. * @param {string} key
  26106. * @return {echarts~ECharts}
  26107. */
  26108. function getInstanceById(key) {
  26109. return instances[key];
  26110. }
  26111. /**
  26112. * Register theme
  26113. */
  26114. function registerTheme(name, theme$$1) {
  26115. themeStorage[name] = theme$$1;
  26116. }
  26117. /**
  26118. * Register option preprocessor
  26119. * @param {Function} preprocessorFunc
  26120. */
  26121. function registerPreprocessor(preprocessorFunc) {
  26122. optionPreprocessorFuncs.push(preprocessorFunc);
  26123. }
  26124. /**
  26125. * @param {number} [priority=1000]
  26126. * @param {Object|Function} processor
  26127. */
  26128. function registerProcessor(priority, processor) {
  26129. normalizeRegister(dataProcessorFuncs, priority, processor, PRIORITY_PROCESSOR_FILTER);
  26130. }
  26131. /**
  26132. * Register postUpdater
  26133. * @param {Function} postUpdateFunc
  26134. */
  26135. function registerPostUpdate(postUpdateFunc) {
  26136. postUpdateFuncs.push(postUpdateFunc);
  26137. }
  26138. /**
  26139. * Usage:
  26140. * registerAction('someAction', 'someEvent', function () { ... });
  26141. * registerAction('someAction', function () { ... });
  26142. * registerAction(
  26143. * {type: 'someAction', event: 'someEvent', update: 'updateView'},
  26144. * function () { ... }
  26145. * );
  26146. *
  26147. * @param {(string|Object)} actionInfo
  26148. * @param {string} actionInfo.type
  26149. * @param {string} [actionInfo.event]
  26150. * @param {string} [actionInfo.update]
  26151. * @param {string} [eventName]
  26152. * @param {Function} action
  26153. */
  26154. function registerAction(actionInfo, eventName, action) {
  26155. if (typeof eventName === 'function') {
  26156. action = eventName;
  26157. eventName = '';
  26158. }
  26159. var actionType = isObject(actionInfo)
  26160. ? actionInfo.type
  26161. : ([actionInfo, actionInfo = {
  26162. event: eventName
  26163. }][0]);
  26164. // Event name is all lowercase
  26165. actionInfo.event = (actionInfo.event || actionType).toLowerCase();
  26166. eventName = actionInfo.event;
  26167. // Validate action type and event name.
  26168. assert(ACTION_REG.test(actionType) && ACTION_REG.test(eventName));
  26169. if (!actions[actionType]) {
  26170. actions[actionType] = {action: action, actionInfo: actionInfo};
  26171. }
  26172. eventActionMap[eventName] = actionType;
  26173. }
  26174. /**
  26175. * @param {string} type
  26176. * @param {*} CoordinateSystem
  26177. */
  26178. function registerCoordinateSystem(type, CoordinateSystem$$1) {
  26179. CoordinateSystemManager.register(type, CoordinateSystem$$1);
  26180. }
  26181. /**
  26182. * Get dimensions of specified coordinate system.
  26183. * @param {string} type
  26184. * @return {Array.<string|Object>}
  26185. */
  26186. function getCoordinateSystemDimensions(type) {
  26187. var coordSysCreator = CoordinateSystemManager.get(type);
  26188. if (coordSysCreator) {
  26189. return coordSysCreator.getDimensionsInfo
  26190. ? coordSysCreator.getDimensionsInfo()
  26191. : coordSysCreator.dimensions.slice();
  26192. }
  26193. }
  26194. /**
  26195. * Layout is a special stage of visual encoding
  26196. * Most visual encoding like color are common for different chart
  26197. * But each chart has it's own layout algorithm
  26198. *
  26199. * @param {number} [priority=1000]
  26200. * @param {Function} layoutTask
  26201. */
  26202. function registerLayout(priority, layoutTask) {
  26203. normalizeRegister(visualFuncs, priority, layoutTask, PRIORITY_VISUAL_LAYOUT, 'layout');
  26204. }
  26205. /**
  26206. * @param {number} [priority=3000]
  26207. * @param {module:echarts/stream/Task} visualTask
  26208. */
  26209. function registerVisual(priority, visualTask) {
  26210. normalizeRegister(visualFuncs, priority, visualTask, PRIORITY_VISUAL_CHART, 'visual');
  26211. }
  26212. /**
  26213. * @param {Object|Function} fn: {seriesType, createOnAllSeries, performRawSeries, reset}
  26214. */
  26215. function normalizeRegister(targetList, priority, fn, defaultPriority, visualType) {
  26216. if (isFunction(priority) || isObject(priority)) {
  26217. fn = priority;
  26218. priority = defaultPriority;
  26219. }
  26220. if (__DEV__) {
  26221. if (isNaN(priority) || priority == null) {
  26222. throw new Error('Illegal priority');
  26223. }
  26224. // Check duplicate
  26225. each(targetList, function (wrap) {
  26226. assert(wrap.__raw !== fn);
  26227. });
  26228. }
  26229. var stageHandler = Scheduler.wrapStageHandler(fn, visualType);
  26230. stageHandler.__prio = priority;
  26231. stageHandler.__raw = fn;
  26232. targetList.push(stageHandler);
  26233. return stageHandler;
  26234. }
  26235. /**
  26236. * @param {string} name
  26237. */
  26238. function registerLoading(name, loadingFx) {
  26239. loadingEffects[name] = loadingFx;
  26240. }
  26241. /**
  26242. * @param {Object} opts
  26243. * @param {string} [superClass]
  26244. */
  26245. function extendComponentModel(opts/*, superClass*/) {
  26246. // var Clazz = ComponentModel;
  26247. // if (superClass) {
  26248. // var classType = parseClassType(superClass);
  26249. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  26250. // }
  26251. return ComponentModel.extend(opts);
  26252. }
  26253. /**
  26254. * @param {Object} opts
  26255. * @param {string} [superClass]
  26256. */
  26257. function extendComponentView(opts/*, superClass*/) {
  26258. // var Clazz = ComponentView;
  26259. // if (superClass) {
  26260. // var classType = parseClassType(superClass);
  26261. // Clazz = ComponentView.getClass(classType.main, classType.sub, true);
  26262. // }
  26263. return Component$1.extend(opts);
  26264. }
  26265. /**
  26266. * @param {Object} opts
  26267. * @param {string} [superClass]
  26268. */
  26269. function extendSeriesModel(opts/*, superClass*/) {
  26270. // var Clazz = SeriesModel;
  26271. // if (superClass) {
  26272. // superClass = 'series.' + superClass.replace('series.', '');
  26273. // var classType = parseClassType(superClass);
  26274. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  26275. // }
  26276. return SeriesModel.extend(opts);
  26277. }
  26278. /**
  26279. * @param {Object} opts
  26280. * @param {string} [superClass]
  26281. */
  26282. function extendChartView(opts/*, superClass*/) {
  26283. // var Clazz = ChartView;
  26284. // if (superClass) {
  26285. // superClass = superClass.replace('series.', '');
  26286. // var classType = parseClassType(superClass);
  26287. // Clazz = ChartView.getClass(classType.main, true);
  26288. // }
  26289. return Chart.extend(opts);
  26290. }
  26291. /**
  26292. * ZRender need a canvas context to do measureText.
  26293. * But in node environment canvas may be created by node-canvas.
  26294. * So we need to specify how to create a canvas instead of using document.createElement('canvas')
  26295. *
  26296. * Be careful of using it in the browser.
  26297. *
  26298. * @param {Function} creator
  26299. * @example
  26300. * var Canvas = require('canvas');
  26301. * var echarts = require('echarts');
  26302. * echarts.setCanvasCreator(function () {
  26303. * // Small size is enough.
  26304. * return new Canvas(32, 32);
  26305. * });
  26306. */
  26307. function setCanvasCreator(creator) {
  26308. $override('createCanvas', creator);
  26309. }
  26310. /**
  26311. * @param {string} mapName
  26312. * @param {Array.<Object>|Object|string} geoJson
  26313. * @param {Object} [specialAreas]
  26314. *
  26315. * @example GeoJSON
  26316. * $.get('USA.json', function (geoJson) {
  26317. * echarts.registerMap('USA', geoJson);
  26318. * // Or
  26319. * echarts.registerMap('USA', {
  26320. * geoJson: geoJson,
  26321. * specialAreas: {}
  26322. * })
  26323. * });
  26324. *
  26325. * $.get('airport.svg', function (svg) {
  26326. * echarts.registerMap('airport', {
  26327. * svg: svg
  26328. * }
  26329. * });
  26330. *
  26331. * echarts.registerMap('eu', [
  26332. * {svg: eu-topographic.svg},
  26333. * {geoJSON: eu.json}
  26334. * ])
  26335. */
  26336. function registerMap(mapName, geoJson, specialAreas) {
  26337. mapDataStorage.registerMap(mapName, geoJson, specialAreas);
  26338. }
  26339. /**
  26340. * @param {string} mapName
  26341. * @return {Object}
  26342. */
  26343. function getMap(mapName) {
  26344. // For backward compatibility, only return the first one.
  26345. var records = mapDataStorage.retrieveMap(mapName);
  26346. return records && records[0] && {
  26347. geoJson: records[0].geoJSON,
  26348. specialAreas: records[0].specialAreas
  26349. };
  26350. }
  26351. registerVisual(PRIORITY_VISUAL_GLOBAL, seriesColor);
  26352. registerPreprocessor(backwardCompat);
  26353. registerProcessor(PRIORITY_PROCESSOR_DATASTACK, dataStack);
  26354. registerLoading('default', loadingDefault);
  26355. // Default actions
  26356. registerAction({
  26357. type: 'highlight',
  26358. event: 'highlight',
  26359. update: 'highlight'
  26360. }, noop);
  26361. registerAction({
  26362. type: 'downplay',
  26363. event: 'downplay',
  26364. update: 'downplay'
  26365. }, noop);
  26366. // Default theme
  26367. registerTheme('light', lightTheme);
  26368. registerTheme('dark', theme);
  26369. // For backward compatibility, where the namespace `dataTool` will
  26370. // be mounted on `echarts` is the extension `dataTool` is imported.
  26371. var dataTool = {};
  26372. /*
  26373. * Licensed to the Apache Software Foundation (ASF) under one
  26374. * or more contributor license agreements. See the NOTICE file
  26375. * distributed with this work for additional information
  26376. * regarding copyright ownership. The ASF licenses this file
  26377. * to you under the Apache License, Version 2.0 (the
  26378. * "License"); you may not use this file except in compliance
  26379. * with the License. You may obtain a copy of the License at
  26380. *
  26381. * http://www.apache.org/licenses/LICENSE-2.0
  26382. *
  26383. * Unless required by applicable law or agreed to in writing,
  26384. * software distributed under the License is distributed on an
  26385. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26386. * KIND, either express or implied. See the License for the
  26387. * specific language governing permissions and limitations
  26388. * under the License.
  26389. */
  26390. function defaultKeyGetter(item) {
  26391. return item;
  26392. }
  26393. /**
  26394. * @param {Array} oldArr
  26395. * @param {Array} newArr
  26396. * @param {Function} oldKeyGetter
  26397. * @param {Function} newKeyGetter
  26398. * @param {Object} [context] Can be visited by this.context in callback.
  26399. */
  26400. function DataDiffer(oldArr, newArr, oldKeyGetter, newKeyGetter, context) {
  26401. this._old = oldArr;
  26402. this._new = newArr;
  26403. this._oldKeyGetter = oldKeyGetter || defaultKeyGetter;
  26404. this._newKeyGetter = newKeyGetter || defaultKeyGetter;
  26405. this.context = context;
  26406. }
  26407. DataDiffer.prototype = {
  26408. constructor: DataDiffer,
  26409. /**
  26410. * Callback function when add a data
  26411. */
  26412. add: function (func) {
  26413. this._add = func;
  26414. return this;
  26415. },
  26416. /**
  26417. * Callback function when update a data
  26418. */
  26419. update: function (func) {
  26420. this._update = func;
  26421. return this;
  26422. },
  26423. /**
  26424. * Callback function when remove a data
  26425. */
  26426. remove: function (func) {
  26427. this._remove = func;
  26428. return this;
  26429. },
  26430. execute: function () {
  26431. var oldArr = this._old;
  26432. var newArr = this._new;
  26433. var oldDataIndexMap = {};
  26434. var newDataIndexMap = {};
  26435. var oldDataKeyArr = [];
  26436. var newDataKeyArr = [];
  26437. var i;
  26438. initIndexMap(oldArr, oldDataIndexMap, oldDataKeyArr, '_oldKeyGetter', this);
  26439. initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter', this);
  26440. for (i = 0; i < oldArr.length; i++) {
  26441. var key = oldDataKeyArr[i];
  26442. var idx = newDataIndexMap[key];
  26443. // idx can never be empty array here. see 'set null' logic below.
  26444. if (idx != null) {
  26445. // Consider there is duplicate key (for example, use dataItem.name as key).
  26446. // We should make sure every item in newArr and oldArr can be visited.
  26447. var len = idx.length;
  26448. if (len) {
  26449. len === 1 && (newDataIndexMap[key] = null);
  26450. idx = idx.shift();
  26451. }
  26452. else {
  26453. newDataIndexMap[key] = null;
  26454. }
  26455. this._update && this._update(idx, i);
  26456. }
  26457. else {
  26458. this._remove && this._remove(i);
  26459. }
  26460. }
  26461. for (var i = 0; i < newDataKeyArr.length; i++) {
  26462. var key = newDataKeyArr[i];
  26463. if (newDataIndexMap.hasOwnProperty(key)) {
  26464. var idx = newDataIndexMap[key];
  26465. if (idx == null) {
  26466. continue;
  26467. }
  26468. // idx can never be empty array here. see 'set null' logic above.
  26469. if (!idx.length) {
  26470. this._add && this._add(idx);
  26471. }
  26472. else {
  26473. for (var j = 0, len = idx.length; j < len; j++) {
  26474. this._add && this._add(idx[j]);
  26475. }
  26476. }
  26477. }
  26478. }
  26479. }
  26480. };
  26481. function initIndexMap(arr, map, keyArr, keyGetterName, dataDiffer) {
  26482. for (var i = 0; i < arr.length; i++) {
  26483. // Add prefix to avoid conflict with Object.prototype.
  26484. var key = '_ec_' + dataDiffer[keyGetterName](arr[i], i);
  26485. var existence = map[key];
  26486. if (existence == null) {
  26487. keyArr.push(key);
  26488. map[key] = i;
  26489. }
  26490. else {
  26491. if (!existence.length) {
  26492. map[key] = existence = [existence];
  26493. }
  26494. existence.push(i);
  26495. }
  26496. }
  26497. }
  26498. /*
  26499. * Licensed to the Apache Software Foundation (ASF) under one
  26500. * or more contributor license agreements. See the NOTICE file
  26501. * distributed with this work for additional information
  26502. * regarding copyright ownership. The ASF licenses this file
  26503. * to you under the Apache License, Version 2.0 (the
  26504. * "License"); you may not use this file except in compliance
  26505. * with the License. You may obtain a copy of the License at
  26506. *
  26507. * http://www.apache.org/licenses/LICENSE-2.0
  26508. *
  26509. * Unless required by applicable law or agreed to in writing,
  26510. * software distributed under the License is distributed on an
  26511. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26512. * KIND, either express or implied. See the License for the
  26513. * specific language governing permissions and limitations
  26514. * under the License.
  26515. */
  26516. var OTHER_DIMENSIONS = createHashMap([
  26517. 'tooltip', 'label', 'itemName', 'itemId', 'seriesName'
  26518. ]);
  26519. function summarizeDimensions(data) {
  26520. var summary = {};
  26521. var encode = summary.encode = {};
  26522. var notExtraCoordDimMap = createHashMap();
  26523. var defaultedLabel = [];
  26524. var defaultedTooltip = [];
  26525. // See the comment of `List.js#userOutput`.
  26526. var userOutput = summary.userOutput = {
  26527. dimensionNames: data.dimensions.slice(),
  26528. encode: {}
  26529. };
  26530. each$1(data.dimensions, function (dimName) {
  26531. var dimItem = data.getDimensionInfo(dimName);
  26532. var coordDim = dimItem.coordDim;
  26533. if (coordDim) {
  26534. if (__DEV__) {
  26535. assert$1(OTHER_DIMENSIONS.get(coordDim) == null);
  26536. }
  26537. var coordDimIndex = dimItem.coordDimIndex;
  26538. getOrCreateEncodeArr(encode, coordDim)[coordDimIndex] = dimName;
  26539. if (!dimItem.isExtraCoord) {
  26540. notExtraCoordDimMap.set(coordDim, 1);
  26541. // Use the last coord dim (and label friendly) as default label,
  26542. // because when dataset is used, it is hard to guess which dimension
  26543. // can be value dimension. If both show x, y on label is not look good,
  26544. // and conventionally y axis is focused more.
  26545. if (mayLabelDimType(dimItem.type)) {
  26546. defaultedLabel[0] = dimName;
  26547. }
  26548. // User output encode do not contain generated coords.
  26549. // And it only has index. User can use index to retrieve value from the raw item array.
  26550. getOrCreateEncodeArr(userOutput.encode, coordDim)[coordDimIndex] = dimItem.index;
  26551. }
  26552. if (dimItem.defaultTooltip) {
  26553. defaultedTooltip.push(dimName);
  26554. }
  26555. }
  26556. OTHER_DIMENSIONS.each(function (v, otherDim) {
  26557. var encodeArr = getOrCreateEncodeArr(encode, otherDim);
  26558. var dimIndex = dimItem.otherDims[otherDim];
  26559. if (dimIndex != null && dimIndex !== false) {
  26560. encodeArr[dimIndex] = dimItem.name;
  26561. }
  26562. });
  26563. });
  26564. var dataDimsOnCoord = [];
  26565. var encodeFirstDimNotExtra = {};
  26566. notExtraCoordDimMap.each(function (v, coordDim) {
  26567. var dimArr = encode[coordDim];
  26568. // ??? FIXME extra coord should not be set in dataDimsOnCoord.
  26569. // But should fix the case that radar axes: simplify the logic
  26570. // of `completeDimension`, remove `extraPrefix`.
  26571. encodeFirstDimNotExtra[coordDim] = dimArr[0];
  26572. // Not necessary to remove duplicate, because a data
  26573. // dim canot on more than one coordDim.
  26574. dataDimsOnCoord = dataDimsOnCoord.concat(dimArr);
  26575. });
  26576. summary.dataDimsOnCoord = dataDimsOnCoord;
  26577. summary.encodeFirstDimNotExtra = encodeFirstDimNotExtra;
  26578. var encodeLabel = encode.label;
  26579. // FIXME `encode.label` is not recommanded, because formatter can not be set
  26580. // in this way. Use label.formatter instead. May be remove this approach someday.
  26581. if (encodeLabel && encodeLabel.length) {
  26582. defaultedLabel = encodeLabel.slice();
  26583. }
  26584. var encodeTooltip = encode.tooltip;
  26585. if (encodeTooltip && encodeTooltip.length) {
  26586. defaultedTooltip = encodeTooltip.slice();
  26587. }
  26588. else if (!defaultedTooltip.length) {
  26589. defaultedTooltip = defaultedLabel.slice();
  26590. }
  26591. encode.defaultedLabel = defaultedLabel;
  26592. encode.defaultedTooltip = defaultedTooltip;
  26593. return summary;
  26594. }
  26595. function getOrCreateEncodeArr(encode, dim) {
  26596. if (!encode.hasOwnProperty(dim)) {
  26597. encode[dim] = [];
  26598. }
  26599. return encode[dim];
  26600. }
  26601. function getDimensionTypeByAxis(axisType) {
  26602. return axisType === 'category'
  26603. ? 'ordinal'
  26604. : axisType === 'time'
  26605. ? 'time'
  26606. : 'float';
  26607. }
  26608. function mayLabelDimType(dimType) {
  26609. // In most cases, ordinal and time do not suitable for label.
  26610. // Ordinal info can be displayed on axis. Time is too long.
  26611. return !(dimType === 'ordinal' || dimType === 'time');
  26612. }
  26613. // function findTheLastDimMayLabel(data) {
  26614. // // Get last value dim
  26615. // var dimensions = data.dimensions.slice();
  26616. // var valueType;
  26617. // var valueDim;
  26618. // while (dimensions.length && (
  26619. // valueDim = dimensions.pop(),
  26620. // valueType = data.getDimensionInfo(valueDim).type,
  26621. // valueType === 'ordinal' || valueType === 'time'
  26622. // )) {} // jshint ignore:line
  26623. // return valueDim;
  26624. // }
  26625. /*
  26626. * Licensed to the Apache Software Foundation (ASF) under one
  26627. * or more contributor license agreements. See the NOTICE file
  26628. * distributed with this work for additional information
  26629. * regarding copyright ownership. The ASF licenses this file
  26630. * to you under the Apache License, Version 2.0 (the
  26631. * "License"); you may not use this file except in compliance
  26632. * with the License. You may obtain a copy of the License at
  26633. *
  26634. * http://www.apache.org/licenses/LICENSE-2.0
  26635. *
  26636. * Unless required by applicable law or agreed to in writing,
  26637. * software distributed under the License is distributed on an
  26638. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26639. * KIND, either express or implied. See the License for the
  26640. * specific language governing permissions and limitations
  26641. * under the License.
  26642. */
  26643. /**
  26644. * @class
  26645. * @param {Object|DataDimensionInfo} [opt] All of the fields will be shallow copied.
  26646. */
  26647. function DataDimensionInfo(opt) {
  26648. if (opt != null) {
  26649. extend(this, opt);
  26650. }
  26651. /**
  26652. * Dimension name.
  26653. * Mandatory.
  26654. * @type {string}
  26655. */
  26656. // this.name;
  26657. /**
  26658. * The origin name in dimsDef, see source helper.
  26659. * If displayName given, the tooltip will displayed vertically.
  26660. * Optional.
  26661. * @type {string}
  26662. */
  26663. // this.displayName;
  26664. /**
  26665. * Which coordSys dimension this dimension mapped to.
  26666. * A `coordDim` can be a "coordSysDim" that the coordSys required
  26667. * (for example, an item in `coordSysDims` of `model/referHelper#CoordSysInfo`),
  26668. * or an generated "extra coord name" if does not mapped to any "coordSysDim"
  26669. * (That is determined by whether `isExtraCoord` is `true`).
  26670. * Mandatory.
  26671. * @type {string}
  26672. */
  26673. // this.coordDim;
  26674. /**
  26675. * The index of this dimension in `series.encode[coordDim]`.
  26676. * Mandatory.
  26677. * @type {number}
  26678. */
  26679. // this.coordDimIndex;
  26680. /**
  26681. * Dimension type. The enumerable values are the key of
  26682. * `dataCtors` of `data/List`.
  26683. * Optional.
  26684. * @type {string}
  26685. */
  26686. // this.type;
  26687. /**
  26688. * This index of this dimension info in `data/List#_dimensionInfos`.
  26689. * Mandatory after added to `data/List`.
  26690. * @type {number}
  26691. */
  26692. // this.index;
  26693. /**
  26694. * The format of `otherDims` is:
  26695. * ```js
  26696. * {
  26697. * tooltip: number optional,
  26698. * label: number optional,
  26699. * itemName: number optional,
  26700. * seriesName: number optional,
  26701. * }
  26702. * ```
  26703. *
  26704. * A `series.encode` can specified these fields:
  26705. * ```js
  26706. * encode: {
  26707. * // "3, 1, 5" is the index of data dimension.
  26708. * tooltip: [3, 1, 5],
  26709. * label: [0, 3],
  26710. * ...
  26711. * }
  26712. * ```
  26713. * `otherDims` is the parse result of the `series.encode` above, like:
  26714. * ```js
  26715. * // Suppose the index of this data dimension is `3`.
  26716. * this.otherDims = {
  26717. * // `3` is at the index `0` of the `encode.tooltip`
  26718. * tooltip: 0,
  26719. * // `3` is at the index `1` of the `encode.tooltip`
  26720. * label: 1
  26721. * };
  26722. * ```
  26723. *
  26724. * This prop should never be `null`/`undefined` after initialized.
  26725. * @type {Object}
  26726. */
  26727. this.otherDims = {};
  26728. /**
  26729. * Be `true` if this dimension is not mapped to any "coordSysDim" that the
  26730. * "coordSys" required.
  26731. * Mandatory.
  26732. * @type {boolean}
  26733. */
  26734. // this.isExtraCoord;
  26735. /**
  26736. * @type {module:data/OrdinalMeta}
  26737. */
  26738. // this.ordinalMeta;
  26739. /**
  26740. * Whether to create inverted indices.
  26741. * @type {boolean}
  26742. */
  26743. // this.createInvertedIndices;
  26744. }
  26745. /*
  26746. * Licensed to the Apache Software Foundation (ASF) under one
  26747. * or more contributor license agreements. See the NOTICE file
  26748. * distributed with this work for additional information
  26749. * regarding copyright ownership. The ASF licenses this file
  26750. * to you under the Apache License, Version 2.0 (the
  26751. * "License"); you may not use this file except in compliance
  26752. * with the License. You may obtain a copy of the License at
  26753. *
  26754. * http://www.apache.org/licenses/LICENSE-2.0
  26755. *
  26756. * Unless required by applicable law or agreed to in writing,
  26757. * software distributed under the License is distributed on an
  26758. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26759. * KIND, either express or implied. See the License for the
  26760. * specific language governing permissions and limitations
  26761. * under the License.
  26762. */
  26763. /* global Float64Array, Int32Array, Uint32Array, Uint16Array */
  26764. /**
  26765. * List for data storage
  26766. * @module echarts/data/List
  26767. */
  26768. var isObject$4 = isObject$1;
  26769. var UNDEFINED = 'undefined';
  26770. var INDEX_NOT_FOUND = -1;
  26771. // Use prefix to avoid index to be the same as otherIdList[idx],
  26772. // which will cause weird udpate animation.
  26773. var ID_PREFIX = 'e\0\0';
  26774. var dataCtors = {
  26775. 'float': typeof Float64Array === UNDEFINED
  26776. ? Array : Float64Array,
  26777. 'int': typeof Int32Array === UNDEFINED
  26778. ? Array : Int32Array,
  26779. // Ordinal data type can be string or int
  26780. 'ordinal': Array,
  26781. 'number': Array,
  26782. 'time': Array
  26783. };
  26784. // Caution: MUST not use `new CtorUint32Array(arr, 0, len)`, because the Ctor of array is
  26785. // different from the Ctor of typed array.
  26786. var CtorUint32Array = typeof Uint32Array === UNDEFINED ? Array : Uint32Array;
  26787. var CtorInt32Array = typeof Int32Array === UNDEFINED ? Array : Int32Array;
  26788. var CtorUint16Array = typeof Uint16Array === UNDEFINED ? Array : Uint16Array;
  26789. function getIndicesCtor(list) {
  26790. // The possible max value in this._indicies is always this._rawCount despite of filtering.
  26791. return list._rawCount > 65535 ? CtorUint32Array : CtorUint16Array;
  26792. }
  26793. function cloneChunk(originalChunk) {
  26794. var Ctor = originalChunk.constructor;
  26795. // Only shallow clone is enough when Array.
  26796. return Ctor === Array ? originalChunk.slice() : new Ctor(originalChunk);
  26797. }
  26798. var TRANSFERABLE_PROPERTIES = [
  26799. 'hasItemOption', '_nameList', '_idList', '_invertedIndicesMap',
  26800. '_rawData', '_chunkSize', '_chunkCount', '_dimValueGetter',
  26801. '_count', '_rawCount', '_nameDimIdx', '_idDimIdx'
  26802. ];
  26803. var CLONE_PROPERTIES = [
  26804. '_extent', '_approximateExtent', '_rawExtent'
  26805. ];
  26806. function transferProperties(target, source) {
  26807. each$1(TRANSFERABLE_PROPERTIES.concat(source.__wrappedMethods || []), function (propName) {
  26808. if (source.hasOwnProperty(propName)) {
  26809. target[propName] = source[propName];
  26810. }
  26811. });
  26812. target.__wrappedMethods = source.__wrappedMethods;
  26813. each$1(CLONE_PROPERTIES, function (propName) {
  26814. target[propName] = clone(source[propName]);
  26815. });
  26816. target._calculationInfo = extend(source._calculationInfo);
  26817. }
  26818. /**
  26819. * @constructor
  26820. * @alias module:echarts/data/List
  26821. *
  26822. * @param {Array.<string|Object|module:data/DataDimensionInfo>} dimensions
  26823. * For example, ['someDimName', {name: 'someDimName', type: 'someDimType'}, ...].
  26824. * Dimensions should be concrete names like x, y, z, lng, lat, angle, radius
  26825. * @param {module:echarts/model/Model} hostModel
  26826. */
  26827. var List = function (dimensions, hostModel) {
  26828. dimensions = dimensions || ['x', 'y'];
  26829. var dimensionInfos = {};
  26830. var dimensionNames = [];
  26831. var invertedIndicesMap = {};
  26832. for (var i = 0; i < dimensions.length; i++) {
  26833. // Use the original dimensions[i], where other flag props may exists.
  26834. var dimensionInfo = dimensions[i];
  26835. if (isString(dimensionInfo)) {
  26836. dimensionInfo = new DataDimensionInfo({name: dimensionInfo});
  26837. }
  26838. else if (!(dimensionInfo instanceof DataDimensionInfo)) {
  26839. dimensionInfo = new DataDimensionInfo(dimensionInfo);
  26840. }
  26841. var dimensionName = dimensionInfo.name;
  26842. dimensionInfo.type = dimensionInfo.type || 'float';
  26843. if (!dimensionInfo.coordDim) {
  26844. dimensionInfo.coordDim = dimensionName;
  26845. dimensionInfo.coordDimIndex = 0;
  26846. }
  26847. dimensionInfo.otherDims = dimensionInfo.otherDims || {};
  26848. dimensionNames.push(dimensionName);
  26849. dimensionInfos[dimensionName] = dimensionInfo;
  26850. dimensionInfo.index = i;
  26851. if (dimensionInfo.createInvertedIndices) {
  26852. invertedIndicesMap[dimensionName] = [];
  26853. }
  26854. }
  26855. /**
  26856. * @readOnly
  26857. * @type {Array.<string>}
  26858. */
  26859. this.dimensions = dimensionNames;
  26860. /**
  26861. * Infomation of each data dimension, like data type.
  26862. * @type {Object}
  26863. */
  26864. this._dimensionInfos = dimensionInfos;
  26865. /**
  26866. * @type {module:echarts/model/Model}
  26867. */
  26868. this.hostModel = hostModel;
  26869. /**
  26870. * @type {module:echarts/model/Model}
  26871. */
  26872. this.dataType;
  26873. /**
  26874. * Indices stores the indices of data subset after filtered.
  26875. * This data subset will be used in chart.
  26876. * @type {Array.<number>}
  26877. * @readOnly
  26878. */
  26879. this._indices = null;
  26880. this._count = 0;
  26881. this._rawCount = 0;
  26882. /**
  26883. * Data storage
  26884. * @type {Object.<key, Array.<TypedArray|Array>>}
  26885. * @private
  26886. */
  26887. this._storage = {};
  26888. /**
  26889. * @type {Array.<string>}
  26890. */
  26891. this._nameList = [];
  26892. /**
  26893. * @type {Array.<string>}
  26894. */
  26895. this._idList = [];
  26896. /**
  26897. * Models of data option is stored sparse for optimizing memory cost
  26898. * @type {Array.<module:echarts/model/Model>}
  26899. * @private
  26900. */
  26901. this._optionModels = [];
  26902. /**
  26903. * Global visual properties after visual coding
  26904. * @type {Object}
  26905. * @private
  26906. */
  26907. this._visual = {};
  26908. /**
  26909. * Globel layout properties.
  26910. * @type {Object}
  26911. * @private
  26912. */
  26913. this._layout = {};
  26914. /**
  26915. * Item visual properties after visual coding
  26916. * @type {Array.<Object>}
  26917. * @private
  26918. */
  26919. this._itemVisuals = [];
  26920. /**
  26921. * Key: visual type, Value: boolean
  26922. * @type {Object}
  26923. * @readOnly
  26924. */
  26925. this.hasItemVisual = {};
  26926. /**
  26927. * Item layout properties after layout
  26928. * @type {Array.<Object>}
  26929. * @private
  26930. */
  26931. this._itemLayouts = [];
  26932. /**
  26933. * Graphic elemnents
  26934. * @type {Array.<module:zrender/Element>}
  26935. * @private
  26936. */
  26937. this._graphicEls = [];
  26938. /**
  26939. * Max size of each chunk.
  26940. * @type {number}
  26941. * @private
  26942. */
  26943. this._chunkSize = 1e5;
  26944. /**
  26945. * @type {number}
  26946. * @private
  26947. */
  26948. this._chunkCount = 0;
  26949. /**
  26950. * @type {Array.<Array|Object>}
  26951. * @private
  26952. */
  26953. this._rawData;
  26954. /**
  26955. * Raw extent will not be cloned, but only transfered.
  26956. * It will not be calculated util needed.
  26957. * key: dim,
  26958. * value: {end: number, extent: Array.<number>}
  26959. * @type {Object}
  26960. * @private
  26961. */
  26962. this._rawExtent = {};
  26963. /**
  26964. * @type {Object}
  26965. * @private
  26966. */
  26967. this._extent = {};
  26968. /**
  26969. * key: dim
  26970. * value: extent
  26971. * @type {Object}
  26972. * @private
  26973. */
  26974. this._approximateExtent = {};
  26975. /**
  26976. * Cache summary info for fast visit. See "dimensionHelper".
  26977. * @type {Object}
  26978. * @private
  26979. */
  26980. this._dimensionsSummary = summarizeDimensions(this);
  26981. /**
  26982. * @type {Object.<Array|TypedArray>}
  26983. * @private
  26984. */
  26985. this._invertedIndicesMap = invertedIndicesMap;
  26986. /**
  26987. * @type {Object}
  26988. * @private
  26989. */
  26990. this._calculationInfo = {};
  26991. /**
  26992. * User output info of this data.
  26993. * DO NOT use it in other places!
  26994. *
  26995. * When preparing user params for user callbacks, we have
  26996. * to clone these inner data structures to prevent users
  26997. * from modifying them to effect built-in logic. And for
  26998. * performance consideration we make this `userOutput` to
  26999. * avoid clone them too many times.
  27000. *
  27001. * @type {Object}
  27002. * @readOnly
  27003. */
  27004. this.userOutput = this._dimensionsSummary.userOutput;
  27005. };
  27006. var listProto = List.prototype;
  27007. listProto.type = 'list';
  27008. /**
  27009. * If each data item has it's own option
  27010. * @type {boolean}
  27011. */
  27012. listProto.hasItemOption = true;
  27013. /**
  27014. * The meanings of the input parameter `dim`:
  27015. *
  27016. * + If dim is a number (e.g., `1`), it means the index of the dimension.
  27017. * For example, `getDimension(0)` will return 'x' or 'lng' or 'radius'.
  27018. * + If dim is a number-like string (e.g., `"1"`):
  27019. * + If there is the same concrete dim name defined in `this.dimensions`, it means that concrete name.
  27020. * + If not, it will be converted to a number, which means the index of the dimension.
  27021. * (why? because of the backward compatbility. We have been tolerating number-like string in
  27022. * dimension setting, although now it seems that it is not a good idea.)
  27023. * For example, `visualMap[i].dimension: "1"` is the same meaning as `visualMap[i].dimension: 1`,
  27024. * if no dimension name is defined as `"1"`.
  27025. * + If dim is a not-number-like string, it means the concrete dim name.
  27026. * For example, it can be be default name `"x"`, `"y"`, `"z"`, `"lng"`, `"lat"`, `"angle"`, `"radius"`,
  27027. * or customized in `dimensions` property of option like `"age"`.
  27028. *
  27029. * Get dimension name
  27030. * @param {string|number} dim See above.
  27031. * @return {string} Concrete dim name.
  27032. */
  27033. listProto.getDimension = function (dim) {
  27034. if (typeof dim === 'number'
  27035. // If being a number-like string but not being defined a dimension name.
  27036. || (!isNaN(dim) && !this._dimensionInfos.hasOwnProperty(dim))
  27037. ) {
  27038. dim = this.dimensions[dim];
  27039. }
  27040. return dim;
  27041. };
  27042. /**
  27043. * Get type and calculation info of particular dimension
  27044. * @param {string|number} dim
  27045. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  27046. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  27047. */
  27048. listProto.getDimensionInfo = function (dim) {
  27049. // Do not clone, because there may be categories in dimInfo.
  27050. return this._dimensionInfos[this.getDimension(dim)];
  27051. };
  27052. /**
  27053. * @return {Array.<string>} concrete dimension name list on coord.
  27054. */
  27055. listProto.getDimensionsOnCoord = function () {
  27056. return this._dimensionsSummary.dataDimsOnCoord.slice();
  27057. };
  27058. /**
  27059. * @param {string} coordDim
  27060. * @param {number} [idx] A coordDim may map to more than one data dim.
  27061. * If idx is `true`, return a array of all mapped dims.
  27062. * If idx is not specified, return the first dim not extra.
  27063. * @return {string|Array.<string>} concrete data dim.
  27064. * If idx is number, and not found, return null/undefined.
  27065. * If idx is `true`, and not found, return empty array (always return array).
  27066. */
  27067. listProto.mapDimension = function (coordDim, idx) {
  27068. var dimensionsSummary = this._dimensionsSummary;
  27069. if (idx == null) {
  27070. return dimensionsSummary.encodeFirstDimNotExtra[coordDim];
  27071. }
  27072. var dims = dimensionsSummary.encode[coordDim];
  27073. return idx === true
  27074. // always return array if idx is `true`
  27075. ? (dims || []).slice()
  27076. : (dims && dims[idx]);
  27077. };
  27078. /**
  27079. * Initialize from data
  27080. * @param {Array.<Object|number|Array>} data source or data or data provider.
  27081. * @param {Array.<string>} [nameLIst] The name of a datum is used on data diff and
  27082. * defualt label/tooltip.
  27083. * A name can be specified in encode.itemName,
  27084. * or dataItem.name (only for series option data),
  27085. * or provided in nameList from outside.
  27086. * @param {Function} [dimValueGetter] (dataItem, dimName, dataIndex, dimIndex) => number
  27087. */
  27088. listProto.initData = function (data, nameList, dimValueGetter) {
  27089. var notProvider = Source.isInstance(data) || isArrayLike(data);
  27090. if (notProvider) {
  27091. data = new DefaultDataProvider(data, this.dimensions.length);
  27092. }
  27093. if (__DEV__) {
  27094. if (!notProvider && (typeof data.getItem !== 'function' || typeof data.count !== 'function')) {
  27095. throw new Error('Inavlid data provider.');
  27096. }
  27097. }
  27098. this._rawData = data;
  27099. // Clear
  27100. this._storage = {};
  27101. this._indices = null;
  27102. this._nameList = nameList || [];
  27103. this._idList = [];
  27104. this._nameRepeatCount = {};
  27105. if (!dimValueGetter) {
  27106. this.hasItemOption = false;
  27107. }
  27108. /**
  27109. * @readOnly
  27110. */
  27111. this.defaultDimValueGetter = defaultDimValueGetters[
  27112. this._rawData.getSource().sourceFormat
  27113. ];
  27114. // Default dim value getter
  27115. this._dimValueGetter = dimValueGetter = dimValueGetter
  27116. || this.defaultDimValueGetter;
  27117. this._dimValueGetterArrayRows = defaultDimValueGetters.arrayRows;
  27118. // Reset raw extent.
  27119. this._rawExtent = {};
  27120. this._initDataFromProvider(0, data.count());
  27121. // If data has no item option.
  27122. if (data.pure) {
  27123. this.hasItemOption = false;
  27124. }
  27125. };
  27126. listProto.getProvider = function () {
  27127. return this._rawData;
  27128. };
  27129. /**
  27130. * Caution: Can be only called on raw data (before `this._indices` created).
  27131. */
  27132. listProto.appendData = function (data) {
  27133. if (__DEV__) {
  27134. assert$1(!this._indices, 'appendData can only be called on raw data.');
  27135. }
  27136. var rawData = this._rawData;
  27137. var start = this.count();
  27138. rawData.appendData(data);
  27139. var end = rawData.count();
  27140. if (!rawData.persistent) {
  27141. end += start;
  27142. }
  27143. this._initDataFromProvider(start, end);
  27144. };
  27145. /**
  27146. * Caution: Can be only called on raw data (before `this._indices` created).
  27147. * This method does not modify `rawData` (`dataProvider`), but only
  27148. * add values to storage.
  27149. *
  27150. * The final count will be increased by `Math.max(values.length, names.length)`.
  27151. *
  27152. * @param {Array.<Array.<*>>} values That is the SourceType: 'arrayRows', like
  27153. * [
  27154. * [12, 33, 44],
  27155. * [NaN, 43, 1],
  27156. * ['-', 'asdf', 0]
  27157. * ]
  27158. * Each item is exaclty cooresponding to a dimension.
  27159. * @param {Array.<string>} [names]
  27160. */
  27161. listProto.appendValues = function (values, names) {
  27162. var chunkSize = this._chunkSize;
  27163. var storage = this._storage;
  27164. var dimensions = this.dimensions;
  27165. var dimLen = dimensions.length;
  27166. var rawExtent = this._rawExtent;
  27167. var start = this.count();
  27168. var end = start + Math.max(values.length, names ? names.length : 0);
  27169. var originalChunkCount = this._chunkCount;
  27170. for (var i = 0; i < dimLen; i++) {
  27171. var dim = dimensions[i];
  27172. if (!rawExtent[dim]) {
  27173. rawExtent[dim] = getInitialExtent();
  27174. }
  27175. if (!storage[dim]) {
  27176. storage[dim] = [];
  27177. }
  27178. prepareChunks(storage, this._dimensionInfos[dim], chunkSize, originalChunkCount, end);
  27179. this._chunkCount = storage[dim].length;
  27180. }
  27181. var emptyDataItem = new Array(dimLen);
  27182. for (var idx = start; idx < end; idx++) {
  27183. var sourceIdx = idx - start;
  27184. var chunkIndex = Math.floor(idx / chunkSize);
  27185. var chunkOffset = idx % chunkSize;
  27186. // Store the data by dimensions
  27187. for (var k = 0; k < dimLen; k++) {
  27188. var dim = dimensions[k];
  27189. var val = this._dimValueGetterArrayRows(
  27190. values[sourceIdx] || emptyDataItem, dim, sourceIdx, k
  27191. );
  27192. storage[dim][chunkIndex][chunkOffset] = val;
  27193. var dimRawExtent = rawExtent[dim];
  27194. val < dimRawExtent[0] && (dimRawExtent[0] = val);
  27195. val > dimRawExtent[1] && (dimRawExtent[1] = val);
  27196. }
  27197. if (names) {
  27198. this._nameList[idx] = names[sourceIdx];
  27199. }
  27200. }
  27201. this._rawCount = this._count = end;
  27202. // Reset data extent
  27203. this._extent = {};
  27204. prepareInvertedIndex(this);
  27205. };
  27206. listProto._initDataFromProvider = function (start, end) {
  27207. // Optimize.
  27208. if (start >= end) {
  27209. return;
  27210. }
  27211. var chunkSize = this._chunkSize;
  27212. var rawData = this._rawData;
  27213. var storage = this._storage;
  27214. var dimensions = this.dimensions;
  27215. var dimLen = dimensions.length;
  27216. var dimensionInfoMap = this._dimensionInfos;
  27217. var nameList = this._nameList;
  27218. var idList = this._idList;
  27219. var rawExtent = this._rawExtent;
  27220. var nameRepeatCount = this._nameRepeatCount = {};
  27221. var nameDimIdx;
  27222. var originalChunkCount = this._chunkCount;
  27223. for (var i = 0; i < dimLen; i++) {
  27224. var dim = dimensions[i];
  27225. if (!rawExtent[dim]) {
  27226. rawExtent[dim] = getInitialExtent();
  27227. }
  27228. var dimInfo = dimensionInfoMap[dim];
  27229. if (dimInfo.otherDims.itemName === 0) {
  27230. nameDimIdx = this._nameDimIdx = i;
  27231. }
  27232. if (dimInfo.otherDims.itemId === 0) {
  27233. this._idDimIdx = i;
  27234. }
  27235. if (!storage[dim]) {
  27236. storage[dim] = [];
  27237. }
  27238. prepareChunks(storage, dimInfo, chunkSize, originalChunkCount, end);
  27239. this._chunkCount = storage[dim].length;
  27240. }
  27241. var dataItem = new Array(dimLen);
  27242. for (var idx = start; idx < end; idx++) {
  27243. // NOTICE: Try not to write things into dataItem
  27244. dataItem = rawData.getItem(idx, dataItem);
  27245. // Each data item is value
  27246. // [1, 2]
  27247. // 2
  27248. // Bar chart, line chart which uses category axis
  27249. // only gives the 'y' value. 'x' value is the indices of category
  27250. // Use a tempValue to normalize the value to be a (x, y) value
  27251. var chunkIndex = Math.floor(idx / chunkSize);
  27252. var chunkOffset = idx % chunkSize;
  27253. // Store the data by dimensions
  27254. for (var k = 0; k < dimLen; k++) {
  27255. var dim = dimensions[k];
  27256. var dimStorage = storage[dim][chunkIndex];
  27257. // PENDING NULL is empty or zero
  27258. var val = this._dimValueGetter(dataItem, dim, idx, k);
  27259. dimStorage[chunkOffset] = val;
  27260. var dimRawExtent = rawExtent[dim];
  27261. val < dimRawExtent[0] && (dimRawExtent[0] = val);
  27262. val > dimRawExtent[1] && (dimRawExtent[1] = val);
  27263. }
  27264. // ??? FIXME not check by pure but sourceFormat?
  27265. // TODO refactor these logic.
  27266. if (!rawData.pure) {
  27267. var name = nameList[idx];
  27268. if (dataItem && name == null) {
  27269. // If dataItem is {name: ...}, it has highest priority.
  27270. // That is appropriate for many common cases.
  27271. if (dataItem.name != null) {
  27272. // There is no other place to persistent dataItem.name,
  27273. // so save it to nameList.
  27274. nameList[idx] = name = dataItem.name;
  27275. }
  27276. else if (nameDimIdx != null) {
  27277. var nameDim = dimensions[nameDimIdx];
  27278. var nameDimChunk = storage[nameDim][chunkIndex];
  27279. if (nameDimChunk) {
  27280. name = nameDimChunk[chunkOffset];
  27281. var ordinalMeta = dimensionInfoMap[nameDim].ordinalMeta;
  27282. if (ordinalMeta && ordinalMeta.categories.length) {
  27283. name = ordinalMeta.categories[name];
  27284. }
  27285. }
  27286. }
  27287. }
  27288. // Try using the id in option
  27289. // id or name is used on dynamical data, mapping old and new items.
  27290. var id = dataItem == null ? null : dataItem.id;
  27291. if (id == null && name != null) {
  27292. // Use name as id and add counter to avoid same name
  27293. nameRepeatCount[name] = nameRepeatCount[name] || 0;
  27294. id = name;
  27295. if (nameRepeatCount[name] > 0) {
  27296. id += '__ec__' + nameRepeatCount[name];
  27297. }
  27298. nameRepeatCount[name]++;
  27299. }
  27300. id != null && (idList[idx] = id);
  27301. }
  27302. }
  27303. if (!rawData.persistent && rawData.clean) {
  27304. // Clean unused data if data source is typed array.
  27305. rawData.clean();
  27306. }
  27307. this._rawCount = this._count = end;
  27308. // Reset data extent
  27309. this._extent = {};
  27310. prepareInvertedIndex(this);
  27311. };
  27312. function prepareChunks(storage, dimInfo, chunkSize, chunkCount, end) {
  27313. var DataCtor = dataCtors[dimInfo.type];
  27314. var lastChunkIndex = chunkCount - 1;
  27315. var dim = dimInfo.name;
  27316. var resizeChunkArray = storage[dim][lastChunkIndex];
  27317. if (resizeChunkArray && resizeChunkArray.length < chunkSize) {
  27318. var newStore = new DataCtor(Math.min(end - lastChunkIndex * chunkSize, chunkSize));
  27319. // The cost of the copy is probably inconsiderable
  27320. // within the initial chunkSize.
  27321. for (var j = 0; j < resizeChunkArray.length; j++) {
  27322. newStore[j] = resizeChunkArray[j];
  27323. }
  27324. storage[dim][lastChunkIndex] = newStore;
  27325. }
  27326. // Create new chunks.
  27327. for (var k = chunkCount * chunkSize; k < end; k += chunkSize) {
  27328. storage[dim].push(new DataCtor(Math.min(end - k, chunkSize)));
  27329. }
  27330. }
  27331. function prepareInvertedIndex(list) {
  27332. var invertedIndicesMap = list._invertedIndicesMap;
  27333. each$1(invertedIndicesMap, function (invertedIndices, dim) {
  27334. var dimInfo = list._dimensionInfos[dim];
  27335. // Currently, only dimensions that has ordinalMeta can create inverted indices.
  27336. var ordinalMeta = dimInfo.ordinalMeta;
  27337. if (ordinalMeta) {
  27338. invertedIndices = invertedIndicesMap[dim] = new CtorInt32Array(
  27339. ordinalMeta.categories.length
  27340. );
  27341. // The default value of TypedArray is 0. To avoid miss
  27342. // mapping to 0, we should set it as INDEX_NOT_FOUND.
  27343. for (var i = 0; i < invertedIndices.length; i++) {
  27344. invertedIndices[i] = INDEX_NOT_FOUND;
  27345. }
  27346. for (var i = 0; i < list._count; i++) {
  27347. // Only support the case that all values are distinct.
  27348. invertedIndices[list.get(dim, i)] = i;
  27349. }
  27350. }
  27351. });
  27352. }
  27353. function getRawValueFromStore(list, dimIndex, rawIndex) {
  27354. var val;
  27355. if (dimIndex != null) {
  27356. var chunkSize = list._chunkSize;
  27357. var chunkIndex = Math.floor(rawIndex / chunkSize);
  27358. var chunkOffset = rawIndex % chunkSize;
  27359. var dim = list.dimensions[dimIndex];
  27360. var chunk = list._storage[dim][chunkIndex];
  27361. if (chunk) {
  27362. val = chunk[chunkOffset];
  27363. var ordinalMeta = list._dimensionInfos[dim].ordinalMeta;
  27364. if (ordinalMeta && ordinalMeta.categories.length) {
  27365. val = ordinalMeta.categories[val];
  27366. }
  27367. }
  27368. }
  27369. return val;
  27370. }
  27371. /**
  27372. * @return {number}
  27373. */
  27374. listProto.count = function () {
  27375. return this._count;
  27376. };
  27377. listProto.getIndices = function () {
  27378. var newIndices;
  27379. var indices = this._indices;
  27380. if (indices) {
  27381. var Ctor = indices.constructor;
  27382. var thisCount = this._count;
  27383. // `new Array(a, b, c)` is different from `new Uint32Array(a, b, c)`.
  27384. if (Ctor === Array) {
  27385. newIndices = new Ctor(thisCount);
  27386. for (var i = 0; i < thisCount; i++) {
  27387. newIndices[i] = indices[i];
  27388. }
  27389. }
  27390. else {
  27391. newIndices = new Ctor(indices.buffer, 0, thisCount);
  27392. }
  27393. }
  27394. else {
  27395. var Ctor = getIndicesCtor(this);
  27396. var newIndices = new Ctor(this.count());
  27397. for (var i = 0; i < newIndices.length; i++) {
  27398. newIndices[i] = i;
  27399. }
  27400. }
  27401. return newIndices;
  27402. };
  27403. /**
  27404. * Get value. Return NaN if idx is out of range.
  27405. * @param {string} dim Dim must be concrete name.
  27406. * @param {number} idx
  27407. * @param {boolean} stack
  27408. * @return {number}
  27409. */
  27410. listProto.get = function (dim, idx /*, stack */) {
  27411. if (!(idx >= 0 && idx < this._count)) {
  27412. return NaN;
  27413. }
  27414. var storage = this._storage;
  27415. if (!storage[dim]) {
  27416. // TODO Warn ?
  27417. return NaN;
  27418. }
  27419. idx = this.getRawIndex(idx);
  27420. var chunkIndex = Math.floor(idx / this._chunkSize);
  27421. var chunkOffset = idx % this._chunkSize;
  27422. var chunkStore = storage[dim][chunkIndex];
  27423. var value = chunkStore[chunkOffset];
  27424. // FIXME ordinal data type is not stackable
  27425. // if (stack) {
  27426. // var dimensionInfo = this._dimensionInfos[dim];
  27427. // if (dimensionInfo && dimensionInfo.stackable) {
  27428. // var stackedOn = this.stackedOn;
  27429. // while (stackedOn) {
  27430. // // Get no stacked data of stacked on
  27431. // var stackedValue = stackedOn.get(dim, idx);
  27432. // // Considering positive stack, negative stack and empty data
  27433. // if ((value >= 0 && stackedValue > 0) // Positive stack
  27434. // || (value <= 0 && stackedValue < 0) // Negative stack
  27435. // ) {
  27436. // value += stackedValue;
  27437. // }
  27438. // stackedOn = stackedOn.stackedOn;
  27439. // }
  27440. // }
  27441. // }
  27442. return value;
  27443. };
  27444. /**
  27445. * @param {string} dim concrete dim
  27446. * @param {number} rawIndex
  27447. * @return {number|string}
  27448. */
  27449. listProto.getByRawIndex = function (dim, rawIdx) {
  27450. if (!(rawIdx >= 0 && rawIdx < this._rawCount)) {
  27451. return NaN;
  27452. }
  27453. var dimStore = this._storage[dim];
  27454. if (!dimStore) {
  27455. // TODO Warn ?
  27456. return NaN;
  27457. }
  27458. var chunkIndex = Math.floor(rawIdx / this._chunkSize);
  27459. var chunkOffset = rawIdx % this._chunkSize;
  27460. var chunkStore = dimStore[chunkIndex];
  27461. return chunkStore[chunkOffset];
  27462. };
  27463. /**
  27464. * FIXME Use `get` on chrome maybe slow(in filterSelf and selectRange).
  27465. * Hack a much simpler _getFast
  27466. * @private
  27467. */
  27468. listProto._getFast = function (dim, rawIdx) {
  27469. var chunkIndex = Math.floor(rawIdx / this._chunkSize);
  27470. var chunkOffset = rawIdx % this._chunkSize;
  27471. var chunkStore = this._storage[dim][chunkIndex];
  27472. return chunkStore[chunkOffset];
  27473. };
  27474. /**
  27475. * Get value for multi dimensions.
  27476. * @param {Array.<string>} [dimensions] If ignored, using all dimensions.
  27477. * @param {number} idx
  27478. * @return {number}
  27479. */
  27480. listProto.getValues = function (dimensions, idx /*, stack */) {
  27481. var values = [];
  27482. if (!isArray(dimensions)) {
  27483. // stack = idx;
  27484. idx = dimensions;
  27485. dimensions = this.dimensions;
  27486. }
  27487. for (var i = 0, len = dimensions.length; i < len; i++) {
  27488. values.push(this.get(dimensions[i], idx /*, stack */));
  27489. }
  27490. return values;
  27491. };
  27492. /**
  27493. * If value is NaN. Inlcuding '-'
  27494. * Only check the coord dimensions.
  27495. * @param {string} dim
  27496. * @param {number} idx
  27497. * @return {number}
  27498. */
  27499. listProto.hasValue = function (idx) {
  27500. var dataDimsOnCoord = this._dimensionsSummary.dataDimsOnCoord;
  27501. for (var i = 0, len = dataDimsOnCoord.length; i < len; i++) {
  27502. // Ordinal type originally can be string or number.
  27503. // But when an ordinal type is used on coord, it can
  27504. // not be string but only number. So we can also use isNaN.
  27505. if (isNaN(this.get(dataDimsOnCoord[i], idx))) {
  27506. return false;
  27507. }
  27508. }
  27509. return true;
  27510. };
  27511. /**
  27512. * Get extent of data in one dimension
  27513. * @param {string} dim
  27514. * @param {boolean} stack
  27515. */
  27516. listProto.getDataExtent = function (dim /*, stack */) {
  27517. // Make sure use concrete dim as cache name.
  27518. dim = this.getDimension(dim);
  27519. var dimData = this._storage[dim];
  27520. var initialExtent = getInitialExtent();
  27521. // stack = !!((stack || false) && this.getCalculationInfo(dim));
  27522. if (!dimData) {
  27523. return initialExtent;
  27524. }
  27525. // Make more strict checkings to ensure hitting cache.
  27526. var currEnd = this.count();
  27527. // var cacheName = [dim, !!stack].join('_');
  27528. // var cacheName = dim;
  27529. // Consider the most cases when using data zoom, `getDataExtent`
  27530. // happened before filtering. We cache raw extent, which is not
  27531. // necessary to be cleared and recalculated when restore data.
  27532. var useRaw = !this._indices; // && !stack;
  27533. var dimExtent;
  27534. if (useRaw) {
  27535. return this._rawExtent[dim].slice();
  27536. }
  27537. dimExtent = this._extent[dim];
  27538. if (dimExtent) {
  27539. return dimExtent.slice();
  27540. }
  27541. dimExtent = initialExtent;
  27542. var min = dimExtent[0];
  27543. var max = dimExtent[1];
  27544. for (var i = 0; i < currEnd; i++) {
  27545. // var value = stack ? this.get(dim, i, true) : this._getFast(dim, this.getRawIndex(i));
  27546. var value = this._getFast(dim, this.getRawIndex(i));
  27547. value < min && (min = value);
  27548. value > max && (max = value);
  27549. }
  27550. dimExtent = [min, max];
  27551. this._extent[dim] = dimExtent;
  27552. return dimExtent;
  27553. };
  27554. /**
  27555. * Optimize for the scenario that data is filtered by a given extent.
  27556. * Consider that if data amount is more than hundreds of thousand,
  27557. * extent calculation will cost more than 10ms and the cache will
  27558. * be erased because of the filtering.
  27559. */
  27560. listProto.getApproximateExtent = function (dim /*, stack */) {
  27561. dim = this.getDimension(dim);
  27562. return this._approximateExtent[dim] || this.getDataExtent(dim /*, stack */);
  27563. };
  27564. listProto.setApproximateExtent = function (extent, dim /*, stack */) {
  27565. dim = this.getDimension(dim);
  27566. this._approximateExtent[dim] = extent.slice();
  27567. };
  27568. /**
  27569. * @param {string} key
  27570. * @return {*}
  27571. */
  27572. listProto.getCalculationInfo = function (key) {
  27573. return this._calculationInfo[key];
  27574. };
  27575. /**
  27576. * @param {string|Object} key or k-v object
  27577. * @param {*} [value]
  27578. */
  27579. listProto.setCalculationInfo = function (key, value) {
  27580. isObject$4(key)
  27581. ? extend(this._calculationInfo, key)
  27582. : (this._calculationInfo[key] = value);
  27583. };
  27584. /**
  27585. * Get sum of data in one dimension
  27586. * @param {string} dim
  27587. */
  27588. listProto.getSum = function (dim /*, stack */) {
  27589. var dimData = this._storage[dim];
  27590. var sum = 0;
  27591. if (dimData) {
  27592. for (var i = 0, len = this.count(); i < len; i++) {
  27593. var value = this.get(dim, i /*, stack */);
  27594. if (!isNaN(value)) {
  27595. sum += value;
  27596. }
  27597. }
  27598. }
  27599. return sum;
  27600. };
  27601. /**
  27602. * Get median of data in one dimension
  27603. * @param {string} dim
  27604. */
  27605. listProto.getMedian = function (dim /*, stack */) {
  27606. var dimDataArray = [];
  27607. // map all data of one dimension
  27608. this.each(dim, function (val, idx) {
  27609. if (!isNaN(val)) {
  27610. dimDataArray.push(val);
  27611. }
  27612. });
  27613. // TODO
  27614. // Use quick select?
  27615. // immutability & sort
  27616. var sortedDimDataArray = [].concat(dimDataArray).sort(function (a, b) {
  27617. return a - b;
  27618. });
  27619. var len = this.count();
  27620. // calculate median
  27621. return len === 0
  27622. ? 0
  27623. : len % 2 === 1
  27624. ? sortedDimDataArray[(len - 1) / 2]
  27625. : (sortedDimDataArray[len / 2] + sortedDimDataArray[len / 2 - 1]) / 2;
  27626. };
  27627. // /**
  27628. // * Retreive the index with given value
  27629. // * @param {string} dim Concrete dimension.
  27630. // * @param {number} value
  27631. // * @return {number}
  27632. // */
  27633. // Currently incorrect: should return dataIndex but not rawIndex.
  27634. // Do not fix it until this method is to be used somewhere.
  27635. // FIXME Precision of float value
  27636. // listProto.indexOf = function (dim, value) {
  27637. // var storage = this._storage;
  27638. // var dimData = storage[dim];
  27639. // var chunkSize = this._chunkSize;
  27640. // if (dimData) {
  27641. // for (var i = 0, len = this.count(); i < len; i++) {
  27642. // var chunkIndex = Math.floor(i / chunkSize);
  27643. // var chunkOffset = i % chunkSize;
  27644. // if (dimData[chunkIndex][chunkOffset] === value) {
  27645. // return i;
  27646. // }
  27647. // }
  27648. // }
  27649. // return -1;
  27650. // };
  27651. /**
  27652. * Only support the dimension which inverted index created.
  27653. * Do not support other cases until required.
  27654. * @param {string} concrete dim
  27655. * @param {number|string} value
  27656. * @return {number} rawIndex
  27657. */
  27658. listProto.rawIndexOf = function (dim, value) {
  27659. var invertedIndices = dim && this._invertedIndicesMap[dim];
  27660. if (__DEV__) {
  27661. if (!invertedIndices) {
  27662. throw new Error('Do not supported yet');
  27663. }
  27664. }
  27665. var rawIndex = invertedIndices[value];
  27666. if (rawIndex == null || isNaN(rawIndex)) {
  27667. return INDEX_NOT_FOUND;
  27668. }
  27669. return rawIndex;
  27670. };
  27671. /**
  27672. * Retreive the index with given name
  27673. * @param {number} idx
  27674. * @param {number} name
  27675. * @return {number}
  27676. */
  27677. listProto.indexOfName = function (name) {
  27678. for (var i = 0, len = this.count(); i < len; i++) {
  27679. if (this.getName(i) === name) {
  27680. return i;
  27681. }
  27682. }
  27683. return -1;
  27684. };
  27685. /**
  27686. * Retreive the index with given raw data index
  27687. * @param {number} idx
  27688. * @param {number} name
  27689. * @return {number}
  27690. */
  27691. listProto.indexOfRawIndex = function (rawIndex) {
  27692. if (rawIndex >= this._rawCount || rawIndex < 0) {
  27693. return -1;
  27694. }
  27695. if (!this._indices) {
  27696. return rawIndex;
  27697. }
  27698. // Indices are ascending
  27699. var indices = this._indices;
  27700. // If rawIndex === dataIndex
  27701. var rawDataIndex = indices[rawIndex];
  27702. if (rawDataIndex != null && rawDataIndex < this._count && rawDataIndex === rawIndex) {
  27703. return rawIndex;
  27704. }
  27705. var left = 0;
  27706. var right = this._count - 1;
  27707. while (left <= right) {
  27708. var mid = (left + right) / 2 | 0;
  27709. if (indices[mid] < rawIndex) {
  27710. left = mid + 1;
  27711. }
  27712. else if (indices[mid] > rawIndex) {
  27713. right = mid - 1;
  27714. }
  27715. else {
  27716. return mid;
  27717. }
  27718. }
  27719. return -1;
  27720. };
  27721. /**
  27722. * Retreive the index of nearest value
  27723. * @param {string} dim
  27724. * @param {number} value
  27725. * @param {number} [maxDistance=Infinity]
  27726. * @return {Array.<number>} If and only if multiple indices has
  27727. * the same value, they are put to the result.
  27728. */
  27729. listProto.indicesOfNearest = function (dim, value, maxDistance) {
  27730. var storage = this._storage;
  27731. var dimData = storage[dim];
  27732. var nearestIndices = [];
  27733. if (!dimData) {
  27734. return nearestIndices;
  27735. }
  27736. if (maxDistance == null) {
  27737. maxDistance = Infinity;
  27738. }
  27739. var minDist = Infinity;
  27740. var minDiff = -1;
  27741. var nearestIndicesLen = 0;
  27742. // Check the test case of `test/ut/spec/data/List.js`.
  27743. for (var i = 0, len = this.count(); i < len; i++) {
  27744. var diff = value - this.get(dim, i);
  27745. var dist = Math.abs(diff);
  27746. if (dist <= maxDistance) {
  27747. // When the `value` is at the middle of `this.get(dim, i)` and `this.get(dim, i+1)`,
  27748. // we'd better not push both of them to `nearestIndices`, otherwise it is easy to
  27749. // get more than one item in `nearestIndices` (more specifically, in `tooltip`).
  27750. // So we chose the one that `diff >= 0` in this csae.
  27751. // But if `this.get(dim, i)` and `this.get(dim, j)` get the same value, both of them
  27752. // should be push to `nearestIndices`.
  27753. if (dist < minDist
  27754. || (dist === minDist && diff >= 0 && minDiff < 0)
  27755. ) {
  27756. minDist = dist;
  27757. minDiff = diff;
  27758. nearestIndicesLen = 0;
  27759. }
  27760. if (diff === minDiff) {
  27761. nearestIndices[nearestIndicesLen++] = i;
  27762. }
  27763. }
  27764. }
  27765. nearestIndices.length = nearestIndicesLen;
  27766. return nearestIndices;
  27767. };
  27768. /**
  27769. * Get raw data index
  27770. * @param {number} idx
  27771. * @return {number}
  27772. */
  27773. listProto.getRawIndex = getRawIndexWithoutIndices;
  27774. function getRawIndexWithoutIndices(idx) {
  27775. return idx;
  27776. }
  27777. function getRawIndexWithIndices(idx) {
  27778. if (idx < this._count && idx >= 0) {
  27779. return this._indices[idx];
  27780. }
  27781. return -1;
  27782. }
  27783. /**
  27784. * Get raw data item
  27785. * @param {number} idx
  27786. * @return {number}
  27787. */
  27788. listProto.getRawDataItem = function (idx) {
  27789. if (!this._rawData.persistent) {
  27790. var val = [];
  27791. for (var i = 0; i < this.dimensions.length; i++) {
  27792. var dim = this.dimensions[i];
  27793. val.push(this.get(dim, idx));
  27794. }
  27795. return val;
  27796. }
  27797. else {
  27798. return this._rawData.getItem(this.getRawIndex(idx));
  27799. }
  27800. };
  27801. /**
  27802. * @param {number} idx
  27803. * @param {boolean} [notDefaultIdx=false]
  27804. * @return {string}
  27805. */
  27806. listProto.getName = function (idx) {
  27807. var rawIndex = this.getRawIndex(idx);
  27808. return this._nameList[rawIndex]
  27809. || getRawValueFromStore(this, this._nameDimIdx, rawIndex)
  27810. || '';
  27811. };
  27812. /**
  27813. * @param {number} idx
  27814. * @param {boolean} [notDefaultIdx=false]
  27815. * @return {string}
  27816. */
  27817. listProto.getId = function (idx) {
  27818. return getId(this, this.getRawIndex(idx));
  27819. };
  27820. function getId(list, rawIndex) {
  27821. var id = list._idList[rawIndex];
  27822. if (id == null) {
  27823. id = getRawValueFromStore(list, list._idDimIdx, rawIndex);
  27824. }
  27825. if (id == null) {
  27826. // FIXME Check the usage in graph, should not use prefix.
  27827. id = ID_PREFIX + rawIndex;
  27828. }
  27829. return id;
  27830. }
  27831. function normalizeDimensions(dimensions) {
  27832. if (!isArray(dimensions)) {
  27833. dimensions = [dimensions];
  27834. }
  27835. return dimensions;
  27836. }
  27837. function validateDimensions(list, dims) {
  27838. for (var i = 0; i < dims.length; i++) {
  27839. // stroage may be empty when no data, so use
  27840. // dimensionInfos to check.
  27841. if (!list._dimensionInfos[dims[i]]) {
  27842. console.error('Unkown dimension ' + dims[i]);
  27843. }
  27844. }
  27845. }
  27846. /**
  27847. * Data iteration
  27848. * @param {string|Array.<string>}
  27849. * @param {Function} cb
  27850. * @param {*} [context=this]
  27851. *
  27852. * @example
  27853. * list.each('x', function (x, idx) {});
  27854. * list.each(['x', 'y'], function (x, y, idx) {});
  27855. * list.each(function (idx) {})
  27856. */
  27857. listProto.each = function (dims, cb, context, contextCompat) {
  27858. 'use strict';
  27859. if (!this._count) {
  27860. return;
  27861. }
  27862. if (typeof dims === 'function') {
  27863. contextCompat = context;
  27864. context = cb;
  27865. cb = dims;
  27866. dims = [];
  27867. }
  27868. // contextCompat just for compat echarts3
  27869. context = context || contextCompat || this;
  27870. dims = map(normalizeDimensions(dims), this.getDimension, this);
  27871. if (__DEV__) {
  27872. validateDimensions(this, dims);
  27873. }
  27874. var dimSize = dims.length;
  27875. for (var i = 0; i < this.count(); i++) {
  27876. // Simple optimization
  27877. switch (dimSize) {
  27878. case 0:
  27879. cb.call(context, i);
  27880. break;
  27881. case 1:
  27882. cb.call(context, this.get(dims[0], i), i);
  27883. break;
  27884. case 2:
  27885. cb.call(context, this.get(dims[0], i), this.get(dims[1], i), i);
  27886. break;
  27887. default:
  27888. var k = 0;
  27889. var value = [];
  27890. for (; k < dimSize; k++) {
  27891. value[k] = this.get(dims[k], i);
  27892. }
  27893. // Index
  27894. value[k] = i;
  27895. cb.apply(context, value);
  27896. }
  27897. }
  27898. };
  27899. /**
  27900. * Data filter
  27901. * @param {string|Array.<string>}
  27902. * @param {Function} cb
  27903. * @param {*} [context=this]
  27904. */
  27905. listProto.filterSelf = function (dimensions, cb, context, contextCompat) {
  27906. 'use strict';
  27907. if (!this._count) {
  27908. return;
  27909. }
  27910. if (typeof dimensions === 'function') {
  27911. contextCompat = context;
  27912. context = cb;
  27913. cb = dimensions;
  27914. dimensions = [];
  27915. }
  27916. // contextCompat just for compat echarts3
  27917. context = context || contextCompat || this;
  27918. dimensions = map(
  27919. normalizeDimensions(dimensions), this.getDimension, this
  27920. );
  27921. if (__DEV__) {
  27922. validateDimensions(this, dimensions);
  27923. }
  27924. var count = this.count();
  27925. var Ctor = getIndicesCtor(this);
  27926. var newIndices = new Ctor(count);
  27927. var value = [];
  27928. var dimSize = dimensions.length;
  27929. var offset = 0;
  27930. var dim0 = dimensions[0];
  27931. for (var i = 0; i < count; i++) {
  27932. var keep;
  27933. var rawIdx = this.getRawIndex(i);
  27934. // Simple optimization
  27935. if (dimSize === 0) {
  27936. keep = cb.call(context, i);
  27937. }
  27938. else if (dimSize === 1) {
  27939. var val = this._getFast(dim0, rawIdx);
  27940. keep = cb.call(context, val, i);
  27941. }
  27942. else {
  27943. for (var k = 0; k < dimSize; k++) {
  27944. value[k] = this._getFast(dim0, rawIdx);
  27945. }
  27946. value[k] = i;
  27947. keep = cb.apply(context, value);
  27948. }
  27949. if (keep) {
  27950. newIndices[offset++] = rawIdx;
  27951. }
  27952. }
  27953. // Set indices after filtered.
  27954. if (offset < count) {
  27955. this._indices = newIndices;
  27956. }
  27957. this._count = offset;
  27958. // Reset data extent
  27959. this._extent = {};
  27960. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  27961. return this;
  27962. };
  27963. /**
  27964. * Select data in range. (For optimization of filter)
  27965. * (Manually inline code, support 5 million data filtering in data zoom.)
  27966. */
  27967. listProto.selectRange = function (range) {
  27968. 'use strict';
  27969. if (!this._count) {
  27970. return;
  27971. }
  27972. var dimensions = [];
  27973. for (var dim in range) {
  27974. if (range.hasOwnProperty(dim)) {
  27975. dimensions.push(dim);
  27976. }
  27977. }
  27978. if (__DEV__) {
  27979. validateDimensions(this, dimensions);
  27980. }
  27981. var dimSize = dimensions.length;
  27982. if (!dimSize) {
  27983. return;
  27984. }
  27985. var originalCount = this.count();
  27986. var Ctor = getIndicesCtor(this);
  27987. var newIndices = new Ctor(originalCount);
  27988. var offset = 0;
  27989. var dim0 = dimensions[0];
  27990. var min = range[dim0][0];
  27991. var max = range[dim0][1];
  27992. var quickFinished = false;
  27993. if (!this._indices) {
  27994. // Extreme optimization for common case. About 2x faster in chrome.
  27995. var idx = 0;
  27996. if (dimSize === 1) {
  27997. var dimStorage = this._storage[dimensions[0]];
  27998. for (var k = 0; k < this._chunkCount; k++) {
  27999. var chunkStorage = dimStorage[k];
  28000. var len = Math.min(this._count - k * this._chunkSize, this._chunkSize);
  28001. for (var i = 0; i < len; i++) {
  28002. var val = chunkStorage[i];
  28003. // NaN will not be filtered. Consider the case, in line chart, empty
  28004. // value indicates the line should be broken. But for the case like
  28005. // scatter plot, a data item with empty value will not be rendered,
  28006. // but the axis extent may be effected if some other dim of the data
  28007. // item has value. Fortunately it is not a significant negative effect.
  28008. if (
  28009. (val >= min && val <= max) || isNaN(val)
  28010. ) {
  28011. newIndices[offset++] = idx;
  28012. }
  28013. idx++;
  28014. }
  28015. }
  28016. quickFinished = true;
  28017. }
  28018. else if (dimSize === 2) {
  28019. var dimStorage = this._storage[dim0];
  28020. var dimStorage2 = this._storage[dimensions[1]];
  28021. var min2 = range[dimensions[1]][0];
  28022. var max2 = range[dimensions[1]][1];
  28023. for (var k = 0; k < this._chunkCount; k++) {
  28024. var chunkStorage = dimStorage[k];
  28025. var chunkStorage2 = dimStorage2[k];
  28026. var len = Math.min(this._count - k * this._chunkSize, this._chunkSize);
  28027. for (var i = 0; i < len; i++) {
  28028. var val = chunkStorage[i];
  28029. var val2 = chunkStorage2[i];
  28030. // Do not filter NaN, see comment above.
  28031. if ((
  28032. (val >= min && val <= max) || isNaN(val)
  28033. )
  28034. && (
  28035. (val2 >= min2 && val2 <= max2) || isNaN(val2)
  28036. )
  28037. ) {
  28038. newIndices[offset++] = idx;
  28039. }
  28040. idx++;
  28041. }
  28042. }
  28043. quickFinished = true;
  28044. }
  28045. }
  28046. if (!quickFinished) {
  28047. if (dimSize === 1) {
  28048. for (var i = 0; i < originalCount; i++) {
  28049. var rawIndex = this.getRawIndex(i);
  28050. var val = this._getFast(dim0, rawIndex);
  28051. // Do not filter NaN, see comment above.
  28052. if (
  28053. (val >= min && val <= max) || isNaN(val)
  28054. ) {
  28055. newIndices[offset++] = rawIndex;
  28056. }
  28057. }
  28058. }
  28059. else {
  28060. for (var i = 0; i < originalCount; i++) {
  28061. var keep = true;
  28062. var rawIndex = this.getRawIndex(i);
  28063. for (var k = 0; k < dimSize; k++) {
  28064. var dimk = dimensions[k];
  28065. var val = this._getFast(dim, rawIndex);
  28066. // Do not filter NaN, see comment above.
  28067. if (val < range[dimk][0] || val > range[dimk][1]) {
  28068. keep = false;
  28069. }
  28070. }
  28071. if (keep) {
  28072. newIndices[offset++] = this.getRawIndex(i);
  28073. }
  28074. }
  28075. }
  28076. }
  28077. // Set indices after filtered.
  28078. if (offset < originalCount) {
  28079. this._indices = newIndices;
  28080. }
  28081. this._count = offset;
  28082. // Reset data extent
  28083. this._extent = {};
  28084. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  28085. return this;
  28086. };
  28087. /**
  28088. * Data mapping to a plain array
  28089. * @param {string|Array.<string>} [dimensions]
  28090. * @param {Function} cb
  28091. * @param {*} [context=this]
  28092. * @return {Array}
  28093. */
  28094. listProto.mapArray = function (dimensions, cb, context, contextCompat) {
  28095. 'use strict';
  28096. if (typeof dimensions === 'function') {
  28097. contextCompat = context;
  28098. context = cb;
  28099. cb = dimensions;
  28100. dimensions = [];
  28101. }
  28102. // contextCompat just for compat echarts3
  28103. context = context || contextCompat || this;
  28104. var result = [];
  28105. this.each(dimensions, function () {
  28106. result.push(cb && cb.apply(this, arguments));
  28107. }, context);
  28108. return result;
  28109. };
  28110. // Data in excludeDimensions is copied, otherwise transfered.
  28111. function cloneListForMapAndSample(original, excludeDimensions) {
  28112. var allDimensions = original.dimensions;
  28113. var list = new List(
  28114. map(allDimensions, original.getDimensionInfo, original),
  28115. original.hostModel
  28116. );
  28117. // FIXME If needs stackedOn, value may already been stacked
  28118. transferProperties(list, original);
  28119. var storage = list._storage = {};
  28120. var originalStorage = original._storage;
  28121. // Init storage
  28122. for (var i = 0; i < allDimensions.length; i++) {
  28123. var dim = allDimensions[i];
  28124. if (originalStorage[dim]) {
  28125. // Notice that we do not reset invertedIndicesMap here, becuase
  28126. // there is no scenario of mapping or sampling ordinal dimension.
  28127. if (indexOf(excludeDimensions, dim) >= 0) {
  28128. storage[dim] = cloneDimStore(originalStorage[dim]);
  28129. list._rawExtent[dim] = getInitialExtent();
  28130. list._extent[dim] = null;
  28131. }
  28132. else {
  28133. // Direct reference for other dimensions
  28134. storage[dim] = originalStorage[dim];
  28135. }
  28136. }
  28137. }
  28138. return list;
  28139. }
  28140. function cloneDimStore(originalDimStore) {
  28141. var newDimStore = new Array(originalDimStore.length);
  28142. for (var j = 0; j < originalDimStore.length; j++) {
  28143. newDimStore[j] = cloneChunk(originalDimStore[j]);
  28144. }
  28145. return newDimStore;
  28146. }
  28147. function getInitialExtent() {
  28148. return [Infinity, -Infinity];
  28149. }
  28150. /**
  28151. * Data mapping to a new List with given dimensions
  28152. * @param {string|Array.<string>} dimensions
  28153. * @param {Function} cb
  28154. * @param {*} [context=this]
  28155. * @return {Array}
  28156. */
  28157. listProto.map = function (dimensions, cb, context, contextCompat) {
  28158. 'use strict';
  28159. // contextCompat just for compat echarts3
  28160. context = context || contextCompat || this;
  28161. dimensions = map(
  28162. normalizeDimensions(dimensions), this.getDimension, this
  28163. );
  28164. if (__DEV__) {
  28165. validateDimensions(this, dimensions);
  28166. }
  28167. var list = cloneListForMapAndSample(this, dimensions);
  28168. // Following properties are all immutable.
  28169. // So we can reference to the same value
  28170. list._indices = this._indices;
  28171. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  28172. var storage = list._storage;
  28173. var tmpRetValue = [];
  28174. var chunkSize = this._chunkSize;
  28175. var dimSize = dimensions.length;
  28176. var dataCount = this.count();
  28177. var values = [];
  28178. var rawExtent = list._rawExtent;
  28179. for (var dataIndex = 0; dataIndex < dataCount; dataIndex++) {
  28180. for (var dimIndex = 0; dimIndex < dimSize; dimIndex++) {
  28181. values[dimIndex] = this.get(dimensions[dimIndex], dataIndex /*, stack */);
  28182. }
  28183. values[dimSize] = dataIndex;
  28184. var retValue = cb && cb.apply(context, values);
  28185. if (retValue != null) {
  28186. // a number or string (in oridinal dimension)?
  28187. if (typeof retValue !== 'object') {
  28188. tmpRetValue[0] = retValue;
  28189. retValue = tmpRetValue;
  28190. }
  28191. var rawIndex = this.getRawIndex(dataIndex);
  28192. var chunkIndex = Math.floor(rawIndex / chunkSize);
  28193. var chunkOffset = rawIndex % chunkSize;
  28194. for (var i = 0; i < retValue.length; i++) {
  28195. var dim = dimensions[i];
  28196. var val = retValue[i];
  28197. var rawExtentOnDim = rawExtent[dim];
  28198. var dimStore = storage[dim];
  28199. if (dimStore) {
  28200. dimStore[chunkIndex][chunkOffset] = val;
  28201. }
  28202. if (val < rawExtentOnDim[0]) {
  28203. rawExtentOnDim[0] = val;
  28204. }
  28205. if (val > rawExtentOnDim[1]) {
  28206. rawExtentOnDim[1] = val;
  28207. }
  28208. }
  28209. }
  28210. }
  28211. return list;
  28212. };
  28213. /**
  28214. * Large data down sampling on given dimension
  28215. * @param {string} dimension
  28216. * @param {number} rate
  28217. * @param {Function} sampleValue
  28218. * @param {Function} sampleIndex Sample index for name and id
  28219. */
  28220. listProto.downSample = function (dimension, rate, sampleValue, sampleIndex) {
  28221. var list = cloneListForMapAndSample(this, [dimension]);
  28222. var targetStorage = list._storage;
  28223. var frameValues = [];
  28224. var frameSize = Math.floor(1 / rate);
  28225. var dimStore = targetStorage[dimension];
  28226. var len = this.count();
  28227. var chunkSize = this._chunkSize;
  28228. var rawExtentOnDim = list._rawExtent[dimension];
  28229. var newIndices = new (getIndicesCtor(this))(len);
  28230. var offset = 0;
  28231. for (var i = 0; i < len; i += frameSize) {
  28232. // Last frame
  28233. if (frameSize > len - i) {
  28234. frameSize = len - i;
  28235. frameValues.length = frameSize;
  28236. }
  28237. for (var k = 0; k < frameSize; k++) {
  28238. var dataIdx = this.getRawIndex(i + k);
  28239. var originalChunkIndex = Math.floor(dataIdx / chunkSize);
  28240. var originalChunkOffset = dataIdx % chunkSize;
  28241. frameValues[k] = dimStore[originalChunkIndex][originalChunkOffset];
  28242. }
  28243. var value = sampleValue(frameValues);
  28244. var sampleFrameIdx = this.getRawIndex(
  28245. Math.min(i + sampleIndex(frameValues, value) || 0, len - 1)
  28246. );
  28247. var sampleChunkIndex = Math.floor(sampleFrameIdx / chunkSize);
  28248. var sampleChunkOffset = sampleFrameIdx % chunkSize;
  28249. // Only write value on the filtered data
  28250. dimStore[sampleChunkIndex][sampleChunkOffset] = value;
  28251. if (value < rawExtentOnDim[0]) {
  28252. rawExtentOnDim[0] = value;
  28253. }
  28254. if (value > rawExtentOnDim[1]) {
  28255. rawExtentOnDim[1] = value;
  28256. }
  28257. newIndices[offset++] = sampleFrameIdx;
  28258. }
  28259. list._count = offset;
  28260. list._indices = newIndices;
  28261. list.getRawIndex = getRawIndexWithIndices;
  28262. return list;
  28263. };
  28264. /**
  28265. * Get model of one data item.
  28266. *
  28267. * @param {number} idx
  28268. */
  28269. // FIXME Model proxy ?
  28270. listProto.getItemModel = function (idx) {
  28271. var hostModel = this.hostModel;
  28272. return new Model(this.getRawDataItem(idx), hostModel, hostModel && hostModel.ecModel);
  28273. };
  28274. /**
  28275. * Create a data differ
  28276. * @param {module:echarts/data/List} otherList
  28277. * @return {module:echarts/data/DataDiffer}
  28278. */
  28279. listProto.diff = function (otherList) {
  28280. var thisList = this;
  28281. return new DataDiffer(
  28282. otherList ? otherList.getIndices() : [],
  28283. this.getIndices(),
  28284. function (idx) {
  28285. return getId(otherList, idx);
  28286. },
  28287. function (idx) {
  28288. return getId(thisList, idx);
  28289. }
  28290. );
  28291. };
  28292. /**
  28293. * Get visual property.
  28294. * @param {string} key
  28295. */
  28296. listProto.getVisual = function (key) {
  28297. var visual = this._visual;
  28298. return visual && visual[key];
  28299. };
  28300. /**
  28301. * Set visual property
  28302. * @param {string|Object} key
  28303. * @param {*} [value]
  28304. *
  28305. * @example
  28306. * setVisual('color', color);
  28307. * setVisual({
  28308. * 'color': color
  28309. * });
  28310. */
  28311. listProto.setVisual = function (key, val) {
  28312. if (isObject$4(key)) {
  28313. for (var name in key) {
  28314. if (key.hasOwnProperty(name)) {
  28315. this.setVisual(name, key[name]);
  28316. }
  28317. }
  28318. return;
  28319. }
  28320. this._visual = this._visual || {};
  28321. this._visual[key] = val;
  28322. };
  28323. /**
  28324. * Set layout property.
  28325. * @param {string|Object} key
  28326. * @param {*} [val]
  28327. */
  28328. listProto.setLayout = function (key, val) {
  28329. if (isObject$4(key)) {
  28330. for (var name in key) {
  28331. if (key.hasOwnProperty(name)) {
  28332. this.setLayout(name, key[name]);
  28333. }
  28334. }
  28335. return;
  28336. }
  28337. this._layout[key] = val;
  28338. };
  28339. /**
  28340. * Get layout property.
  28341. * @param {string} key.
  28342. * @return {*}
  28343. */
  28344. listProto.getLayout = function (key) {
  28345. return this._layout[key];
  28346. };
  28347. /**
  28348. * Get layout of single data item
  28349. * @param {number} idx
  28350. */
  28351. listProto.getItemLayout = function (idx) {
  28352. return this._itemLayouts[idx];
  28353. };
  28354. /**
  28355. * Set layout of single data item
  28356. * @param {number} idx
  28357. * @param {Object} layout
  28358. * @param {boolean=} [merge=false]
  28359. */
  28360. listProto.setItemLayout = function (idx, layout, merge$$1) {
  28361. this._itemLayouts[idx] = merge$$1
  28362. ? extend(this._itemLayouts[idx] || {}, layout)
  28363. : layout;
  28364. };
  28365. /**
  28366. * Clear all layout of single data item
  28367. */
  28368. listProto.clearItemLayouts = function () {
  28369. this._itemLayouts.length = 0;
  28370. };
  28371. /**
  28372. * Get visual property of single data item
  28373. * @param {number} idx
  28374. * @param {string} key
  28375. * @param {boolean} [ignoreParent=false]
  28376. */
  28377. listProto.getItemVisual = function (idx, key, ignoreParent) {
  28378. var itemVisual = this._itemVisuals[idx];
  28379. var val = itemVisual && itemVisual[key];
  28380. if (val == null && !ignoreParent) {
  28381. // Use global visual property
  28382. return this.getVisual(key);
  28383. }
  28384. return val;
  28385. };
  28386. /**
  28387. * Set visual property of single data item
  28388. *
  28389. * @param {number} idx
  28390. * @param {string|Object} key
  28391. * @param {*} [value]
  28392. *
  28393. * @example
  28394. * setItemVisual(0, 'color', color);
  28395. * setItemVisual(0, {
  28396. * 'color': color
  28397. * });
  28398. */
  28399. listProto.setItemVisual = function (idx, key, value) {
  28400. var itemVisual = this._itemVisuals[idx] || {};
  28401. var hasItemVisual = this.hasItemVisual;
  28402. this._itemVisuals[idx] = itemVisual;
  28403. if (isObject$4(key)) {
  28404. for (var name in key) {
  28405. if (key.hasOwnProperty(name)) {
  28406. itemVisual[name] = key[name];
  28407. hasItemVisual[name] = true;
  28408. }
  28409. }
  28410. return;
  28411. }
  28412. itemVisual[key] = value;
  28413. hasItemVisual[key] = true;
  28414. };
  28415. /**
  28416. * Clear itemVisuals and list visual.
  28417. */
  28418. listProto.clearAllVisual = function () {
  28419. this._visual = {};
  28420. this._itemVisuals = [];
  28421. this.hasItemVisual = {};
  28422. };
  28423. var setItemDataAndSeriesIndex = function (child) {
  28424. child.seriesIndex = this.seriesIndex;
  28425. child.dataIndex = this.dataIndex;
  28426. child.dataType = this.dataType;
  28427. };
  28428. /**
  28429. * Set graphic element relative to data. It can be set as null
  28430. * @param {number} idx
  28431. * @param {module:zrender/Element} [el]
  28432. */
  28433. listProto.setItemGraphicEl = function (idx, el) {
  28434. var hostModel = this.hostModel;
  28435. if (el) {
  28436. // Add data index and series index for indexing the data by element
  28437. // Useful in tooltip
  28438. el.dataIndex = idx;
  28439. el.dataType = this.dataType;
  28440. el.seriesIndex = hostModel && hostModel.seriesIndex;
  28441. if (el.type === 'group') {
  28442. el.traverse(setItemDataAndSeriesIndex, el);
  28443. }
  28444. }
  28445. this._graphicEls[idx] = el;
  28446. };
  28447. /**
  28448. * @param {number} idx
  28449. * @return {module:zrender/Element}
  28450. */
  28451. listProto.getItemGraphicEl = function (idx) {
  28452. return this._graphicEls[idx];
  28453. };
  28454. /**
  28455. * @param {Function} cb
  28456. * @param {*} context
  28457. */
  28458. listProto.eachItemGraphicEl = function (cb, context) {
  28459. each$1(this._graphicEls, function (el, idx) {
  28460. if (el) {
  28461. cb && cb.call(context, el, idx);
  28462. }
  28463. });
  28464. };
  28465. /**
  28466. * Shallow clone a new list except visual and layout properties, and graph elements.
  28467. * New list only change the indices.
  28468. */
  28469. listProto.cloneShallow = function (list) {
  28470. if (!list) {
  28471. var dimensionInfoList = map(this.dimensions, this.getDimensionInfo, this);
  28472. list = new List(dimensionInfoList, this.hostModel);
  28473. }
  28474. // FIXME
  28475. list._storage = this._storage;
  28476. transferProperties(list, this);
  28477. // Clone will not change the data extent and indices
  28478. if (this._indices) {
  28479. var Ctor = this._indices.constructor;
  28480. list._indices = new Ctor(this._indices);
  28481. }
  28482. else {
  28483. list._indices = null;
  28484. }
  28485. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  28486. return list;
  28487. };
  28488. /**
  28489. * Wrap some method to add more feature
  28490. * @param {string} methodName
  28491. * @param {Function} injectFunction
  28492. */
  28493. listProto.wrapMethod = function (methodName, injectFunction) {
  28494. var originalMethod = this[methodName];
  28495. if (typeof originalMethod !== 'function') {
  28496. return;
  28497. }
  28498. this.__wrappedMethods = this.__wrappedMethods || [];
  28499. this.__wrappedMethods.push(methodName);
  28500. this[methodName] = function () {
  28501. var res = originalMethod.apply(this, arguments);
  28502. return injectFunction.apply(this, [res].concat(slice(arguments)));
  28503. };
  28504. };
  28505. // Methods that create a new list based on this list should be listed here.
  28506. // Notice that those method should `RETURN` the new list.
  28507. listProto.TRANSFERABLE_METHODS = ['cloneShallow', 'downSample', 'map'];
  28508. // Methods that change indices of this list should be listed here.
  28509. listProto.CHANGABLE_METHODS = ['filterSelf', 'selectRange'];
  28510. /*
  28511. * Licensed to the Apache Software Foundation (ASF) under one
  28512. * or more contributor license agreements. See the NOTICE file
  28513. * distributed with this work for additional information
  28514. * regarding copyright ownership. The ASF licenses this file
  28515. * to you under the Apache License, Version 2.0 (the
  28516. * "License"); you may not use this file except in compliance
  28517. * with the License. You may obtain a copy of the License at
  28518. *
  28519. * http://www.apache.org/licenses/LICENSE-2.0
  28520. *
  28521. * Unless required by applicable law or agreed to in writing,
  28522. * software distributed under the License is distributed on an
  28523. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28524. * KIND, either express or implied. See the License for the
  28525. * specific language governing permissions and limitations
  28526. * under the License.
  28527. */
  28528. /**
  28529. * @deprecated
  28530. * Use `echarts/data/helper/createDimensions` instead.
  28531. */
  28532. /**
  28533. * @see {module:echarts/test/ut/spec/data/completeDimensions}
  28534. *
  28535. * This method builds the relationship between:
  28536. * + "what the coord sys or series requires (see `sysDims`)",
  28537. * + "what the user defines (in `encode` and `dimensions`, see `opt.dimsDef` and `opt.encodeDef`)"
  28538. * + "what the data source provids (see `source`)".
  28539. *
  28540. * Some guess strategy will be adapted if user does not define something.
  28541. * If no 'value' dimension specified, the first no-named dimension will be
  28542. * named as 'value'.
  28543. *
  28544. * @param {Array.<string>} sysDims Necessary dimensions, like ['x', 'y'], which
  28545. * provides not only dim template, but also default order.
  28546. * properties: 'name', 'type', 'displayName'.
  28547. * `name` of each item provides default coord name.
  28548. * [{dimsDef: [string|Object, ...]}, ...] dimsDef of sysDim item provides default dim name, and
  28549. * provide dims count that the sysDim required.
  28550. * [{ordinalMeta}] can be specified.
  28551. * @param {module:echarts/data/Source|Array|Object} source or data (for compatibal with pervious)
  28552. * @param {Object} [opt]
  28553. * @param {Array.<Object|string>} [opt.dimsDef] option.series.dimensions User defined dimensions
  28554. * For example: ['asdf', {name, type}, ...].
  28555. * @param {Object|HashMap} [opt.encodeDef] option.series.encode {x: 2, y: [3, 1], tooltip: [1, 2], label: 3}
  28556. * @param {Function} [opt.encodeDefaulter] Called if no `opt.encodeDef` exists.
  28557. * If not specified, auto find the next available data dim.
  28558. * param source {module:data/Source}
  28559. * param dimCount {number}
  28560. * return {Object} encode Never be `null/undefined`.
  28561. * @param {string} [opt.generateCoord] Generate coord dim with the given name.
  28562. * If not specified, extra dim names will be:
  28563. * 'value', 'value0', 'value1', ...
  28564. * @param {number} [opt.generateCoordCount] By default, the generated dim name is `generateCoord`.
  28565. * If `generateCoordCount` specified, the generated dim names will be:
  28566. * `generateCoord` + 0, `generateCoord` + 1, ...
  28567. * can be Infinity, indicate that use all of the remain columns.
  28568. * @param {number} [opt.dimCount] If not specified, guess by the first data item.
  28569. * @return {Array.<module:data/DataDimensionInfo>}
  28570. */
  28571. function completeDimensions(sysDims, source, opt) {
  28572. if (!Source.isInstance(source)) {
  28573. source = Source.seriesDataToSource(source);
  28574. }
  28575. opt = opt || {};
  28576. sysDims = (sysDims || []).slice();
  28577. var dimsDef = (opt.dimsDef || []).slice();
  28578. var dataDimNameMap = createHashMap();
  28579. var coordDimNameMap = createHashMap();
  28580. // var valueCandidate;
  28581. var result = [];
  28582. var dimCount = getDimCount(source, sysDims, dimsDef, opt.dimCount);
  28583. // Apply user defined dims (`name` and `type`) and init result.
  28584. for (var i = 0; i < dimCount; i++) {
  28585. var dimDefItem = dimsDef[i] = extend(
  28586. {}, isObject$1(dimsDef[i]) ? dimsDef[i] : {name: dimsDef[i]}
  28587. );
  28588. var userDimName = dimDefItem.name;
  28589. var resultItem = result[i] = new DataDimensionInfo();
  28590. // Name will be applied later for avoiding duplication.
  28591. if (userDimName != null && dataDimNameMap.get(userDimName) == null) {
  28592. // Only if `series.dimensions` is defined in option
  28593. // displayName, will be set, and dimension will be diplayed vertically in
  28594. // tooltip by default.
  28595. resultItem.name = resultItem.displayName = userDimName;
  28596. dataDimNameMap.set(userDimName, i);
  28597. }
  28598. dimDefItem.type != null && (resultItem.type = dimDefItem.type);
  28599. dimDefItem.displayName != null && (resultItem.displayName = dimDefItem.displayName);
  28600. }
  28601. var encodeDef = opt.encodeDef;
  28602. if (!encodeDef && opt.encodeDefaulter) {
  28603. encodeDef = opt.encodeDefaulter(source, dimCount);
  28604. }
  28605. encodeDef = createHashMap(encodeDef);
  28606. // Set `coordDim` and `coordDimIndex` by `encodeDef` and normalize `encodeDef`.
  28607. encodeDef.each(function (dataDims, coordDim) {
  28608. dataDims = normalizeToArray(dataDims).slice();
  28609. // Note: It is allowed that `dataDims.length` is `0`, e.g., options is
  28610. // `{encode: {x: -1, y: 1}}`. Should not filter anything in
  28611. // this case.
  28612. if (dataDims.length === 1 && !isString(dataDims[0]) && dataDims[0] < 0) {
  28613. encodeDef.set(coordDim, false);
  28614. return;
  28615. }
  28616. var validDataDims = encodeDef.set(coordDim, []);
  28617. each$1(dataDims, function (resultDimIdx, idx) {
  28618. // The input resultDimIdx can be dim name or index.
  28619. isString(resultDimIdx) && (resultDimIdx = dataDimNameMap.get(resultDimIdx));
  28620. if (resultDimIdx != null && resultDimIdx < dimCount) {
  28621. validDataDims[idx] = resultDimIdx;
  28622. applyDim(result[resultDimIdx], coordDim, idx);
  28623. }
  28624. });
  28625. });
  28626. // Apply templetes and default order from `sysDims`.
  28627. var availDimIdx = 0;
  28628. each$1(sysDims, function (sysDimItem, sysDimIndex) {
  28629. var coordDim;
  28630. var sysDimItem;
  28631. var sysDimItemDimsDef;
  28632. var sysDimItemOtherDims;
  28633. if (isString(sysDimItem)) {
  28634. coordDim = sysDimItem;
  28635. sysDimItem = {};
  28636. }
  28637. else {
  28638. coordDim = sysDimItem.name;
  28639. var ordinalMeta = sysDimItem.ordinalMeta;
  28640. sysDimItem.ordinalMeta = null;
  28641. sysDimItem = clone(sysDimItem);
  28642. sysDimItem.ordinalMeta = ordinalMeta;
  28643. // `coordDimIndex` should not be set directly.
  28644. sysDimItemDimsDef = sysDimItem.dimsDef;
  28645. sysDimItemOtherDims = sysDimItem.otherDims;
  28646. sysDimItem.name = sysDimItem.coordDim = sysDimItem.coordDimIndex =
  28647. sysDimItem.dimsDef = sysDimItem.otherDims = null;
  28648. }
  28649. var dataDims = encodeDef.get(coordDim);
  28650. // negative resultDimIdx means no need to mapping.
  28651. if (dataDims === false) {
  28652. return;
  28653. }
  28654. var dataDims = normalizeToArray(dataDims);
  28655. // dimensions provides default dim sequences.
  28656. if (!dataDims.length) {
  28657. for (var i = 0; i < (sysDimItemDimsDef && sysDimItemDimsDef.length || 1); i++) {
  28658. while (availDimIdx < result.length && result[availDimIdx].coordDim != null) {
  28659. availDimIdx++;
  28660. }
  28661. availDimIdx < result.length && dataDims.push(availDimIdx++);
  28662. }
  28663. }
  28664. // Apply templates.
  28665. each$1(dataDims, function (resultDimIdx, coordDimIndex) {
  28666. var resultItem = result[resultDimIdx];
  28667. applyDim(defaults(resultItem, sysDimItem), coordDim, coordDimIndex);
  28668. if (resultItem.name == null && sysDimItemDimsDef) {
  28669. var sysDimItemDimsDefItem = sysDimItemDimsDef[coordDimIndex];
  28670. !isObject$1(sysDimItemDimsDefItem) && (sysDimItemDimsDefItem = {name: sysDimItemDimsDefItem});
  28671. resultItem.name = resultItem.displayName = sysDimItemDimsDefItem.name;
  28672. resultItem.defaultTooltip = sysDimItemDimsDefItem.defaultTooltip;
  28673. }
  28674. // FIXME refactor, currently only used in case: {otherDims: {tooltip: false}}
  28675. sysDimItemOtherDims && defaults(resultItem.otherDims, sysDimItemOtherDims);
  28676. });
  28677. });
  28678. function applyDim(resultItem, coordDim, coordDimIndex) {
  28679. if (OTHER_DIMENSIONS.get(coordDim) != null) {
  28680. resultItem.otherDims[coordDim] = coordDimIndex;
  28681. }
  28682. else {
  28683. resultItem.coordDim = coordDim;
  28684. resultItem.coordDimIndex = coordDimIndex;
  28685. coordDimNameMap.set(coordDim, true);
  28686. }
  28687. }
  28688. // Make sure the first extra dim is 'value'.
  28689. var generateCoord = opt.generateCoord;
  28690. var generateCoordCount = opt.generateCoordCount;
  28691. var fromZero = generateCoordCount != null;
  28692. generateCoordCount = generateCoord ? (generateCoordCount || 1) : 0;
  28693. var extra = generateCoord || 'value';
  28694. // Set dim `name` and other `coordDim` and other props.
  28695. for (var resultDimIdx = 0; resultDimIdx < dimCount; resultDimIdx++) {
  28696. var resultItem = result[resultDimIdx] = result[resultDimIdx] || new DataDimensionInfo();
  28697. var coordDim = resultItem.coordDim;
  28698. if (coordDim == null) {
  28699. resultItem.coordDim = genName(
  28700. extra, coordDimNameMap, fromZero
  28701. );
  28702. resultItem.coordDimIndex = 0;
  28703. if (!generateCoord || generateCoordCount <= 0) {
  28704. resultItem.isExtraCoord = true;
  28705. }
  28706. generateCoordCount--;
  28707. }
  28708. resultItem.name == null && (resultItem.name = genName(
  28709. resultItem.coordDim,
  28710. dataDimNameMap
  28711. ));
  28712. if (resultItem.type == null
  28713. && (
  28714. guessOrdinal(source, resultDimIdx, resultItem.name) === BE_ORDINAL.Must
  28715. // Consider the case:
  28716. // {
  28717. // dataset: {source: [
  28718. // ['2001', 123],
  28719. // ['2002', 456],
  28720. // ...
  28721. // ['The others', 987],
  28722. // ]},
  28723. // series: {type: 'pie'}
  28724. // }
  28725. // The first colum should better be treated as a "ordinal" although it
  28726. // might not able to be detected as an "ordinal" by `guessOrdinal`.
  28727. || (resultItem.isExtraCoord
  28728. && (resultItem.otherDims.itemName != null
  28729. || resultItem.otherDims.seriesName != null
  28730. )
  28731. )
  28732. )
  28733. ) {
  28734. resultItem.type = 'ordinal';
  28735. }
  28736. }
  28737. return result;
  28738. }
  28739. // ??? TODO
  28740. // Originally detect dimCount by data[0]. Should we
  28741. // optimize it to only by sysDims and dimensions and encode.
  28742. // So only necessary dims will be initialized.
  28743. // But
  28744. // (1) custom series should be considered. where other dims
  28745. // may be visited.
  28746. // (2) sometimes user need to calcualte bubble size or use visualMap
  28747. // on other dimensions besides coordSys needed.
  28748. // So, dims that is not used by system, should be shared in storage?
  28749. function getDimCount(source, sysDims, dimsDef, optDimCount) {
  28750. // Note that the result dimCount should not small than columns count
  28751. // of data, otherwise `dataDimNameMap` checking will be incorrect.
  28752. var dimCount = Math.max(
  28753. source.dimensionsDetectCount || 1,
  28754. sysDims.length,
  28755. dimsDef.length,
  28756. optDimCount || 0
  28757. );
  28758. each$1(sysDims, function (sysDimItem) {
  28759. var sysDimItemDimsDef = sysDimItem.dimsDef;
  28760. sysDimItemDimsDef && (dimCount = Math.max(dimCount, sysDimItemDimsDef.length));
  28761. });
  28762. return dimCount;
  28763. }
  28764. function genName(name, map$$1, fromZero) {
  28765. if (fromZero || map$$1.get(name) != null) {
  28766. var i = 0;
  28767. while (map$$1.get(name + i) != null) {
  28768. i++;
  28769. }
  28770. name += i;
  28771. }
  28772. map$$1.set(name, true);
  28773. return name;
  28774. }
  28775. /*
  28776. * Licensed to the Apache Software Foundation (ASF) under one
  28777. * or more contributor license agreements. See the NOTICE file
  28778. * distributed with this work for additional information
  28779. * regarding copyright ownership. The ASF licenses this file
  28780. * to you under the Apache License, Version 2.0 (the
  28781. * "License"); you may not use this file except in compliance
  28782. * with the License. You may obtain a copy of the License at
  28783. *
  28784. * http://www.apache.org/licenses/LICENSE-2.0
  28785. *
  28786. * Unless required by applicable law or agreed to in writing,
  28787. * software distributed under the License is distributed on an
  28788. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28789. * KIND, either express or implied. See the License for the
  28790. * specific language governing permissions and limitations
  28791. * under the License.
  28792. */
  28793. /**
  28794. * Substitute `completeDimensions`.
  28795. * `completeDimensions` is to be deprecated.
  28796. */
  28797. /**
  28798. * @param {module:echarts/data/Source|module:echarts/data/List} source or data.
  28799. * @param {Object|Array} [opt]
  28800. * @param {Array.<string|Object>} [opt.coordDimensions=[]]
  28801. * @param {number} [opt.dimensionsCount]
  28802. * @param {string} [opt.generateCoord]
  28803. * @param {string} [opt.generateCoordCount]
  28804. * @param {Array.<string|Object>} [opt.dimensionsDefine=source.dimensionsDefine] Overwrite source define.
  28805. * @param {Object|HashMap} [opt.encodeDefine=source.encodeDefine] Overwrite source define.
  28806. * @param {Function} [opt.encodeDefaulter] Make default encode if user not specified.
  28807. * @return {Array.<Object>} dimensionsInfo
  28808. */
  28809. var createDimensions = function (source, opt) {
  28810. opt = opt || {};
  28811. return completeDimensions(opt.coordDimensions || [], source, {
  28812. dimsDef: opt.dimensionsDefine || source.dimensionsDefine,
  28813. encodeDef: opt.encodeDefine || source.encodeDefine,
  28814. dimCount: opt.dimensionsCount,
  28815. encodeDefaulter: opt.encodeDefaulter,
  28816. generateCoord: opt.generateCoord,
  28817. generateCoordCount: opt.generateCoordCount
  28818. });
  28819. };
  28820. /*
  28821. * Licensed to the Apache Software Foundation (ASF) under one
  28822. * or more contributor license agreements. See the NOTICE file
  28823. * distributed with this work for additional information
  28824. * regarding copyright ownership. The ASF licenses this file
  28825. * to you under the Apache License, Version 2.0 (the
  28826. * "License"); you may not use this file except in compliance
  28827. * with the License. You may obtain a copy of the License at
  28828. *
  28829. * http://www.apache.org/licenses/LICENSE-2.0
  28830. *
  28831. * Unless required by applicable law or agreed to in writing,
  28832. * software distributed under the License is distributed on an
  28833. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28834. * KIND, either express or implied. See the License for the
  28835. * specific language governing permissions and limitations
  28836. * under the License.
  28837. */
  28838. /**
  28839. * Helper for model references.
  28840. * There are many manners to refer axis/coordSys.
  28841. */
  28842. // TODO
  28843. // merge relevant logic to this file?
  28844. // check: "modelHelper" of tooltip and "BrushTargetManager".
  28845. /**
  28846. * @class
  28847. * For example:
  28848. * {
  28849. * coordSysName: 'cartesian2d',
  28850. * coordSysDims: ['x', 'y', ...],
  28851. * axisMap: HashMap({
  28852. * x: xAxisModel,
  28853. * y: yAxisModel
  28854. * }),
  28855. * categoryAxisMap: HashMap({
  28856. * x: xAxisModel,
  28857. * y: undefined
  28858. * }),
  28859. * // The index of the first category axis in `coordSysDims`.
  28860. * // `null/undefined` means no category axis exists.
  28861. * firstCategoryDimIndex: 1,
  28862. * // To replace user specified encode.
  28863. * }
  28864. */
  28865. function CoordSysInfo(coordSysName) {
  28866. /**
  28867. * @type {string}
  28868. */
  28869. this.coordSysName = coordSysName;
  28870. /**
  28871. * @type {Array.<string>}
  28872. */
  28873. this.coordSysDims = [];
  28874. /**
  28875. * @type {module:zrender/core/util#HashMap}
  28876. */
  28877. this.axisMap = createHashMap();
  28878. /**
  28879. * @type {module:zrender/core/util#HashMap}
  28880. */
  28881. this.categoryAxisMap = createHashMap();
  28882. /**
  28883. * @type {number}
  28884. */
  28885. this.firstCategoryDimIndex = null;
  28886. }
  28887. /**
  28888. * @return {module:model/referHelper#CoordSysInfo}
  28889. */
  28890. function getCoordSysInfoBySeries(seriesModel) {
  28891. var coordSysName = seriesModel.get('coordinateSystem');
  28892. var result = new CoordSysInfo(coordSysName);
  28893. var fetch = fetchers[coordSysName];
  28894. if (fetch) {
  28895. fetch(seriesModel, result, result.axisMap, result.categoryAxisMap);
  28896. return result;
  28897. }
  28898. }
  28899. var fetchers = {
  28900. cartesian2d: function (seriesModel, result, axisMap, categoryAxisMap) {
  28901. var xAxisModel = seriesModel.getReferringComponents('xAxis')[0];
  28902. var yAxisModel = seriesModel.getReferringComponents('yAxis')[0];
  28903. if (__DEV__) {
  28904. if (!xAxisModel) {
  28905. throw new Error('xAxis "' + retrieve(
  28906. seriesModel.get('xAxisIndex'),
  28907. seriesModel.get('xAxisId'),
  28908. 0
  28909. ) + '" not found');
  28910. }
  28911. if (!yAxisModel) {
  28912. throw new Error('yAxis "' + retrieve(
  28913. seriesModel.get('xAxisIndex'),
  28914. seriesModel.get('yAxisId'),
  28915. 0
  28916. ) + '" not found');
  28917. }
  28918. }
  28919. result.coordSysDims = ['x', 'y'];
  28920. axisMap.set('x', xAxisModel);
  28921. axisMap.set('y', yAxisModel);
  28922. if (isCategory(xAxisModel)) {
  28923. categoryAxisMap.set('x', xAxisModel);
  28924. result.firstCategoryDimIndex = 0;
  28925. }
  28926. if (isCategory(yAxisModel)) {
  28927. categoryAxisMap.set('y', yAxisModel);
  28928. result.firstCategoryDimIndex == null & (result.firstCategoryDimIndex = 1);
  28929. }
  28930. },
  28931. singleAxis: function (seriesModel, result, axisMap, categoryAxisMap) {
  28932. var singleAxisModel = seriesModel.getReferringComponents('singleAxis')[0];
  28933. if (__DEV__) {
  28934. if (!singleAxisModel) {
  28935. throw new Error('singleAxis should be specified.');
  28936. }
  28937. }
  28938. result.coordSysDims = ['single'];
  28939. axisMap.set('single', singleAxisModel);
  28940. if (isCategory(singleAxisModel)) {
  28941. categoryAxisMap.set('single', singleAxisModel);
  28942. result.firstCategoryDimIndex = 0;
  28943. }
  28944. },
  28945. polar: function (seriesModel, result, axisMap, categoryAxisMap) {
  28946. var polarModel = seriesModel.getReferringComponents('polar')[0];
  28947. var radiusAxisModel = polarModel.findAxisModel('radiusAxis');
  28948. var angleAxisModel = polarModel.findAxisModel('angleAxis');
  28949. if (__DEV__) {
  28950. if (!angleAxisModel) {
  28951. throw new Error('angleAxis option not found');
  28952. }
  28953. if (!radiusAxisModel) {
  28954. throw new Error('radiusAxis option not found');
  28955. }
  28956. }
  28957. result.coordSysDims = ['radius', 'angle'];
  28958. axisMap.set('radius', radiusAxisModel);
  28959. axisMap.set('angle', angleAxisModel);
  28960. if (isCategory(radiusAxisModel)) {
  28961. categoryAxisMap.set('radius', radiusAxisModel);
  28962. result.firstCategoryDimIndex = 0;
  28963. }
  28964. if (isCategory(angleAxisModel)) {
  28965. categoryAxisMap.set('angle', angleAxisModel);
  28966. result.firstCategoryDimIndex == null && (result.firstCategoryDimIndex = 1);
  28967. }
  28968. },
  28969. geo: function (seriesModel, result, axisMap, categoryAxisMap) {
  28970. result.coordSysDims = ['lng', 'lat'];
  28971. },
  28972. parallel: function (seriesModel, result, axisMap, categoryAxisMap) {
  28973. var ecModel = seriesModel.ecModel;
  28974. var parallelModel = ecModel.getComponent(
  28975. 'parallel', seriesModel.get('parallelIndex')
  28976. );
  28977. var coordSysDims = result.coordSysDims = parallelModel.dimensions.slice();
  28978. each$1(parallelModel.parallelAxisIndex, function (axisIndex, index) {
  28979. var axisModel = ecModel.getComponent('parallelAxis', axisIndex);
  28980. var axisDim = coordSysDims[index];
  28981. axisMap.set(axisDim, axisModel);
  28982. if (isCategory(axisModel) && result.firstCategoryDimIndex == null) {
  28983. categoryAxisMap.set(axisDim, axisModel);
  28984. result.firstCategoryDimIndex = index;
  28985. }
  28986. });
  28987. }
  28988. };
  28989. function isCategory(axisModel) {
  28990. return axisModel.get('type') === 'category';
  28991. }
  28992. /*
  28993. * Licensed to the Apache Software Foundation (ASF) under one
  28994. * or more contributor license agreements. See the NOTICE file
  28995. * distributed with this work for additional information
  28996. * regarding copyright ownership. The ASF licenses this file
  28997. * to you under the Apache License, Version 2.0 (the
  28998. * "License"); you may not use this file except in compliance
  28999. * with the License. You may obtain a copy of the License at
  29000. *
  29001. * http://www.apache.org/licenses/LICENSE-2.0
  29002. *
  29003. * Unless required by applicable law or agreed to in writing,
  29004. * software distributed under the License is distributed on an
  29005. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29006. * KIND, either express or implied. See the License for the
  29007. * specific language governing permissions and limitations
  29008. * under the License.
  29009. */
  29010. /**
  29011. * Note that it is too complicated to support 3d stack by value
  29012. * (have to create two-dimension inverted index), so in 3d case
  29013. * we just support that stacked by index.
  29014. *
  29015. * @param {module:echarts/model/Series} seriesModel
  29016. * @param {Array.<string|Object>} dimensionInfoList The same as the input of <module:echarts/data/List>.
  29017. * The input dimensionInfoList will be modified.
  29018. * @param {Object} [opt]
  29019. * @param {boolean} [opt.stackedCoordDimension=''] Specify a coord dimension if needed.
  29020. * @param {boolean} [opt.byIndex=false]
  29021. * @return {Object} calculationInfo
  29022. * {
  29023. * stackedDimension: string
  29024. * stackedByDimension: string
  29025. * isStackedByIndex: boolean
  29026. * stackedOverDimension: string
  29027. * stackResultDimension: string
  29028. * }
  29029. */
  29030. function enableDataStack(seriesModel, dimensionInfoList, opt) {
  29031. opt = opt || {};
  29032. var byIndex = opt.byIndex;
  29033. var stackedCoordDimension = opt.stackedCoordDimension;
  29034. // Compatibal: when `stack` is set as '', do not stack.
  29035. var mayStack = !!(seriesModel && seriesModel.get('stack'));
  29036. var stackedByDimInfo;
  29037. var stackedDimInfo;
  29038. var stackResultDimension;
  29039. var stackedOverDimension;
  29040. each$1(dimensionInfoList, function (dimensionInfo, index) {
  29041. if (isString(dimensionInfo)) {
  29042. dimensionInfoList[index] = dimensionInfo = {name: dimensionInfo};
  29043. }
  29044. if (mayStack && !dimensionInfo.isExtraCoord) {
  29045. // Find the first ordinal dimension as the stackedByDimInfo.
  29046. if (!byIndex && !stackedByDimInfo && dimensionInfo.ordinalMeta) {
  29047. stackedByDimInfo = dimensionInfo;
  29048. }
  29049. // Find the first stackable dimension as the stackedDimInfo.
  29050. if (!stackedDimInfo
  29051. && dimensionInfo.type !== 'ordinal'
  29052. && dimensionInfo.type !== 'time'
  29053. && (!stackedCoordDimension || stackedCoordDimension === dimensionInfo.coordDim)
  29054. ) {
  29055. stackedDimInfo = dimensionInfo;
  29056. }
  29057. }
  29058. });
  29059. if (stackedDimInfo && !byIndex && !stackedByDimInfo) {
  29060. // Compatible with previous design, value axis (time axis) only stack by index.
  29061. // It may make sense if the user provides elaborately constructed data.
  29062. byIndex = true;
  29063. }
  29064. // Add stack dimension, they can be both calculated by coordinate system in `unionExtent`.
  29065. // That put stack logic in List is for using conveniently in echarts extensions, but it
  29066. // might not be a good way.
  29067. if (stackedDimInfo) {
  29068. // Use a weird name that not duplicated with other names.
  29069. stackResultDimension = '__\0ecstackresult';
  29070. stackedOverDimension = '__\0ecstackedover';
  29071. // Create inverted index to fast query index by value.
  29072. if (stackedByDimInfo) {
  29073. stackedByDimInfo.createInvertedIndices = true;
  29074. }
  29075. var stackedDimCoordDim = stackedDimInfo.coordDim;
  29076. var stackedDimType = stackedDimInfo.type;
  29077. var stackedDimCoordIndex = 0;
  29078. each$1(dimensionInfoList, function (dimensionInfo) {
  29079. if (dimensionInfo.coordDim === stackedDimCoordDim) {
  29080. stackedDimCoordIndex++;
  29081. }
  29082. });
  29083. dimensionInfoList.push({
  29084. name: stackResultDimension,
  29085. coordDim: stackedDimCoordDim,
  29086. coordDimIndex: stackedDimCoordIndex,
  29087. type: stackedDimType,
  29088. isExtraCoord: true,
  29089. isCalculationCoord: true
  29090. });
  29091. stackedDimCoordIndex++;
  29092. dimensionInfoList.push({
  29093. name: stackedOverDimension,
  29094. // This dimension contains stack base (generally, 0), so do not set it as
  29095. // `stackedDimCoordDim` to avoid extent calculation, consider log scale.
  29096. coordDim: stackedOverDimension,
  29097. coordDimIndex: stackedDimCoordIndex,
  29098. type: stackedDimType,
  29099. isExtraCoord: true,
  29100. isCalculationCoord: true
  29101. });
  29102. }
  29103. return {
  29104. stackedDimension: stackedDimInfo && stackedDimInfo.name,
  29105. stackedByDimension: stackedByDimInfo && stackedByDimInfo.name,
  29106. isStackedByIndex: byIndex,
  29107. stackedOverDimension: stackedOverDimension,
  29108. stackResultDimension: stackResultDimension
  29109. };
  29110. }
  29111. /**
  29112. * @param {module:echarts/data/List} data
  29113. * @param {string} stackedDim
  29114. */
  29115. function isDimensionStacked(data, stackedDim /*, stackedByDim*/) {
  29116. // Each single series only maps to one pair of axis. So we do not need to
  29117. // check stackByDim, whatever stacked by a dimension or stacked by index.
  29118. return !!stackedDim && stackedDim === data.getCalculationInfo('stackedDimension');
  29119. // && (
  29120. // stackedByDim != null
  29121. // ? stackedByDim === data.getCalculationInfo('stackedByDimension')
  29122. // : data.getCalculationInfo('isStackedByIndex')
  29123. // );
  29124. }
  29125. /**
  29126. * @param {module:echarts/data/List} data
  29127. * @param {string} targetDim
  29128. * @param {string} [stackedByDim] If not input this parameter, check whether
  29129. * stacked by index.
  29130. * @return {string} dimension
  29131. */
  29132. function getStackedDimension(data, targetDim) {
  29133. return isDimensionStacked(data, targetDim)
  29134. ? data.getCalculationInfo('stackResultDimension')
  29135. : targetDim;
  29136. }
  29137. /*
  29138. * Licensed to the Apache Software Foundation (ASF) under one
  29139. * or more contributor license agreements. See the NOTICE file
  29140. * distributed with this work for additional information
  29141. * regarding copyright ownership. The ASF licenses this file
  29142. * to you under the Apache License, Version 2.0 (the
  29143. * "License"); you may not use this file except in compliance
  29144. * with the License. You may obtain a copy of the License at
  29145. *
  29146. * http://www.apache.org/licenses/LICENSE-2.0
  29147. *
  29148. * Unless required by applicable law or agreed to in writing,
  29149. * software distributed under the License is distributed on an
  29150. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29151. * KIND, either express or implied. See the License for the
  29152. * specific language governing permissions and limitations
  29153. * under the License.
  29154. */
  29155. /**
  29156. * @param {module:echarts/data/Source|Array} source Or raw data.
  29157. * @param {module:echarts/model/Series} seriesModel
  29158. * @param {Object} [opt]
  29159. * @param {string} [opt.generateCoord]
  29160. * @param {boolean} [opt.useEncodeDefaulter]
  29161. */
  29162. function createListFromArray(source, seriesModel, opt) {
  29163. opt = opt || {};
  29164. if (!Source.isInstance(source)) {
  29165. source = Source.seriesDataToSource(source);
  29166. }
  29167. var coordSysName = seriesModel.get('coordinateSystem');
  29168. var registeredCoordSys = CoordinateSystemManager.get(coordSysName);
  29169. var coordSysInfo = getCoordSysInfoBySeries(seriesModel);
  29170. var coordSysDimDefs;
  29171. if (coordSysInfo) {
  29172. coordSysDimDefs = map(coordSysInfo.coordSysDims, function (dim) {
  29173. var dimInfo = {name: dim};
  29174. var axisModel = coordSysInfo.axisMap.get(dim);
  29175. if (axisModel) {
  29176. var axisType = axisModel.get('type');
  29177. dimInfo.type = getDimensionTypeByAxis(axisType);
  29178. // dimInfo.stackable = isStackable(axisType);
  29179. }
  29180. return dimInfo;
  29181. });
  29182. }
  29183. if (!coordSysDimDefs) {
  29184. // Get dimensions from registered coordinate system
  29185. coordSysDimDefs = (registeredCoordSys && (
  29186. registeredCoordSys.getDimensionsInfo
  29187. ? registeredCoordSys.getDimensionsInfo()
  29188. : registeredCoordSys.dimensions.slice()
  29189. )) || ['x', 'y'];
  29190. }
  29191. var dimInfoList = createDimensions(source, {
  29192. coordDimensions: coordSysDimDefs,
  29193. generateCoord: opt.generateCoord,
  29194. encodeDefaulter: opt.useEncodeDefaulter
  29195. ? curry(makeSeriesEncodeForAxisCoordSys, coordSysDimDefs, seriesModel)
  29196. : null
  29197. });
  29198. var firstCategoryDimIndex;
  29199. var hasNameEncode;
  29200. coordSysInfo && each$1(dimInfoList, function (dimInfo, dimIndex) {
  29201. var coordDim = dimInfo.coordDim;
  29202. var categoryAxisModel = coordSysInfo.categoryAxisMap.get(coordDim);
  29203. if (categoryAxisModel) {
  29204. if (firstCategoryDimIndex == null) {
  29205. firstCategoryDimIndex = dimIndex;
  29206. }
  29207. dimInfo.ordinalMeta = categoryAxisModel.getOrdinalMeta();
  29208. }
  29209. if (dimInfo.otherDims.itemName != null) {
  29210. hasNameEncode = true;
  29211. }
  29212. });
  29213. if (!hasNameEncode && firstCategoryDimIndex != null) {
  29214. dimInfoList[firstCategoryDimIndex].otherDims.itemName = 0;
  29215. }
  29216. var stackCalculationInfo = enableDataStack(seriesModel, dimInfoList);
  29217. var list = new List(dimInfoList, seriesModel);
  29218. list.setCalculationInfo(stackCalculationInfo);
  29219. var dimValueGetter = (firstCategoryDimIndex != null && isNeedCompleteOrdinalData(source))
  29220. ? function (itemOpt, dimName, dataIndex, dimIndex) {
  29221. // Use dataIndex as ordinal value in categoryAxis
  29222. return dimIndex === firstCategoryDimIndex
  29223. ? dataIndex
  29224. : this.defaultDimValueGetter(itemOpt, dimName, dataIndex, dimIndex);
  29225. }
  29226. : null;
  29227. list.hasItemOption = false;
  29228. list.initData(source, null, dimValueGetter);
  29229. return list;
  29230. }
  29231. function isNeedCompleteOrdinalData(source) {
  29232. if (source.sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  29233. var sampleItem = firstDataNotNull(source.data || []);
  29234. return sampleItem != null
  29235. && !isArray(getDataItemValue(sampleItem));
  29236. }
  29237. }
  29238. function firstDataNotNull(data) {
  29239. var i = 0;
  29240. while (i < data.length && data[i] == null) {
  29241. i++;
  29242. }
  29243. return data[i];
  29244. }
  29245. /*
  29246. * Licensed to the Apache Software Foundation (ASF) under one
  29247. * or more contributor license agreements. See the NOTICE file
  29248. * distributed with this work for additional information
  29249. * regarding copyright ownership. The ASF licenses this file
  29250. * to you under the Apache License, Version 2.0 (the
  29251. * "License"); you may not use this file except in compliance
  29252. * with the License. You may obtain a copy of the License at
  29253. *
  29254. * http://www.apache.org/licenses/LICENSE-2.0
  29255. *
  29256. * Unless required by applicable law or agreed to in writing,
  29257. * software distributed under the License is distributed on an
  29258. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29259. * KIND, either express or implied. See the License for the
  29260. * specific language governing permissions and limitations
  29261. * under the License.
  29262. */
  29263. /**
  29264. * // Scale class management
  29265. * @module echarts/scale/Scale
  29266. */
  29267. /**
  29268. * @param {Object} [setting]
  29269. */
  29270. function Scale(setting) {
  29271. this._setting = setting || {};
  29272. /**
  29273. * Extent
  29274. * @type {Array.<number>}
  29275. * @protected
  29276. */
  29277. this._extent = [Infinity, -Infinity];
  29278. /**
  29279. * Step is calculated in adjustExtent
  29280. * @type {Array.<number>}
  29281. * @protected
  29282. */
  29283. this._interval = 0;
  29284. this.init && this.init.apply(this, arguments);
  29285. }
  29286. /**
  29287. * Parse input val to valid inner number.
  29288. * @param {*} val
  29289. * @return {number}
  29290. */
  29291. Scale.prototype.parse = function (val) {
  29292. // Notice: This would be a trap here, If the implementation
  29293. // of this method depends on extent, and this method is used
  29294. // before extent set (like in dataZoom), it would be wrong.
  29295. // Nevertheless, parse does not depend on extent generally.
  29296. return val;
  29297. };
  29298. Scale.prototype.getSetting = function (name) {
  29299. return this._setting[name];
  29300. };
  29301. Scale.prototype.contain = function (val) {
  29302. var extent = this._extent;
  29303. return val >= extent[0] && val <= extent[1];
  29304. };
  29305. /**
  29306. * Normalize value to linear [0, 1], return 0.5 if extent span is 0
  29307. * @param {number} val
  29308. * @return {number}
  29309. */
  29310. Scale.prototype.normalize = function (val) {
  29311. var extent = this._extent;
  29312. if (extent[1] === extent[0]) {
  29313. return 0.5;
  29314. }
  29315. return (val - extent[0]) / (extent[1] - extent[0]);
  29316. };
  29317. /**
  29318. * Scale normalized value
  29319. * @param {number} val
  29320. * @return {number}
  29321. */
  29322. Scale.prototype.scale = function (val) {
  29323. var extent = this._extent;
  29324. return val * (extent[1] - extent[0]) + extent[0];
  29325. };
  29326. /**
  29327. * Set extent from data
  29328. * @param {Array.<number>} other
  29329. */
  29330. Scale.prototype.unionExtent = function (other) {
  29331. var extent = this._extent;
  29332. other[0] < extent[0] && (extent[0] = other[0]);
  29333. other[1] > extent[1] && (extent[1] = other[1]);
  29334. // not setExtent because in log axis it may transformed to power
  29335. // this.setExtent(extent[0], extent[1]);
  29336. };
  29337. /**
  29338. * Set extent from data
  29339. * @param {module:echarts/data/List} data
  29340. * @param {string} dim
  29341. */
  29342. Scale.prototype.unionExtentFromData = function (data, dim) {
  29343. this.unionExtent(data.getApproximateExtent(dim));
  29344. };
  29345. /**
  29346. * Get extent
  29347. * @return {Array.<number>}
  29348. */
  29349. Scale.prototype.getExtent = function () {
  29350. return this._extent.slice();
  29351. };
  29352. /**
  29353. * Set extent
  29354. * @param {number} start
  29355. * @param {number} end
  29356. */
  29357. Scale.prototype.setExtent = function (start, end) {
  29358. var thisExtent = this._extent;
  29359. if (!isNaN(start)) {
  29360. thisExtent[0] = start;
  29361. }
  29362. if (!isNaN(end)) {
  29363. thisExtent[1] = end;
  29364. }
  29365. };
  29366. /**
  29367. * When axis extent depends on data and no data exists,
  29368. * axis ticks should not be drawn, which is named 'blank'.
  29369. */
  29370. Scale.prototype.isBlank = function () {
  29371. return this._isBlank;
  29372. },
  29373. /**
  29374. * When axis extent depends on data and no data exists,
  29375. * axis ticks should not be drawn, which is named 'blank'.
  29376. */
  29377. Scale.prototype.setBlank = function (isBlank) {
  29378. this._isBlank = isBlank;
  29379. };
  29380. /**
  29381. * @abstract
  29382. * @param {*} tick
  29383. * @return {string} label of the tick.
  29384. */
  29385. Scale.prototype.getLabel = null;
  29386. enableClassExtend(Scale);
  29387. enableClassManagement(Scale, {
  29388. registerWhenExtend: true
  29389. });
  29390. /*
  29391. * Licensed to the Apache Software Foundation (ASF) under one
  29392. * or more contributor license agreements. See the NOTICE file
  29393. * distributed with this work for additional information
  29394. * regarding copyright ownership. The ASF licenses this file
  29395. * to you under the Apache License, Version 2.0 (the
  29396. * "License"); you may not use this file except in compliance
  29397. * with the License. You may obtain a copy of the License at
  29398. *
  29399. * http://www.apache.org/licenses/LICENSE-2.0
  29400. *
  29401. * Unless required by applicable law or agreed to in writing,
  29402. * software distributed under the License is distributed on an
  29403. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29404. * KIND, either express or implied. See the License for the
  29405. * specific language governing permissions and limitations
  29406. * under the License.
  29407. */
  29408. /**
  29409. * @constructor
  29410. * @param {Object} [opt]
  29411. * @param {Object} [opt.categories=[]]
  29412. * @param {Object} [opt.needCollect=false]
  29413. * @param {Object} [opt.deduplication=false]
  29414. */
  29415. function OrdinalMeta(opt) {
  29416. /**
  29417. * @readOnly
  29418. * @type {Array.<string>}
  29419. */
  29420. this.categories = opt.categories || [];
  29421. /**
  29422. * @private
  29423. * @type {boolean}
  29424. */
  29425. this._needCollect = opt.needCollect;
  29426. /**
  29427. * @private
  29428. * @type {boolean}
  29429. */
  29430. this._deduplication = opt.deduplication;
  29431. /**
  29432. * @private
  29433. * @type {boolean}
  29434. */
  29435. this._map;
  29436. }
  29437. /**
  29438. * @param {module:echarts/model/Model} axisModel
  29439. * @return {module:echarts/data/OrdinalMeta}
  29440. */
  29441. OrdinalMeta.createByAxisModel = function (axisModel) {
  29442. var option = axisModel.option;
  29443. var data = option.data;
  29444. var categories = data && map(data, getName);
  29445. return new OrdinalMeta({
  29446. categories: categories,
  29447. needCollect: !categories,
  29448. // deduplication is default in axis.
  29449. deduplication: option.dedplication !== false
  29450. });
  29451. };
  29452. var proto$1 = OrdinalMeta.prototype;
  29453. /**
  29454. * @param {string} category
  29455. * @return {number} ordinal
  29456. */
  29457. proto$1.getOrdinal = function (category) {
  29458. return getOrCreateMap(this).get(category);
  29459. };
  29460. /**
  29461. * @param {*} category
  29462. * @return {number} The ordinal. If not found, return NaN.
  29463. */
  29464. proto$1.parseAndCollect = function (category) {
  29465. var index;
  29466. var needCollect = this._needCollect;
  29467. // The value of category dim can be the index of the given category set.
  29468. // This feature is only supported when !needCollect, because we should
  29469. // consider a common case: a value is 2017, which is a number but is
  29470. // expected to be tread as a category. This case usually happen in dataset,
  29471. // where it happent to be no need of the index feature.
  29472. if (typeof category !== 'string' && !needCollect) {
  29473. return category;
  29474. }
  29475. // Optimize for the scenario:
  29476. // category is ['2012-01-01', '2012-01-02', ...], where the input
  29477. // data has been ensured not duplicate and is large data.
  29478. // Notice, if a dataset dimension provide categroies, usually echarts
  29479. // should remove duplication except user tell echarts dont do that
  29480. // (set axis.deduplication = false), because echarts do not know whether
  29481. // the values in the category dimension has duplication (consider the
  29482. // parallel-aqi example)
  29483. if (needCollect && !this._deduplication) {
  29484. index = this.categories.length;
  29485. this.categories[index] = category;
  29486. return index;
  29487. }
  29488. var map$$1 = getOrCreateMap(this);
  29489. index = map$$1.get(category);
  29490. if (index == null) {
  29491. if (needCollect) {
  29492. index = this.categories.length;
  29493. this.categories[index] = category;
  29494. map$$1.set(category, index);
  29495. }
  29496. else {
  29497. index = NaN;
  29498. }
  29499. }
  29500. return index;
  29501. };
  29502. // Consider big data, do not create map until needed.
  29503. function getOrCreateMap(ordinalMeta) {
  29504. return ordinalMeta._map || (
  29505. ordinalMeta._map = createHashMap(ordinalMeta.categories)
  29506. );
  29507. }
  29508. function getName(obj) {
  29509. if (isObject$1(obj) && obj.value != null) {
  29510. return obj.value;
  29511. }
  29512. else {
  29513. return obj + '';
  29514. }
  29515. }
  29516. /*
  29517. * Licensed to the Apache Software Foundation (ASF) under one
  29518. * or more contributor license agreements. See the NOTICE file
  29519. * distributed with this work for additional information
  29520. * regarding copyright ownership. The ASF licenses this file
  29521. * to you under the Apache License, Version 2.0 (the
  29522. * "License"); you may not use this file except in compliance
  29523. * with the License. You may obtain a copy of the License at
  29524. *
  29525. * http://www.apache.org/licenses/LICENSE-2.0
  29526. *
  29527. * Unless required by applicable law or agreed to in writing,
  29528. * software distributed under the License is distributed on an
  29529. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29530. * KIND, either express or implied. See the License for the
  29531. * specific language governing permissions and limitations
  29532. * under the License.
  29533. */
  29534. /**
  29535. * Linear continuous scale
  29536. * @module echarts/coord/scale/Ordinal
  29537. *
  29538. * http://en.wikipedia.org/wiki/Level_of_measurement
  29539. */
  29540. // FIXME only one data
  29541. var scaleProto = Scale.prototype;
  29542. var OrdinalScale = Scale.extend({
  29543. type: 'ordinal',
  29544. /**
  29545. * @param {module:echarts/data/OrdianlMeta|Array.<string>} ordinalMeta
  29546. */
  29547. init: function (ordinalMeta, extent) {
  29548. // Caution: Should not use instanceof, consider ec-extensions using
  29549. // import approach to get OrdinalMeta class.
  29550. if (!ordinalMeta || isArray(ordinalMeta)) {
  29551. ordinalMeta = new OrdinalMeta({categories: ordinalMeta});
  29552. }
  29553. this._ordinalMeta = ordinalMeta;
  29554. this._extent = extent || [0, ordinalMeta.categories.length - 1];
  29555. },
  29556. parse: function (val) {
  29557. return typeof val === 'string'
  29558. ? this._ordinalMeta.getOrdinal(val)
  29559. // val might be float.
  29560. : Math.round(val);
  29561. },
  29562. contain: function (rank) {
  29563. rank = this.parse(rank);
  29564. return scaleProto.contain.call(this, rank)
  29565. && this._ordinalMeta.categories[rank] != null;
  29566. },
  29567. /**
  29568. * Normalize given rank or name to linear [0, 1]
  29569. * @param {number|string} [val]
  29570. * @return {number}
  29571. */
  29572. normalize: function (val) {
  29573. return scaleProto.normalize.call(this, this.parse(val));
  29574. },
  29575. scale: function (val) {
  29576. return Math.round(scaleProto.scale.call(this, val));
  29577. },
  29578. /**
  29579. * @return {Array}
  29580. */
  29581. getTicks: function () {
  29582. var ticks = [];
  29583. var extent = this._extent;
  29584. var rank = extent[0];
  29585. while (rank <= extent[1]) {
  29586. ticks.push(rank);
  29587. rank++;
  29588. }
  29589. return ticks;
  29590. },
  29591. /**
  29592. * Get item on rank n
  29593. * @param {number} n
  29594. * @return {string}
  29595. */
  29596. getLabel: function (n) {
  29597. if (!this.isBlank()) {
  29598. // Note that if no data, ordinalMeta.categories is an empty array.
  29599. return this._ordinalMeta.categories[n];
  29600. }
  29601. },
  29602. /**
  29603. * @return {number}
  29604. */
  29605. count: function () {
  29606. return this._extent[1] - this._extent[0] + 1;
  29607. },
  29608. /**
  29609. * @override
  29610. */
  29611. unionExtentFromData: function (data, dim) {
  29612. this.unionExtent(data.getApproximateExtent(dim));
  29613. },
  29614. getOrdinalMeta: function () {
  29615. return this._ordinalMeta;
  29616. },
  29617. niceTicks: noop,
  29618. niceExtent: noop
  29619. });
  29620. /**
  29621. * @return {module:echarts/scale/Time}
  29622. */
  29623. OrdinalScale.create = function () {
  29624. return new OrdinalScale();
  29625. };
  29626. /*
  29627. * Licensed to the Apache Software Foundation (ASF) under one
  29628. * or more contributor license agreements. See the NOTICE file
  29629. * distributed with this work for additional information
  29630. * regarding copyright ownership. The ASF licenses this file
  29631. * to you under the Apache License, Version 2.0 (the
  29632. * "License"); you may not use this file except in compliance
  29633. * with the License. You may obtain a copy of the License at
  29634. *
  29635. * http://www.apache.org/licenses/LICENSE-2.0
  29636. *
  29637. * Unless required by applicable law or agreed to in writing,
  29638. * software distributed under the License is distributed on an
  29639. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29640. * KIND, either express or implied. See the License for the
  29641. * specific language governing permissions and limitations
  29642. * under the License.
  29643. */
  29644. /**
  29645. * For testable.
  29646. */
  29647. var roundNumber$1 = round$1;
  29648. /**
  29649. * @param {Array.<number>} extent Both extent[0] and extent[1] should be valid number.
  29650. * Should be extent[0] < extent[1].
  29651. * @param {number} splitNumber splitNumber should be >= 1.
  29652. * @param {number} [minInterval]
  29653. * @param {number} [maxInterval]
  29654. * @return {Object} {interval, intervalPrecision, niceTickExtent}
  29655. */
  29656. function intervalScaleNiceTicks(extent, splitNumber, minInterval, maxInterval) {
  29657. var result = {};
  29658. var span = extent[1] - extent[0];
  29659. var interval = result.interval = nice(span / splitNumber, true);
  29660. if (minInterval != null && interval < minInterval) {
  29661. interval = result.interval = minInterval;
  29662. }
  29663. if (maxInterval != null && interval > maxInterval) {
  29664. interval = result.interval = maxInterval;
  29665. }
  29666. // Tow more digital for tick.
  29667. var precision = result.intervalPrecision = getIntervalPrecision(interval);
  29668. // Niced extent inside original extent
  29669. var niceTickExtent = result.niceTickExtent = [
  29670. roundNumber$1(Math.ceil(extent[0] / interval) * interval, precision),
  29671. roundNumber$1(Math.floor(extent[1] / interval) * interval, precision)
  29672. ];
  29673. fixExtent(niceTickExtent, extent);
  29674. return result;
  29675. }
  29676. /**
  29677. * @param {number} interval
  29678. * @return {number} interval precision
  29679. */
  29680. function getIntervalPrecision(interval) {
  29681. // Tow more digital for tick.
  29682. return getPrecisionSafe(interval) + 2;
  29683. }
  29684. function clamp(niceTickExtent, idx, extent) {
  29685. niceTickExtent[idx] = Math.max(Math.min(niceTickExtent[idx], extent[1]), extent[0]);
  29686. }
  29687. // In some cases (e.g., splitNumber is 1), niceTickExtent may be out of extent.
  29688. function fixExtent(niceTickExtent, extent) {
  29689. !isFinite(niceTickExtent[0]) && (niceTickExtent[0] = extent[0]);
  29690. !isFinite(niceTickExtent[1]) && (niceTickExtent[1] = extent[1]);
  29691. clamp(niceTickExtent, 0, extent);
  29692. clamp(niceTickExtent, 1, extent);
  29693. if (niceTickExtent[0] > niceTickExtent[1]) {
  29694. niceTickExtent[0] = niceTickExtent[1];
  29695. }
  29696. }
  29697. /*
  29698. * Licensed to the Apache Software Foundation (ASF) under one
  29699. * or more contributor license agreements. See the NOTICE file
  29700. * distributed with this work for additional information
  29701. * regarding copyright ownership. The ASF licenses this file
  29702. * to you under the Apache License, Version 2.0 (the
  29703. * "License"); you may not use this file except in compliance
  29704. * with the License. You may obtain a copy of the License at
  29705. *
  29706. * http://www.apache.org/licenses/LICENSE-2.0
  29707. *
  29708. * Unless required by applicable law or agreed to in writing,
  29709. * software distributed under the License is distributed on an
  29710. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29711. * KIND, either express or implied. See the License for the
  29712. * specific language governing permissions and limitations
  29713. * under the License.
  29714. */
  29715. /**
  29716. * Interval scale
  29717. * @module echarts/scale/Interval
  29718. */
  29719. var roundNumber = round$1;
  29720. /**
  29721. * @alias module:echarts/coord/scale/Interval
  29722. * @constructor
  29723. */
  29724. var IntervalScale = Scale.extend({
  29725. type: 'interval',
  29726. _interval: 0,
  29727. _intervalPrecision: 2,
  29728. setExtent: function (start, end) {
  29729. var thisExtent = this._extent;
  29730. //start,end may be a Number like '25',so...
  29731. if (!isNaN(start)) {
  29732. thisExtent[0] = parseFloat(start);
  29733. }
  29734. if (!isNaN(end)) {
  29735. thisExtent[1] = parseFloat(end);
  29736. }
  29737. },
  29738. unionExtent: function (other) {
  29739. var extent = this._extent;
  29740. other[0] < extent[0] && (extent[0] = other[0]);
  29741. other[1] > extent[1] && (extent[1] = other[1]);
  29742. // unionExtent may called by it's sub classes
  29743. IntervalScale.prototype.setExtent.call(this, extent[0], extent[1]);
  29744. },
  29745. /**
  29746. * Get interval
  29747. */
  29748. getInterval: function () {
  29749. return this._interval;
  29750. },
  29751. /**
  29752. * Set interval
  29753. */
  29754. setInterval: function (interval) {
  29755. this._interval = interval;
  29756. // Dropped auto calculated niceExtent and use user setted extent
  29757. // We assume user wan't to set both interval, min, max to get a better result
  29758. this._niceExtent = this._extent.slice();
  29759. this._intervalPrecision = getIntervalPrecision(interval);
  29760. },
  29761. /**
  29762. * @param {boolean} [expandToNicedExtent=false] If expand the ticks to niced extent.
  29763. * @return {Array.<number>}
  29764. */
  29765. getTicks: function (expandToNicedExtent) {
  29766. var interval = this._interval;
  29767. var extent = this._extent;
  29768. var niceTickExtent = this._niceExtent;
  29769. var intervalPrecision = this._intervalPrecision;
  29770. var ticks = [];
  29771. // If interval is 0, return [];
  29772. if (!interval) {
  29773. return ticks;
  29774. }
  29775. // Consider this case: using dataZoom toolbox, zoom and zoom.
  29776. var safeLimit = 10000;
  29777. if (extent[0] < niceTickExtent[0]) {
  29778. if (expandToNicedExtent) {
  29779. ticks.push(roundNumber(niceTickExtent[0] - interval, intervalPrecision));
  29780. }
  29781. else {
  29782. ticks.push(extent[0]);
  29783. }
  29784. }
  29785. var tick = niceTickExtent[0];
  29786. while (tick <= niceTickExtent[1]) {
  29787. ticks.push(tick);
  29788. // Avoid rounding error
  29789. tick = roundNumber(tick + interval, intervalPrecision);
  29790. if (tick === ticks[ticks.length - 1]) {
  29791. // Consider out of safe float point, e.g.,
  29792. // -3711126.9907707 + 2e-10 === -3711126.9907707
  29793. break;
  29794. }
  29795. if (ticks.length > safeLimit) {
  29796. return [];
  29797. }
  29798. }
  29799. // Consider this case: the last item of ticks is smaller
  29800. // than niceTickExtent[1] and niceTickExtent[1] === extent[1].
  29801. var lastNiceTick = ticks.length ? ticks[ticks.length - 1] : niceTickExtent[1];
  29802. if (extent[1] > lastNiceTick) {
  29803. if (expandToNicedExtent) {
  29804. ticks.push(roundNumber(lastNiceTick + interval, intervalPrecision));
  29805. }
  29806. else {
  29807. ticks.push(extent[1]);
  29808. }
  29809. }
  29810. return ticks;
  29811. },
  29812. /**
  29813. * @param {number} [splitNumber=5]
  29814. * @return {Array.<Array.<number>>}
  29815. */
  29816. getMinorTicks: function (splitNumber) {
  29817. var ticks = this.getTicks(true);
  29818. var minorTicks = [];
  29819. var extent = this.getExtent();
  29820. for (var i = 1; i < ticks.length; i++) {
  29821. var nextTick = ticks[i];
  29822. var prevTick = ticks[i - 1];
  29823. var count = 0;
  29824. var minorTicksGroup = [];
  29825. var interval = nextTick - prevTick;
  29826. var minorInterval = interval / splitNumber;
  29827. while (count < splitNumber - 1) {
  29828. var minorTick = round$1(prevTick + (count + 1) * minorInterval);
  29829. // For the first and last interval. The count may be less than splitNumber.
  29830. if (minorTick > extent[0] && minorTick < extent[1]) {
  29831. minorTicksGroup.push(minorTick);
  29832. }
  29833. count++;
  29834. }
  29835. minorTicks.push(minorTicksGroup);
  29836. }
  29837. return minorTicks;
  29838. },
  29839. /**
  29840. * @param {number} data
  29841. * @param {Object} [opt]
  29842. * @param {number|string} [opt.precision] If 'auto', use nice presision.
  29843. * @param {boolean} [opt.pad] returns 1.50 but not 1.5 if precision is 2.
  29844. * @return {string}
  29845. */
  29846. getLabel: function (data, opt) {
  29847. if (data == null) {
  29848. return '';
  29849. }
  29850. var precision = opt && opt.precision;
  29851. if (precision == null) {
  29852. precision = getPrecisionSafe(data) || 0;
  29853. }
  29854. else if (precision === 'auto') {
  29855. // Should be more precise then tick.
  29856. precision = this._intervalPrecision;
  29857. }
  29858. // (1) If `precision` is set, 12.005 should be display as '12.00500'.
  29859. // (2) Use roundNumber (toFixed) to avoid scientific notation like '3.5e-7'.
  29860. data = roundNumber(data, precision, true);
  29861. return addCommas(data);
  29862. },
  29863. /**
  29864. * Update interval and extent of intervals for nice ticks
  29865. *
  29866. * @param {number} [splitNumber = 5] Desired number of ticks
  29867. * @param {number} [minInterval]
  29868. * @param {number} [maxInterval]
  29869. */
  29870. niceTicks: function (splitNumber, minInterval, maxInterval) {
  29871. splitNumber = splitNumber || 5;
  29872. var extent = this._extent;
  29873. var span = extent[1] - extent[0];
  29874. if (!isFinite(span)) {
  29875. return;
  29876. }
  29877. // User may set axis min 0 and data are all negative
  29878. // FIXME If it needs to reverse ?
  29879. if (span < 0) {
  29880. span = -span;
  29881. extent.reverse();
  29882. }
  29883. var result = intervalScaleNiceTicks(
  29884. extent, splitNumber, minInterval, maxInterval
  29885. );
  29886. this._intervalPrecision = result.intervalPrecision;
  29887. this._interval = result.interval;
  29888. this._niceExtent = result.niceTickExtent;
  29889. },
  29890. /**
  29891. * Nice extent.
  29892. * @param {Object} opt
  29893. * @param {number} [opt.splitNumber = 5] Given approx tick number
  29894. * @param {boolean} [opt.fixMin=false]
  29895. * @param {boolean} [opt.fixMax=false]
  29896. * @param {boolean} [opt.minInterval]
  29897. * @param {boolean} [opt.maxInterval]
  29898. */
  29899. niceExtent: function (opt) {
  29900. var extent = this._extent;
  29901. // If extent start and end are same, expand them
  29902. if (extent[0] === extent[1]) {
  29903. if (extent[0] !== 0) {
  29904. // Expand extent
  29905. var expandSize = extent[0];
  29906. // In the fowllowing case
  29907. // Axis has been fixed max 100
  29908. // Plus data are all 100 and axis extent are [100, 100].
  29909. // Extend to the both side will cause expanded max is larger than fixed max.
  29910. // So only expand to the smaller side.
  29911. if (!opt.fixMax) {
  29912. extent[1] += expandSize / 2;
  29913. extent[0] -= expandSize / 2;
  29914. }
  29915. else {
  29916. extent[0] -= expandSize / 2;
  29917. }
  29918. }
  29919. else {
  29920. extent[1] = 1;
  29921. }
  29922. }
  29923. var span = extent[1] - extent[0];
  29924. // If there are no data and extent are [Infinity, -Infinity]
  29925. if (!isFinite(span)) {
  29926. extent[0] = 0;
  29927. extent[1] = 1;
  29928. }
  29929. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  29930. // var extent = this._extent;
  29931. var interval = this._interval;
  29932. if (!opt.fixMin) {
  29933. extent[0] = roundNumber(Math.floor(extent[0] / interval) * interval);
  29934. }
  29935. if (!opt.fixMax) {
  29936. extent[1] = roundNumber(Math.ceil(extent[1] / interval) * interval);
  29937. }
  29938. }
  29939. });
  29940. /**
  29941. * @return {module:echarts/scale/Time}
  29942. */
  29943. IntervalScale.create = function () {
  29944. return new IntervalScale();
  29945. };
  29946. /*
  29947. * Licensed to the Apache Software Foundation (ASF) under one
  29948. * or more contributor license agreements. See the NOTICE file
  29949. * distributed with this work for additional information
  29950. * regarding copyright ownership. The ASF licenses this file
  29951. * to you under the Apache License, Version 2.0 (the
  29952. * "License"); you may not use this file except in compliance
  29953. * with the License. You may obtain a copy of the License at
  29954. *
  29955. * http://www.apache.org/licenses/LICENSE-2.0
  29956. *
  29957. * Unless required by applicable law or agreed to in writing,
  29958. * software distributed under the License is distributed on an
  29959. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29960. * KIND, either express or implied. See the License for the
  29961. * specific language governing permissions and limitations
  29962. * under the License.
  29963. */
  29964. /* global Float32Array */
  29965. var STACK_PREFIX = '__ec_stack_';
  29966. var LARGE_BAR_MIN_WIDTH = 0.5;
  29967. var LargeArr = typeof Float32Array !== 'undefined' ? Float32Array : Array;
  29968. function getSeriesStackId(seriesModel) {
  29969. return seriesModel.get('stack') || STACK_PREFIX + seriesModel.seriesIndex;
  29970. }
  29971. function getAxisKey(axis) {
  29972. return axis.dim + axis.index;
  29973. }
  29974. /**
  29975. * @param {Object} opt
  29976. * @param {module:echarts/coord/Axis} opt.axis Only support category axis currently.
  29977. * @param {number} opt.count Positive interger.
  29978. * @param {number} [opt.barWidth]
  29979. * @param {number} [opt.barMaxWidth]
  29980. * @param {number} [opt.barMinWidth]
  29981. * @param {number} [opt.barGap]
  29982. * @param {number} [opt.barCategoryGap]
  29983. * @return {Object} {width, offset, offsetCenter} If axis.type is not 'category', return undefined.
  29984. */
  29985. function getLayoutOnAxis(opt) {
  29986. var params = [];
  29987. var baseAxis = opt.axis;
  29988. var axisKey = 'axis0';
  29989. if (baseAxis.type !== 'category') {
  29990. return;
  29991. }
  29992. var bandWidth = baseAxis.getBandWidth();
  29993. for (var i = 0; i < opt.count || 0; i++) {
  29994. params.push(defaults({
  29995. bandWidth: bandWidth,
  29996. axisKey: axisKey,
  29997. stackId: STACK_PREFIX + i
  29998. }, opt));
  29999. }
  30000. var widthAndOffsets = doCalBarWidthAndOffset(params);
  30001. var result = [];
  30002. for (var i = 0; i < opt.count; i++) {
  30003. var item = widthAndOffsets[axisKey][STACK_PREFIX + i];
  30004. item.offsetCenter = item.offset + item.width / 2;
  30005. result.push(item);
  30006. }
  30007. return result;
  30008. }
  30009. function prepareLayoutBarSeries(seriesType, ecModel) {
  30010. var seriesModels = [];
  30011. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  30012. // Check series coordinate, do layout for cartesian2d only
  30013. if (isOnCartesian(seriesModel) && !isInLargeMode(seriesModel)) {
  30014. seriesModels.push(seriesModel);
  30015. }
  30016. });
  30017. return seriesModels;
  30018. }
  30019. /**
  30020. * Map from (baseAxis.dim + '_' + baseAxis.index) to min gap of two adjacent
  30021. * values.
  30022. * This works for time axes, value axes, and log axes.
  30023. * For a single time axis, return value is in the form like
  30024. * {'x_0': [1000000]}.
  30025. * The value of 1000000 is in milliseconds.
  30026. */
  30027. function getValueAxesMinGaps(barSeries) {
  30028. /**
  30029. * Map from axis.index to values.
  30030. * For a single time axis, axisValues is in the form like
  30031. * {'x_0': [1495555200000, 1495641600000, 1495728000000]}.
  30032. * Items in axisValues[x], e.g. 1495555200000, are time values of all
  30033. * series.
  30034. */
  30035. var axisValues = {};
  30036. each$1(barSeries, function (seriesModel) {
  30037. var cartesian = seriesModel.coordinateSystem;
  30038. var baseAxis = cartesian.getBaseAxis();
  30039. if (baseAxis.type !== 'time' && baseAxis.type !== 'value') {
  30040. return;
  30041. }
  30042. var data = seriesModel.getData();
  30043. var key = baseAxis.dim + '_' + baseAxis.index;
  30044. var dim = data.mapDimension(baseAxis.dim);
  30045. for (var i = 0, cnt = data.count(); i < cnt; ++i) {
  30046. var value = data.get(dim, i);
  30047. if (!axisValues[key]) {
  30048. // No previous data for the axis
  30049. axisValues[key] = [value];
  30050. }
  30051. else {
  30052. // No value in previous series
  30053. axisValues[key].push(value);
  30054. }
  30055. // Ignore duplicated time values in the same axis
  30056. }
  30057. });
  30058. var axisMinGaps = [];
  30059. for (var key in axisValues) {
  30060. if (axisValues.hasOwnProperty(key)) {
  30061. var valuesInAxis = axisValues[key];
  30062. if (valuesInAxis) {
  30063. // Sort axis values into ascending order to calculate gaps
  30064. valuesInAxis.sort(function (a, b) {
  30065. return a - b;
  30066. });
  30067. var min = null;
  30068. for (var j = 1; j < valuesInAxis.length; ++j) {
  30069. var delta = valuesInAxis[j] - valuesInAxis[j - 1];
  30070. if (delta > 0) {
  30071. // Ignore 0 delta because they are of the same axis value
  30072. min = min === null ? delta : Math.min(min, delta);
  30073. }
  30074. }
  30075. // Set to null if only have one data
  30076. axisMinGaps[key] = min;
  30077. }
  30078. }
  30079. }
  30080. return axisMinGaps;
  30081. }
  30082. function makeColumnLayout(barSeries) {
  30083. var axisMinGaps = getValueAxesMinGaps(barSeries);
  30084. var seriesInfoList = [];
  30085. each$1(barSeries, function (seriesModel) {
  30086. var cartesian = seriesModel.coordinateSystem;
  30087. var baseAxis = cartesian.getBaseAxis();
  30088. var axisExtent = baseAxis.getExtent();
  30089. var bandWidth;
  30090. if (baseAxis.type === 'category') {
  30091. bandWidth = baseAxis.getBandWidth();
  30092. }
  30093. else if (baseAxis.type === 'value' || baseAxis.type === 'time') {
  30094. var key = baseAxis.dim + '_' + baseAxis.index;
  30095. var minGap = axisMinGaps[key];
  30096. var extentSpan = Math.abs(axisExtent[1] - axisExtent[0]);
  30097. var scale = baseAxis.scale.getExtent();
  30098. var scaleSpan = Math.abs(scale[1] - scale[0]);
  30099. bandWidth = minGap
  30100. ? extentSpan / scaleSpan * minGap
  30101. : extentSpan; // When there is only one data value
  30102. }
  30103. else {
  30104. var data = seriesModel.getData();
  30105. bandWidth = Math.abs(axisExtent[1] - axisExtent[0]) / data.count();
  30106. }
  30107. var barWidth = parsePercent$1(
  30108. seriesModel.get('barWidth'), bandWidth
  30109. );
  30110. var barMaxWidth = parsePercent$1(
  30111. seriesModel.get('barMaxWidth'), bandWidth
  30112. );
  30113. var barMinWidth = parsePercent$1(
  30114. // barMinWidth by default is 1 in cartesian. Because in value axis,
  30115. // the auto-calculated bar width might be less than 1.
  30116. seriesModel.get('barMinWidth') || 1, bandWidth
  30117. );
  30118. var barGap = seriesModel.get('barGap');
  30119. var barCategoryGap = seriesModel.get('barCategoryGap');
  30120. seriesInfoList.push({
  30121. bandWidth: bandWidth,
  30122. barWidth: barWidth,
  30123. barMaxWidth: barMaxWidth,
  30124. barMinWidth: barMinWidth,
  30125. barGap: barGap,
  30126. barCategoryGap: barCategoryGap,
  30127. axisKey: getAxisKey(baseAxis),
  30128. stackId: getSeriesStackId(seriesModel)
  30129. });
  30130. });
  30131. return doCalBarWidthAndOffset(seriesInfoList);
  30132. }
  30133. function doCalBarWidthAndOffset(seriesInfoList) {
  30134. // Columns info on each category axis. Key is cartesian name
  30135. var columnsMap = {};
  30136. each$1(seriesInfoList, function (seriesInfo, idx) {
  30137. var axisKey = seriesInfo.axisKey;
  30138. var bandWidth = seriesInfo.bandWidth;
  30139. var columnsOnAxis = columnsMap[axisKey] || {
  30140. bandWidth: bandWidth,
  30141. remainedWidth: bandWidth,
  30142. autoWidthCount: 0,
  30143. categoryGap: '20%',
  30144. gap: '30%',
  30145. stacks: {}
  30146. };
  30147. var stacks = columnsOnAxis.stacks;
  30148. columnsMap[axisKey] = columnsOnAxis;
  30149. var stackId = seriesInfo.stackId;
  30150. if (!stacks[stackId]) {
  30151. columnsOnAxis.autoWidthCount++;
  30152. }
  30153. stacks[stackId] = stacks[stackId] || {
  30154. width: 0,
  30155. maxWidth: 0
  30156. };
  30157. // Caution: In a single coordinate system, these barGrid attributes
  30158. // will be shared by series. Consider that they have default values,
  30159. // only the attributes set on the last series will work.
  30160. // Do not change this fact unless there will be a break change.
  30161. var barWidth = seriesInfo.barWidth;
  30162. if (barWidth && !stacks[stackId].width) {
  30163. // See #6312, do not restrict width.
  30164. stacks[stackId].width = barWidth;
  30165. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  30166. columnsOnAxis.remainedWidth -= barWidth;
  30167. }
  30168. var barMaxWidth = seriesInfo.barMaxWidth;
  30169. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  30170. var barMinWidth = seriesInfo.barMinWidth;
  30171. barMinWidth && (stacks[stackId].minWidth = barMinWidth);
  30172. var barGap = seriesInfo.barGap;
  30173. (barGap != null) && (columnsOnAxis.gap = barGap);
  30174. var barCategoryGap = seriesInfo.barCategoryGap;
  30175. (barCategoryGap != null) && (columnsOnAxis.categoryGap = barCategoryGap);
  30176. });
  30177. var result = {};
  30178. each$1(columnsMap, function (columnsOnAxis, coordSysName) {
  30179. result[coordSysName] = {};
  30180. var stacks = columnsOnAxis.stacks;
  30181. var bandWidth = columnsOnAxis.bandWidth;
  30182. var categoryGap = parsePercent$1(columnsOnAxis.categoryGap, bandWidth);
  30183. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  30184. var remainedWidth = columnsOnAxis.remainedWidth;
  30185. var autoWidthCount = columnsOnAxis.autoWidthCount;
  30186. var autoWidth = (remainedWidth - categoryGap)
  30187. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  30188. autoWidth = Math.max(autoWidth, 0);
  30189. // Find if any auto calculated bar exceeded maxBarWidth
  30190. each$1(stacks, function (column) {
  30191. var maxWidth = column.maxWidth;
  30192. var minWidth = column.minWidth;
  30193. if (!column.width) {
  30194. var finalWidth = autoWidth;
  30195. if (maxWidth && maxWidth < finalWidth) {
  30196. finalWidth = Math.min(maxWidth, remainedWidth);
  30197. }
  30198. // `minWidth` has higher priority. `minWidth` decide that wheter the
  30199. // bar is able to be visible. So `minWidth` should not be restricted
  30200. // by `maxWidth` or `remainedWidth` (which is from `bandWidth`). In
  30201. // the extreme cases for `value` axis, bars are allowed to overlap
  30202. // with each other if `minWidth` specified.
  30203. if (minWidth && minWidth > finalWidth) {
  30204. finalWidth = minWidth;
  30205. }
  30206. if (finalWidth !== autoWidth) {
  30207. column.width = finalWidth;
  30208. remainedWidth -= finalWidth + barGapPercent * finalWidth;
  30209. autoWidthCount--;
  30210. }
  30211. }
  30212. else {
  30213. // `barMinWidth/barMaxWidth` has higher priority than `barWidth`, as
  30214. // CSS does. Becuase barWidth can be a percent value, where
  30215. // `barMaxWidth` can be used to restrict the final width.
  30216. var finalWidth = column.width;
  30217. if (maxWidth) {
  30218. finalWidth = Math.min(finalWidth, maxWidth);
  30219. }
  30220. // `minWidth` has higher priority, as described above
  30221. if (minWidth) {
  30222. finalWidth = Math.max(finalWidth, minWidth);
  30223. }
  30224. column.width = finalWidth;
  30225. remainedWidth -= finalWidth + barGapPercent * finalWidth;
  30226. autoWidthCount--;
  30227. }
  30228. });
  30229. // Recalculate width again
  30230. autoWidth = (remainedWidth - categoryGap)
  30231. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  30232. autoWidth = Math.max(autoWidth, 0);
  30233. var widthSum = 0;
  30234. var lastColumn;
  30235. each$1(stacks, function (column, idx) {
  30236. if (!column.width) {
  30237. column.width = autoWidth;
  30238. }
  30239. lastColumn = column;
  30240. widthSum += column.width * (1 + barGapPercent);
  30241. });
  30242. if (lastColumn) {
  30243. widthSum -= lastColumn.width * barGapPercent;
  30244. }
  30245. var offset = -widthSum / 2;
  30246. each$1(stacks, function (column, stackId) {
  30247. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  30248. bandWidth: bandWidth,
  30249. offset: offset,
  30250. width: column.width
  30251. };
  30252. offset += column.width * (1 + barGapPercent);
  30253. });
  30254. });
  30255. return result;
  30256. }
  30257. /**
  30258. * @param {Object} barWidthAndOffset The result of makeColumnLayout
  30259. * @param {module:echarts/coord/Axis} axis
  30260. * @param {module:echarts/model/Series} [seriesModel] If not provided, return all.
  30261. * @return {Object} {stackId: {offset, width}} or {offset, width} if seriesModel provided.
  30262. */
  30263. function retrieveColumnLayout(barWidthAndOffset, axis, seriesModel) {
  30264. if (barWidthAndOffset && axis) {
  30265. var result = barWidthAndOffset[getAxisKey(axis)];
  30266. if (result != null && seriesModel != null) {
  30267. result = result[getSeriesStackId(seriesModel)];
  30268. }
  30269. return result;
  30270. }
  30271. }
  30272. /**
  30273. * @param {string} seriesType
  30274. * @param {module:echarts/model/Global} ecModel
  30275. */
  30276. function layout(seriesType, ecModel) {
  30277. var seriesModels = prepareLayoutBarSeries(seriesType, ecModel);
  30278. var barWidthAndOffset = makeColumnLayout(seriesModels);
  30279. var lastStackCoords = {};
  30280. each$1(seriesModels, function (seriesModel) {
  30281. var data = seriesModel.getData();
  30282. var cartesian = seriesModel.coordinateSystem;
  30283. var baseAxis = cartesian.getBaseAxis();
  30284. var stackId = getSeriesStackId(seriesModel);
  30285. var columnLayoutInfo = barWidthAndOffset[getAxisKey(baseAxis)][stackId];
  30286. var columnOffset = columnLayoutInfo.offset;
  30287. var columnWidth = columnLayoutInfo.width;
  30288. var valueAxis = cartesian.getOtherAxis(baseAxis);
  30289. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  30290. lastStackCoords[stackId] = lastStackCoords[stackId] || [];
  30291. data.setLayout({
  30292. bandWidth: columnLayoutInfo.bandWidth,
  30293. offset: columnOffset,
  30294. size: columnWidth
  30295. });
  30296. var valueDim = data.mapDimension(valueAxis.dim);
  30297. var baseDim = data.mapDimension(baseAxis.dim);
  30298. var stacked = isDimensionStacked(data, valueDim /*, baseDim*/);
  30299. var isValueAxisH = valueAxis.isHorizontal();
  30300. var valueAxisStart = getValueAxisStart(baseAxis, valueAxis, stacked);
  30301. for (var idx = 0, len = data.count(); idx < len; idx++) {
  30302. var value = data.get(valueDim, idx);
  30303. var baseValue = data.get(baseDim, idx);
  30304. var sign = value >= 0 ? 'p' : 'n';
  30305. var baseCoord = valueAxisStart;
  30306. // Because of the barMinHeight, we can not use the value in
  30307. // stackResultDimension directly.
  30308. if (stacked) {
  30309. // Only ordinal axis can be stacked.
  30310. if (!lastStackCoords[stackId][baseValue]) {
  30311. lastStackCoords[stackId][baseValue] = {
  30312. p: valueAxisStart, // Positive stack
  30313. n: valueAxisStart // Negative stack
  30314. };
  30315. }
  30316. // Should also consider #4243
  30317. baseCoord = lastStackCoords[stackId][baseValue][sign];
  30318. }
  30319. var x;
  30320. var y;
  30321. var width;
  30322. var height;
  30323. if (isValueAxisH) {
  30324. var coord = cartesian.dataToPoint([value, baseValue]);
  30325. x = baseCoord;
  30326. y = coord[1] + columnOffset;
  30327. width = coord[0] - valueAxisStart;
  30328. height = columnWidth;
  30329. if (Math.abs(width) < barMinHeight) {
  30330. width = (width < 0 ? -1 : 1) * barMinHeight;
  30331. }
  30332. // Ignore stack from NaN value
  30333. if (!isNaN(width)) {
  30334. stacked && (lastStackCoords[stackId][baseValue][sign] += width);
  30335. }
  30336. }
  30337. else {
  30338. var coord = cartesian.dataToPoint([baseValue, value]);
  30339. x = coord[0] + columnOffset;
  30340. y = baseCoord;
  30341. width = columnWidth;
  30342. height = coord[1] - valueAxisStart;
  30343. if (Math.abs(height) < barMinHeight) {
  30344. // Include zero to has a positive bar
  30345. height = (height <= 0 ? -1 : 1) * barMinHeight;
  30346. }
  30347. // Ignore stack from NaN value
  30348. if (!isNaN(height)) {
  30349. stacked && (lastStackCoords[stackId][baseValue][sign] += height);
  30350. }
  30351. }
  30352. data.setItemLayout(idx, {
  30353. x: x,
  30354. y: y,
  30355. width: width,
  30356. height: height
  30357. });
  30358. }
  30359. }, this);
  30360. }
  30361. // TODO: Do not support stack in large mode yet.
  30362. var largeLayout = {
  30363. seriesType: 'bar',
  30364. plan: createRenderPlanner(),
  30365. reset: function (seriesModel) {
  30366. if (!isOnCartesian(seriesModel) || !isInLargeMode(seriesModel)) {
  30367. return;
  30368. }
  30369. var data = seriesModel.getData();
  30370. var cartesian = seriesModel.coordinateSystem;
  30371. var coordLayout = cartesian.grid.getRect();
  30372. var baseAxis = cartesian.getBaseAxis();
  30373. var valueAxis = cartesian.getOtherAxis(baseAxis);
  30374. var valueDim = data.mapDimension(valueAxis.dim);
  30375. var baseDim = data.mapDimension(baseAxis.dim);
  30376. var valueAxisHorizontal = valueAxis.isHorizontal();
  30377. var valueDimIdx = valueAxisHorizontal ? 0 : 1;
  30378. var barWidth = retrieveColumnLayout(
  30379. makeColumnLayout([seriesModel]), baseAxis, seriesModel
  30380. ).width;
  30381. if (!(barWidth > LARGE_BAR_MIN_WIDTH)) { // jshint ignore:line
  30382. barWidth = LARGE_BAR_MIN_WIDTH;
  30383. }
  30384. return {progress: progress};
  30385. function progress(params, data) {
  30386. var count = params.count;
  30387. var largePoints = new LargeArr(count * 2);
  30388. var largeBackgroundPoints = new LargeArr(count * 2);
  30389. var largeDataIndices = new LargeArr(count);
  30390. var dataIndex;
  30391. var coord = [];
  30392. var valuePair = [];
  30393. var pointsOffset = 0;
  30394. var idxOffset = 0;
  30395. while ((dataIndex = params.next()) != null) {
  30396. valuePair[valueDimIdx] = data.get(valueDim, dataIndex);
  30397. valuePair[1 - valueDimIdx] = data.get(baseDim, dataIndex);
  30398. coord = cartesian.dataToPoint(valuePair, null, coord);
  30399. // Data index might not be in order, depends on `progressiveChunkMode`.
  30400. largeBackgroundPoints[pointsOffset] = valueAxisHorizontal
  30401. ? coordLayout.x + coordLayout.width : coord[0];
  30402. largePoints[pointsOffset++] = coord[0];
  30403. largeBackgroundPoints[pointsOffset] = valueAxisHorizontal
  30404. ? coord[1] : coordLayout.y + coordLayout.height;
  30405. largePoints[pointsOffset++] = coord[1];
  30406. largeDataIndices[idxOffset++] = dataIndex;
  30407. }
  30408. data.setLayout({
  30409. largePoints: largePoints,
  30410. largeDataIndices: largeDataIndices,
  30411. largeBackgroundPoints: largeBackgroundPoints,
  30412. barWidth: barWidth,
  30413. valueAxisStart: getValueAxisStart(baseAxis, valueAxis, false),
  30414. backgroundStart: valueAxisHorizontal ? coordLayout.x : coordLayout.y,
  30415. valueAxisHorizontal: valueAxisHorizontal
  30416. });
  30417. }
  30418. }
  30419. };
  30420. function isOnCartesian(seriesModel) {
  30421. return seriesModel.coordinateSystem && seriesModel.coordinateSystem.type === 'cartesian2d';
  30422. }
  30423. function isInLargeMode(seriesModel) {
  30424. return seriesModel.pipelineContext && seriesModel.pipelineContext.large;
  30425. }
  30426. // See cases in `test/bar-start.html` and `#7412`, `#8747`.
  30427. function getValueAxisStart(baseAxis, valueAxis, stacked) {
  30428. return valueAxis.toGlobalCoord(valueAxis.dataToCoord(valueAxis.type === 'log' ? 1 : 0));
  30429. }
  30430. /*
  30431. * Licensed to the Apache Software Foundation (ASF) under one
  30432. * or more contributor license agreements. See the NOTICE file
  30433. * distributed with this work for additional information
  30434. * regarding copyright ownership. The ASF licenses this file
  30435. * to you under the Apache License, Version 2.0 (the
  30436. * "License"); you may not use this file except in compliance
  30437. * with the License. You may obtain a copy of the License at
  30438. *
  30439. * http://www.apache.org/licenses/LICENSE-2.0
  30440. *
  30441. * Unless required by applicable law or agreed to in writing,
  30442. * software distributed under the License is distributed on an
  30443. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30444. * KIND, either express or implied. See the License for the
  30445. * specific language governing permissions and limitations
  30446. * under the License.
  30447. */
  30448. /*
  30449. * A third-party license is embeded for some of the code in this file:
  30450. * The "scaleLevels" was originally copied from "d3.js" with some
  30451. * modifications made for this project.
  30452. * (See more details in the comment on the definition of "scaleLevels" below.)
  30453. * The use of the source code of this file is also subject to the terms
  30454. * and consitions of the license of "d3.js" (BSD-3Clause, see
  30455. * </licenses/LICENSE-d3>).
  30456. */
  30457. // [About UTC and local time zone]:
  30458. // In most cases, `number.parseDate` will treat input data string as local time
  30459. // (except time zone is specified in time string). And `format.formateTime` returns
  30460. // local time by default. option.useUTC is false by default. This design have
  30461. // concidered these common case:
  30462. // (1) Time that is persistent in server is in UTC, but it is needed to be diplayed
  30463. // in local time by default.
  30464. // (2) By default, the input data string (e.g., '2011-01-02') should be displayed
  30465. // as its original time, without any time difference.
  30466. var intervalScaleProto = IntervalScale.prototype;
  30467. var mathCeil = Math.ceil;
  30468. var mathFloor = Math.floor;
  30469. var ONE_SECOND = 1000;
  30470. var ONE_MINUTE = ONE_SECOND * 60;
  30471. var ONE_HOUR = ONE_MINUTE * 60;
  30472. var ONE_DAY = ONE_HOUR * 24;
  30473. // FIXME 公用?
  30474. var bisect = function (a, x, lo, hi) {
  30475. while (lo < hi) {
  30476. var mid = lo + hi >>> 1;
  30477. if (a[mid][1] < x) {
  30478. lo = mid + 1;
  30479. }
  30480. else {
  30481. hi = mid;
  30482. }
  30483. }
  30484. return lo;
  30485. };
  30486. /**
  30487. * @alias module:echarts/coord/scale/Time
  30488. * @constructor
  30489. */
  30490. var TimeScale = IntervalScale.extend({
  30491. type: 'time',
  30492. /**
  30493. * @override
  30494. */
  30495. getLabel: function (val) {
  30496. var stepLvl = this._stepLvl;
  30497. var date = new Date(val);
  30498. return formatTime(stepLvl[0], date, this.getSetting('useUTC'));
  30499. },
  30500. /**
  30501. * @override
  30502. */
  30503. niceExtent: function (opt) {
  30504. var extent = this._extent;
  30505. // If extent start and end are same, expand them
  30506. if (extent[0] === extent[1]) {
  30507. // Expand extent
  30508. extent[0] -= ONE_DAY;
  30509. extent[1] += ONE_DAY;
  30510. }
  30511. // If there are no data and extent are [Infinity, -Infinity]
  30512. if (extent[1] === -Infinity && extent[0] === Infinity) {
  30513. var d = new Date();
  30514. extent[1] = +new Date(d.getFullYear(), d.getMonth(), d.getDate());
  30515. extent[0] = extent[1] - ONE_DAY;
  30516. }
  30517. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  30518. // var extent = this._extent;
  30519. var interval = this._interval;
  30520. if (!opt.fixMin) {
  30521. extent[0] = round$1(mathFloor(extent[0] / interval) * interval);
  30522. }
  30523. if (!opt.fixMax) {
  30524. extent[1] = round$1(mathCeil(extent[1] / interval) * interval);
  30525. }
  30526. },
  30527. /**
  30528. * @override
  30529. */
  30530. niceTicks: function (approxTickNum, minInterval, maxInterval) {
  30531. approxTickNum = approxTickNum || 10;
  30532. var extent = this._extent;
  30533. var span = extent[1] - extent[0];
  30534. var approxInterval = span / approxTickNum;
  30535. if (minInterval != null && approxInterval < minInterval) {
  30536. approxInterval = minInterval;
  30537. }
  30538. if (maxInterval != null && approxInterval > maxInterval) {
  30539. approxInterval = maxInterval;
  30540. }
  30541. var scaleLevelsLen = scaleLevels.length;
  30542. var idx = bisect(scaleLevels, approxInterval, 0, scaleLevelsLen);
  30543. var level = scaleLevels[Math.min(idx, scaleLevelsLen - 1)];
  30544. var interval = level[1];
  30545. // Same with interval scale if span is much larger than 1 year
  30546. if (level[0] === 'year') {
  30547. var yearSpan = span / interval;
  30548. // From "Nice Numbers for Graph Labels" of Graphic Gems
  30549. // var niceYearSpan = numberUtil.nice(yearSpan, false);
  30550. var yearStep = nice(yearSpan / approxTickNum, true);
  30551. interval *= yearStep;
  30552. }
  30553. var timezoneOffset = this.getSetting('useUTC')
  30554. ? 0 : (new Date(+extent[0] || +extent[1])).getTimezoneOffset() * 60 * 1000;
  30555. var niceExtent = [
  30556. Math.round(mathCeil((extent[0] - timezoneOffset) / interval) * interval + timezoneOffset),
  30557. Math.round(mathFloor((extent[1] - timezoneOffset) / interval) * interval + timezoneOffset)
  30558. ];
  30559. fixExtent(niceExtent, extent);
  30560. this._stepLvl = level;
  30561. // Interval will be used in getTicks
  30562. this._interval = interval;
  30563. this._niceExtent = niceExtent;
  30564. },
  30565. parse: function (val) {
  30566. // val might be float.
  30567. return +parseDate(val);
  30568. }
  30569. });
  30570. each$1(['contain', 'normalize'], function (methodName) {
  30571. TimeScale.prototype[methodName] = function (val) {
  30572. return intervalScaleProto[methodName].call(this, this.parse(val));
  30573. };
  30574. });
  30575. /**
  30576. * This implementation was originally copied from "d3.js"
  30577. * <https://github.com/d3/d3/blob/b516d77fb8566b576088e73410437494717ada26/src/time/scale.js>
  30578. * with some modifications made for this program.
  30579. * See the license statement at the head of this file.
  30580. */
  30581. var scaleLevels = [
  30582. // Format interval
  30583. ['hh:mm:ss', ONE_SECOND], // 1s
  30584. ['hh:mm:ss', ONE_SECOND * 5], // 5s
  30585. ['hh:mm:ss', ONE_SECOND * 10], // 10s
  30586. ['hh:mm:ss', ONE_SECOND * 15], // 15s
  30587. ['hh:mm:ss', ONE_SECOND * 30], // 30s
  30588. ['hh:mm\nMM-dd', ONE_MINUTE], // 1m
  30589. ['hh:mm\nMM-dd', ONE_MINUTE * 5], // 5m
  30590. ['hh:mm\nMM-dd', ONE_MINUTE * 10], // 10m
  30591. ['hh:mm\nMM-dd', ONE_MINUTE * 15], // 15m
  30592. ['hh:mm\nMM-dd', ONE_MINUTE * 30], // 30m
  30593. ['hh:mm\nMM-dd', ONE_HOUR], // 1h
  30594. ['hh:mm\nMM-dd', ONE_HOUR * 2], // 2h
  30595. ['hh:mm\nMM-dd', ONE_HOUR * 6], // 6h
  30596. ['hh:mm\nMM-dd', ONE_HOUR * 12], // 12h
  30597. ['MM-dd\nyyyy', ONE_DAY], // 1d
  30598. ['MM-dd\nyyyy', ONE_DAY * 2], // 2d
  30599. ['MM-dd\nyyyy', ONE_DAY * 3], // 3d
  30600. ['MM-dd\nyyyy', ONE_DAY * 4], // 4d
  30601. ['MM-dd\nyyyy', ONE_DAY * 5], // 5d
  30602. ['MM-dd\nyyyy', ONE_DAY * 6], // 6d
  30603. ['week', ONE_DAY * 7], // 7d
  30604. ['MM-dd\nyyyy', ONE_DAY * 10], // 10d
  30605. ['week', ONE_DAY * 14], // 2w
  30606. ['week', ONE_DAY * 21], // 3w
  30607. ['month', ONE_DAY * 31], // 1M
  30608. ['week', ONE_DAY * 42], // 6w
  30609. ['month', ONE_DAY * 62], // 2M
  30610. ['week', ONE_DAY * 70], // 10w
  30611. ['quarter', ONE_DAY * 95], // 3M
  30612. ['month', ONE_DAY * 31 * 4], // 4M
  30613. ['month', ONE_DAY * 31 * 5], // 5M
  30614. ['half-year', ONE_DAY * 380 / 2], // 6M
  30615. ['month', ONE_DAY * 31 * 8], // 8M
  30616. ['month', ONE_DAY * 31 * 10], // 10M
  30617. ['year', ONE_DAY * 380] // 1Y
  30618. ];
  30619. /**
  30620. * @param {module:echarts/model/Model}
  30621. * @return {module:echarts/scale/Time}
  30622. */
  30623. TimeScale.create = function (model) {
  30624. return new TimeScale({useUTC: model.ecModel.get('useUTC')});
  30625. };
  30626. /*
  30627. * Licensed to the Apache Software Foundation (ASF) under one
  30628. * or more contributor license agreements. See the NOTICE file
  30629. * distributed with this work for additional information
  30630. * regarding copyright ownership. The ASF licenses this file
  30631. * to you under the Apache License, Version 2.0 (the
  30632. * "License"); you may not use this file except in compliance
  30633. * with the License. You may obtain a copy of the License at
  30634. *
  30635. * http://www.apache.org/licenses/LICENSE-2.0
  30636. *
  30637. * Unless required by applicable law or agreed to in writing,
  30638. * software distributed under the License is distributed on an
  30639. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30640. * KIND, either express or implied. See the License for the
  30641. * specific language governing permissions and limitations
  30642. * under the License.
  30643. */
  30644. /**
  30645. * Log scale
  30646. * @module echarts/scale/Log
  30647. */
  30648. // Use some method of IntervalScale
  30649. var scaleProto$1 = Scale.prototype;
  30650. var intervalScaleProto$1 = IntervalScale.prototype;
  30651. var getPrecisionSafe$1 = getPrecisionSafe;
  30652. var roundingErrorFix = round$1;
  30653. var mathFloor$1 = Math.floor;
  30654. var mathCeil$1 = Math.ceil;
  30655. var mathPow$1 = Math.pow;
  30656. var mathLog = Math.log;
  30657. var LogScale = Scale.extend({
  30658. type: 'log',
  30659. base: 10,
  30660. $constructor: function () {
  30661. Scale.apply(this, arguments);
  30662. this._originalScale = new IntervalScale();
  30663. },
  30664. /**
  30665. * @param {boolean} [expandToNicedExtent=false] If expand the ticks to niced extent.
  30666. * @return {Array.<number>}
  30667. */
  30668. getTicks: function (expandToNicedExtent) {
  30669. var originalScale = this._originalScale;
  30670. var extent = this._extent;
  30671. var originalExtent = originalScale.getExtent();
  30672. return map(intervalScaleProto$1.getTicks.call(this, expandToNicedExtent), function (val) {
  30673. var powVal = round$1(mathPow$1(this.base, val));
  30674. // Fix #4158
  30675. powVal = (val === extent[0] && originalScale.__fixMin)
  30676. ? fixRoundingError(powVal, originalExtent[0])
  30677. : powVal;
  30678. powVal = (val === extent[1] && originalScale.__fixMax)
  30679. ? fixRoundingError(powVal, originalExtent[1])
  30680. : powVal;
  30681. return powVal;
  30682. }, this);
  30683. },
  30684. /**
  30685. * @param {number} splitNumber
  30686. * @return {Array.<Array.<number>>}
  30687. */
  30688. getMinorTicks: intervalScaleProto$1.getMinorTicks,
  30689. /**
  30690. * @param {number} val
  30691. * @return {string}
  30692. */
  30693. getLabel: intervalScaleProto$1.getLabel,
  30694. /**
  30695. * @param {number} val
  30696. * @return {number}
  30697. */
  30698. scale: function (val) {
  30699. val = scaleProto$1.scale.call(this, val);
  30700. return mathPow$1(this.base, val);
  30701. },
  30702. /**
  30703. * @param {number} start
  30704. * @param {number} end
  30705. */
  30706. setExtent: function (start, end) {
  30707. var base = this.base;
  30708. start = mathLog(start) / mathLog(base);
  30709. end = mathLog(end) / mathLog(base);
  30710. intervalScaleProto$1.setExtent.call(this, start, end);
  30711. },
  30712. /**
  30713. * @return {number} end
  30714. */
  30715. getExtent: function () {
  30716. var base = this.base;
  30717. var extent = scaleProto$1.getExtent.call(this);
  30718. extent[0] = mathPow$1(base, extent[0]);
  30719. extent[1] = mathPow$1(base, extent[1]);
  30720. // Fix #4158
  30721. var originalScale = this._originalScale;
  30722. var originalExtent = originalScale.getExtent();
  30723. originalScale.__fixMin && (extent[0] = fixRoundingError(extent[0], originalExtent[0]));
  30724. originalScale.__fixMax && (extent[1] = fixRoundingError(extent[1], originalExtent[1]));
  30725. return extent;
  30726. },
  30727. /**
  30728. * @param {Array.<number>} extent
  30729. */
  30730. unionExtent: function (extent) {
  30731. this._originalScale.unionExtent(extent);
  30732. var base = this.base;
  30733. extent[0] = mathLog(extent[0]) / mathLog(base);
  30734. extent[1] = mathLog(extent[1]) / mathLog(base);
  30735. scaleProto$1.unionExtent.call(this, extent);
  30736. },
  30737. /**
  30738. * @override
  30739. */
  30740. unionExtentFromData: function (data, dim) {
  30741. // TODO
  30742. // filter value that <= 0
  30743. this.unionExtent(data.getApproximateExtent(dim));
  30744. },
  30745. /**
  30746. * Update interval and extent of intervals for nice ticks
  30747. * @param {number} [approxTickNum = 10] Given approx tick number
  30748. */
  30749. niceTicks: function (approxTickNum) {
  30750. approxTickNum = approxTickNum || 10;
  30751. var extent = this._extent;
  30752. var span = extent[1] - extent[0];
  30753. if (span === Infinity || span <= 0) {
  30754. return;
  30755. }
  30756. var interval = quantity(span);
  30757. var err = approxTickNum / span * interval;
  30758. // Filter ticks to get closer to the desired count.
  30759. if (err <= 0.5) {
  30760. interval *= 10;
  30761. }
  30762. // Interval should be integer
  30763. while (!isNaN(interval) && Math.abs(interval) < 1 && Math.abs(interval) > 0) {
  30764. interval *= 10;
  30765. }
  30766. var niceExtent = [
  30767. round$1(mathCeil$1(extent[0] / interval) * interval),
  30768. round$1(mathFloor$1(extent[1] / interval) * interval)
  30769. ];
  30770. this._interval = interval;
  30771. this._niceExtent = niceExtent;
  30772. },
  30773. /**
  30774. * Nice extent.
  30775. * @override
  30776. */
  30777. niceExtent: function (opt) {
  30778. intervalScaleProto$1.niceExtent.call(this, opt);
  30779. var originalScale = this._originalScale;
  30780. originalScale.__fixMin = opt.fixMin;
  30781. originalScale.__fixMax = opt.fixMax;
  30782. }
  30783. });
  30784. each$1(['contain', 'normalize'], function (methodName) {
  30785. LogScale.prototype[methodName] = function (val) {
  30786. val = mathLog(val) / mathLog(this.base);
  30787. return scaleProto$1[methodName].call(this, val);
  30788. };
  30789. });
  30790. LogScale.create = function () {
  30791. return new LogScale();
  30792. };
  30793. function fixRoundingError(val, originalVal) {
  30794. return roundingErrorFix(val, getPrecisionSafe$1(originalVal));
  30795. }
  30796. /*
  30797. * Licensed to the Apache Software Foundation (ASF) under one
  30798. * or more contributor license agreements. See the NOTICE file
  30799. * distributed with this work for additional information
  30800. * regarding copyright ownership. The ASF licenses this file
  30801. * to you under the Apache License, Version 2.0 (the
  30802. * "License"); you may not use this file except in compliance
  30803. * with the License. You may obtain a copy of the License at
  30804. *
  30805. * http://www.apache.org/licenses/LICENSE-2.0
  30806. *
  30807. * Unless required by applicable law or agreed to in writing,
  30808. * software distributed under the License is distributed on an
  30809. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30810. * KIND, either express or implied. See the License for the
  30811. * specific language governing permissions and limitations
  30812. * under the License.
  30813. */
  30814. /**
  30815. * Get axis scale extent before niced.
  30816. * Item of returned array can only be number (including Infinity and NaN).
  30817. */
  30818. function getScaleExtent(scale, model) {
  30819. var scaleType = scale.type;
  30820. var min = model.getMin();
  30821. var max = model.getMax();
  30822. var originalExtent = scale.getExtent();
  30823. var axisDataLen;
  30824. var boundaryGap;
  30825. var span;
  30826. if (scaleType === 'ordinal') {
  30827. axisDataLen = model.getCategories().length;
  30828. }
  30829. else {
  30830. boundaryGap = model.get('boundaryGap');
  30831. if (!isArray(boundaryGap)) {
  30832. boundaryGap = [boundaryGap || 0, boundaryGap || 0];
  30833. }
  30834. if (typeof boundaryGap[0] === 'boolean') {
  30835. if (__DEV__) {
  30836. console.warn('Boolean type for boundaryGap is only '
  30837. + 'allowed for ordinal axis. Please use string in '
  30838. + 'percentage instead, e.g., "20%". Currently, '
  30839. + 'boundaryGap is set to be 0.');
  30840. }
  30841. boundaryGap = [0, 0];
  30842. }
  30843. boundaryGap[0] = parsePercent$1(boundaryGap[0], 1);
  30844. boundaryGap[1] = parsePercent$1(boundaryGap[1], 1);
  30845. span = (originalExtent[1] - originalExtent[0])
  30846. || Math.abs(originalExtent[0]);
  30847. }
  30848. // Notice: When min/max is not set (that is, when there are null/undefined,
  30849. // which is the most common case), these cases should be ensured:
  30850. // (1) For 'ordinal', show all axis.data.
  30851. // (2) For others:
  30852. // + `boundaryGap` is applied (if min/max set, boundaryGap is
  30853. // disabled).
  30854. // + If `needCrossZero`, min/max should be zero, otherwise, min/max should
  30855. // be the result that originalExtent enlarged by boundaryGap.
  30856. // (3) If no data, it should be ensured that `scale.setBlank` is set.
  30857. // FIXME
  30858. // (1) When min/max is 'dataMin' or 'dataMax', should boundaryGap be able to used?
  30859. // (2) When `needCrossZero` and all data is positive/negative, should it be ensured
  30860. // that the results processed by boundaryGap are positive/negative?
  30861. if (min === 'dataMin') {
  30862. min = originalExtent[0];
  30863. }
  30864. else if (typeof min === 'function') {
  30865. min = min({
  30866. min: originalExtent[0],
  30867. max: originalExtent[1]
  30868. });
  30869. }
  30870. if (max === 'dataMax') {
  30871. max = originalExtent[1];
  30872. }
  30873. else if (typeof max === 'function') {
  30874. max = max({
  30875. min: originalExtent[0],
  30876. max: originalExtent[1]
  30877. });
  30878. }
  30879. var fixMin = min != null;
  30880. var fixMax = max != null;
  30881. if (min == null) {
  30882. min = scaleType === 'ordinal'
  30883. ? (axisDataLen ? 0 : NaN)
  30884. : originalExtent[0] - boundaryGap[0] * span;
  30885. }
  30886. if (max == null) {
  30887. max = scaleType === 'ordinal'
  30888. ? (axisDataLen ? axisDataLen - 1 : NaN)
  30889. : originalExtent[1] + boundaryGap[1] * span;
  30890. }
  30891. (min == null || !isFinite(min)) && (min = NaN);
  30892. (max == null || !isFinite(max)) && (max = NaN);
  30893. scale.setBlank(
  30894. eqNaN(min)
  30895. || eqNaN(max)
  30896. || (scaleType === 'ordinal' && !scale.getOrdinalMeta().categories.length)
  30897. );
  30898. // Evaluate if axis needs cross zero
  30899. if (model.getNeedCrossZero()) {
  30900. // Axis is over zero and min is not set
  30901. if (min > 0 && max > 0 && !fixMin) {
  30902. min = 0;
  30903. }
  30904. // Axis is under zero and max is not set
  30905. if (min < 0 && max < 0 && !fixMax) {
  30906. max = 0;
  30907. }
  30908. }
  30909. // If bars are placed on a base axis of type time or interval account for axis boundary overflow and current axis
  30910. // is base axis
  30911. // FIXME
  30912. // (1) Consider support value axis, where below zero and axis `onZero` should be handled properly.
  30913. // (2) Refactor the logic with `barGrid`. Is it not need to `makeBarWidthAndOffsetInfo` twice with different extent?
  30914. // Should not depend on series type `bar`?
  30915. // (3) Fix that might overlap when using dataZoom.
  30916. // (4) Consider other chart types using `barGrid`?
  30917. // See #6728, #4862, `test/bar-overflow-time-plot.html`
  30918. var ecModel = model.ecModel;
  30919. if (ecModel && (scaleType === 'time' /*|| scaleType === 'interval' */)) {
  30920. var barSeriesModels = prepareLayoutBarSeries('bar', ecModel);
  30921. var isBaseAxisAndHasBarSeries;
  30922. each$1(barSeriesModels, function (seriesModel) {
  30923. isBaseAxisAndHasBarSeries |= seriesModel.getBaseAxis() === model.axis;
  30924. });
  30925. if (isBaseAxisAndHasBarSeries) {
  30926. // Calculate placement of bars on axis
  30927. var barWidthAndOffset = makeColumnLayout(barSeriesModels);
  30928. // Adjust axis min and max to account for overflow
  30929. var adjustedScale = adjustScaleForOverflow(min, max, model, barWidthAndOffset);
  30930. min = adjustedScale.min;
  30931. max = adjustedScale.max;
  30932. }
  30933. }
  30934. return {
  30935. extent: [min, max],
  30936. // "fix" means "fixed", the value should not be
  30937. // changed in the subsequent steps.
  30938. fixMin: fixMin,
  30939. fixMax: fixMax
  30940. };
  30941. }
  30942. function adjustScaleForOverflow(min, max, model, barWidthAndOffset) {
  30943. // Get Axis Length
  30944. var axisExtent = model.axis.getExtent();
  30945. var axisLength = axisExtent[1] - axisExtent[0];
  30946. // Get bars on current base axis and calculate min and max overflow
  30947. var barsOnCurrentAxis = retrieveColumnLayout(barWidthAndOffset, model.axis);
  30948. if (barsOnCurrentAxis === undefined) {
  30949. return {min: min, max: max};
  30950. }
  30951. var minOverflow = Infinity;
  30952. each$1(barsOnCurrentAxis, function (item) {
  30953. minOverflow = Math.min(item.offset, minOverflow);
  30954. });
  30955. var maxOverflow = -Infinity;
  30956. each$1(barsOnCurrentAxis, function (item) {
  30957. maxOverflow = Math.max(item.offset + item.width, maxOverflow);
  30958. });
  30959. minOverflow = Math.abs(minOverflow);
  30960. maxOverflow = Math.abs(maxOverflow);
  30961. var totalOverFlow = minOverflow + maxOverflow;
  30962. // Calulate required buffer based on old range and overflow
  30963. var oldRange = max - min;
  30964. var oldRangePercentOfNew = (1 - (minOverflow + maxOverflow) / axisLength);
  30965. var overflowBuffer = ((oldRange / oldRangePercentOfNew) - oldRange);
  30966. max += overflowBuffer * (maxOverflow / totalOverFlow);
  30967. min -= overflowBuffer * (minOverflow / totalOverFlow);
  30968. return {min: min, max: max};
  30969. }
  30970. function niceScaleExtent(scale, model) {
  30971. var extentInfo = getScaleExtent(scale, model);
  30972. var extent = extentInfo.extent;
  30973. var splitNumber = model.get('splitNumber');
  30974. if (scale.type === 'log') {
  30975. scale.base = model.get('logBase');
  30976. }
  30977. var scaleType = scale.type;
  30978. scale.setExtent(extent[0], extent[1]);
  30979. scale.niceExtent({
  30980. splitNumber: splitNumber,
  30981. fixMin: extentInfo.fixMin,
  30982. fixMax: extentInfo.fixMax,
  30983. minInterval: (scaleType === 'interval' || scaleType === 'time')
  30984. ? model.get('minInterval') : null,
  30985. maxInterval: (scaleType === 'interval' || scaleType === 'time')
  30986. ? model.get('maxInterval') : null
  30987. });
  30988. // If some one specified the min, max. And the default calculated interval
  30989. // is not good enough. He can specify the interval. It is often appeared
  30990. // in angle axis with angle 0 - 360. Interval calculated in interval scale is hard
  30991. // to be 60.
  30992. // FIXME
  30993. var interval = model.get('interval');
  30994. if (interval != null) {
  30995. scale.setInterval && scale.setInterval(interval);
  30996. }
  30997. }
  30998. /**
  30999. * @param {module:echarts/model/Model} model
  31000. * @param {string} [axisType] Default retrieve from model.type
  31001. * @return {module:echarts/scale/*}
  31002. */
  31003. function createScaleByModel(model, axisType) {
  31004. axisType = axisType || model.get('type');
  31005. if (axisType) {
  31006. switch (axisType) {
  31007. // Buildin scale
  31008. case 'category':
  31009. return new OrdinalScale(
  31010. model.getOrdinalMeta
  31011. ? model.getOrdinalMeta()
  31012. : model.getCategories(),
  31013. [Infinity, -Infinity]
  31014. );
  31015. case 'value':
  31016. return new IntervalScale();
  31017. // Extended scale, like time and log
  31018. default:
  31019. return (Scale.getClass(axisType) || IntervalScale).create(model);
  31020. }
  31021. }
  31022. }
  31023. /**
  31024. * Check if the axis corss 0
  31025. */
  31026. function ifAxisCrossZero(axis) {
  31027. var dataExtent = axis.scale.getExtent();
  31028. var min = dataExtent[0];
  31029. var max = dataExtent[1];
  31030. return !((min > 0 && max > 0) || (min < 0 && max < 0));
  31031. }
  31032. /**
  31033. * @param {module:echarts/coord/Axis} axis
  31034. * @return {Function} Label formatter function.
  31035. * param: {number} tickValue,
  31036. * param: {number} idx, the index in all ticks.
  31037. * If category axis, this param is not requied.
  31038. * return: {string} label string.
  31039. */
  31040. function makeLabelFormatter(axis) {
  31041. var labelFormatter = axis.getLabelModel().get('formatter');
  31042. var categoryTickStart = axis.type === 'category' ? axis.scale.getExtent()[0] : null;
  31043. if (typeof labelFormatter === 'string') {
  31044. labelFormatter = (function (tpl) {
  31045. return function (val) {
  31046. // For category axis, get raw value; for numeric axis,
  31047. // get foramtted label like '1,333,444'.
  31048. val = axis.scale.getLabel(val);
  31049. return tpl.replace('{value}', val != null ? val : '');
  31050. };
  31051. })(labelFormatter);
  31052. // Consider empty array
  31053. return labelFormatter;
  31054. }
  31055. else if (typeof labelFormatter === 'function') {
  31056. return function (tickValue, idx) {
  31057. // The original intention of `idx` is "the index of the tick in all ticks".
  31058. // But the previous implementation of category axis do not consider the
  31059. // `axisLabel.interval`, which cause that, for example, the `interval` is
  31060. // `1`, then the ticks "name5", "name7", "name9" are displayed, where the
  31061. // corresponding `idx` are `0`, `2`, `4`, but not `0`, `1`, `2`. So we keep
  31062. // the definition here for back compatibility.
  31063. if (categoryTickStart != null) {
  31064. idx = tickValue - categoryTickStart;
  31065. }
  31066. return labelFormatter(getAxisRawValue(axis, tickValue), idx);
  31067. };
  31068. }
  31069. else {
  31070. return function (tick) {
  31071. return axis.scale.getLabel(tick);
  31072. };
  31073. }
  31074. }
  31075. function getAxisRawValue(axis, value) {
  31076. // In category axis with data zoom, tick is not the original
  31077. // index of axis.data. So tick should not be exposed to user
  31078. // in category axis.
  31079. return axis.type === 'category' ? axis.scale.getLabel(value) : value;
  31080. }
  31081. /**
  31082. * @param {module:echarts/coord/Axis} axis
  31083. * @return {module:zrender/core/BoundingRect} Be null/undefined if no labels.
  31084. */
  31085. function estimateLabelUnionRect(axis) {
  31086. var axisModel = axis.model;
  31087. var scale = axis.scale;
  31088. if (!axisModel.get('axisLabel.show') || scale.isBlank()) {
  31089. return;
  31090. }
  31091. var isCategory = axis.type === 'category';
  31092. var realNumberScaleTicks;
  31093. var tickCount;
  31094. var categoryScaleExtent = scale.getExtent();
  31095. // Optimize for large category data, avoid call `getTicks()`.
  31096. if (isCategory) {
  31097. tickCount = scale.count();
  31098. }
  31099. else {
  31100. realNumberScaleTicks = scale.getTicks();
  31101. tickCount = realNumberScaleTicks.length;
  31102. }
  31103. var axisLabelModel = axis.getLabelModel();
  31104. var labelFormatter = makeLabelFormatter(axis);
  31105. var rect;
  31106. var step = 1;
  31107. // Simple optimization for large amount of labels
  31108. if (tickCount > 40) {
  31109. step = Math.ceil(tickCount / 40);
  31110. }
  31111. for (var i = 0; i < tickCount; i += step) {
  31112. var tickValue = realNumberScaleTicks ? realNumberScaleTicks[i] : categoryScaleExtent[0] + i;
  31113. var label = labelFormatter(tickValue);
  31114. var unrotatedSingleRect = axisLabelModel.getTextRect(label);
  31115. var singleRect = rotateTextRect(unrotatedSingleRect, axisLabelModel.get('rotate') || 0);
  31116. rect ? rect.union(singleRect) : (rect = singleRect);
  31117. }
  31118. return rect;
  31119. }
  31120. function rotateTextRect(textRect, rotate) {
  31121. var rotateRadians = rotate * Math.PI / 180;
  31122. var boundingBox = textRect.plain();
  31123. var beforeWidth = boundingBox.width;
  31124. var beforeHeight = boundingBox.height;
  31125. var afterWidth = beforeWidth * Math.cos(rotateRadians) + beforeHeight * Math.sin(rotateRadians);
  31126. var afterHeight = beforeWidth * Math.sin(rotateRadians) + beforeHeight * Math.cos(rotateRadians);
  31127. var rotatedRect = new BoundingRect(boundingBox.x, boundingBox.y, afterWidth, afterHeight);
  31128. return rotatedRect;
  31129. }
  31130. /**
  31131. * @param {module:echarts/src/model/Model} model axisLabelModel or axisTickModel
  31132. * @return {number|String} Can be null|'auto'|number|function
  31133. */
  31134. function getOptionCategoryInterval(model) {
  31135. var interval = model.get('interval');
  31136. return interval == null ? 'auto' : interval;
  31137. }
  31138. /**
  31139. * Set `categoryInterval` as 0 implicitly indicates that
  31140. * show all labels reguardless of overlap.
  31141. * @param {Object} axis axisModel.axis
  31142. * @return {boolean}
  31143. */
  31144. function shouldShowAllLabels(axis) {
  31145. return axis.type === 'category'
  31146. && getOptionCategoryInterval(axis.getLabelModel()) === 0;
  31147. }
  31148. /*
  31149. * Licensed to the Apache Software Foundation (ASF) under one
  31150. * or more contributor license agreements. See the NOTICE file
  31151. * distributed with this work for additional information
  31152. * regarding copyright ownership. The ASF licenses this file
  31153. * to you under the Apache License, Version 2.0 (the
  31154. * "License"); you may not use this file except in compliance
  31155. * with the License. You may obtain a copy of the License at
  31156. *
  31157. * http://www.apache.org/licenses/LICENSE-2.0
  31158. *
  31159. * Unless required by applicable law or agreed to in writing,
  31160. * software distributed under the License is distributed on an
  31161. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31162. * KIND, either express or implied. See the License for the
  31163. * specific language governing permissions and limitations
  31164. * under the License.
  31165. */
  31166. // import * as axisHelper from './axisHelper';
  31167. var axisModelCommonMixin = {
  31168. /**
  31169. * @param {boolean} origin
  31170. * @return {number|string} min value or 'dataMin' or null/undefined (means auto) or NaN
  31171. */
  31172. getMin: function (origin) {
  31173. var option = this.option;
  31174. var min = (!origin && option.rangeStart != null)
  31175. ? option.rangeStart : option.min;
  31176. if (this.axis
  31177. && min != null
  31178. && min !== 'dataMin'
  31179. && typeof min !== 'function'
  31180. && !eqNaN(min)
  31181. ) {
  31182. min = this.axis.scale.parse(min);
  31183. }
  31184. return min;
  31185. },
  31186. /**
  31187. * @param {boolean} origin
  31188. * @return {number|string} max value or 'dataMax' or null/undefined (means auto) or NaN
  31189. */
  31190. getMax: function (origin) {
  31191. var option = this.option;
  31192. var max = (!origin && option.rangeEnd != null)
  31193. ? option.rangeEnd : option.max;
  31194. if (this.axis
  31195. && max != null
  31196. && max !== 'dataMax'
  31197. && typeof max !== 'function'
  31198. && !eqNaN(max)
  31199. ) {
  31200. max = this.axis.scale.parse(max);
  31201. }
  31202. return max;
  31203. },
  31204. /**
  31205. * @return {boolean}
  31206. */
  31207. getNeedCrossZero: function () {
  31208. var option = this.option;
  31209. return (option.rangeStart != null || option.rangeEnd != null)
  31210. ? false : !option.scale;
  31211. },
  31212. /**
  31213. * Should be implemented by each axis model if necessary.
  31214. * @return {module:echarts/model/Component} coordinate system model
  31215. */
  31216. getCoordSysModel: noop,
  31217. /**
  31218. * @param {number} rangeStart Can only be finite number or null/undefined or NaN.
  31219. * @param {number} rangeEnd Can only be finite number or null/undefined or NaN.
  31220. */
  31221. setRange: function (rangeStart, rangeEnd) {
  31222. this.option.rangeStart = rangeStart;
  31223. this.option.rangeEnd = rangeEnd;
  31224. },
  31225. /**
  31226. * Reset range
  31227. */
  31228. resetRange: function () {
  31229. // rangeStart and rangeEnd is readonly.
  31230. this.option.rangeStart = this.option.rangeEnd = null;
  31231. }
  31232. };
  31233. /*
  31234. * Licensed to the Apache Software Foundation (ASF) under one
  31235. * or more contributor license agreements. See the NOTICE file
  31236. * distributed with this work for additional information
  31237. * regarding copyright ownership. The ASF licenses this file
  31238. * to you under the Apache License, Version 2.0 (the
  31239. * "License"); you may not use this file except in compliance
  31240. * with the License. You may obtain a copy of the License at
  31241. *
  31242. * http://www.apache.org/licenses/LICENSE-2.0
  31243. *
  31244. * Unless required by applicable law or agreed to in writing,
  31245. * software distributed under the License is distributed on an
  31246. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31247. * KIND, either express or implied. See the License for the
  31248. * specific language governing permissions and limitations
  31249. * under the License.
  31250. */
  31251. // Symbol factory
  31252. /**
  31253. * Triangle shape
  31254. * @inner
  31255. */
  31256. var Triangle = extendShape({
  31257. type: 'triangle',
  31258. shape: {
  31259. cx: 0,
  31260. cy: 0,
  31261. width: 0,
  31262. height: 0
  31263. },
  31264. buildPath: function (path, shape) {
  31265. var cx = shape.cx;
  31266. var cy = shape.cy;
  31267. var width = shape.width / 2;
  31268. var height = shape.height / 2;
  31269. path.moveTo(cx, cy - height);
  31270. path.lineTo(cx + width, cy + height);
  31271. path.lineTo(cx - width, cy + height);
  31272. path.closePath();
  31273. }
  31274. });
  31275. /**
  31276. * Diamond shape
  31277. * @inner
  31278. */
  31279. var Diamond = extendShape({
  31280. type: 'diamond',
  31281. shape: {
  31282. cx: 0,
  31283. cy: 0,
  31284. width: 0,
  31285. height: 0
  31286. },
  31287. buildPath: function (path, shape) {
  31288. var cx = shape.cx;
  31289. var cy = shape.cy;
  31290. var width = shape.width / 2;
  31291. var height = shape.height / 2;
  31292. path.moveTo(cx, cy - height);
  31293. path.lineTo(cx + width, cy);
  31294. path.lineTo(cx, cy + height);
  31295. path.lineTo(cx - width, cy);
  31296. path.closePath();
  31297. }
  31298. });
  31299. /**
  31300. * Pin shape
  31301. * @inner
  31302. */
  31303. var Pin = extendShape({
  31304. type: 'pin',
  31305. shape: {
  31306. // x, y on the cusp
  31307. x: 0,
  31308. y: 0,
  31309. width: 0,
  31310. height: 0
  31311. },
  31312. buildPath: function (path, shape) {
  31313. var x = shape.x;
  31314. var y = shape.y;
  31315. var w = shape.width / 5 * 3;
  31316. // Height must be larger than width
  31317. var h = Math.max(w, shape.height);
  31318. var r = w / 2;
  31319. // Dist on y with tangent point and circle center
  31320. var dy = r * r / (h - r);
  31321. var cy = y - h + r + dy;
  31322. var angle = Math.asin(dy / r);
  31323. // Dist on x with tangent point and circle center
  31324. var dx = Math.cos(angle) * r;
  31325. var tanX = Math.sin(angle);
  31326. var tanY = Math.cos(angle);
  31327. var cpLen = r * 0.6;
  31328. var cpLen2 = r * 0.7;
  31329. path.moveTo(x - dx, cy + dy);
  31330. path.arc(
  31331. x, cy, r,
  31332. Math.PI - angle,
  31333. Math.PI * 2 + angle
  31334. );
  31335. path.bezierCurveTo(
  31336. x + dx - tanX * cpLen, cy + dy + tanY * cpLen,
  31337. x, y - cpLen2,
  31338. x, y
  31339. );
  31340. path.bezierCurveTo(
  31341. x, y - cpLen2,
  31342. x - dx + tanX * cpLen, cy + dy + tanY * cpLen,
  31343. x - dx, cy + dy
  31344. );
  31345. path.closePath();
  31346. }
  31347. });
  31348. /**
  31349. * Arrow shape
  31350. * @inner
  31351. */
  31352. var Arrow = extendShape({
  31353. type: 'arrow',
  31354. shape: {
  31355. x: 0,
  31356. y: 0,
  31357. width: 0,
  31358. height: 0
  31359. },
  31360. buildPath: function (ctx, shape) {
  31361. var height = shape.height;
  31362. var width = shape.width;
  31363. var x = shape.x;
  31364. var y = shape.y;
  31365. var dx = width / 3 * 2;
  31366. ctx.moveTo(x, y);
  31367. ctx.lineTo(x + dx, y + height);
  31368. ctx.lineTo(x, y + height / 4 * 3);
  31369. ctx.lineTo(x - dx, y + height);
  31370. ctx.lineTo(x, y);
  31371. ctx.closePath();
  31372. }
  31373. });
  31374. /**
  31375. * Map of path contructors
  31376. * @type {Object.<string, module:zrender/graphic/Path>}
  31377. */
  31378. var symbolCtors = {
  31379. line: Line,
  31380. rect: Rect,
  31381. roundRect: Rect,
  31382. square: Rect,
  31383. circle: Circle,
  31384. diamond: Diamond,
  31385. pin: Pin,
  31386. arrow: Arrow,
  31387. triangle: Triangle
  31388. };
  31389. var symbolShapeMakers = {
  31390. line: function (x, y, w, h, shape) {
  31391. // FIXME
  31392. shape.x1 = x;
  31393. shape.y1 = y + h / 2;
  31394. shape.x2 = x + w;
  31395. shape.y2 = y + h / 2;
  31396. },
  31397. rect: function (x, y, w, h, shape) {
  31398. shape.x = x;
  31399. shape.y = y;
  31400. shape.width = w;
  31401. shape.height = h;
  31402. },
  31403. roundRect: function (x, y, w, h, shape) {
  31404. shape.x = x;
  31405. shape.y = y;
  31406. shape.width = w;
  31407. shape.height = h;
  31408. shape.r = Math.min(w, h) / 4;
  31409. },
  31410. square: function (x, y, w, h, shape) {
  31411. var size = Math.min(w, h);
  31412. shape.x = x;
  31413. shape.y = y;
  31414. shape.width = size;
  31415. shape.height = size;
  31416. },
  31417. circle: function (x, y, w, h, shape) {
  31418. // Put circle in the center of square
  31419. shape.cx = x + w / 2;
  31420. shape.cy = y + h / 2;
  31421. shape.r = Math.min(w, h) / 2;
  31422. },
  31423. diamond: function (x, y, w, h, shape) {
  31424. shape.cx = x + w / 2;
  31425. shape.cy = y + h / 2;
  31426. shape.width = w;
  31427. shape.height = h;
  31428. },
  31429. pin: function (x, y, w, h, shape) {
  31430. shape.x = x + w / 2;
  31431. shape.y = y + h / 2;
  31432. shape.width = w;
  31433. shape.height = h;
  31434. },
  31435. arrow: function (x, y, w, h, shape) {
  31436. shape.x = x + w / 2;
  31437. shape.y = y + h / 2;
  31438. shape.width = w;
  31439. shape.height = h;
  31440. },
  31441. triangle: function (x, y, w, h, shape) {
  31442. shape.cx = x + w / 2;
  31443. shape.cy = y + h / 2;
  31444. shape.width = w;
  31445. shape.height = h;
  31446. }
  31447. };
  31448. var symbolBuildProxies = {};
  31449. each$1(symbolCtors, function (Ctor, name) {
  31450. symbolBuildProxies[name] = new Ctor();
  31451. });
  31452. var SymbolClz = extendShape({
  31453. type: 'symbol',
  31454. shape: {
  31455. symbolType: '',
  31456. x: 0,
  31457. y: 0,
  31458. width: 0,
  31459. height: 0
  31460. },
  31461. calculateTextPosition: function (out, style, rect) {
  31462. var res = calculateTextPosition(out, style, rect);
  31463. var shape = this.shape;
  31464. if (shape && shape.symbolType === 'pin' && style.textPosition === 'inside') {
  31465. res.y = rect.y + rect.height * 0.4;
  31466. }
  31467. return res;
  31468. },
  31469. buildPath: function (ctx, shape, inBundle) {
  31470. var symbolType = shape.symbolType;
  31471. if (symbolType !== 'none') {
  31472. var proxySymbol = symbolBuildProxies[symbolType];
  31473. if (!proxySymbol) {
  31474. // Default rect
  31475. symbolType = 'rect';
  31476. proxySymbol = symbolBuildProxies[symbolType];
  31477. }
  31478. symbolShapeMakers[symbolType](
  31479. shape.x, shape.y, shape.width, shape.height, proxySymbol.shape
  31480. );
  31481. proxySymbol.buildPath(ctx, proxySymbol.shape, inBundle);
  31482. }
  31483. }
  31484. });
  31485. // Provide setColor helper method to avoid determine if set the fill or stroke outside
  31486. function symbolPathSetColor(color, innerColor) {
  31487. if (this.type !== 'image') {
  31488. var symbolStyle = this.style;
  31489. var symbolShape = this.shape;
  31490. if (symbolShape && symbolShape.symbolType === 'line') {
  31491. symbolStyle.stroke = color;
  31492. }
  31493. else if (this.__isEmptyBrush) {
  31494. symbolStyle.stroke = color;
  31495. symbolStyle.fill = innerColor || '#fff';
  31496. }
  31497. else {
  31498. // FIXME 判断图形默认是填充还是描边,使用 onlyStroke ?
  31499. symbolStyle.fill && (symbolStyle.fill = color);
  31500. symbolStyle.stroke && (symbolStyle.stroke = color);
  31501. }
  31502. this.dirty(false);
  31503. }
  31504. }
  31505. /**
  31506. * Create a symbol element with given symbol configuration: shape, x, y, width, height, color
  31507. * @param {string} symbolType
  31508. * @param {number} x
  31509. * @param {number} y
  31510. * @param {number} w
  31511. * @param {number} h
  31512. * @param {string} color
  31513. * @param {boolean} [keepAspect=false] whether to keep the ratio of w/h,
  31514. * for path and image only.
  31515. */
  31516. function createSymbol(symbolType, x, y, w, h, color, keepAspect) {
  31517. // TODO Support image object, DynamicImage.
  31518. var isEmpty = symbolType.indexOf('empty') === 0;
  31519. if (isEmpty) {
  31520. symbolType = symbolType.substr(5, 1).toLowerCase() + symbolType.substr(6);
  31521. }
  31522. var symbolPath;
  31523. if (symbolType.indexOf('image://') === 0) {
  31524. symbolPath = makeImage(
  31525. symbolType.slice(8),
  31526. new BoundingRect(x, y, w, h),
  31527. keepAspect ? 'center' : 'cover'
  31528. );
  31529. }
  31530. else if (symbolType.indexOf('path://') === 0) {
  31531. symbolPath = makePath(
  31532. symbolType.slice(7),
  31533. {},
  31534. new BoundingRect(x, y, w, h),
  31535. keepAspect ? 'center' : 'cover'
  31536. );
  31537. }
  31538. else {
  31539. symbolPath = new SymbolClz({
  31540. shape: {
  31541. symbolType: symbolType,
  31542. x: x,
  31543. y: y,
  31544. width: w,
  31545. height: h
  31546. }
  31547. });
  31548. }
  31549. symbolPath.__isEmptyBrush = isEmpty;
  31550. symbolPath.setColor = symbolPathSetColor;
  31551. symbolPath.setColor(color);
  31552. return symbolPath;
  31553. }
  31554. /*
  31555. * Licensed to the Apache Software Foundation (ASF) under one
  31556. * or more contributor license agreements. See the NOTICE file
  31557. * distributed with this work for additional information
  31558. * regarding copyright ownership. The ASF licenses this file
  31559. * to you under the Apache License, Version 2.0 (the
  31560. * "License"); you may not use this file except in compliance
  31561. * with the License. You may obtain a copy of the License at
  31562. *
  31563. * http://www.apache.org/licenses/LICENSE-2.0
  31564. *
  31565. * Unless required by applicable law or agreed to in writing,
  31566. * software distributed under the License is distributed on an
  31567. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31568. * KIND, either express or implied. See the License for the
  31569. * specific language governing permissions and limitations
  31570. * under the License.
  31571. */
  31572. // import createGraphFromNodeEdge from './chart/helper/createGraphFromNodeEdge';
  31573. /**
  31574. * Create a muti dimension List structure from seriesModel.
  31575. * @param {module:echarts/model/Model} seriesModel
  31576. * @return {module:echarts/data/List} list
  31577. */
  31578. function createList(seriesModel) {
  31579. return createListFromArray(seriesModel.getSource(), seriesModel);
  31580. }
  31581. var dataStack$1 = {
  31582. isDimensionStacked: isDimensionStacked,
  31583. enableDataStack: enableDataStack,
  31584. getStackedDimension: getStackedDimension
  31585. };
  31586. /**
  31587. * Create scale
  31588. * @param {Array.<number>} dataExtent
  31589. * @param {Object|module:echarts/Model} option
  31590. */
  31591. function createScale(dataExtent, option) {
  31592. var axisModel = option;
  31593. if (!Model.isInstance(option)) {
  31594. axisModel = new Model(option);
  31595. mixin(axisModel, axisModelCommonMixin);
  31596. }
  31597. var scale = createScaleByModel(axisModel);
  31598. scale.setExtent(dataExtent[0], dataExtent[1]);
  31599. niceScaleExtent(scale, axisModel);
  31600. return scale;
  31601. }
  31602. /**
  31603. * Mixin common methods to axis model,
  31604. *
  31605. * Inlcude methods
  31606. * `getFormattedLabels() => Array.<string>`
  31607. * `getCategories() => Array.<string>`
  31608. * `getMin(origin: boolean) => number`
  31609. * `getMax(origin: boolean) => number`
  31610. * `getNeedCrossZero() => boolean`
  31611. * `setRange(start: number, end: number)`
  31612. * `resetRange()`
  31613. */
  31614. function mixinAxisModelCommonMethods(Model$$1) {
  31615. mixin(Model$$1, axisModelCommonMixin);
  31616. }
  31617. var helper = (Object.freeze || Object)({
  31618. createList: createList,
  31619. getLayoutRect: getLayoutRect,
  31620. dataStack: dataStack$1,
  31621. createScale: createScale,
  31622. mixinAxisModelCommonMethods: mixinAxisModelCommonMethods,
  31623. completeDimensions: completeDimensions,
  31624. createDimensions: createDimensions,
  31625. createSymbol: createSymbol
  31626. });
  31627. var EPSILON$3 = 1e-8;
  31628. function isAroundEqual$1(a, b) {
  31629. return Math.abs(a - b) < EPSILON$3;
  31630. }
  31631. function contain$1(points, x, y) {
  31632. var w = 0;
  31633. var p = points[0];
  31634. if (!p) {
  31635. return false;
  31636. }
  31637. for (var i = 1; i < points.length; i++) {
  31638. var p2 = points[i];
  31639. w += windingLine(p[0], p[1], p2[0], p2[1], x, y);
  31640. p = p2;
  31641. }
  31642. // Close polygon
  31643. var p0 = points[0];
  31644. if (!isAroundEqual$1(p[0], p0[0]) || !isAroundEqual$1(p[1], p0[1])) {
  31645. w += windingLine(p[0], p[1], p0[0], p0[1], x, y);
  31646. }
  31647. return w !== 0;
  31648. }
  31649. /*
  31650. * Licensed to the Apache Software Foundation (ASF) under one
  31651. * or more contributor license agreements. See the NOTICE file
  31652. * distributed with this work for additional information
  31653. * regarding copyright ownership. The ASF licenses this file
  31654. * to you under the Apache License, Version 2.0 (the
  31655. * "License"); you may not use this file except in compliance
  31656. * with the License. You may obtain a copy of the License at
  31657. *
  31658. * http://www.apache.org/licenses/LICENSE-2.0
  31659. *
  31660. * Unless required by applicable law or agreed to in writing,
  31661. * software distributed under the License is distributed on an
  31662. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31663. * KIND, either express or implied. See the License for the
  31664. * specific language governing permissions and limitations
  31665. * under the License.
  31666. */
  31667. /**
  31668. * @module echarts/coord/geo/Region
  31669. */
  31670. /**
  31671. * @param {string|Region} name
  31672. * @param {Array} geometries
  31673. * @param {Array.<number>} cp
  31674. */
  31675. function Region(name, geometries, cp) {
  31676. /**
  31677. * @type {string}
  31678. * @readOnly
  31679. */
  31680. this.name = name;
  31681. /**
  31682. * @type {Array.<Array>}
  31683. * @readOnly
  31684. */
  31685. this.geometries = geometries;
  31686. if (!cp) {
  31687. var rect = this.getBoundingRect();
  31688. cp = [
  31689. rect.x + rect.width / 2,
  31690. rect.y + rect.height / 2
  31691. ];
  31692. }
  31693. else {
  31694. cp = [cp[0], cp[1]];
  31695. }
  31696. /**
  31697. * @type {Array.<number>}
  31698. */
  31699. this.center = cp;
  31700. }
  31701. Region.prototype = {
  31702. constructor: Region,
  31703. properties: null,
  31704. /**
  31705. * @return {module:zrender/core/BoundingRect}
  31706. */
  31707. getBoundingRect: function () {
  31708. var rect = this._rect;
  31709. if (rect) {
  31710. return rect;
  31711. }
  31712. var MAX_NUMBER = Number.MAX_VALUE;
  31713. var min$$1 = [MAX_NUMBER, MAX_NUMBER];
  31714. var max$$1 = [-MAX_NUMBER, -MAX_NUMBER];
  31715. var min2 = [];
  31716. var max2 = [];
  31717. var geometries = this.geometries;
  31718. for (var i = 0; i < geometries.length; i++) {
  31719. // Only support polygon
  31720. if (geometries[i].type !== 'polygon') {
  31721. continue;
  31722. }
  31723. // Doesn't consider hole
  31724. var exterior = geometries[i].exterior;
  31725. fromPoints(exterior, min2, max2);
  31726. min(min$$1, min$$1, min2);
  31727. max(max$$1, max$$1, max2);
  31728. }
  31729. // No data
  31730. if (i === 0) {
  31731. min$$1[0] = min$$1[1] = max$$1[0] = max$$1[1] = 0;
  31732. }
  31733. return (this._rect = new BoundingRect(
  31734. min$$1[0], min$$1[1], max$$1[0] - min$$1[0], max$$1[1] - min$$1[1]
  31735. ));
  31736. },
  31737. /**
  31738. * @param {<Array.<number>} coord
  31739. * @return {boolean}
  31740. */
  31741. contain: function (coord) {
  31742. var rect = this.getBoundingRect();
  31743. var geometries = this.geometries;
  31744. if (!rect.contain(coord[0], coord[1])) {
  31745. return false;
  31746. }
  31747. loopGeo: for (var i = 0, len$$1 = geometries.length; i < len$$1; i++) {
  31748. // Only support polygon.
  31749. if (geometries[i].type !== 'polygon') {
  31750. continue;
  31751. }
  31752. var exterior = geometries[i].exterior;
  31753. var interiors = geometries[i].interiors;
  31754. if (contain$1(exterior, coord[0], coord[1])) {
  31755. // Not in the region if point is in the hole.
  31756. for (var k = 0; k < (interiors ? interiors.length : 0); k++) {
  31757. if (contain$1(interiors[k])) {
  31758. continue loopGeo;
  31759. }
  31760. }
  31761. return true;
  31762. }
  31763. }
  31764. return false;
  31765. },
  31766. transformTo: function (x, y, width, height) {
  31767. var rect = this.getBoundingRect();
  31768. var aspect = rect.width / rect.height;
  31769. if (!width) {
  31770. width = aspect * height;
  31771. }
  31772. else if (!height) {
  31773. height = width / aspect;
  31774. }
  31775. var target = new BoundingRect(x, y, width, height);
  31776. var transform = rect.calculateTransform(target);
  31777. var geometries = this.geometries;
  31778. for (var i = 0; i < geometries.length; i++) {
  31779. // Only support polygon.
  31780. if (geometries[i].type !== 'polygon') {
  31781. continue;
  31782. }
  31783. var exterior = geometries[i].exterior;
  31784. var interiors = geometries[i].interiors;
  31785. for (var p = 0; p < exterior.length; p++) {
  31786. applyTransform(exterior[p], exterior[p], transform);
  31787. }
  31788. for (var h = 0; h < (interiors ? interiors.length : 0); h++) {
  31789. for (var p = 0; p < interiors[h].length; p++) {
  31790. applyTransform(interiors[h][p], interiors[h][p], transform);
  31791. }
  31792. }
  31793. }
  31794. rect = this._rect;
  31795. rect.copy(target);
  31796. // Update center
  31797. this.center = [
  31798. rect.x + rect.width / 2,
  31799. rect.y + rect.height / 2
  31800. ];
  31801. },
  31802. cloneShallow: function (name) {
  31803. name == null && (name = this.name);
  31804. var newRegion = new Region(name, this.geometries, this.center);
  31805. newRegion._rect = this._rect;
  31806. newRegion.transformTo = null; // Simply avoid to be called.
  31807. return newRegion;
  31808. }
  31809. };
  31810. /*
  31811. * Licensed to the Apache Software Foundation (ASF) under one
  31812. * or more contributor license agreements. See the NOTICE file
  31813. * distributed with this work for additional information
  31814. * regarding copyright ownership. The ASF licenses this file
  31815. * to you under the Apache License, Version 2.0 (the
  31816. * "License"); you may not use this file except in compliance
  31817. * with the License. You may obtain a copy of the License at
  31818. *
  31819. * http://www.apache.org/licenses/LICENSE-2.0
  31820. *
  31821. * Unless required by applicable law or agreed to in writing,
  31822. * software distributed under the License is distributed on an
  31823. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31824. * KIND, either express or implied. See the License for the
  31825. * specific language governing permissions and limitations
  31826. * under the License.
  31827. */
  31828. /**
  31829. * Parse and decode geo json
  31830. * @module echarts/coord/geo/parseGeoJson
  31831. */
  31832. function decode(json) {
  31833. if (!json.UTF8Encoding) {
  31834. return json;
  31835. }
  31836. var encodeScale = json.UTF8Scale;
  31837. if (encodeScale == null) {
  31838. encodeScale = 1024;
  31839. }
  31840. var features = json.features;
  31841. for (var f = 0; f < features.length; f++) {
  31842. var feature = features[f];
  31843. var geometry = feature.geometry;
  31844. var coordinates = geometry.coordinates;
  31845. var encodeOffsets = geometry.encodeOffsets;
  31846. for (var c = 0; c < coordinates.length; c++) {
  31847. var coordinate = coordinates[c];
  31848. if (geometry.type === 'Polygon') {
  31849. coordinates[c] = decodePolygon(
  31850. coordinate,
  31851. encodeOffsets[c],
  31852. encodeScale
  31853. );
  31854. }
  31855. else if (geometry.type === 'MultiPolygon') {
  31856. for (var c2 = 0; c2 < coordinate.length; c2++) {
  31857. var polygon = coordinate[c2];
  31858. coordinate[c2] = decodePolygon(
  31859. polygon,
  31860. encodeOffsets[c][c2],
  31861. encodeScale
  31862. );
  31863. }
  31864. }
  31865. }
  31866. }
  31867. // Has been decoded
  31868. json.UTF8Encoding = false;
  31869. return json;
  31870. }
  31871. function decodePolygon(coordinate, encodeOffsets, encodeScale) {
  31872. var result = [];
  31873. var prevX = encodeOffsets[0];
  31874. var prevY = encodeOffsets[1];
  31875. for (var i = 0; i < coordinate.length; i += 2) {
  31876. var x = coordinate.charCodeAt(i) - 64;
  31877. var y = coordinate.charCodeAt(i + 1) - 64;
  31878. // ZigZag decoding
  31879. x = (x >> 1) ^ (-(x & 1));
  31880. y = (y >> 1) ^ (-(y & 1));
  31881. // Delta deocding
  31882. x += prevX;
  31883. y += prevY;
  31884. prevX = x;
  31885. prevY = y;
  31886. // Dequantize
  31887. result.push([x / encodeScale, y / encodeScale]);
  31888. }
  31889. return result;
  31890. }
  31891. /**
  31892. * @alias module:echarts/coord/geo/parseGeoJson
  31893. * @param {Object} geoJson
  31894. * @param {string} nameProperty
  31895. * @return {module:zrender/container/Group}
  31896. */
  31897. var parseGeoJson$1 = function (geoJson, nameProperty) {
  31898. decode(geoJson);
  31899. return map(filter(geoJson.features, function (featureObj) {
  31900. // Output of mapshaper may have geometry null
  31901. return featureObj.geometry
  31902. && featureObj.properties
  31903. && featureObj.geometry.coordinates.length > 0;
  31904. }), function (featureObj) {
  31905. var properties = featureObj.properties;
  31906. var geo = featureObj.geometry;
  31907. var coordinates = geo.coordinates;
  31908. var geometries = [];
  31909. if (geo.type === 'Polygon') {
  31910. geometries.push({
  31911. type: 'polygon',
  31912. // According to the GeoJSON specification.
  31913. // First must be exterior, and the rest are all interior(holes).
  31914. exterior: coordinates[0],
  31915. interiors: coordinates.slice(1)
  31916. });
  31917. }
  31918. if (geo.type === 'MultiPolygon') {
  31919. each$1(coordinates, function (item) {
  31920. if (item[0]) {
  31921. geometries.push({
  31922. type: 'polygon',
  31923. exterior: item[0],
  31924. interiors: item.slice(1)
  31925. });
  31926. }
  31927. });
  31928. }
  31929. var region = new Region(
  31930. properties[nameProperty || 'name'],
  31931. geometries,
  31932. properties.cp
  31933. );
  31934. region.properties = properties;
  31935. return region;
  31936. });
  31937. };
  31938. /*
  31939. * Licensed to the Apache Software Foundation (ASF) under one
  31940. * or more contributor license agreements. See the NOTICE file
  31941. * distributed with this work for additional information
  31942. * regarding copyright ownership. The ASF licenses this file
  31943. * to you under the Apache License, Version 2.0 (the
  31944. * "License"); you may not use this file except in compliance
  31945. * with the License. You may obtain a copy of the License at
  31946. *
  31947. * http://www.apache.org/licenses/LICENSE-2.0
  31948. *
  31949. * Unless required by applicable law or agreed to in writing,
  31950. * software distributed under the License is distributed on an
  31951. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31952. * KIND, either express or implied. See the License for the
  31953. * specific language governing permissions and limitations
  31954. * under the License.
  31955. */
  31956. var inner$6 = makeInner();
  31957. /**
  31958. * @param {module:echats/coord/Axis} axis
  31959. * @return {Object} {
  31960. * labels: [{
  31961. * formattedLabel: string,
  31962. * rawLabel: string,
  31963. * tickValue: number
  31964. * }, ...],
  31965. * labelCategoryInterval: number
  31966. * }
  31967. */
  31968. function createAxisLabels(axis) {
  31969. // Only ordinal scale support tick interval
  31970. return axis.type === 'category'
  31971. ? makeCategoryLabels(axis)
  31972. : makeRealNumberLabels(axis);
  31973. }
  31974. /**
  31975. * @param {module:echats/coord/Axis} axis
  31976. * @param {module:echarts/model/Model} tickModel For example, can be axisTick, splitLine, splitArea.
  31977. * @return {Object} {
  31978. * ticks: Array.<number>
  31979. * tickCategoryInterval: number
  31980. * }
  31981. */
  31982. function createAxisTicks(axis, tickModel) {
  31983. // Only ordinal scale support tick interval
  31984. return axis.type === 'category'
  31985. ? makeCategoryTicks(axis, tickModel)
  31986. : {ticks: axis.scale.getTicks()};
  31987. }
  31988. function makeCategoryLabels(axis) {
  31989. var labelModel = axis.getLabelModel();
  31990. var result = makeCategoryLabelsActually(axis, labelModel);
  31991. return (!labelModel.get('show') || axis.scale.isBlank())
  31992. ? {labels: [], labelCategoryInterval: result.labelCategoryInterval}
  31993. : result;
  31994. }
  31995. function makeCategoryLabelsActually(axis, labelModel) {
  31996. var labelsCache = getListCache(axis, 'labels');
  31997. var optionLabelInterval = getOptionCategoryInterval(labelModel);
  31998. var result = listCacheGet(labelsCache, optionLabelInterval);
  31999. if (result) {
  32000. return result;
  32001. }
  32002. var labels;
  32003. var numericLabelInterval;
  32004. if (isFunction$1(optionLabelInterval)) {
  32005. labels = makeLabelsByCustomizedCategoryInterval(axis, optionLabelInterval);
  32006. }
  32007. else {
  32008. numericLabelInterval = optionLabelInterval === 'auto'
  32009. ? makeAutoCategoryInterval(axis) : optionLabelInterval;
  32010. labels = makeLabelsByNumericCategoryInterval(axis, numericLabelInterval);
  32011. }
  32012. // Cache to avoid calling interval function repeatly.
  32013. return listCacheSet(labelsCache, optionLabelInterval, {
  32014. labels: labels, labelCategoryInterval: numericLabelInterval
  32015. });
  32016. }
  32017. function makeCategoryTicks(axis, tickModel) {
  32018. var ticksCache = getListCache(axis, 'ticks');
  32019. var optionTickInterval = getOptionCategoryInterval(tickModel);
  32020. var result = listCacheGet(ticksCache, optionTickInterval);
  32021. if (result) {
  32022. return result;
  32023. }
  32024. var ticks;
  32025. var tickCategoryInterval;
  32026. // Optimize for the case that large category data and no label displayed,
  32027. // we should not return all ticks.
  32028. if (!tickModel.get('show') || axis.scale.isBlank()) {
  32029. ticks = [];
  32030. }
  32031. if (isFunction$1(optionTickInterval)) {
  32032. ticks = makeLabelsByCustomizedCategoryInterval(axis, optionTickInterval, true);
  32033. }
  32034. // Always use label interval by default despite label show. Consider this
  32035. // scenario, Use multiple grid with the xAxis sync, and only one xAxis shows
  32036. // labels. `splitLine` and `axisTick` should be consistent in this case.
  32037. else if (optionTickInterval === 'auto') {
  32038. var labelsResult = makeCategoryLabelsActually(axis, axis.getLabelModel());
  32039. tickCategoryInterval = labelsResult.labelCategoryInterval;
  32040. ticks = map(labelsResult.labels, function (labelItem) {
  32041. return labelItem.tickValue;
  32042. });
  32043. }
  32044. else {
  32045. tickCategoryInterval = optionTickInterval;
  32046. ticks = makeLabelsByNumericCategoryInterval(axis, tickCategoryInterval, true);
  32047. }
  32048. // Cache to avoid calling interval function repeatly.
  32049. return listCacheSet(ticksCache, optionTickInterval, {
  32050. ticks: ticks, tickCategoryInterval: tickCategoryInterval
  32051. });
  32052. }
  32053. function makeRealNumberLabels(axis) {
  32054. var ticks = axis.scale.getTicks();
  32055. var labelFormatter = makeLabelFormatter(axis);
  32056. return {
  32057. labels: map(ticks, function (tickValue, idx) {
  32058. return {
  32059. formattedLabel: labelFormatter(tickValue, idx),
  32060. rawLabel: axis.scale.getLabel(tickValue),
  32061. tickValue: tickValue
  32062. };
  32063. })
  32064. };
  32065. }
  32066. // Large category data calculation is performence sensitive, and ticks and label
  32067. // probably be fetched by multiple times. So we cache the result.
  32068. // axis is created each time during a ec process, so we do not need to clear cache.
  32069. function getListCache(axis, prop) {
  32070. // Because key can be funciton, and cache size always be small, we use array cache.
  32071. return inner$6(axis)[prop] || (inner$6(axis)[prop] = []);
  32072. }
  32073. function listCacheGet(cache, key) {
  32074. for (var i = 0; i < cache.length; i++) {
  32075. if (cache[i].key === key) {
  32076. return cache[i].value;
  32077. }
  32078. }
  32079. }
  32080. function listCacheSet(cache, key, value) {
  32081. cache.push({key: key, value: value});
  32082. return value;
  32083. }
  32084. function makeAutoCategoryInterval(axis) {
  32085. var result = inner$6(axis).autoInterval;
  32086. return result != null
  32087. ? result
  32088. : (inner$6(axis).autoInterval = axis.calculateCategoryInterval());
  32089. }
  32090. /**
  32091. * Calculate interval for category axis ticks and labels.
  32092. * To get precise result, at least one of `getRotate` and `isHorizontal`
  32093. * should be implemented in axis.
  32094. */
  32095. function calculateCategoryInterval(axis) {
  32096. var params = fetchAutoCategoryIntervalCalculationParams(axis);
  32097. var labelFormatter = makeLabelFormatter(axis);
  32098. var rotation = (params.axisRotate - params.labelRotate) / 180 * Math.PI;
  32099. var ordinalScale = axis.scale;
  32100. var ordinalExtent = ordinalScale.getExtent();
  32101. // Providing this method is for optimization:
  32102. // avoid generating a long array by `getTicks`
  32103. // in large category data case.
  32104. var tickCount = ordinalScale.count();
  32105. if (ordinalExtent[1] - ordinalExtent[0] < 1) {
  32106. return 0;
  32107. }
  32108. var step = 1;
  32109. // Simple optimization. Empirical value: tick count should less than 40.
  32110. if (tickCount > 40) {
  32111. step = Math.max(1, Math.floor(tickCount / 40));
  32112. }
  32113. var tickValue = ordinalExtent[0];
  32114. var unitSpan = axis.dataToCoord(tickValue + 1) - axis.dataToCoord(tickValue);
  32115. var unitW = Math.abs(unitSpan * Math.cos(rotation));
  32116. var unitH = Math.abs(unitSpan * Math.sin(rotation));
  32117. var maxW = 0;
  32118. var maxH = 0;
  32119. // Caution: Performance sensitive for large category data.
  32120. // Consider dataZoom, we should make appropriate step to avoid O(n) loop.
  32121. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  32122. var width = 0;
  32123. var height = 0;
  32124. // Not precise, do not consider align and vertical align
  32125. // and each distance from axis line yet.
  32126. var rect = getBoundingRect(
  32127. labelFormatter(tickValue), params.font, 'center', 'top'
  32128. );
  32129. // Magic number
  32130. width = rect.width * 1.3;
  32131. height = rect.height * 1.3;
  32132. // Min size, void long loop.
  32133. maxW = Math.max(maxW, width, 7);
  32134. maxH = Math.max(maxH, height, 7);
  32135. }
  32136. var dw = maxW / unitW;
  32137. var dh = maxH / unitH;
  32138. // 0/0 is NaN, 1/0 is Infinity.
  32139. isNaN(dw) && (dw = Infinity);
  32140. isNaN(dh) && (dh = Infinity);
  32141. var interval = Math.max(0, Math.floor(Math.min(dw, dh)));
  32142. var cache = inner$6(axis.model);
  32143. var axisExtent = axis.getExtent();
  32144. var lastAutoInterval = cache.lastAutoInterval;
  32145. var lastTickCount = cache.lastTickCount;
  32146. // Use cache to keep interval stable while moving zoom window,
  32147. // otherwise the calculated interval might jitter when the zoom
  32148. // window size is close to the interval-changing size.
  32149. // For example, if all of the axis labels are `a, b, c, d, e, f, g`.
  32150. // The jitter will cause that sometimes the displayed labels are
  32151. // `a, d, g` (interval: 2) sometimes `a, c, e`(interval: 1).
  32152. if (lastAutoInterval != null
  32153. && lastTickCount != null
  32154. && Math.abs(lastAutoInterval - interval) <= 1
  32155. && Math.abs(lastTickCount - tickCount) <= 1
  32156. // Always choose the bigger one, otherwise the critical
  32157. // point is not the same when zooming in or zooming out.
  32158. && lastAutoInterval > interval
  32159. // If the axis change is caused by chart resize, the cache should not
  32160. // be used. Otherwise some hiden labels might not be shown again.
  32161. && cache.axisExtend0 === axisExtent[0]
  32162. && cache.axisExtend1 === axisExtent[1]
  32163. ) {
  32164. interval = lastAutoInterval;
  32165. }
  32166. // Only update cache if cache not used, otherwise the
  32167. // changing of interval is too insensitive.
  32168. else {
  32169. cache.lastTickCount = tickCount;
  32170. cache.lastAutoInterval = interval;
  32171. cache.axisExtend0 = axisExtent[0];
  32172. cache.axisExtend1 = axisExtent[1];
  32173. }
  32174. return interval;
  32175. }
  32176. function fetchAutoCategoryIntervalCalculationParams(axis) {
  32177. var labelModel = axis.getLabelModel();
  32178. return {
  32179. axisRotate: axis.getRotate
  32180. ? axis.getRotate()
  32181. : (axis.isHorizontal && !axis.isHorizontal())
  32182. ? 90
  32183. : 0,
  32184. labelRotate: labelModel.get('rotate') || 0,
  32185. font: labelModel.getFont()
  32186. };
  32187. }
  32188. function makeLabelsByNumericCategoryInterval(axis, categoryInterval, onlyTick) {
  32189. var labelFormatter = makeLabelFormatter(axis);
  32190. var ordinalScale = axis.scale;
  32191. var ordinalExtent = ordinalScale.getExtent();
  32192. var labelModel = axis.getLabelModel();
  32193. var result = [];
  32194. // TODO: axisType: ordinalTime, pick the tick from each month/day/year/...
  32195. var step = Math.max((categoryInterval || 0) + 1, 1);
  32196. var startTick = ordinalExtent[0];
  32197. var tickCount = ordinalScale.count();
  32198. // Calculate start tick based on zero if possible to keep label consistent
  32199. // while zooming and moving while interval > 0. Otherwise the selection
  32200. // of displayable ticks and symbols probably keep changing.
  32201. // 3 is empirical value.
  32202. if (startTick !== 0 && step > 1 && tickCount / step > 2) {
  32203. startTick = Math.round(Math.ceil(startTick / step) * step);
  32204. }
  32205. // (1) Only add min max label here but leave overlap checking
  32206. // to render stage, which also ensure the returned list
  32207. // suitable for splitLine and splitArea rendering.
  32208. // (2) Scales except category always contain min max label so
  32209. // do not need to perform this process.
  32210. var showAllLabel = shouldShowAllLabels(axis);
  32211. var includeMinLabel = labelModel.get('showMinLabel') || showAllLabel;
  32212. var includeMaxLabel = labelModel.get('showMaxLabel') || showAllLabel;
  32213. if (includeMinLabel && startTick !== ordinalExtent[0]) {
  32214. addItem(ordinalExtent[0]);
  32215. }
  32216. // Optimize: avoid generating large array by `ordinalScale.getTicks()`.
  32217. var tickValue = startTick;
  32218. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  32219. addItem(tickValue);
  32220. }
  32221. if (includeMaxLabel && tickValue - step !== ordinalExtent[1]) {
  32222. addItem(ordinalExtent[1]);
  32223. }
  32224. function addItem(tVal) {
  32225. result.push(onlyTick
  32226. ? tVal
  32227. : {
  32228. formattedLabel: labelFormatter(tVal),
  32229. rawLabel: ordinalScale.getLabel(tVal),
  32230. tickValue: tVal
  32231. }
  32232. );
  32233. }
  32234. return result;
  32235. }
  32236. // When interval is function, the result `false` means ignore the tick.
  32237. // It is time consuming for large category data.
  32238. function makeLabelsByCustomizedCategoryInterval(axis, categoryInterval, onlyTick) {
  32239. var ordinalScale = axis.scale;
  32240. var labelFormatter = makeLabelFormatter(axis);
  32241. var result = [];
  32242. each$1(ordinalScale.getTicks(), function (tickValue) {
  32243. var rawLabel = ordinalScale.getLabel(tickValue);
  32244. if (categoryInterval(tickValue, rawLabel)) {
  32245. result.push(onlyTick
  32246. ? tickValue
  32247. : {
  32248. formattedLabel: labelFormatter(tickValue),
  32249. rawLabel: rawLabel,
  32250. tickValue: tickValue
  32251. }
  32252. );
  32253. }
  32254. });
  32255. return result;
  32256. }
  32257. /*
  32258. * Licensed to the Apache Software Foundation (ASF) under one
  32259. * or more contributor license agreements. See the NOTICE file
  32260. * distributed with this work for additional information
  32261. * regarding copyright ownership. The ASF licenses this file
  32262. * to you under the Apache License, Version 2.0 (the
  32263. * "License"); you may not use this file except in compliance
  32264. * with the License. You may obtain a copy of the License at
  32265. *
  32266. * http://www.apache.org/licenses/LICENSE-2.0
  32267. *
  32268. * Unless required by applicable law or agreed to in writing,
  32269. * software distributed under the License is distributed on an
  32270. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32271. * KIND, either express or implied. See the License for the
  32272. * specific language governing permissions and limitations
  32273. * under the License.
  32274. */
  32275. var NORMALIZED_EXTENT = [0, 1];
  32276. /**
  32277. * Base class of Axis.
  32278. * @constructor
  32279. */
  32280. var Axis = function (dim, scale, extent) {
  32281. /**
  32282. * Axis dimension. Such as 'x', 'y', 'z', 'angle', 'radius'.
  32283. * @type {string}
  32284. */
  32285. this.dim = dim;
  32286. /**
  32287. * Axis scale
  32288. * @type {module:echarts/coord/scale/*}
  32289. */
  32290. this.scale = scale;
  32291. /**
  32292. * @type {Array.<number>}
  32293. * @private
  32294. */
  32295. this._extent = extent || [0, 0];
  32296. /**
  32297. * @type {boolean}
  32298. */
  32299. this.inverse = false;
  32300. /**
  32301. * Usually true when axis has a ordinal scale
  32302. * @type {boolean}
  32303. */
  32304. this.onBand = false;
  32305. };
  32306. Axis.prototype = {
  32307. constructor: Axis,
  32308. /**
  32309. * If axis extent contain given coord
  32310. * @param {number} coord
  32311. * @return {boolean}
  32312. */
  32313. contain: function (coord) {
  32314. var extent = this._extent;
  32315. var min = Math.min(extent[0], extent[1]);
  32316. var max = Math.max(extent[0], extent[1]);
  32317. return coord >= min && coord <= max;
  32318. },
  32319. /**
  32320. * If axis extent contain given data
  32321. * @param {number} data
  32322. * @return {boolean}
  32323. */
  32324. containData: function (data) {
  32325. return this.scale.contain(data);
  32326. },
  32327. /**
  32328. * Get coord extent.
  32329. * @return {Array.<number>}
  32330. */
  32331. getExtent: function () {
  32332. return this._extent.slice();
  32333. },
  32334. /**
  32335. * Get precision used for formatting
  32336. * @param {Array.<number>} [dataExtent]
  32337. * @return {number}
  32338. */
  32339. getPixelPrecision: function (dataExtent) {
  32340. return getPixelPrecision(
  32341. dataExtent || this.scale.getExtent(),
  32342. this._extent
  32343. );
  32344. },
  32345. /**
  32346. * Set coord extent
  32347. * @param {number} start
  32348. * @param {number} end
  32349. */
  32350. setExtent: function (start, end) {
  32351. var extent = this._extent;
  32352. extent[0] = start;
  32353. extent[1] = end;
  32354. },
  32355. /**
  32356. * Convert data to coord. Data is the rank if it has an ordinal scale
  32357. * @param {number} data
  32358. * @param {boolean} clamp
  32359. * @return {number}
  32360. */
  32361. dataToCoord: function (data, clamp) {
  32362. var extent = this._extent;
  32363. var scale = this.scale;
  32364. data = scale.normalize(data);
  32365. if (this.onBand && scale.type === 'ordinal') {
  32366. extent = extent.slice();
  32367. fixExtentWithBands(extent, scale.count());
  32368. }
  32369. return linearMap(data, NORMALIZED_EXTENT, extent, clamp);
  32370. },
  32371. /**
  32372. * Convert coord to data. Data is the rank if it has an ordinal scale
  32373. * @param {number} coord
  32374. * @param {boolean} clamp
  32375. * @return {number}
  32376. */
  32377. coordToData: function (coord, clamp) {
  32378. var extent = this._extent;
  32379. var scale = this.scale;
  32380. if (this.onBand && scale.type === 'ordinal') {
  32381. extent = extent.slice();
  32382. fixExtentWithBands(extent, scale.count());
  32383. }
  32384. var t = linearMap(coord, extent, NORMALIZED_EXTENT, clamp);
  32385. return this.scale.scale(t);
  32386. },
  32387. /**
  32388. * Convert pixel point to data in axis
  32389. * @param {Array.<number>} point
  32390. * @param {boolean} clamp
  32391. * @return {number} data
  32392. */
  32393. pointToData: function (point, clamp) {
  32394. // Should be implemented in derived class if necessary.
  32395. },
  32396. /**
  32397. * Different from `zrUtil.map(axis.getTicks(), axis.dataToCoord, axis)`,
  32398. * `axis.getTicksCoords` considers `onBand`, which is used by
  32399. * `boundaryGap:true` of category axis and splitLine and splitArea.
  32400. * @param {Object} [opt]
  32401. * @param {Model} [opt.tickModel=axis.model.getModel('axisTick')]
  32402. * @param {boolean} [opt.clamp] If `true`, the first and the last
  32403. * tick must be at the axis end points. Otherwise, clip ticks
  32404. * that outside the axis extent.
  32405. * @return {Array.<Object>} [{
  32406. * coord: ...,
  32407. * tickValue: ...
  32408. * }, ...]
  32409. */
  32410. getTicksCoords: function (opt) {
  32411. opt = opt || {};
  32412. var tickModel = opt.tickModel || this.getTickModel();
  32413. var result = createAxisTicks(this, tickModel);
  32414. var ticks = result.ticks;
  32415. var ticksCoords = map(ticks, function (tickValue) {
  32416. return {
  32417. coord: this.dataToCoord(tickValue),
  32418. tickValue: tickValue
  32419. };
  32420. }, this);
  32421. var alignWithLabel = tickModel.get('alignWithLabel');
  32422. fixOnBandTicksCoords(
  32423. this, ticksCoords, alignWithLabel, opt.clamp
  32424. );
  32425. return ticksCoords;
  32426. },
  32427. /**
  32428. * @return {Array.<Array.<Object>>} [{ coord: ..., tickValue: ...}]
  32429. */
  32430. getMinorTicksCoords: function () {
  32431. if (this.scale.type === 'ordinal') {
  32432. // Category axis doesn't support minor ticks
  32433. return [];
  32434. }
  32435. var minorTickModel = this.model.getModel('minorTick');
  32436. var splitNumber = minorTickModel.get('splitNumber');
  32437. // Protection.
  32438. if (!(splitNumber > 0 && splitNumber < 100)) {
  32439. splitNumber = 5;
  32440. }
  32441. var minorTicks = this.scale.getMinorTicks(splitNumber);
  32442. var minorTicksCoords = map(minorTicks, function (minorTicksGroup) {
  32443. return map(minorTicksGroup, function (minorTick) {
  32444. return {
  32445. coord: this.dataToCoord(minorTick),
  32446. tickValue: minorTick
  32447. };
  32448. }, this);
  32449. }, this);
  32450. return minorTicksCoords;
  32451. },
  32452. /**
  32453. * @return {Array.<Object>} [{
  32454. * formattedLabel: string,
  32455. * rawLabel: axis.scale.getLabel(tickValue)
  32456. * tickValue: number
  32457. * }, ...]
  32458. */
  32459. getViewLabels: function () {
  32460. return createAxisLabels(this).labels;
  32461. },
  32462. /**
  32463. * @return {module:echarts/coord/model/Model}
  32464. */
  32465. getLabelModel: function () {
  32466. return this.model.getModel('axisLabel');
  32467. },
  32468. /**
  32469. * Notice here we only get the default tick model. For splitLine
  32470. * or splitArea, we should pass the splitLineModel or splitAreaModel
  32471. * manually when calling `getTicksCoords`.
  32472. * In GL, this method may be overrided to:
  32473. * `axisModel.getModel('axisTick', grid3DModel.getModel('axisTick'));`
  32474. * @return {module:echarts/coord/model/Model}
  32475. */
  32476. getTickModel: function () {
  32477. return this.model.getModel('axisTick');
  32478. },
  32479. /**
  32480. * Get width of band
  32481. * @return {number}
  32482. */
  32483. getBandWidth: function () {
  32484. var axisExtent = this._extent;
  32485. var dataExtent = this.scale.getExtent();
  32486. var len = dataExtent[1] - dataExtent[0] + (this.onBand ? 1 : 0);
  32487. // Fix #2728, avoid NaN when only one data.
  32488. len === 0 && (len = 1);
  32489. var size = Math.abs(axisExtent[1] - axisExtent[0]);
  32490. return Math.abs(size) / len;
  32491. },
  32492. /**
  32493. * @abstract
  32494. * @return {boolean} Is horizontal
  32495. */
  32496. isHorizontal: null,
  32497. /**
  32498. * @abstract
  32499. * @return {number} Get axis rotate, by degree.
  32500. */
  32501. getRotate: null,
  32502. /**
  32503. * Only be called in category axis.
  32504. * Can be overrided, consider other axes like in 3D.
  32505. * @return {number} Auto interval for cateogry axis tick and label
  32506. */
  32507. calculateCategoryInterval: function () {
  32508. return calculateCategoryInterval(this);
  32509. }
  32510. };
  32511. function fixExtentWithBands(extent, nTick) {
  32512. var size = extent[1] - extent[0];
  32513. var len = nTick;
  32514. var margin = size / len / 2;
  32515. extent[0] += margin;
  32516. extent[1] -= margin;
  32517. }
  32518. // If axis has labels [1, 2, 3, 4]. Bands on the axis are
  32519. // |---1---|---2---|---3---|---4---|.
  32520. // So the displayed ticks and splitLine/splitArea should between
  32521. // each data item, otherwise cause misleading (e.g., split tow bars
  32522. // of a single data item when there are two bar series).
  32523. // Also consider if tickCategoryInterval > 0 and onBand, ticks and
  32524. // splitLine/spliteArea should layout appropriately corresponding
  32525. // to displayed labels. (So we should not use `getBandWidth` in this
  32526. // case).
  32527. function fixOnBandTicksCoords(axis, ticksCoords, alignWithLabel, clamp) {
  32528. var ticksLen = ticksCoords.length;
  32529. if (!axis.onBand || alignWithLabel || !ticksLen) {
  32530. return;
  32531. }
  32532. var axisExtent = axis.getExtent();
  32533. var last;
  32534. var diffSize;
  32535. if (ticksLen === 1) {
  32536. ticksCoords[0].coord = axisExtent[0];
  32537. last = ticksCoords[1] = {coord: axisExtent[0]};
  32538. }
  32539. else {
  32540. var crossLen = ticksCoords[ticksLen - 1].tickValue - ticksCoords[0].tickValue;
  32541. var shift = (ticksCoords[ticksLen - 1].coord - ticksCoords[0].coord) / crossLen;
  32542. each$1(ticksCoords, function (ticksItem) {
  32543. ticksItem.coord -= shift / 2;
  32544. });
  32545. var dataExtent = axis.scale.getExtent();
  32546. diffSize = 1 + dataExtent[1] - ticksCoords[ticksLen - 1].tickValue;
  32547. last = {coord: ticksCoords[ticksLen - 1].coord + shift * diffSize};
  32548. ticksCoords.push(last);
  32549. }
  32550. var inverse = axisExtent[0] > axisExtent[1];
  32551. // Handling clamp.
  32552. if (littleThan(ticksCoords[0].coord, axisExtent[0])) {
  32553. clamp ? (ticksCoords[0].coord = axisExtent[0]) : ticksCoords.shift();
  32554. }
  32555. if (clamp && littleThan(axisExtent[0], ticksCoords[0].coord)) {
  32556. ticksCoords.unshift({coord: axisExtent[0]});
  32557. }
  32558. if (littleThan(axisExtent[1], last.coord)) {
  32559. clamp ? (last.coord = axisExtent[1]) : ticksCoords.pop();
  32560. }
  32561. if (clamp && littleThan(last.coord, axisExtent[1])) {
  32562. ticksCoords.push({coord: axisExtent[1]});
  32563. }
  32564. function littleThan(a, b) {
  32565. // Avoid rounding error cause calculated tick coord different with extent.
  32566. // It may cause an extra unecessary tick added.
  32567. a = round$1(a);
  32568. b = round$1(b);
  32569. return inverse ? a > b : a < b;
  32570. }
  32571. }
  32572. /*
  32573. * Licensed to the Apache Software Foundation (ASF) under one
  32574. * or more contributor license agreements. See the NOTICE file
  32575. * distributed with this work for additional information
  32576. * regarding copyright ownership. The ASF licenses this file
  32577. * to you under the Apache License, Version 2.0 (the
  32578. * "License"); you may not use this file except in compliance
  32579. * with the License. You may obtain a copy of the License at
  32580. *
  32581. * http://www.apache.org/licenses/LICENSE-2.0
  32582. *
  32583. * Unless required by applicable law or agreed to in writing,
  32584. * software distributed under the License is distributed on an
  32585. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32586. * KIND, either express or implied. See the License for the
  32587. * specific language governing permissions and limitations
  32588. * under the License.
  32589. */
  32590. /**
  32591. * Do not mount those modules on 'src/echarts' for better tree shaking.
  32592. */
  32593. var parseGeoJson = parseGeoJson$1;
  32594. var ecUtil = {};
  32595. each$1(
  32596. [
  32597. 'map', 'each', 'filter', 'indexOf', 'inherits', 'reduce', 'filter',
  32598. 'bind', 'curry', 'isArray', 'isString', 'isObject', 'isFunction',
  32599. 'extend', 'defaults', 'clone', 'merge'
  32600. ],
  32601. function (name) {
  32602. ecUtil[name] = zrUtil[name];
  32603. }
  32604. );
  32605. var graphic$1 = {};
  32606. each$1(
  32607. [
  32608. 'extendShape', 'extendPath', 'makePath', 'makeImage',
  32609. 'mergePath', 'resizePath', 'createIcon',
  32610. 'setHoverStyle', 'setLabelStyle', 'setTextStyle', 'setText',
  32611. 'getFont', 'updateProps', 'initProps', 'getTransform',
  32612. 'clipPointsByRect', 'clipRectByRect',
  32613. 'registerShape', 'getShapeClass',
  32614. 'Group',
  32615. 'Image',
  32616. 'Text',
  32617. 'Circle',
  32618. 'Sector',
  32619. 'Ring',
  32620. 'Polygon',
  32621. 'Polyline',
  32622. 'Rect',
  32623. 'Line',
  32624. 'BezierCurve',
  32625. 'Arc',
  32626. 'IncrementalDisplayable',
  32627. 'CompoundPath',
  32628. 'LinearGradient',
  32629. 'RadialGradient',
  32630. 'BoundingRect'
  32631. ],
  32632. function (name) {
  32633. graphic$1[name] = graphic[name];
  32634. }
  32635. );
  32636. /*
  32637. * Licensed to the Apache Software Foundation (ASF) under one
  32638. * or more contributor license agreements. See the NOTICE file
  32639. * distributed with this work for additional information
  32640. * regarding copyright ownership. The ASF licenses this file
  32641. * to you under the Apache License, Version 2.0 (the
  32642. * "License"); you may not use this file except in compliance
  32643. * with the License. You may obtain a copy of the License at
  32644. *
  32645. * http://www.apache.org/licenses/LICENSE-2.0
  32646. *
  32647. * Unless required by applicable law or agreed to in writing,
  32648. * software distributed under the License is distributed on an
  32649. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32650. * KIND, either express or implied. See the License for the
  32651. * specific language governing permissions and limitations
  32652. * under the License.
  32653. */
  32654. SeriesModel.extend({
  32655. type: 'series.line',
  32656. dependencies: ['grid', 'polar'],
  32657. getInitialData: function (option, ecModel) {
  32658. if (__DEV__) {
  32659. var coordSys = option.coordinateSystem;
  32660. if (coordSys !== 'polar' && coordSys !== 'cartesian2d') {
  32661. throw new Error('Line not support coordinateSystem besides cartesian and polar');
  32662. }
  32663. }
  32664. return createListFromArray(this.getSource(), this, {useEncodeDefaulter: true});
  32665. },
  32666. defaultOption: {
  32667. zlevel: 0,
  32668. z: 2,
  32669. coordinateSystem: 'cartesian2d',
  32670. legendHoverLink: true,
  32671. hoverAnimation: true,
  32672. // stack: null
  32673. // xAxisIndex: 0,
  32674. // yAxisIndex: 0,
  32675. // polarIndex: 0,
  32676. // If clip the overflow value
  32677. clip: true,
  32678. // cursor: null,
  32679. label: {
  32680. position: 'top'
  32681. },
  32682. // itemStyle: {
  32683. // },
  32684. lineStyle: {
  32685. width: 2,
  32686. type: 'solid'
  32687. },
  32688. // areaStyle: {
  32689. // origin of areaStyle. Valid values:
  32690. // `'auto'/null/undefined`: from axisLine to data
  32691. // `'start'`: from min to data
  32692. // `'end'`: from data to max
  32693. // origin: 'auto'
  32694. // },
  32695. // false, 'start', 'end', 'middle'
  32696. step: false,
  32697. // Disabled if step is true
  32698. smooth: false,
  32699. smoothMonotone: null,
  32700. symbol: 'emptyCircle',
  32701. symbolSize: 4,
  32702. symbolRotate: null,
  32703. showSymbol: true,
  32704. // `false`: follow the label interval strategy.
  32705. // `true`: show all symbols.
  32706. // `'auto'`: If possible, show all symbols, otherwise
  32707. // follow the label interval strategy.
  32708. showAllSymbol: 'auto',
  32709. // Whether to connect break point.
  32710. connectNulls: false,
  32711. // Sampling for large data. Can be: 'average', 'max', 'min', 'sum'.
  32712. sampling: 'none',
  32713. animationEasing: 'linear',
  32714. // Disable progressive
  32715. progressive: 0,
  32716. hoverLayerThreshold: Infinity
  32717. }
  32718. });
  32719. /*
  32720. * Licensed to the Apache Software Foundation (ASF) under one
  32721. * or more contributor license agreements. See the NOTICE file
  32722. * distributed with this work for additional information
  32723. * regarding copyright ownership. The ASF licenses this file
  32724. * to you under the Apache License, Version 2.0 (the
  32725. * "License"); you may not use this file except in compliance
  32726. * with the License. You may obtain a copy of the License at
  32727. *
  32728. * http://www.apache.org/licenses/LICENSE-2.0
  32729. *
  32730. * Unless required by applicable law or agreed to in writing,
  32731. * software distributed under the License is distributed on an
  32732. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32733. * KIND, either express or implied. See the License for the
  32734. * specific language governing permissions and limitations
  32735. * under the License.
  32736. */
  32737. /**
  32738. * @param {module:echarts/data/List} data
  32739. * @param {number} dataIndex
  32740. * @return {string} label string. Not null/undefined
  32741. */
  32742. function getDefaultLabel(data, dataIndex) {
  32743. var labelDims = data.mapDimension('defaultedLabel', true);
  32744. var len = labelDims.length;
  32745. // Simple optimization (in lots of cases, label dims length is 1)
  32746. if (len === 1) {
  32747. return retrieveRawValue(data, dataIndex, labelDims[0]);
  32748. }
  32749. else if (len) {
  32750. var vals = [];
  32751. for (var i = 0; i < labelDims.length; i++) {
  32752. var val = retrieveRawValue(data, dataIndex, labelDims[i]);
  32753. vals.push(val);
  32754. }
  32755. return vals.join(' ');
  32756. }
  32757. }
  32758. /*
  32759. * Licensed to the Apache Software Foundation (ASF) under one
  32760. * or more contributor license agreements. See the NOTICE file
  32761. * distributed with this work for additional information
  32762. * regarding copyright ownership. The ASF licenses this file
  32763. * to you under the Apache License, Version 2.0 (the
  32764. * "License"); you may not use this file except in compliance
  32765. * with the License. You may obtain a copy of the License at
  32766. *
  32767. * http://www.apache.org/licenses/LICENSE-2.0
  32768. *
  32769. * Unless required by applicable law or agreed to in writing,
  32770. * software distributed under the License is distributed on an
  32771. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32772. * KIND, either express or implied. See the License for the
  32773. * specific language governing permissions and limitations
  32774. * under the License.
  32775. */
  32776. /**
  32777. * @module echarts/chart/helper/Symbol
  32778. */
  32779. /**
  32780. * @constructor
  32781. * @alias {module:echarts/chart/helper/Symbol}
  32782. * @param {module:echarts/data/List} data
  32783. * @param {number} idx
  32784. * @extends {module:zrender/graphic/Group}
  32785. */
  32786. function SymbolClz$1(data, idx, seriesScope) {
  32787. Group.call(this);
  32788. this.updateData(data, idx, seriesScope);
  32789. }
  32790. var symbolProto = SymbolClz$1.prototype;
  32791. /**
  32792. * @public
  32793. * @static
  32794. * @param {module:echarts/data/List} data
  32795. * @param {number} dataIndex
  32796. * @return {Array.<number>} [width, height]
  32797. */
  32798. var getSymbolSize = SymbolClz$1.getSymbolSize = function (data, idx) {
  32799. var symbolSize = data.getItemVisual(idx, 'symbolSize');
  32800. return symbolSize instanceof Array
  32801. ? symbolSize.slice()
  32802. : [+symbolSize, +symbolSize];
  32803. };
  32804. function getScale(symbolSize) {
  32805. return [symbolSize[0] / 2, symbolSize[1] / 2];
  32806. }
  32807. function driftSymbol(dx, dy) {
  32808. this.parent.drift(dx, dy);
  32809. }
  32810. symbolProto._createSymbol = function (
  32811. symbolType,
  32812. data,
  32813. idx,
  32814. symbolSize,
  32815. keepAspect
  32816. ) {
  32817. // Remove paths created before
  32818. this.removeAll();
  32819. var color = data.getItemVisual(idx, 'color');
  32820. // var symbolPath = createSymbol(
  32821. // symbolType, -0.5, -0.5, 1, 1, color
  32822. // );
  32823. // If width/height are set too small (e.g., set to 1) on ios10
  32824. // and macOS Sierra, a circle stroke become a rect, no matter what
  32825. // the scale is set. So we set width/height as 2. See #4150.
  32826. var symbolPath = createSymbol(
  32827. symbolType, -1, -1, 2, 2, color, keepAspect
  32828. );
  32829. symbolPath.attr({
  32830. z2: 100,
  32831. culling: true,
  32832. scale: getScale(symbolSize)
  32833. });
  32834. // Rewrite drift method
  32835. symbolPath.drift = driftSymbol;
  32836. this._symbolType = symbolType;
  32837. this.add(symbolPath);
  32838. };
  32839. /**
  32840. * Stop animation
  32841. * @param {boolean} toLastFrame
  32842. */
  32843. symbolProto.stopSymbolAnimation = function (toLastFrame) {
  32844. this.childAt(0).stopAnimation(toLastFrame);
  32845. };
  32846. /**
  32847. * FIXME:
  32848. * Caution: This method breaks the encapsulation of this module,
  32849. * but it indeed brings convenience. So do not use the method
  32850. * unless you detailedly know all the implements of `Symbol`,
  32851. * especially animation.
  32852. *
  32853. * Get symbol path element.
  32854. */
  32855. symbolProto.getSymbolPath = function () {
  32856. return this.childAt(0);
  32857. };
  32858. /**
  32859. * Get scale(aka, current symbol size).
  32860. * Including the change caused by animation
  32861. */
  32862. symbolProto.getScale = function () {
  32863. return this.childAt(0).scale;
  32864. };
  32865. /**
  32866. * Highlight symbol
  32867. */
  32868. symbolProto.highlight = function () {
  32869. this.childAt(0).trigger('emphasis');
  32870. };
  32871. /**
  32872. * Downplay symbol
  32873. */
  32874. symbolProto.downplay = function () {
  32875. this.childAt(0).trigger('normal');
  32876. };
  32877. /**
  32878. * @param {number} zlevel
  32879. * @param {number} z
  32880. */
  32881. symbolProto.setZ = function (zlevel, z) {
  32882. var symbolPath = this.childAt(0);
  32883. symbolPath.zlevel = zlevel;
  32884. symbolPath.z = z;
  32885. };
  32886. symbolProto.setDraggable = function (draggable) {
  32887. var symbolPath = this.childAt(0);
  32888. symbolPath.draggable = draggable;
  32889. symbolPath.cursor = draggable ? 'move' : symbolPath.cursor;
  32890. };
  32891. /**
  32892. * Update symbol properties
  32893. * @param {module:echarts/data/List} data
  32894. * @param {number} idx
  32895. * @param {Object} [seriesScope]
  32896. * @param {Object} [seriesScope.itemStyle]
  32897. * @param {Object} [seriesScope.hoverItemStyle]
  32898. * @param {Object} [seriesScope.symbolRotate]
  32899. * @param {Object} [seriesScope.symbolOffset]
  32900. * @param {module:echarts/model/Model} [seriesScope.labelModel]
  32901. * @param {module:echarts/model/Model} [seriesScope.hoverLabelModel]
  32902. * @param {boolean} [seriesScope.hoverAnimation]
  32903. * @param {Object} [seriesScope.cursorStyle]
  32904. * @param {module:echarts/model/Model} [seriesScope.itemModel]
  32905. * @param {string} [seriesScope.symbolInnerColor]
  32906. * @param {Object} [seriesScope.fadeIn=false]
  32907. */
  32908. symbolProto.updateData = function (data, idx, seriesScope) {
  32909. this.silent = false;
  32910. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  32911. var seriesModel = data.hostModel;
  32912. var symbolSize = getSymbolSize(data, idx);
  32913. var isInit = symbolType !== this._symbolType;
  32914. if (isInit) {
  32915. var keepAspect = data.getItemVisual(idx, 'symbolKeepAspect');
  32916. this._createSymbol(symbolType, data, idx, symbolSize, keepAspect);
  32917. }
  32918. else {
  32919. var symbolPath = this.childAt(0);
  32920. symbolPath.silent = false;
  32921. updateProps(symbolPath, {
  32922. scale: getScale(symbolSize)
  32923. }, seriesModel, idx);
  32924. }
  32925. this._updateCommon(data, idx, symbolSize, seriesScope);
  32926. if (isInit) {
  32927. var symbolPath = this.childAt(0);
  32928. var fadeIn = seriesScope && seriesScope.fadeIn;
  32929. var target = {scale: symbolPath.scale.slice()};
  32930. fadeIn && (target.style = {opacity: symbolPath.style.opacity});
  32931. symbolPath.scale = [0, 0];
  32932. fadeIn && (symbolPath.style.opacity = 0);
  32933. initProps(symbolPath, target, seriesModel, idx);
  32934. }
  32935. this._seriesModel = seriesModel;
  32936. };
  32937. // Update common properties
  32938. var normalStyleAccessPath = ['itemStyle'];
  32939. var emphasisStyleAccessPath = ['emphasis', 'itemStyle'];
  32940. var normalLabelAccessPath = ['label'];
  32941. var emphasisLabelAccessPath = ['emphasis', 'label'];
  32942. /**
  32943. * @param {module:echarts/data/List} data
  32944. * @param {number} idx
  32945. * @param {Array.<number>} symbolSize
  32946. * @param {Object} [seriesScope]
  32947. */
  32948. symbolProto._updateCommon = function (data, idx, symbolSize, seriesScope) {
  32949. var symbolPath = this.childAt(0);
  32950. var seriesModel = data.hostModel;
  32951. var color = data.getItemVisual(idx, 'color');
  32952. // Reset style
  32953. if (symbolPath.type !== 'image') {
  32954. symbolPath.useStyle({
  32955. strokeNoScale: true
  32956. });
  32957. }
  32958. else {
  32959. symbolPath.setStyle({
  32960. opacity: null,
  32961. shadowBlur: null,
  32962. shadowOffsetX: null,
  32963. shadowOffsetY: null,
  32964. shadowColor: null
  32965. });
  32966. }
  32967. var itemStyle = seriesScope && seriesScope.itemStyle;
  32968. var hoverItemStyle = seriesScope && seriesScope.hoverItemStyle;
  32969. var symbolOffset = seriesScope && seriesScope.symbolOffset;
  32970. var labelModel = seriesScope && seriesScope.labelModel;
  32971. var hoverLabelModel = seriesScope && seriesScope.hoverLabelModel;
  32972. var hoverAnimation = seriesScope && seriesScope.hoverAnimation;
  32973. var cursorStyle = seriesScope && seriesScope.cursorStyle;
  32974. if (!seriesScope || data.hasItemOption) {
  32975. var itemModel = (seriesScope && seriesScope.itemModel)
  32976. ? seriesScope.itemModel : data.getItemModel(idx);
  32977. // Color must be excluded.
  32978. // Because symbol provide setColor individually to set fill and stroke
  32979. itemStyle = itemModel.getModel(normalStyleAccessPath).getItemStyle(['color']);
  32980. hoverItemStyle = itemModel.getModel(emphasisStyleAccessPath).getItemStyle();
  32981. symbolOffset = itemModel.getShallow('symbolOffset');
  32982. labelModel = itemModel.getModel(normalLabelAccessPath);
  32983. hoverLabelModel = itemModel.getModel(emphasisLabelAccessPath);
  32984. hoverAnimation = itemModel.getShallow('hoverAnimation');
  32985. cursorStyle = itemModel.getShallow('cursor');
  32986. }
  32987. else {
  32988. hoverItemStyle = extend({}, hoverItemStyle);
  32989. }
  32990. var elStyle = symbolPath.style;
  32991. var symbolRotate = data.getItemVisual(idx, 'symbolRotate');
  32992. symbolPath.attr('rotation', (symbolRotate || 0) * Math.PI / 180 || 0);
  32993. if (symbolOffset) {
  32994. symbolPath.attr('position', [
  32995. parsePercent$1(symbolOffset[0], symbolSize[0]),
  32996. parsePercent$1(symbolOffset[1], symbolSize[1])
  32997. ]);
  32998. }
  32999. cursorStyle && symbolPath.attr('cursor', cursorStyle);
  33000. // PENDING setColor before setStyle!!!
  33001. symbolPath.setColor(color, seriesScope && seriesScope.symbolInnerColor);
  33002. symbolPath.setStyle(itemStyle);
  33003. var opacity = data.getItemVisual(idx, 'opacity');
  33004. if (opacity != null) {
  33005. elStyle.opacity = opacity;
  33006. }
  33007. var liftZ = data.getItemVisual(idx, 'liftZ');
  33008. var z2Origin = symbolPath.__z2Origin;
  33009. if (liftZ != null) {
  33010. if (z2Origin == null) {
  33011. symbolPath.__z2Origin = symbolPath.z2;
  33012. symbolPath.z2 += liftZ;
  33013. }
  33014. }
  33015. else if (z2Origin != null) {
  33016. symbolPath.z2 = z2Origin;
  33017. symbolPath.__z2Origin = null;
  33018. }
  33019. var useNameLabel = seriesScope && seriesScope.useNameLabel;
  33020. setLabelStyle(
  33021. elStyle, hoverItemStyle, labelModel, hoverLabelModel,
  33022. {
  33023. labelFetcher: seriesModel,
  33024. labelDataIndex: idx,
  33025. defaultText: getLabelDefaultText,
  33026. isRectText: true,
  33027. autoColor: color
  33028. }
  33029. );
  33030. // Do not execute util needed.
  33031. function getLabelDefaultText(idx, opt) {
  33032. return useNameLabel ? data.getName(idx) : getDefaultLabel(data, idx);
  33033. }
  33034. symbolPath.__symbolOriginalScale = getScale(symbolSize);
  33035. symbolPath.hoverStyle = hoverItemStyle;
  33036. symbolPath.highDownOnUpdate = (
  33037. hoverAnimation && seriesModel.isAnimationEnabled()
  33038. ) ? highDownOnUpdate : null;
  33039. setHoverStyle(symbolPath);
  33040. };
  33041. function highDownOnUpdate(fromState, toState) {
  33042. // Do not support this hover animation util some scenario required.
  33043. // Animation can only be supported in hover layer when using `el.incremetal`.
  33044. if (this.incremental || this.useHoverLayer) {
  33045. return;
  33046. }
  33047. if (toState === 'emphasis') {
  33048. var scale = this.__symbolOriginalScale;
  33049. var ratio = scale[1] / scale[0];
  33050. var emphasisOpt = {
  33051. scale: [
  33052. Math.max(scale[0] * 1.1, scale[0] + 3),
  33053. Math.max(scale[1] * 1.1, scale[1] + 3 * ratio)
  33054. ]
  33055. };
  33056. // FIXME
  33057. // modify it after support stop specified animation.
  33058. // toState === fromState
  33059. // ? (this.stopAnimation(), this.attr(emphasisOpt))
  33060. this.animateTo(emphasisOpt, 400, 'elasticOut');
  33061. }
  33062. else if (toState === 'normal') {
  33063. this.animateTo({
  33064. scale: this.__symbolOriginalScale
  33065. }, 400, 'elasticOut');
  33066. }
  33067. }
  33068. /**
  33069. * @param {Function} cb
  33070. * @param {Object} [opt]
  33071. * @param {Object} [opt.keepLabel=true]
  33072. */
  33073. symbolProto.fadeOut = function (cb, opt) {
  33074. var symbolPath = this.childAt(0);
  33075. // Avoid mistaken hover when fading out
  33076. this.silent = symbolPath.silent = true;
  33077. // Not show text when animating
  33078. !(opt && opt.keepLabel) && (symbolPath.style.text = null);
  33079. updateProps(
  33080. symbolPath,
  33081. {
  33082. style: {opacity: 0},
  33083. scale: [0, 0]
  33084. },
  33085. this._seriesModel,
  33086. this.dataIndex,
  33087. cb
  33088. );
  33089. };
  33090. inherits(SymbolClz$1, Group);
  33091. /*
  33092. * Licensed to the Apache Software Foundation (ASF) under one
  33093. * or more contributor license agreements. See the NOTICE file
  33094. * distributed with this work for additional information
  33095. * regarding copyright ownership. The ASF licenses this file
  33096. * to you under the Apache License, Version 2.0 (the
  33097. * "License"); you may not use this file except in compliance
  33098. * with the License. You may obtain a copy of the License at
  33099. *
  33100. * http://www.apache.org/licenses/LICENSE-2.0
  33101. *
  33102. * Unless required by applicable law or agreed to in writing,
  33103. * software distributed under the License is distributed on an
  33104. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33105. * KIND, either express or implied. See the License for the
  33106. * specific language governing permissions and limitations
  33107. * under the License.
  33108. */
  33109. /**
  33110. * @module echarts/chart/helper/SymbolDraw
  33111. */
  33112. /**
  33113. * @constructor
  33114. * @alias module:echarts/chart/helper/SymbolDraw
  33115. * @param {module:zrender/graphic/Group} [symbolCtor]
  33116. */
  33117. function SymbolDraw(symbolCtor) {
  33118. this.group = new Group();
  33119. this._symbolCtor = symbolCtor || SymbolClz$1;
  33120. }
  33121. var symbolDrawProto = SymbolDraw.prototype;
  33122. function symbolNeedsDraw(data, point, idx, opt) {
  33123. return point && !isNaN(point[0]) && !isNaN(point[1])
  33124. && !(opt.isIgnore && opt.isIgnore(idx))
  33125. // We do not set clipShape on group, because it will cut part of
  33126. // the symbol element shape. We use the same clip shape here as
  33127. // the line clip.
  33128. && !(opt.clipShape && !opt.clipShape.contain(point[0], point[1]))
  33129. && data.getItemVisual(idx, 'symbol') !== 'none';
  33130. }
  33131. /**
  33132. * Update symbols draw by new data
  33133. * @param {module:echarts/data/List} data
  33134. * @param {Object} [opt] Or isIgnore
  33135. * @param {Function} [opt.isIgnore]
  33136. * @param {Object} [opt.clipShape]
  33137. */
  33138. symbolDrawProto.updateData = function (data, opt) {
  33139. opt = normalizeUpdateOpt(opt);
  33140. var group = this.group;
  33141. var seriesModel = data.hostModel;
  33142. var oldData = this._data;
  33143. var SymbolCtor = this._symbolCtor;
  33144. var seriesScope = makeSeriesScope(data);
  33145. // There is no oldLineData only when first rendering or switching from
  33146. // stream mode to normal mode, where previous elements should be removed.
  33147. if (!oldData) {
  33148. group.removeAll();
  33149. }
  33150. data.diff(oldData)
  33151. .add(function (newIdx) {
  33152. var point = data.getItemLayout(newIdx);
  33153. if (symbolNeedsDraw(data, point, newIdx, opt)) {
  33154. var symbolEl = new SymbolCtor(data, newIdx, seriesScope);
  33155. symbolEl.attr('position', point);
  33156. data.setItemGraphicEl(newIdx, symbolEl);
  33157. group.add(symbolEl);
  33158. }
  33159. })
  33160. .update(function (newIdx, oldIdx) {
  33161. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  33162. var point = data.getItemLayout(newIdx);
  33163. if (!symbolNeedsDraw(data, point, newIdx, opt)) {
  33164. group.remove(symbolEl);
  33165. return;
  33166. }
  33167. if (!symbolEl) {
  33168. symbolEl = new SymbolCtor(data, newIdx);
  33169. symbolEl.attr('position', point);
  33170. }
  33171. else {
  33172. symbolEl.updateData(data, newIdx, seriesScope);
  33173. updateProps(symbolEl, {
  33174. position: point
  33175. }, seriesModel);
  33176. }
  33177. // Add back
  33178. group.add(symbolEl);
  33179. data.setItemGraphicEl(newIdx, symbolEl);
  33180. })
  33181. .remove(function (oldIdx) {
  33182. var el = oldData.getItemGraphicEl(oldIdx);
  33183. el && el.fadeOut(function () {
  33184. group.remove(el);
  33185. });
  33186. })
  33187. .execute();
  33188. this._data = data;
  33189. };
  33190. symbolDrawProto.isPersistent = function () {
  33191. return true;
  33192. };
  33193. symbolDrawProto.updateLayout = function () {
  33194. var data = this._data;
  33195. if (data) {
  33196. // Not use animation
  33197. data.eachItemGraphicEl(function (el, idx) {
  33198. var point = data.getItemLayout(idx);
  33199. el.attr('position', point);
  33200. });
  33201. }
  33202. };
  33203. symbolDrawProto.incrementalPrepareUpdate = function (data) {
  33204. this._seriesScope = makeSeriesScope(data);
  33205. this._data = null;
  33206. this.group.removeAll();
  33207. };
  33208. /**
  33209. * Update symbols draw by new data
  33210. * @param {module:echarts/data/List} data
  33211. * @param {Object} [opt] Or isIgnore
  33212. * @param {Function} [opt.isIgnore]
  33213. * @param {Object} [opt.clipShape]
  33214. */
  33215. symbolDrawProto.incrementalUpdate = function (taskParams, data, opt) {
  33216. opt = normalizeUpdateOpt(opt);
  33217. function updateIncrementalAndHover(el) {
  33218. if (!el.isGroup) {
  33219. el.incremental = el.useHoverLayer = true;
  33220. }
  33221. }
  33222. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  33223. var point = data.getItemLayout(idx);
  33224. if (symbolNeedsDraw(data, point, idx, opt)) {
  33225. var el = new this._symbolCtor(data, idx, this._seriesScope);
  33226. el.traverse(updateIncrementalAndHover);
  33227. el.attr('position', point);
  33228. this.group.add(el);
  33229. data.setItemGraphicEl(idx, el);
  33230. }
  33231. }
  33232. };
  33233. function normalizeUpdateOpt(opt) {
  33234. if (opt != null && !isObject$1(opt)) {
  33235. opt = {isIgnore: opt};
  33236. }
  33237. return opt || {};
  33238. }
  33239. symbolDrawProto.remove = function (enableAnimation) {
  33240. var group = this.group;
  33241. var data = this._data;
  33242. // Incremental model do not have this._data.
  33243. if (data && enableAnimation) {
  33244. data.eachItemGraphicEl(function (el) {
  33245. el.fadeOut(function () {
  33246. group.remove(el);
  33247. });
  33248. });
  33249. }
  33250. else {
  33251. group.removeAll();
  33252. }
  33253. };
  33254. function makeSeriesScope(data) {
  33255. var seriesModel = data.hostModel;
  33256. return {
  33257. itemStyle: seriesModel.getModel('itemStyle').getItemStyle(['color']),
  33258. hoverItemStyle: seriesModel.getModel('emphasis.itemStyle').getItemStyle(),
  33259. symbolRotate: seriesModel.get('symbolRotate'),
  33260. symbolOffset: seriesModel.get('symbolOffset'),
  33261. hoverAnimation: seriesModel.get('hoverAnimation'),
  33262. labelModel: seriesModel.getModel('label'),
  33263. hoverLabelModel: seriesModel.getModel('emphasis.label'),
  33264. cursorStyle: seriesModel.get('cursor')
  33265. };
  33266. }
  33267. /*
  33268. * Licensed to the Apache Software Foundation (ASF) under one
  33269. * or more contributor license agreements. See the NOTICE file
  33270. * distributed with this work for additional information
  33271. * regarding copyright ownership. The ASF licenses this file
  33272. * to you under the Apache License, Version 2.0 (the
  33273. * "License"); you may not use this file except in compliance
  33274. * with the License. You may obtain a copy of the License at
  33275. *
  33276. * http://www.apache.org/licenses/LICENSE-2.0
  33277. *
  33278. * Unless required by applicable law or agreed to in writing,
  33279. * software distributed under the License is distributed on an
  33280. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33281. * KIND, either express or implied. See the License for the
  33282. * specific language governing permissions and limitations
  33283. * under the License.
  33284. */
  33285. /**
  33286. * @param {Object} coordSys
  33287. * @param {module:echarts/data/List} data
  33288. * @param {string} valueOrigin lineSeries.option.areaStyle.origin
  33289. */
  33290. function prepareDataCoordInfo(coordSys, data, valueOrigin) {
  33291. var baseAxis = coordSys.getBaseAxis();
  33292. var valueAxis = coordSys.getOtherAxis(baseAxis);
  33293. var valueStart = getValueStart(valueAxis, valueOrigin);
  33294. var baseAxisDim = baseAxis.dim;
  33295. var valueAxisDim = valueAxis.dim;
  33296. var valueDim = data.mapDimension(valueAxisDim);
  33297. var baseDim = data.mapDimension(baseAxisDim);
  33298. var baseDataOffset = valueAxisDim === 'x' || valueAxisDim === 'radius' ? 1 : 0;
  33299. var dims = map(coordSys.dimensions, function (coordDim) {
  33300. return data.mapDimension(coordDim);
  33301. });
  33302. var stacked;
  33303. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  33304. if (stacked |= isDimensionStacked(data, dims[0] /*, dims[1]*/)) { // jshint ignore:line
  33305. dims[0] = stackResultDim;
  33306. }
  33307. if (stacked |= isDimensionStacked(data, dims[1] /*, dims[0]*/)) { // jshint ignore:line
  33308. dims[1] = stackResultDim;
  33309. }
  33310. return {
  33311. dataDimsForPoint: dims,
  33312. valueStart: valueStart,
  33313. valueAxisDim: valueAxisDim,
  33314. baseAxisDim: baseAxisDim,
  33315. stacked: !!stacked,
  33316. valueDim: valueDim,
  33317. baseDim: baseDim,
  33318. baseDataOffset: baseDataOffset,
  33319. stackedOverDimension: data.getCalculationInfo('stackedOverDimension')
  33320. };
  33321. }
  33322. function getValueStart(valueAxis, valueOrigin) {
  33323. var valueStart = 0;
  33324. var extent = valueAxis.scale.getExtent();
  33325. if (valueOrigin === 'start') {
  33326. valueStart = extent[0];
  33327. }
  33328. else if (valueOrigin === 'end') {
  33329. valueStart = extent[1];
  33330. }
  33331. // auto
  33332. else {
  33333. // Both positive
  33334. if (extent[0] > 0) {
  33335. valueStart = extent[0];
  33336. }
  33337. // Both negative
  33338. else if (extent[1] < 0) {
  33339. valueStart = extent[1];
  33340. }
  33341. // If is one positive, and one negative, onZero shall be true
  33342. }
  33343. return valueStart;
  33344. }
  33345. function getStackedOnPoint(dataCoordInfo, coordSys, data, idx) {
  33346. var value = NaN;
  33347. if (dataCoordInfo.stacked) {
  33348. value = data.get(data.getCalculationInfo('stackedOverDimension'), idx);
  33349. }
  33350. if (isNaN(value)) {
  33351. value = dataCoordInfo.valueStart;
  33352. }
  33353. var baseDataOffset = dataCoordInfo.baseDataOffset;
  33354. var stackedData = [];
  33355. stackedData[baseDataOffset] = data.get(dataCoordInfo.baseDim, idx);
  33356. stackedData[1 - baseDataOffset] = value;
  33357. return coordSys.dataToPoint(stackedData);
  33358. }
  33359. /*
  33360. * Licensed to the Apache Software Foundation (ASF) under one
  33361. * or more contributor license agreements. See the NOTICE file
  33362. * distributed with this work for additional information
  33363. * regarding copyright ownership. The ASF licenses this file
  33364. * to you under the Apache License, Version 2.0 (the
  33365. * "License"); you may not use this file except in compliance
  33366. * with the License. You may obtain a copy of the License at
  33367. *
  33368. * http://www.apache.org/licenses/LICENSE-2.0
  33369. *
  33370. * Unless required by applicable law or agreed to in writing,
  33371. * software distributed under the License is distributed on an
  33372. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33373. * KIND, either express or implied. See the License for the
  33374. * specific language governing permissions and limitations
  33375. * under the License.
  33376. */
  33377. // var arrayDiff = require('zrender/src/core/arrayDiff');
  33378. // 'zrender/src/core/arrayDiff' has been used before, but it did
  33379. // not do well in performance when roam with fixed dataZoom window.
  33380. // function convertToIntId(newIdList, oldIdList) {
  33381. // // Generate int id instead of string id.
  33382. // // Compare string maybe slow in score function of arrDiff
  33383. // // Assume id in idList are all unique
  33384. // var idIndicesMap = {};
  33385. // var idx = 0;
  33386. // for (var i = 0; i < newIdList.length; i++) {
  33387. // idIndicesMap[newIdList[i]] = idx;
  33388. // newIdList[i] = idx++;
  33389. // }
  33390. // for (var i = 0; i < oldIdList.length; i++) {
  33391. // var oldId = oldIdList[i];
  33392. // // Same with newIdList
  33393. // if (idIndicesMap[oldId]) {
  33394. // oldIdList[i] = idIndicesMap[oldId];
  33395. // }
  33396. // else {
  33397. // oldIdList[i] = idx++;
  33398. // }
  33399. // }
  33400. // }
  33401. function diffData(oldData, newData) {
  33402. var diffResult = [];
  33403. newData.diff(oldData)
  33404. .add(function (idx) {
  33405. diffResult.push({cmd: '+', idx: idx});
  33406. })
  33407. .update(function (newIdx, oldIdx) {
  33408. diffResult.push({cmd: '=', idx: oldIdx, idx1: newIdx});
  33409. })
  33410. .remove(function (idx) {
  33411. diffResult.push({cmd: '-', idx: idx});
  33412. })
  33413. .execute();
  33414. return diffResult;
  33415. }
  33416. var lineAnimationDiff = function (
  33417. oldData, newData,
  33418. oldStackedOnPoints, newStackedOnPoints,
  33419. oldCoordSys, newCoordSys,
  33420. oldValueOrigin, newValueOrigin
  33421. ) {
  33422. var diff = diffData(oldData, newData);
  33423. // var newIdList = newData.mapArray(newData.getId);
  33424. // var oldIdList = oldData.mapArray(oldData.getId);
  33425. // convertToIntId(newIdList, oldIdList);
  33426. // // FIXME One data ?
  33427. // diff = arrayDiff(oldIdList, newIdList);
  33428. var currPoints = [];
  33429. var nextPoints = [];
  33430. // Points for stacking base line
  33431. var currStackedPoints = [];
  33432. var nextStackedPoints = [];
  33433. var status = [];
  33434. var sortedIndices = [];
  33435. var rawIndices = [];
  33436. var newDataOldCoordInfo = prepareDataCoordInfo(oldCoordSys, newData, oldValueOrigin);
  33437. var oldDataNewCoordInfo = prepareDataCoordInfo(newCoordSys, oldData, newValueOrigin);
  33438. for (var i = 0; i < diff.length; i++) {
  33439. var diffItem = diff[i];
  33440. var pointAdded = true;
  33441. // FIXME, animation is not so perfect when dataZoom window moves fast
  33442. // Which is in case remvoing or add more than one data in the tail or head
  33443. switch (diffItem.cmd) {
  33444. case '=':
  33445. var currentPt = oldData.getItemLayout(diffItem.idx);
  33446. var nextPt = newData.getItemLayout(diffItem.idx1);
  33447. // If previous data is NaN, use next point directly
  33448. if (isNaN(currentPt[0]) || isNaN(currentPt[1])) {
  33449. currentPt = nextPt.slice();
  33450. }
  33451. currPoints.push(currentPt);
  33452. nextPoints.push(nextPt);
  33453. currStackedPoints.push(oldStackedOnPoints[diffItem.idx]);
  33454. nextStackedPoints.push(newStackedOnPoints[diffItem.idx1]);
  33455. rawIndices.push(newData.getRawIndex(diffItem.idx1));
  33456. break;
  33457. case '+':
  33458. var idx = diffItem.idx;
  33459. currPoints.push(
  33460. oldCoordSys.dataToPoint([
  33461. newData.get(newDataOldCoordInfo.dataDimsForPoint[0], idx),
  33462. newData.get(newDataOldCoordInfo.dataDimsForPoint[1], idx)
  33463. ])
  33464. );
  33465. nextPoints.push(newData.getItemLayout(idx).slice());
  33466. currStackedPoints.push(
  33467. getStackedOnPoint(newDataOldCoordInfo, oldCoordSys, newData, idx)
  33468. );
  33469. nextStackedPoints.push(newStackedOnPoints[idx]);
  33470. rawIndices.push(newData.getRawIndex(idx));
  33471. break;
  33472. case '-':
  33473. var idx = diffItem.idx;
  33474. var rawIndex = oldData.getRawIndex(idx);
  33475. // Data is replaced. In the case of dynamic data queue
  33476. // FIXME FIXME FIXME
  33477. if (rawIndex !== idx) {
  33478. currPoints.push(oldData.getItemLayout(idx));
  33479. nextPoints.push(newCoordSys.dataToPoint([
  33480. oldData.get(oldDataNewCoordInfo.dataDimsForPoint[0], idx),
  33481. oldData.get(oldDataNewCoordInfo.dataDimsForPoint[1], idx)
  33482. ]));
  33483. currStackedPoints.push(oldStackedOnPoints[idx]);
  33484. nextStackedPoints.push(
  33485. getStackedOnPoint(oldDataNewCoordInfo, newCoordSys, oldData, idx)
  33486. );
  33487. rawIndices.push(rawIndex);
  33488. }
  33489. else {
  33490. pointAdded = false;
  33491. }
  33492. }
  33493. // Original indices
  33494. if (pointAdded) {
  33495. status.push(diffItem);
  33496. sortedIndices.push(sortedIndices.length);
  33497. }
  33498. }
  33499. // Diff result may be crossed if all items are changed
  33500. // Sort by data index
  33501. sortedIndices.sort(function (a, b) {
  33502. return rawIndices[a] - rawIndices[b];
  33503. });
  33504. var sortedCurrPoints = [];
  33505. var sortedNextPoints = [];
  33506. var sortedCurrStackedPoints = [];
  33507. var sortedNextStackedPoints = [];
  33508. var sortedStatus = [];
  33509. for (var i = 0; i < sortedIndices.length; i++) {
  33510. var idx = sortedIndices[i];
  33511. sortedCurrPoints[i] = currPoints[idx];
  33512. sortedNextPoints[i] = nextPoints[idx];
  33513. sortedCurrStackedPoints[i] = currStackedPoints[idx];
  33514. sortedNextStackedPoints[i] = nextStackedPoints[idx];
  33515. sortedStatus[i] = status[idx];
  33516. }
  33517. return {
  33518. current: sortedCurrPoints,
  33519. next: sortedNextPoints,
  33520. stackedOnCurrent: sortedCurrStackedPoints,
  33521. stackedOnNext: sortedNextStackedPoints,
  33522. status: sortedStatus
  33523. };
  33524. };
  33525. /*
  33526. * Licensed to the Apache Software Foundation (ASF) under one
  33527. * or more contributor license agreements. See the NOTICE file
  33528. * distributed with this work for additional information
  33529. * regarding copyright ownership. The ASF licenses this file
  33530. * to you under the Apache License, Version 2.0 (the
  33531. * "License"); you may not use this file except in compliance
  33532. * with the License. You may obtain a copy of the License at
  33533. *
  33534. * http://www.apache.org/licenses/LICENSE-2.0
  33535. *
  33536. * Unless required by applicable law or agreed to in writing,
  33537. * software distributed under the License is distributed on an
  33538. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33539. * KIND, either express or implied. See the License for the
  33540. * specific language governing permissions and limitations
  33541. * under the License.
  33542. */
  33543. // Poly path support NaN point
  33544. var vec2Min = min;
  33545. var vec2Max = max;
  33546. var scaleAndAdd$1 = scaleAndAdd;
  33547. var v2Copy = copy;
  33548. // Temporary variable
  33549. var v = [];
  33550. var cp0 = [];
  33551. var cp1 = [];
  33552. function isPointNull(p) {
  33553. return isNaN(p[0]) || isNaN(p[1]);
  33554. }
  33555. function drawSegment(
  33556. ctx, points, start, segLen, allLen,
  33557. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  33558. ) {
  33559. // if (smoothMonotone == null) {
  33560. // if (isMono(points, 'x')) {
  33561. // return drawMono(ctx, points, start, segLen, allLen,
  33562. // dir, smoothMin, smoothMax, smooth, 'x', connectNulls);
  33563. // }
  33564. // else if (isMono(points, 'y')) {
  33565. // return drawMono(ctx, points, start, segLen, allLen,
  33566. // dir, smoothMin, smoothMax, smooth, 'y', connectNulls);
  33567. // }
  33568. // else {
  33569. // return drawNonMono.apply(this, arguments);
  33570. // }
  33571. // }
  33572. // else if (smoothMonotone !== 'none' && isMono(points, smoothMonotone)) {
  33573. // return drawMono.apply(this, arguments);
  33574. // }
  33575. // else {
  33576. // return drawNonMono.apply(this, arguments);
  33577. // }
  33578. if (smoothMonotone === 'none' || !smoothMonotone) {
  33579. return drawNonMono.apply(this, arguments);
  33580. }
  33581. else {
  33582. return drawMono.apply(this, arguments);
  33583. }
  33584. }
  33585. /**
  33586. * Check if points is in monotone.
  33587. *
  33588. * @param {number[][]} points Array of points which is in [x, y] form
  33589. * @param {string} smoothMonotone 'x', 'y', or 'none', stating for which
  33590. * dimension that is checking.
  33591. * If is 'none', `drawNonMono` should be
  33592. * called.
  33593. * If is undefined, either being monotone
  33594. * in 'x' or 'y' will call `drawMono`.
  33595. */
  33596. // function isMono(points, smoothMonotone) {
  33597. // if (points.length <= 1) {
  33598. // return true;
  33599. // }
  33600. // var dim = smoothMonotone === 'x' ? 0 : 1;
  33601. // var last = points[0][dim];
  33602. // var lastDiff = 0;
  33603. // for (var i = 1; i < points.length; ++i) {
  33604. // var diff = points[i][dim] - last;
  33605. // if (!isNaN(diff) && !isNaN(lastDiff)
  33606. // && diff !== 0 && lastDiff !== 0
  33607. // && ((diff >= 0) !== (lastDiff >= 0))
  33608. // ) {
  33609. // return false;
  33610. // }
  33611. // if (!isNaN(diff) && diff !== 0) {
  33612. // lastDiff = diff;
  33613. // last = points[i][dim];
  33614. // }
  33615. // }
  33616. // return true;
  33617. // }
  33618. /**
  33619. * Draw smoothed line in monotone, in which only vertical or horizontal bezier
  33620. * control points will be used. This should be used when points are monotone
  33621. * either in x or y dimension.
  33622. */
  33623. function drawMono(
  33624. ctx, points, start, segLen, allLen,
  33625. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  33626. ) {
  33627. var prevIdx = 0;
  33628. var idx = start;
  33629. for (var k = 0; k < segLen; k++) {
  33630. var p = points[idx];
  33631. if (idx >= allLen || idx < 0) {
  33632. break;
  33633. }
  33634. if (isPointNull(p)) {
  33635. if (connectNulls) {
  33636. idx += dir;
  33637. continue;
  33638. }
  33639. break;
  33640. }
  33641. if (idx === start) {
  33642. ctx[dir > 0 ? 'moveTo' : 'lineTo'](p[0], p[1]);
  33643. }
  33644. else {
  33645. if (smooth > 0) {
  33646. var prevP = points[prevIdx];
  33647. var dim = smoothMonotone === 'y' ? 1 : 0;
  33648. // Length of control point to p, either in x or y, but not both
  33649. var ctrlLen = (p[dim] - prevP[dim]) * smooth;
  33650. v2Copy(cp0, prevP);
  33651. cp0[dim] = prevP[dim] + ctrlLen;
  33652. v2Copy(cp1, p);
  33653. cp1[dim] = p[dim] - ctrlLen;
  33654. ctx.bezierCurveTo(
  33655. cp0[0], cp0[1],
  33656. cp1[0], cp1[1],
  33657. p[0], p[1]
  33658. );
  33659. }
  33660. else {
  33661. ctx.lineTo(p[0], p[1]);
  33662. }
  33663. }
  33664. prevIdx = idx;
  33665. idx += dir;
  33666. }
  33667. return k;
  33668. }
  33669. /**
  33670. * Draw smoothed line in non-monotone, in may cause undesired curve in extreme
  33671. * situations. This should be used when points are non-monotone neither in x or
  33672. * y dimension.
  33673. */
  33674. function drawNonMono(
  33675. ctx, points, start, segLen, allLen,
  33676. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  33677. ) {
  33678. var prevIdx = 0;
  33679. var idx = start;
  33680. for (var k = 0; k < segLen; k++) {
  33681. var p = points[idx];
  33682. if (idx >= allLen || idx < 0) {
  33683. break;
  33684. }
  33685. if (isPointNull(p)) {
  33686. if (connectNulls) {
  33687. idx += dir;
  33688. continue;
  33689. }
  33690. break;
  33691. }
  33692. if (idx === start) {
  33693. ctx[dir > 0 ? 'moveTo' : 'lineTo'](p[0], p[1]);
  33694. v2Copy(cp0, p);
  33695. }
  33696. else {
  33697. if (smooth > 0) {
  33698. var nextIdx = idx + dir;
  33699. var nextP = points[nextIdx];
  33700. if (connectNulls) {
  33701. // Find next point not null
  33702. while (nextP && isPointNull(points[nextIdx])) {
  33703. nextIdx += dir;
  33704. nextP = points[nextIdx];
  33705. }
  33706. }
  33707. var ratioNextSeg = 0.5;
  33708. var prevP = points[prevIdx];
  33709. var nextP = points[nextIdx];
  33710. // Last point
  33711. if (!nextP || isPointNull(nextP)) {
  33712. v2Copy(cp1, p);
  33713. }
  33714. else {
  33715. // If next data is null in not connect case
  33716. if (isPointNull(nextP) && !connectNulls) {
  33717. nextP = p;
  33718. }
  33719. sub(v, nextP, prevP);
  33720. var lenPrevSeg;
  33721. var lenNextSeg;
  33722. if (smoothMonotone === 'x' || smoothMonotone === 'y') {
  33723. var dim = smoothMonotone === 'x' ? 0 : 1;
  33724. lenPrevSeg = Math.abs(p[dim] - prevP[dim]);
  33725. lenNextSeg = Math.abs(p[dim] - nextP[dim]);
  33726. }
  33727. else {
  33728. lenPrevSeg = dist(p, prevP);
  33729. lenNextSeg = dist(p, nextP);
  33730. }
  33731. // Use ratio of seg length
  33732. ratioNextSeg = lenNextSeg / (lenNextSeg + lenPrevSeg);
  33733. scaleAndAdd$1(cp1, p, v, -smooth * (1 - ratioNextSeg));
  33734. }
  33735. // Smooth constraint
  33736. vec2Min(cp0, cp0, smoothMax);
  33737. vec2Max(cp0, cp0, smoothMin);
  33738. vec2Min(cp1, cp1, smoothMax);
  33739. vec2Max(cp1, cp1, smoothMin);
  33740. ctx.bezierCurveTo(
  33741. cp0[0], cp0[1],
  33742. cp1[0], cp1[1],
  33743. p[0], p[1]
  33744. );
  33745. // cp0 of next segment
  33746. scaleAndAdd$1(cp0, p, v, smooth * ratioNextSeg);
  33747. }
  33748. else {
  33749. ctx.lineTo(p[0], p[1]);
  33750. }
  33751. }
  33752. prevIdx = idx;
  33753. idx += dir;
  33754. }
  33755. return k;
  33756. }
  33757. function getBoundingBox(points, smoothConstraint) {
  33758. var ptMin = [Infinity, Infinity];
  33759. var ptMax = [-Infinity, -Infinity];
  33760. if (smoothConstraint) {
  33761. for (var i = 0; i < points.length; i++) {
  33762. var pt = points[i];
  33763. if (pt[0] < ptMin[0]) {
  33764. ptMin[0] = pt[0];
  33765. }
  33766. if (pt[1] < ptMin[1]) {
  33767. ptMin[1] = pt[1];
  33768. }
  33769. if (pt[0] > ptMax[0]) {
  33770. ptMax[0] = pt[0];
  33771. }
  33772. if (pt[1] > ptMax[1]) {
  33773. ptMax[1] = pt[1];
  33774. }
  33775. }
  33776. }
  33777. return {
  33778. min: smoothConstraint ? ptMin : ptMax,
  33779. max: smoothConstraint ? ptMax : ptMin
  33780. };
  33781. }
  33782. var Polyline$1 = Path.extend({
  33783. type: 'ec-polyline',
  33784. shape: {
  33785. points: [],
  33786. smooth: 0,
  33787. smoothConstraint: true,
  33788. smoothMonotone: null,
  33789. connectNulls: false
  33790. },
  33791. style: {
  33792. fill: null,
  33793. stroke: '#000'
  33794. },
  33795. brush: fixClipWithShadow(Path.prototype.brush),
  33796. buildPath: function (ctx, shape) {
  33797. var points = shape.points;
  33798. var i = 0;
  33799. var len$$1 = points.length;
  33800. var result = getBoundingBox(points, shape.smoothConstraint);
  33801. if (shape.connectNulls) {
  33802. // Must remove first and last null values avoid draw error in polygon
  33803. for (; len$$1 > 0; len$$1--) {
  33804. if (!isPointNull(points[len$$1 - 1])) {
  33805. break;
  33806. }
  33807. }
  33808. for (; i < len$$1; i++) {
  33809. if (!isPointNull(points[i])) {
  33810. break;
  33811. }
  33812. }
  33813. }
  33814. while (i < len$$1) {
  33815. i += drawSegment(
  33816. ctx, points, i, len$$1, len$$1,
  33817. 1, result.min, result.max, shape.smooth,
  33818. shape.smoothMonotone, shape.connectNulls
  33819. ) + 1;
  33820. }
  33821. }
  33822. });
  33823. var Polygon$1 = Path.extend({
  33824. type: 'ec-polygon',
  33825. shape: {
  33826. points: [],
  33827. // Offset between stacked base points and points
  33828. stackedOnPoints: [],
  33829. smooth: 0,
  33830. stackedOnSmooth: 0,
  33831. smoothConstraint: true,
  33832. smoothMonotone: null,
  33833. connectNulls: false
  33834. },
  33835. brush: fixClipWithShadow(Path.prototype.brush),
  33836. buildPath: function (ctx, shape) {
  33837. var points = shape.points;
  33838. var stackedOnPoints = shape.stackedOnPoints;
  33839. var i = 0;
  33840. var len$$1 = points.length;
  33841. var smoothMonotone = shape.smoothMonotone;
  33842. var bbox = getBoundingBox(points, shape.smoothConstraint);
  33843. var stackedOnBBox = getBoundingBox(stackedOnPoints, shape.smoothConstraint);
  33844. if (shape.connectNulls) {
  33845. // Must remove first and last null values avoid draw error in polygon
  33846. for (; len$$1 > 0; len$$1--) {
  33847. if (!isPointNull(points[len$$1 - 1])) {
  33848. break;
  33849. }
  33850. }
  33851. for (; i < len$$1; i++) {
  33852. if (!isPointNull(points[i])) {
  33853. break;
  33854. }
  33855. }
  33856. }
  33857. while (i < len$$1) {
  33858. var k = drawSegment(
  33859. ctx, points, i, len$$1, len$$1,
  33860. 1, bbox.min, bbox.max, shape.smooth,
  33861. smoothMonotone, shape.connectNulls
  33862. );
  33863. drawSegment(
  33864. ctx, stackedOnPoints, i + k - 1, k, len$$1,
  33865. -1, stackedOnBBox.min, stackedOnBBox.max, shape.stackedOnSmooth,
  33866. smoothMonotone, shape.connectNulls
  33867. );
  33868. i += k + 1;
  33869. ctx.closePath();
  33870. }
  33871. }
  33872. });
  33873. /*
  33874. * Licensed to the Apache Software Foundation (ASF) under one
  33875. * or more contributor license agreements. See the NOTICE file
  33876. * distributed with this work for additional information
  33877. * regarding copyright ownership. The ASF licenses this file
  33878. * to you under the Apache License, Version 2.0 (the
  33879. * "License"); you may not use this file except in compliance
  33880. * with the License. You may obtain a copy of the License at
  33881. *
  33882. * http://www.apache.org/licenses/LICENSE-2.0
  33883. *
  33884. * Unless required by applicable law or agreed to in writing,
  33885. * software distributed under the License is distributed on an
  33886. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33887. * KIND, either express or implied. See the License for the
  33888. * specific language governing permissions and limitations
  33889. * under the License.
  33890. */
  33891. function createGridClipPath(cartesian, hasAnimation, seriesModel) {
  33892. var rect = cartesian.getArea();
  33893. var isHorizontal = cartesian.getBaseAxis().isHorizontal();
  33894. var x = rect.x;
  33895. var y = rect.y;
  33896. var width = rect.width;
  33897. var height = rect.height;
  33898. var lineWidth = seriesModel.get('lineStyle.width') || 2;
  33899. // Expand the clip path a bit to avoid the border is clipped and looks thinner
  33900. x -= lineWidth / 2;
  33901. y -= lineWidth / 2;
  33902. width += lineWidth;
  33903. height += lineWidth;
  33904. // fix: https://github.com/apache/incubator-echarts/issues/11369
  33905. x = Math.floor(x);
  33906. width = Math.round(width);
  33907. var clipPath = new Rect({
  33908. shape: {
  33909. x: x,
  33910. y: y,
  33911. width: width,
  33912. height: height
  33913. }
  33914. });
  33915. if (hasAnimation) {
  33916. clipPath.shape[isHorizontal ? 'width' : 'height'] = 0;
  33917. initProps(clipPath, {
  33918. shape: {
  33919. width: width,
  33920. height: height
  33921. }
  33922. }, seriesModel);
  33923. }
  33924. return clipPath;
  33925. }
  33926. function createPolarClipPath(polar, hasAnimation, seriesModel) {
  33927. var sectorArea = polar.getArea();
  33928. // Avoid float number rounding error for symbol on the edge of axis extent.
  33929. var clipPath = new Sector({
  33930. shape: {
  33931. cx: round$1(polar.cx, 1),
  33932. cy: round$1(polar.cy, 1),
  33933. r0: round$1(sectorArea.r0, 1),
  33934. r: round$1(sectorArea.r, 1),
  33935. startAngle: sectorArea.startAngle,
  33936. endAngle: sectorArea.endAngle,
  33937. clockwise: sectorArea.clockwise
  33938. }
  33939. });
  33940. if (hasAnimation) {
  33941. clipPath.shape.endAngle = sectorArea.startAngle;
  33942. initProps(clipPath, {
  33943. shape: {
  33944. endAngle: sectorArea.endAngle
  33945. }
  33946. }, seriesModel);
  33947. }
  33948. return clipPath;
  33949. }
  33950. function createClipPath(coordSys, hasAnimation, seriesModel) {
  33951. if (!coordSys) {
  33952. return null;
  33953. }
  33954. else if (coordSys.type === 'polar') {
  33955. return createPolarClipPath(coordSys, hasAnimation, seriesModel);
  33956. }
  33957. else if (coordSys.type === 'cartesian2d') {
  33958. return createGridClipPath(coordSys, hasAnimation, seriesModel);
  33959. }
  33960. return null;
  33961. }
  33962. /*
  33963. * Licensed to the Apache Software Foundation (ASF) under one
  33964. * or more contributor license agreements. See the NOTICE file
  33965. * distributed with this work for additional information
  33966. * regarding copyright ownership. The ASF licenses this file
  33967. * to you under the Apache License, Version 2.0 (the
  33968. * "License"); you may not use this file except in compliance
  33969. * with the License. You may obtain a copy of the License at
  33970. *
  33971. * http://www.apache.org/licenses/LICENSE-2.0
  33972. *
  33973. * Unless required by applicable law or agreed to in writing,
  33974. * software distributed under the License is distributed on an
  33975. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33976. * KIND, either express or implied. See the License for the
  33977. * specific language governing permissions and limitations
  33978. * under the License.
  33979. */
  33980. // FIXME step not support polar
  33981. function isPointsSame(points1, points2) {
  33982. if (points1.length !== points2.length) {
  33983. return;
  33984. }
  33985. for (var i = 0; i < points1.length; i++) {
  33986. var p1 = points1[i];
  33987. var p2 = points2[i];
  33988. if (p1[0] !== p2[0] || p1[1] !== p2[1]) {
  33989. return;
  33990. }
  33991. }
  33992. return true;
  33993. }
  33994. function getBoundingDiff(points1, points2) {
  33995. var min1 = [];
  33996. var max1 = [];
  33997. var min2 = [];
  33998. var max2 = [];
  33999. fromPoints(points1, min1, max1);
  34000. fromPoints(points2, min2, max2);
  34001. // Get a max value from each corner of two boundings.
  34002. return Math.max(
  34003. Math.abs(min1[0] - min2[0]),
  34004. Math.abs(min1[1] - min2[1]),
  34005. Math.abs(max1[0] - max2[0]),
  34006. Math.abs(max1[1] - max2[1])
  34007. );
  34008. }
  34009. function getSmooth(smooth) {
  34010. return typeof (smooth) === 'number' ? smooth : (smooth ? 0.5 : 0);
  34011. }
  34012. /**
  34013. * @param {module:echarts/coord/cartesian/Cartesian2D|module:echarts/coord/polar/Polar} coordSys
  34014. * @param {module:echarts/data/List} data
  34015. * @param {Object} dataCoordInfo
  34016. * @param {Array.<Array.<number>>} points
  34017. */
  34018. function getStackedOnPoints(coordSys, data, dataCoordInfo) {
  34019. if (!dataCoordInfo.valueDim) {
  34020. return [];
  34021. }
  34022. var points = [];
  34023. for (var idx = 0, len = data.count(); idx < len; idx++) {
  34024. points.push(getStackedOnPoint(dataCoordInfo, coordSys, data, idx));
  34025. }
  34026. return points;
  34027. }
  34028. function turnPointsIntoStep(points, coordSys, stepTurnAt) {
  34029. var baseAxis = coordSys.getBaseAxis();
  34030. var baseIndex = baseAxis.dim === 'x' || baseAxis.dim === 'radius' ? 0 : 1;
  34031. var stepPoints = [];
  34032. for (var i = 0; i < points.length - 1; i++) {
  34033. var nextPt = points[i + 1];
  34034. var pt = points[i];
  34035. stepPoints.push(pt);
  34036. var stepPt = [];
  34037. switch (stepTurnAt) {
  34038. case 'end':
  34039. stepPt[baseIndex] = nextPt[baseIndex];
  34040. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  34041. // default is start
  34042. stepPoints.push(stepPt);
  34043. break;
  34044. case 'middle':
  34045. // default is start
  34046. var middle = (pt[baseIndex] + nextPt[baseIndex]) / 2;
  34047. var stepPt2 = [];
  34048. stepPt[baseIndex] = stepPt2[baseIndex] = middle;
  34049. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  34050. stepPt2[1 - baseIndex] = nextPt[1 - baseIndex];
  34051. stepPoints.push(stepPt);
  34052. stepPoints.push(stepPt2);
  34053. break;
  34054. default:
  34055. stepPt[baseIndex] = pt[baseIndex];
  34056. stepPt[1 - baseIndex] = nextPt[1 - baseIndex];
  34057. // default is start
  34058. stepPoints.push(stepPt);
  34059. }
  34060. }
  34061. // Last points
  34062. points[i] && stepPoints.push(points[i]);
  34063. return stepPoints;
  34064. }
  34065. function getVisualGradient(data, coordSys) {
  34066. var visualMetaList = data.getVisual('visualMeta');
  34067. if (!visualMetaList || !visualMetaList.length || !data.count()) {
  34068. // When data.count() is 0, gradient range can not be calculated.
  34069. return;
  34070. }
  34071. if (coordSys.type !== 'cartesian2d') {
  34072. if (__DEV__) {
  34073. console.warn('Visual map on line style is only supported on cartesian2d.');
  34074. }
  34075. return;
  34076. }
  34077. var coordDim;
  34078. var visualMeta;
  34079. for (var i = visualMetaList.length - 1; i >= 0; i--) {
  34080. var dimIndex = visualMetaList[i].dimension;
  34081. var dimName = data.dimensions[dimIndex];
  34082. var dimInfo = data.getDimensionInfo(dimName);
  34083. coordDim = dimInfo && dimInfo.coordDim;
  34084. // Can only be x or y
  34085. if (coordDim === 'x' || coordDim === 'y') {
  34086. visualMeta = visualMetaList[i];
  34087. break;
  34088. }
  34089. }
  34090. if (!visualMeta) {
  34091. if (__DEV__) {
  34092. console.warn('Visual map on line style only support x or y dimension.');
  34093. }
  34094. return;
  34095. }
  34096. // If the area to be rendered is bigger than area defined by LinearGradient,
  34097. // the canvas spec prescribes that the color of the first stop and the last
  34098. // stop should be used. But if two stops are added at offset 0, in effect
  34099. // browsers use the color of the second stop to render area outside
  34100. // LinearGradient. So we can only infinitesimally extend area defined in
  34101. // LinearGradient to render `outerColors`.
  34102. var axis = coordSys.getAxis(coordDim);
  34103. // dataToCoor mapping may not be linear, but must be monotonic.
  34104. var colorStops = map(visualMeta.stops, function (stop) {
  34105. return {
  34106. coord: axis.toGlobalCoord(axis.dataToCoord(stop.value)),
  34107. color: stop.color
  34108. };
  34109. });
  34110. var stopLen = colorStops.length;
  34111. var outerColors = visualMeta.outerColors.slice();
  34112. if (stopLen && colorStops[0].coord > colorStops[stopLen - 1].coord) {
  34113. colorStops.reverse();
  34114. outerColors.reverse();
  34115. }
  34116. var tinyExtent = 10; // Arbitrary value: 10px
  34117. var minCoord = colorStops[0].coord - tinyExtent;
  34118. var maxCoord = colorStops[stopLen - 1].coord + tinyExtent;
  34119. var coordSpan = maxCoord - minCoord;
  34120. if (coordSpan < 1e-3) {
  34121. return 'transparent';
  34122. }
  34123. each$1(colorStops, function (stop) {
  34124. stop.offset = (stop.coord - minCoord) / coordSpan;
  34125. });
  34126. colorStops.push({
  34127. offset: stopLen ? colorStops[stopLen - 1].offset : 0.5,
  34128. color: outerColors[1] || 'transparent'
  34129. });
  34130. colorStops.unshift({ // notice colorStops.length have been changed.
  34131. offset: stopLen ? colorStops[0].offset : 0.5,
  34132. color: outerColors[0] || 'transparent'
  34133. });
  34134. // zrUtil.each(colorStops, function (colorStop) {
  34135. // // Make sure each offset has rounded px to avoid not sharp edge
  34136. // colorStop.offset = (Math.round(colorStop.offset * (end - start) + start) - start) / (end - start);
  34137. // });
  34138. var gradient = new LinearGradient(0, 0, 0, 0, colorStops, true);
  34139. gradient[coordDim] = minCoord;
  34140. gradient[coordDim + '2'] = maxCoord;
  34141. return gradient;
  34142. }
  34143. function getIsIgnoreFunc(seriesModel, data, coordSys) {
  34144. var showAllSymbol = seriesModel.get('showAllSymbol');
  34145. var isAuto = showAllSymbol === 'auto';
  34146. if (showAllSymbol && !isAuto) {
  34147. return;
  34148. }
  34149. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  34150. if (!categoryAxis) {
  34151. return;
  34152. }
  34153. // Note that category label interval strategy might bring some weird effect
  34154. // in some scenario: users may wonder why some of the symbols are not
  34155. // displayed. So we show all symbols as possible as we can.
  34156. if (isAuto
  34157. // Simplify the logic, do not determine label overlap here.
  34158. && canShowAllSymbolForCategory(categoryAxis, data)
  34159. ) {
  34160. return;
  34161. }
  34162. // Otherwise follow the label interval strategy on category axis.
  34163. var categoryDataDim = data.mapDimension(categoryAxis.dim);
  34164. var labelMap = {};
  34165. each$1(categoryAxis.getViewLabels(), function (labelItem) {
  34166. labelMap[labelItem.tickValue] = 1;
  34167. });
  34168. return function (dataIndex) {
  34169. return !labelMap.hasOwnProperty(data.get(categoryDataDim, dataIndex));
  34170. };
  34171. }
  34172. function canShowAllSymbolForCategory(categoryAxis, data) {
  34173. // In mose cases, line is monotonous on category axis, and the label size
  34174. // is close with each other. So we check the symbol size and some of the
  34175. // label size alone with the category axis to estimate whether all symbol
  34176. // can be shown without overlap.
  34177. var axisExtent = categoryAxis.getExtent();
  34178. var availSize = Math.abs(axisExtent[1] - axisExtent[0]) / categoryAxis.scale.count();
  34179. isNaN(availSize) && (availSize = 0); // 0/0 is NaN.
  34180. // Sampling some points, max 5.
  34181. var dataLen = data.count();
  34182. var step = Math.max(1, Math.round(dataLen / 5));
  34183. for (var dataIndex = 0; dataIndex < dataLen; dataIndex += step) {
  34184. if (SymbolClz$1.getSymbolSize(
  34185. data, dataIndex
  34186. // Only for cartesian, where `isHorizontal` exists.
  34187. )[categoryAxis.isHorizontal() ? 1 : 0]
  34188. // Empirical number
  34189. * 1.5 > availSize
  34190. ) {
  34191. return false;
  34192. }
  34193. }
  34194. return true;
  34195. }
  34196. function createLineClipPath(coordSys, hasAnimation, seriesModel) {
  34197. if (coordSys.type === 'cartesian2d') {
  34198. var isHorizontal = coordSys.getBaseAxis().isHorizontal();
  34199. var clipPath = createGridClipPath(coordSys, hasAnimation, seriesModel);
  34200. // Expand clip shape to avoid clipping when line value exceeds axis
  34201. if (!seriesModel.get('clip', true)) {
  34202. var rectShape = clipPath.shape;
  34203. var expandSize = Math.max(rectShape.width, rectShape.height);
  34204. if (isHorizontal) {
  34205. rectShape.y -= expandSize;
  34206. rectShape.height += expandSize * 2;
  34207. }
  34208. else {
  34209. rectShape.x -= expandSize;
  34210. rectShape.width += expandSize * 2;
  34211. }
  34212. }
  34213. return clipPath;
  34214. }
  34215. else {
  34216. return createPolarClipPath(coordSys, hasAnimation, seriesModel);
  34217. }
  34218. }
  34219. Chart.extend({
  34220. type: 'line',
  34221. init: function () {
  34222. var lineGroup = new Group();
  34223. var symbolDraw = new SymbolDraw();
  34224. this.group.add(symbolDraw.group);
  34225. this._symbolDraw = symbolDraw;
  34226. this._lineGroup = lineGroup;
  34227. },
  34228. render: function (seriesModel, ecModel, api) {
  34229. var coordSys = seriesModel.coordinateSystem;
  34230. var group = this.group;
  34231. var data = seriesModel.getData();
  34232. var lineStyleModel = seriesModel.getModel('lineStyle');
  34233. var areaStyleModel = seriesModel.getModel('areaStyle');
  34234. var points = data.mapArray(data.getItemLayout);
  34235. var isCoordSysPolar = coordSys.type === 'polar';
  34236. var prevCoordSys = this._coordSys;
  34237. var symbolDraw = this._symbolDraw;
  34238. var polyline = this._polyline;
  34239. var polygon = this._polygon;
  34240. var lineGroup = this._lineGroup;
  34241. var hasAnimation = seriesModel.get('animation');
  34242. var isAreaChart = !areaStyleModel.isEmpty();
  34243. var valueOrigin = areaStyleModel.get('origin');
  34244. var dataCoordInfo = prepareDataCoordInfo(coordSys, data, valueOrigin);
  34245. var stackedOnPoints = getStackedOnPoints(coordSys, data, dataCoordInfo);
  34246. var showSymbol = seriesModel.get('showSymbol');
  34247. var isIgnoreFunc = showSymbol && !isCoordSysPolar
  34248. && getIsIgnoreFunc(seriesModel, data, coordSys);
  34249. // Remove temporary symbols
  34250. var oldData = this._data;
  34251. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  34252. if (el.__temp) {
  34253. group.remove(el);
  34254. oldData.setItemGraphicEl(idx, null);
  34255. }
  34256. });
  34257. // Remove previous created symbols if showSymbol changed to false
  34258. if (!showSymbol) {
  34259. symbolDraw.remove();
  34260. }
  34261. group.add(lineGroup);
  34262. // FIXME step not support polar
  34263. var step = !isCoordSysPolar && seriesModel.get('step');
  34264. var clipShapeForSymbol;
  34265. if (coordSys && coordSys.getArea && seriesModel.get('clip', true)) {
  34266. clipShapeForSymbol = coordSys.getArea();
  34267. // Avoid float number rounding error for symbol on the edge of axis extent.
  34268. // See #7913 and `test/dataZoom-clip.html`.
  34269. if (clipShapeForSymbol.width != null) {
  34270. clipShapeForSymbol.x -= 0.1;
  34271. clipShapeForSymbol.y -= 0.1;
  34272. clipShapeForSymbol.width += 0.2;
  34273. clipShapeForSymbol.height += 0.2;
  34274. }
  34275. else if (clipShapeForSymbol.r0) {
  34276. clipShapeForSymbol.r0 -= 0.5;
  34277. clipShapeForSymbol.r1 += 0.5;
  34278. }
  34279. }
  34280. this._clipShapeForSymbol = clipShapeForSymbol;
  34281. // Initialization animation or coordinate system changed
  34282. if (
  34283. !(polyline && prevCoordSys.type === coordSys.type && step === this._step)
  34284. ) {
  34285. showSymbol && symbolDraw.updateData(data, {
  34286. isIgnore: isIgnoreFunc,
  34287. clipShape: clipShapeForSymbol
  34288. });
  34289. if (step) {
  34290. // TODO If stacked series is not step
  34291. points = turnPointsIntoStep(points, coordSys, step);
  34292. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  34293. }
  34294. polyline = this._newPolyline(points, coordSys, hasAnimation);
  34295. if (isAreaChart) {
  34296. polygon = this._newPolygon(
  34297. points, stackedOnPoints,
  34298. coordSys, hasAnimation
  34299. );
  34300. }
  34301. lineGroup.setClipPath(createLineClipPath(coordSys, true, seriesModel));
  34302. }
  34303. else {
  34304. if (isAreaChart && !polygon) {
  34305. // If areaStyle is added
  34306. polygon = this._newPolygon(
  34307. points, stackedOnPoints,
  34308. coordSys, hasAnimation
  34309. );
  34310. }
  34311. else if (polygon && !isAreaChart) {
  34312. // If areaStyle is removed
  34313. lineGroup.remove(polygon);
  34314. polygon = this._polygon = null;
  34315. }
  34316. // Update clipPath
  34317. lineGroup.setClipPath(createLineClipPath(coordSys, false, seriesModel));
  34318. // Always update, or it is wrong in the case turning on legend
  34319. // because points are not changed
  34320. showSymbol && symbolDraw.updateData(data, {
  34321. isIgnore: isIgnoreFunc,
  34322. clipShape: clipShapeForSymbol
  34323. });
  34324. // Stop symbol animation and sync with line points
  34325. // FIXME performance?
  34326. data.eachItemGraphicEl(function (el) {
  34327. el.stopAnimation(true);
  34328. });
  34329. // In the case data zoom triggerred refreshing frequently
  34330. // Data may not change if line has a category axis. So it should animate nothing
  34331. if (!isPointsSame(this._stackedOnPoints, stackedOnPoints)
  34332. || !isPointsSame(this._points, points)
  34333. ) {
  34334. if (hasAnimation) {
  34335. this._updateAnimation(
  34336. data, stackedOnPoints, coordSys, api, step, valueOrigin
  34337. );
  34338. }
  34339. else {
  34340. // Not do it in update with animation
  34341. if (step) {
  34342. // TODO If stacked series is not step
  34343. points = turnPointsIntoStep(points, coordSys, step);
  34344. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  34345. }
  34346. polyline.setShape({
  34347. points: points
  34348. });
  34349. polygon && polygon.setShape({
  34350. points: points,
  34351. stackedOnPoints: stackedOnPoints
  34352. });
  34353. }
  34354. }
  34355. }
  34356. var visualColor = getVisualGradient(data, coordSys) || data.getVisual('color');
  34357. polyline.useStyle(defaults(
  34358. // Use color in lineStyle first
  34359. lineStyleModel.getLineStyle(),
  34360. {
  34361. fill: 'none',
  34362. stroke: visualColor,
  34363. lineJoin: 'bevel'
  34364. }
  34365. ));
  34366. var smooth = seriesModel.get('smooth');
  34367. smooth = getSmooth(seriesModel.get('smooth'));
  34368. polyline.setShape({
  34369. smooth: smooth,
  34370. smoothMonotone: seriesModel.get('smoothMonotone'),
  34371. connectNulls: seriesModel.get('connectNulls')
  34372. });
  34373. if (polygon) {
  34374. var stackedOnSeries = data.getCalculationInfo('stackedOnSeries');
  34375. var stackedOnSmooth = 0;
  34376. polygon.useStyle(defaults(
  34377. areaStyleModel.getAreaStyle(),
  34378. {
  34379. fill: visualColor,
  34380. opacity: 0.7,
  34381. lineJoin: 'bevel'
  34382. }
  34383. ));
  34384. if (stackedOnSeries) {
  34385. stackedOnSmooth = getSmooth(stackedOnSeries.get('smooth'));
  34386. }
  34387. polygon.setShape({
  34388. smooth: smooth,
  34389. stackedOnSmooth: stackedOnSmooth,
  34390. smoothMonotone: seriesModel.get('smoothMonotone'),
  34391. connectNulls: seriesModel.get('connectNulls')
  34392. });
  34393. }
  34394. this._data = data;
  34395. // Save the coordinate system for transition animation when data changed
  34396. this._coordSys = coordSys;
  34397. this._stackedOnPoints = stackedOnPoints;
  34398. this._points = points;
  34399. this._step = step;
  34400. this._valueOrigin = valueOrigin;
  34401. },
  34402. dispose: function () {},
  34403. highlight: function (seriesModel, ecModel, api, payload) {
  34404. var data = seriesModel.getData();
  34405. var dataIndex = queryDataIndex(data, payload);
  34406. if (!(dataIndex instanceof Array) && dataIndex != null && dataIndex >= 0) {
  34407. var symbol = data.getItemGraphicEl(dataIndex);
  34408. if (!symbol) {
  34409. // Create a temporary symbol if it is not exists
  34410. var pt = data.getItemLayout(dataIndex);
  34411. if (!pt) {
  34412. // Null data
  34413. return;
  34414. }
  34415. // fix #11360: should't draw symbol outside clipShapeForSymbol
  34416. if (this._clipShapeForSymbol && !this._clipShapeForSymbol.contain(pt[0], pt[1])) {
  34417. return;
  34418. }
  34419. symbol = new SymbolClz$1(data, dataIndex);
  34420. symbol.position = pt;
  34421. symbol.setZ(
  34422. seriesModel.get('zlevel'),
  34423. seriesModel.get('z')
  34424. );
  34425. symbol.ignore = isNaN(pt[0]) || isNaN(pt[1]);
  34426. symbol.__temp = true;
  34427. data.setItemGraphicEl(dataIndex, symbol);
  34428. // Stop scale animation
  34429. symbol.stopSymbolAnimation(true);
  34430. this.group.add(symbol);
  34431. }
  34432. symbol.highlight();
  34433. }
  34434. else {
  34435. // Highlight whole series
  34436. Chart.prototype.highlight.call(
  34437. this, seriesModel, ecModel, api, payload
  34438. );
  34439. }
  34440. },
  34441. downplay: function (seriesModel, ecModel, api, payload) {
  34442. var data = seriesModel.getData();
  34443. var dataIndex = queryDataIndex(data, payload);
  34444. if (dataIndex != null && dataIndex >= 0) {
  34445. var symbol = data.getItemGraphicEl(dataIndex);
  34446. if (symbol) {
  34447. if (symbol.__temp) {
  34448. data.setItemGraphicEl(dataIndex, null);
  34449. this.group.remove(symbol);
  34450. }
  34451. else {
  34452. symbol.downplay();
  34453. }
  34454. }
  34455. }
  34456. else {
  34457. // FIXME
  34458. // can not downplay completely.
  34459. // Downplay whole series
  34460. Chart.prototype.downplay.call(
  34461. this, seriesModel, ecModel, api, payload
  34462. );
  34463. }
  34464. },
  34465. /**
  34466. * @param {module:zrender/container/Group} group
  34467. * @param {Array.<Array.<number>>} points
  34468. * @private
  34469. */
  34470. _newPolyline: function (points) {
  34471. var polyline = this._polyline;
  34472. // Remove previous created polyline
  34473. if (polyline) {
  34474. this._lineGroup.remove(polyline);
  34475. }
  34476. polyline = new Polyline$1({
  34477. shape: {
  34478. points: points
  34479. },
  34480. silent: true,
  34481. z2: 10
  34482. });
  34483. this._lineGroup.add(polyline);
  34484. this._polyline = polyline;
  34485. return polyline;
  34486. },
  34487. /**
  34488. * @param {module:zrender/container/Group} group
  34489. * @param {Array.<Array.<number>>} stackedOnPoints
  34490. * @param {Array.<Array.<number>>} points
  34491. * @private
  34492. */
  34493. _newPolygon: function (points, stackedOnPoints) {
  34494. var polygon = this._polygon;
  34495. // Remove previous created polygon
  34496. if (polygon) {
  34497. this._lineGroup.remove(polygon);
  34498. }
  34499. polygon = new Polygon$1({
  34500. shape: {
  34501. points: points,
  34502. stackedOnPoints: stackedOnPoints
  34503. },
  34504. silent: true
  34505. });
  34506. this._lineGroup.add(polygon);
  34507. this._polygon = polygon;
  34508. return polygon;
  34509. },
  34510. /**
  34511. * @private
  34512. */
  34513. // FIXME Two value axis
  34514. _updateAnimation: function (data, stackedOnPoints, coordSys, api, step, valueOrigin) {
  34515. var polyline = this._polyline;
  34516. var polygon = this._polygon;
  34517. var seriesModel = data.hostModel;
  34518. var diff = lineAnimationDiff(
  34519. this._data, data,
  34520. this._stackedOnPoints, stackedOnPoints,
  34521. this._coordSys, coordSys,
  34522. this._valueOrigin, valueOrigin
  34523. );
  34524. var current = diff.current;
  34525. var stackedOnCurrent = diff.stackedOnCurrent;
  34526. var next = diff.next;
  34527. var stackedOnNext = diff.stackedOnNext;
  34528. if (step) {
  34529. // TODO If stacked series is not step
  34530. current = turnPointsIntoStep(diff.current, coordSys, step);
  34531. stackedOnCurrent = turnPointsIntoStep(diff.stackedOnCurrent, coordSys, step);
  34532. next = turnPointsIntoStep(diff.next, coordSys, step);
  34533. stackedOnNext = turnPointsIntoStep(diff.stackedOnNext, coordSys, step);
  34534. }
  34535. // Don't apply animation if diff is large.
  34536. // For better result and avoid memory explosion problems like
  34537. // https://github.com/apache/incubator-echarts/issues/12229
  34538. if (getBoundingDiff(current, next) > 3000
  34539. || (polygon && getBoundingDiff(stackedOnCurrent, stackedOnNext) > 3000)
  34540. ) {
  34541. polyline.setShape({
  34542. points: next
  34543. });
  34544. if (polygon) {
  34545. polygon.setShape({
  34546. points: next,
  34547. stackedOnPoints: stackedOnNext
  34548. });
  34549. }
  34550. return;
  34551. }
  34552. // `diff.current` is subset of `current` (which should be ensured by
  34553. // turnPointsIntoStep), so points in `__points` can be updated when
  34554. // points in `current` are update during animation.
  34555. polyline.shape.__points = diff.current;
  34556. polyline.shape.points = current;
  34557. updateProps(polyline, {
  34558. shape: {
  34559. points: next
  34560. }
  34561. }, seriesModel);
  34562. if (polygon) {
  34563. polygon.setShape({
  34564. points: current,
  34565. stackedOnPoints: stackedOnCurrent
  34566. });
  34567. updateProps(polygon, {
  34568. shape: {
  34569. points: next,
  34570. stackedOnPoints: stackedOnNext
  34571. }
  34572. }, seriesModel);
  34573. }
  34574. var updatedDataInfo = [];
  34575. var diffStatus = diff.status;
  34576. for (var i = 0; i < diffStatus.length; i++) {
  34577. var cmd = diffStatus[i].cmd;
  34578. if (cmd === '=') {
  34579. var el = data.getItemGraphicEl(diffStatus[i].idx1);
  34580. if (el) {
  34581. updatedDataInfo.push({
  34582. el: el,
  34583. ptIdx: i // Index of points
  34584. });
  34585. }
  34586. }
  34587. }
  34588. if (polyline.animators && polyline.animators.length) {
  34589. polyline.animators[0].during(function () {
  34590. for (var i = 0; i < updatedDataInfo.length; i++) {
  34591. var el = updatedDataInfo[i].el;
  34592. el.attr('position', polyline.shape.__points[updatedDataInfo[i].ptIdx]);
  34593. }
  34594. });
  34595. }
  34596. },
  34597. remove: function (ecModel) {
  34598. var group = this.group;
  34599. var oldData = this._data;
  34600. this._lineGroup.removeAll();
  34601. this._symbolDraw.remove(true);
  34602. // Remove temporary created elements when highlighting
  34603. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  34604. if (el.__temp) {
  34605. group.remove(el);
  34606. oldData.setItemGraphicEl(idx, null);
  34607. }
  34608. });
  34609. this._polyline =
  34610. this._polygon =
  34611. this._coordSys =
  34612. this._points =
  34613. this._stackedOnPoints =
  34614. this._data = null;
  34615. }
  34616. });
  34617. /*
  34618. * Licensed to the Apache Software Foundation (ASF) under one
  34619. * or more contributor license agreements. See the NOTICE file
  34620. * distributed with this work for additional information
  34621. * regarding copyright ownership. The ASF licenses this file
  34622. * to you under the Apache License, Version 2.0 (the
  34623. * "License"); you may not use this file except in compliance
  34624. * with the License. You may obtain a copy of the License at
  34625. *
  34626. * http://www.apache.org/licenses/LICENSE-2.0
  34627. *
  34628. * Unless required by applicable law or agreed to in writing,
  34629. * software distributed under the License is distributed on an
  34630. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34631. * KIND, either express or implied. See the License for the
  34632. * specific language governing permissions and limitations
  34633. * under the License.
  34634. */
  34635. var visualSymbol = function (seriesType, defaultSymbolType, legendSymbol) {
  34636. // Encoding visual for all series include which is filtered for legend drawing
  34637. return {
  34638. seriesType: seriesType,
  34639. // For legend.
  34640. performRawSeries: true,
  34641. reset: function (seriesModel, ecModel, api) {
  34642. var data = seriesModel.getData();
  34643. var symbolType = seriesModel.get('symbol');
  34644. var symbolSize = seriesModel.get('symbolSize');
  34645. var keepAspect = seriesModel.get('symbolKeepAspect');
  34646. var symbolRotate = seriesModel.get('symbolRotate');
  34647. var hasSymbolTypeCallback = isFunction$1(symbolType);
  34648. var hasSymbolSizeCallback = isFunction$1(symbolSize);
  34649. var hasSymbolRotateCallback = isFunction$1(symbolRotate);
  34650. var hasCallback = hasSymbolTypeCallback || hasSymbolSizeCallback || hasSymbolRotateCallback;
  34651. var seriesSymbol = (!hasSymbolTypeCallback && symbolType) ? symbolType : defaultSymbolType;
  34652. var seriesSymbolSize = !hasSymbolSizeCallback ? symbolSize : null;
  34653. data.setVisual({
  34654. legendSymbol: legendSymbol || seriesSymbol,
  34655. // If seting callback functions on `symbol` or `symbolSize`, for simplicity and avoiding
  34656. // to bring trouble, we do not pick a reuslt from one of its calling on data item here,
  34657. // but just use the default value. Callback on `symbol` or `symbolSize` is convenient in
  34658. // some cases but generally it is not recommanded.
  34659. symbol: seriesSymbol,
  34660. symbolSize: seriesSymbolSize,
  34661. symbolKeepAspect: keepAspect,
  34662. symbolRotate: symbolRotate
  34663. });
  34664. // Only visible series has each data be visual encoded
  34665. if (ecModel.isSeriesFiltered(seriesModel)) {
  34666. return;
  34667. }
  34668. function dataEach(data, idx) {
  34669. if (hasCallback) {
  34670. var rawValue = seriesModel.getRawValue(idx);
  34671. var params = seriesModel.getDataParams(idx);
  34672. hasSymbolTypeCallback && data.setItemVisual(idx, 'symbol', symbolType(rawValue, params));
  34673. hasSymbolSizeCallback && data.setItemVisual(idx, 'symbolSize', symbolSize(rawValue, params));
  34674. hasSymbolRotateCallback && data.setItemVisual(idx, 'symbolRotate', symbolRotate(rawValue, params));
  34675. }
  34676. if (data.hasItemOption) {
  34677. var itemModel = data.getItemModel(idx);
  34678. var itemSymbolType = itemModel.getShallow('symbol', true);
  34679. var itemSymbolSize = itemModel.getShallow('symbolSize', true);
  34680. var itemSymbolRotate = itemModel.getShallow('symbolRotate', true);
  34681. var itemSymbolKeepAspect = itemModel.getShallow('symbolKeepAspect', true);
  34682. // If has item symbol
  34683. if (itemSymbolType != null) {
  34684. data.setItemVisual(idx, 'symbol', itemSymbolType);
  34685. }
  34686. if (itemSymbolSize != null) {
  34687. // PENDING Transform symbolSize ?
  34688. data.setItemVisual(idx, 'symbolSize', itemSymbolSize);
  34689. }
  34690. if (itemSymbolRotate != null) {
  34691. data.setItemVisual(idx, 'symbolRotate', itemSymbolRotate);
  34692. }
  34693. if (itemSymbolKeepAspect != null) {
  34694. data.setItemVisual(idx, 'symbolKeepAspect', itemSymbolKeepAspect);
  34695. }
  34696. }
  34697. }
  34698. return { dataEach: (data.hasItemOption || hasCallback) ? dataEach : null };
  34699. }
  34700. };
  34701. };
  34702. /*
  34703. * Licensed to the Apache Software Foundation (ASF) under one
  34704. * or more contributor license agreements. See the NOTICE file
  34705. * distributed with this work for additional information
  34706. * regarding copyright ownership. The ASF licenses this file
  34707. * to you under the Apache License, Version 2.0 (the
  34708. * "License"); you may not use this file except in compliance
  34709. * with the License. You may obtain a copy of the License at
  34710. *
  34711. * http://www.apache.org/licenses/LICENSE-2.0
  34712. *
  34713. * Unless required by applicable law or agreed to in writing,
  34714. * software distributed under the License is distributed on an
  34715. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34716. * KIND, either express or implied. See the License for the
  34717. * specific language governing permissions and limitations
  34718. * under the License.
  34719. */
  34720. /* global Float32Array */
  34721. var pointsLayout = function (seriesType) {
  34722. return {
  34723. seriesType: seriesType,
  34724. plan: createRenderPlanner(),
  34725. reset: function (seriesModel) {
  34726. var data = seriesModel.getData();
  34727. var coordSys = seriesModel.coordinateSystem;
  34728. var pipelineContext = seriesModel.pipelineContext;
  34729. var isLargeRender = pipelineContext.large;
  34730. if (!coordSys) {
  34731. return;
  34732. }
  34733. var dims = map(coordSys.dimensions, function (dim) {
  34734. return data.mapDimension(dim);
  34735. }).slice(0, 2);
  34736. var dimLen = dims.length;
  34737. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  34738. if (isDimensionStacked(data, dims[0] /*, dims[1]*/)) {
  34739. dims[0] = stackResultDim;
  34740. }
  34741. if (isDimensionStacked(data, dims[1] /*, dims[0]*/)) {
  34742. dims[1] = stackResultDim;
  34743. }
  34744. function progress(params, data) {
  34745. var segCount = params.end - params.start;
  34746. var points = isLargeRender && new Float32Array(segCount * dimLen);
  34747. for (var i = params.start, offset = 0, tmpIn = [], tmpOut = []; i < params.end; i++) {
  34748. var point;
  34749. if (dimLen === 1) {
  34750. var x = data.get(dims[0], i);
  34751. point = !isNaN(x) && coordSys.dataToPoint(x, null, tmpOut);
  34752. }
  34753. else {
  34754. var x = tmpIn[0] = data.get(dims[0], i);
  34755. var y = tmpIn[1] = data.get(dims[1], i);
  34756. // Also {Array.<number>}, not undefined to avoid if...else... statement
  34757. point = !isNaN(x) && !isNaN(y) && coordSys.dataToPoint(tmpIn, null, tmpOut);
  34758. }
  34759. if (isLargeRender) {
  34760. points[offset++] = point ? point[0] : NaN;
  34761. points[offset++] = point ? point[1] : NaN;
  34762. }
  34763. else {
  34764. data.setItemLayout(i, (point && point.slice()) || [NaN, NaN]);
  34765. }
  34766. }
  34767. isLargeRender && data.setLayout('symbolPoints', points);
  34768. }
  34769. return dimLen && {progress: progress};
  34770. }
  34771. };
  34772. };
  34773. /*
  34774. * Licensed to the Apache Software Foundation (ASF) under one
  34775. * or more contributor license agreements. See the NOTICE file
  34776. * distributed with this work for additional information
  34777. * regarding copyright ownership. The ASF licenses this file
  34778. * to you under the Apache License, Version 2.0 (the
  34779. * "License"); you may not use this file except in compliance
  34780. * with the License. You may obtain a copy of the License at
  34781. *
  34782. * http://www.apache.org/licenses/LICENSE-2.0
  34783. *
  34784. * Unless required by applicable law or agreed to in writing,
  34785. * software distributed under the License is distributed on an
  34786. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34787. * KIND, either express or implied. See the License for the
  34788. * specific language governing permissions and limitations
  34789. * under the License.
  34790. */
  34791. var samplers = {
  34792. average: function (frame) {
  34793. var sum = 0;
  34794. var count = 0;
  34795. for (var i = 0; i < frame.length; i++) {
  34796. if (!isNaN(frame[i])) {
  34797. sum += frame[i];
  34798. count++;
  34799. }
  34800. }
  34801. // Return NaN if count is 0
  34802. return count === 0 ? NaN : sum / count;
  34803. },
  34804. sum: function (frame) {
  34805. var sum = 0;
  34806. for (var i = 0; i < frame.length; i++) {
  34807. // Ignore NaN
  34808. sum += frame[i] || 0;
  34809. }
  34810. return sum;
  34811. },
  34812. max: function (frame) {
  34813. var max = -Infinity;
  34814. for (var i = 0; i < frame.length; i++) {
  34815. frame[i] > max && (max = frame[i]);
  34816. }
  34817. // NaN will cause illegal axis extent.
  34818. return isFinite(max) ? max : NaN;
  34819. },
  34820. min: function (frame) {
  34821. var min = Infinity;
  34822. for (var i = 0; i < frame.length; i++) {
  34823. frame[i] < min && (min = frame[i]);
  34824. }
  34825. // NaN will cause illegal axis extent.
  34826. return isFinite(min) ? min : NaN;
  34827. },
  34828. // TODO
  34829. // Median
  34830. nearest: function (frame) {
  34831. return frame[0];
  34832. }
  34833. };
  34834. var indexSampler = function (frame, value) {
  34835. return Math.round(frame.length / 2);
  34836. };
  34837. var dataSample = function (seriesType) {
  34838. return {
  34839. seriesType: seriesType,
  34840. modifyOutputEnd: true,
  34841. reset: function (seriesModel, ecModel, api) {
  34842. var data = seriesModel.getData();
  34843. var sampling = seriesModel.get('sampling');
  34844. var coordSys = seriesModel.coordinateSystem;
  34845. // Only cartesian2d support down sampling
  34846. if (coordSys.type === 'cartesian2d' && sampling) {
  34847. var baseAxis = coordSys.getBaseAxis();
  34848. var valueAxis = coordSys.getOtherAxis(baseAxis);
  34849. var extent = baseAxis.getExtent();
  34850. // Coordinste system has been resized
  34851. var size = extent[1] - extent[0];
  34852. var rate = Math.round(data.count() / size);
  34853. if (rate > 1) {
  34854. var sampler;
  34855. if (typeof sampling === 'string') {
  34856. sampler = samplers[sampling];
  34857. }
  34858. else if (typeof sampling === 'function') {
  34859. sampler = sampling;
  34860. }
  34861. if (sampler) {
  34862. // Only support sample the first dim mapped from value axis.
  34863. seriesModel.setData(data.downSample(
  34864. data.mapDimension(valueAxis.dim), 1 / rate, sampler, indexSampler
  34865. ));
  34866. }
  34867. }
  34868. }
  34869. }
  34870. };
  34871. };
  34872. /*
  34873. * Licensed to the Apache Software Foundation (ASF) under one
  34874. * or more contributor license agreements. See the NOTICE file
  34875. * distributed with this work for additional information
  34876. * regarding copyright ownership. The ASF licenses this file
  34877. * to you under the Apache License, Version 2.0 (the
  34878. * "License"); you may not use this file except in compliance
  34879. * with the License. You may obtain a copy of the License at
  34880. *
  34881. * http://www.apache.org/licenses/LICENSE-2.0
  34882. *
  34883. * Unless required by applicable law or agreed to in writing,
  34884. * software distributed under the License is distributed on an
  34885. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34886. * KIND, either express or implied. See the License for the
  34887. * specific language governing permissions and limitations
  34888. * under the License.
  34889. */
  34890. /**
  34891. * Cartesian coordinate system
  34892. * @module echarts/coord/Cartesian
  34893. *
  34894. */
  34895. function dimAxisMapper(dim) {
  34896. return this._axes[dim];
  34897. }
  34898. /**
  34899. * @alias module:echarts/coord/Cartesian
  34900. * @constructor
  34901. */
  34902. var Cartesian = function (name) {
  34903. this._axes = {};
  34904. this._dimList = [];
  34905. /**
  34906. * @type {string}
  34907. */
  34908. this.name = name || '';
  34909. };
  34910. Cartesian.prototype = {
  34911. constructor: Cartesian,
  34912. type: 'cartesian',
  34913. /**
  34914. * Get axis
  34915. * @param {number|string} dim
  34916. * @return {module:echarts/coord/Cartesian~Axis}
  34917. */
  34918. getAxis: function (dim) {
  34919. return this._axes[dim];
  34920. },
  34921. /**
  34922. * Get axes list
  34923. * @return {Array.<module:echarts/coord/Cartesian~Axis>}
  34924. */
  34925. getAxes: function () {
  34926. return map(this._dimList, dimAxisMapper, this);
  34927. },
  34928. /**
  34929. * Get axes list by given scale type
  34930. */
  34931. getAxesByScale: function (scaleType) {
  34932. scaleType = scaleType.toLowerCase();
  34933. return filter(
  34934. this.getAxes(),
  34935. function (axis) {
  34936. return axis.scale.type === scaleType;
  34937. }
  34938. );
  34939. },
  34940. /**
  34941. * Add axis
  34942. * @param {module:echarts/coord/Cartesian.Axis}
  34943. */
  34944. addAxis: function (axis) {
  34945. var dim = axis.dim;
  34946. this._axes[dim] = axis;
  34947. this._dimList.push(dim);
  34948. },
  34949. /**
  34950. * Convert data to coord in nd space
  34951. * @param {Array.<number>|Object.<string, number>} val
  34952. * @return {Array.<number>|Object.<string, number>}
  34953. */
  34954. dataToCoord: function (val) {
  34955. return this._dataCoordConvert(val, 'dataToCoord');
  34956. },
  34957. /**
  34958. * Convert coord in nd space to data
  34959. * @param {Array.<number>|Object.<string, number>} val
  34960. * @return {Array.<number>|Object.<string, number>}
  34961. */
  34962. coordToData: function (val) {
  34963. return this._dataCoordConvert(val, 'coordToData');
  34964. },
  34965. _dataCoordConvert: function (input, method) {
  34966. var dimList = this._dimList;
  34967. var output = input instanceof Array ? [] : {};
  34968. for (var i = 0; i < dimList.length; i++) {
  34969. var dim = dimList[i];
  34970. var axis = this._axes[dim];
  34971. output[dim] = axis[method](input[dim]);
  34972. }
  34973. return output;
  34974. }
  34975. };
  34976. /*
  34977. * Licensed to the Apache Software Foundation (ASF) under one
  34978. * or more contributor license agreements. See the NOTICE file
  34979. * distributed with this work for additional information
  34980. * regarding copyright ownership. The ASF licenses this file
  34981. * to you under the Apache License, Version 2.0 (the
  34982. * "License"); you may not use this file except in compliance
  34983. * with the License. You may obtain a copy of the License at
  34984. *
  34985. * http://www.apache.org/licenses/LICENSE-2.0
  34986. *
  34987. * Unless required by applicable law or agreed to in writing,
  34988. * software distributed under the License is distributed on an
  34989. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34990. * KIND, either express or implied. See the License for the
  34991. * specific language governing permissions and limitations
  34992. * under the License.
  34993. */
  34994. function Cartesian2D(name) {
  34995. Cartesian.call(this, name);
  34996. }
  34997. Cartesian2D.prototype = {
  34998. constructor: Cartesian2D,
  34999. type: 'cartesian2d',
  35000. /**
  35001. * @type {Array.<string>}
  35002. * @readOnly
  35003. */
  35004. dimensions: ['x', 'y'],
  35005. /**
  35006. * Base axis will be used on stacking.
  35007. *
  35008. * @return {module:echarts/coord/cartesian/Axis2D}
  35009. */
  35010. getBaseAxis: function () {
  35011. return this.getAxesByScale('ordinal')[0]
  35012. || this.getAxesByScale('time')[0]
  35013. || this.getAxis('x');
  35014. },
  35015. /**
  35016. * If contain point
  35017. * @param {Array.<number>} point
  35018. * @return {boolean}
  35019. */
  35020. containPoint: function (point) {
  35021. var axisX = this.getAxis('x');
  35022. var axisY = this.getAxis('y');
  35023. return axisX.contain(axisX.toLocalCoord(point[0]))
  35024. && axisY.contain(axisY.toLocalCoord(point[1]));
  35025. },
  35026. /**
  35027. * If contain data
  35028. * @param {Array.<number>} data
  35029. * @return {boolean}
  35030. */
  35031. containData: function (data) {
  35032. return this.getAxis('x').containData(data[0])
  35033. && this.getAxis('y').containData(data[1]);
  35034. },
  35035. /**
  35036. * @param {Array.<number>} data
  35037. * @param {Array.<number>} out
  35038. * @return {Array.<number>}
  35039. */
  35040. dataToPoint: function (data, reserved, out) {
  35041. var xAxis = this.getAxis('x');
  35042. var yAxis = this.getAxis('y');
  35043. out = out || [];
  35044. out[0] = xAxis.toGlobalCoord(xAxis.dataToCoord(data[0]));
  35045. out[1] = yAxis.toGlobalCoord(yAxis.dataToCoord(data[1]));
  35046. return out;
  35047. },
  35048. /**
  35049. * @param {Array.<number>} data
  35050. * @param {Array.<number>} out
  35051. * @return {Array.<number>}
  35052. */
  35053. clampData: function (data, out) {
  35054. var xScale = this.getAxis('x').scale;
  35055. var yScale = this.getAxis('y').scale;
  35056. var xAxisExtent = xScale.getExtent();
  35057. var yAxisExtent = yScale.getExtent();
  35058. var x = xScale.parse(data[0]);
  35059. var y = yScale.parse(data[1]);
  35060. out = out || [];
  35061. out[0] = Math.min(
  35062. Math.max(Math.min(xAxisExtent[0], xAxisExtent[1]), x),
  35063. Math.max(xAxisExtent[0], xAxisExtent[1])
  35064. );
  35065. out[1] = Math.min(
  35066. Math.max(Math.min(yAxisExtent[0], yAxisExtent[1]), y),
  35067. Math.max(yAxisExtent[0], yAxisExtent[1])
  35068. );
  35069. return out;
  35070. },
  35071. /**
  35072. * @param {Array.<number>} point
  35073. * @param {Array.<number>} out
  35074. * @return {Array.<number>}
  35075. */
  35076. pointToData: function (point, out) {
  35077. var xAxis = this.getAxis('x');
  35078. var yAxis = this.getAxis('y');
  35079. out = out || [];
  35080. out[0] = xAxis.coordToData(xAxis.toLocalCoord(point[0]));
  35081. out[1] = yAxis.coordToData(yAxis.toLocalCoord(point[1]));
  35082. return out;
  35083. },
  35084. /**
  35085. * Get other axis
  35086. * @param {module:echarts/coord/cartesian/Axis2D} axis
  35087. */
  35088. getOtherAxis: function (axis) {
  35089. return this.getAxis(axis.dim === 'x' ? 'y' : 'x');
  35090. },
  35091. /**
  35092. * Get rect area of cartesian.
  35093. * Area will have a contain function to determine if a point is in the coordinate system.
  35094. * @return {BoundingRect}
  35095. */
  35096. getArea: function () {
  35097. var xExtent = this.getAxis('x').getGlobalExtent();
  35098. var yExtent = this.getAxis('y').getGlobalExtent();
  35099. var x = Math.min(xExtent[0], xExtent[1]);
  35100. var y = Math.min(yExtent[0], yExtent[1]);
  35101. var width = Math.max(xExtent[0], xExtent[1]) - x;
  35102. var height = Math.max(yExtent[0], yExtent[1]) - y;
  35103. var rect = new BoundingRect(x, y, width, height);
  35104. return rect;
  35105. }
  35106. };
  35107. inherits(Cartesian2D, Cartesian);
  35108. /*
  35109. * Licensed to the Apache Software Foundation (ASF) under one
  35110. * or more contributor license agreements. See the NOTICE file
  35111. * distributed with this work for additional information
  35112. * regarding copyright ownership. The ASF licenses this file
  35113. * to you under the Apache License, Version 2.0 (the
  35114. * "License"); you may not use this file except in compliance
  35115. * with the License. You may obtain a copy of the License at
  35116. *
  35117. * http://www.apache.org/licenses/LICENSE-2.0
  35118. *
  35119. * Unless required by applicable law or agreed to in writing,
  35120. * software distributed under the License is distributed on an
  35121. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35122. * KIND, either express or implied. See the License for the
  35123. * specific language governing permissions and limitations
  35124. * under the License.
  35125. */
  35126. /**
  35127. * Extend axis 2d
  35128. * @constructor module:echarts/coord/cartesian/Axis2D
  35129. * @extends {module:echarts/coord/cartesian/Axis}
  35130. * @param {string} dim
  35131. * @param {*} scale
  35132. * @param {Array.<number>} coordExtent
  35133. * @param {string} axisType
  35134. * @param {string} position
  35135. */
  35136. var Axis2D = function (dim, scale, coordExtent, axisType, position) {
  35137. Axis.call(this, dim, scale, coordExtent);
  35138. /**
  35139. * Axis type
  35140. * - 'category'
  35141. * - 'value'
  35142. * - 'time'
  35143. * - 'log'
  35144. * @type {string}
  35145. */
  35146. this.type = axisType || 'value';
  35147. /**
  35148. * Axis position
  35149. * - 'top'
  35150. * - 'bottom'
  35151. * - 'left'
  35152. * - 'right'
  35153. */
  35154. this.position = position || 'bottom';
  35155. };
  35156. Axis2D.prototype = {
  35157. constructor: Axis2D,
  35158. /**
  35159. * Index of axis, can be used as key
  35160. */
  35161. index: 0,
  35162. /**
  35163. * Implemented in <module:echarts/coord/cartesian/Grid>.
  35164. * @return {Array.<module:echarts/coord/cartesian/Axis2D>}
  35165. * If not on zero of other axis, return null/undefined.
  35166. * If no axes, return an empty array.
  35167. */
  35168. getAxesOnZeroOf: null,
  35169. /**
  35170. * Axis model
  35171. * @param {module:echarts/coord/cartesian/AxisModel}
  35172. */
  35173. model: null,
  35174. isHorizontal: function () {
  35175. var position = this.position;
  35176. return position === 'top' || position === 'bottom';
  35177. },
  35178. /**
  35179. * Each item cooresponds to this.getExtent(), which
  35180. * means globalExtent[0] may greater than globalExtent[1],
  35181. * unless `asc` is input.
  35182. *
  35183. * @param {boolean} [asc]
  35184. * @return {Array.<number>}
  35185. */
  35186. getGlobalExtent: function (asc) {
  35187. var ret = this.getExtent();
  35188. ret[0] = this.toGlobalCoord(ret[0]);
  35189. ret[1] = this.toGlobalCoord(ret[1]);
  35190. asc && ret[0] > ret[1] && ret.reverse();
  35191. return ret;
  35192. },
  35193. getOtherAxis: function () {
  35194. this.grid.getOtherAxis();
  35195. },
  35196. /**
  35197. * @override
  35198. */
  35199. pointToData: function (point, clamp) {
  35200. return this.coordToData(this.toLocalCoord(point[this.dim === 'x' ? 0 : 1]), clamp);
  35201. },
  35202. /**
  35203. * Transform global coord to local coord,
  35204. * i.e. var localCoord = axis.toLocalCoord(80);
  35205. * designate by module:echarts/coord/cartesian/Grid.
  35206. * @type {Function}
  35207. */
  35208. toLocalCoord: null,
  35209. /**
  35210. * Transform global coord to local coord,
  35211. * i.e. var globalCoord = axis.toLocalCoord(40);
  35212. * designate by module:echarts/coord/cartesian/Grid.
  35213. * @type {Function}
  35214. */
  35215. toGlobalCoord: null
  35216. };
  35217. inherits(Axis2D, Axis);
  35218. /*
  35219. * Licensed to the Apache Software Foundation (ASF) under one
  35220. * or more contributor license agreements. See the NOTICE file
  35221. * distributed with this work for additional information
  35222. * regarding copyright ownership. The ASF licenses this file
  35223. * to you under the Apache License, Version 2.0 (the
  35224. * "License"); you may not use this file except in compliance
  35225. * with the License. You may obtain a copy of the License at
  35226. *
  35227. * http://www.apache.org/licenses/LICENSE-2.0
  35228. *
  35229. * Unless required by applicable law or agreed to in writing,
  35230. * software distributed under the License is distributed on an
  35231. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35232. * KIND, either express or implied. See the License for the
  35233. * specific language governing permissions and limitations
  35234. * under the License.
  35235. */
  35236. var defaultOption = {
  35237. show: true,
  35238. zlevel: 0,
  35239. z: 0,
  35240. // Inverse the axis.
  35241. inverse: false,
  35242. // Axis name displayed.
  35243. name: '',
  35244. // 'start' | 'middle' | 'end'
  35245. nameLocation: 'end',
  35246. // By degree. By defualt auto rotate by nameLocation.
  35247. nameRotate: null,
  35248. nameTruncate: {
  35249. maxWidth: null,
  35250. ellipsis: '...',
  35251. placeholder: '.'
  35252. },
  35253. // Use global text style by default.
  35254. nameTextStyle: {},
  35255. // The gap between axisName and axisLine.
  35256. nameGap: 15,
  35257. // Default `false` to support tooltip.
  35258. silent: false,
  35259. // Default `false` to avoid legacy user event listener fail.
  35260. triggerEvent: false,
  35261. tooltip: {
  35262. show: false
  35263. },
  35264. axisPointer: {},
  35265. axisLine: {
  35266. show: true,
  35267. onZero: true,
  35268. onZeroAxisIndex: null,
  35269. lineStyle: {
  35270. color: '#333',
  35271. width: 1,
  35272. type: 'solid'
  35273. },
  35274. // The arrow at both ends the the axis.
  35275. symbol: ['none', 'none'],
  35276. symbolSize: [10, 15]
  35277. },
  35278. axisTick: {
  35279. show: true,
  35280. // Whether axisTick is inside the grid or outside the grid.
  35281. inside: false,
  35282. // The length of axisTick.
  35283. length: 5,
  35284. lineStyle: {
  35285. width: 1
  35286. }
  35287. },
  35288. axisLabel: {
  35289. show: true,
  35290. // Whether axisLabel is inside the grid or outside the grid.
  35291. inside: false,
  35292. rotate: 0,
  35293. // true | false | null/undefined (auto)
  35294. showMinLabel: null,
  35295. // true | false | null/undefined (auto)
  35296. showMaxLabel: null,
  35297. margin: 8,
  35298. // formatter: null,
  35299. fontSize: 12
  35300. },
  35301. splitLine: {
  35302. show: true,
  35303. lineStyle: {
  35304. color: ['#ccc'],
  35305. width: 1,
  35306. type: 'solid'
  35307. }
  35308. },
  35309. splitArea: {
  35310. show: false,
  35311. areaStyle: {
  35312. color: ['rgba(250,250,250,0.3)', 'rgba(200,200,200,0.3)']
  35313. }
  35314. }
  35315. };
  35316. var axisDefault = {};
  35317. axisDefault.categoryAxis = merge({
  35318. // The gap at both ends of the axis. For categoryAxis, boolean.
  35319. boundaryGap: true,
  35320. // Set false to faster category collection.
  35321. // Only usefull in the case like: category is
  35322. // ['2012-01-01', '2012-01-02', ...], where the input
  35323. // data has been ensured not duplicate and is large data.
  35324. // null means "auto":
  35325. // if axis.data provided, do not deduplication,
  35326. // else do deduplication.
  35327. deduplication: null,
  35328. // splitArea: {
  35329. // show: false
  35330. // },
  35331. splitLine: {
  35332. show: false
  35333. },
  35334. axisTick: {
  35335. // If tick is align with label when boundaryGap is true
  35336. alignWithLabel: false,
  35337. interval: 'auto'
  35338. },
  35339. axisLabel: {
  35340. interval: 'auto'
  35341. }
  35342. }, defaultOption);
  35343. axisDefault.valueAxis = merge({
  35344. // The gap at both ends of the axis. For value axis, [GAP, GAP], where
  35345. // `GAP` can be an absolute pixel number (like `35`), or percent (like `'30%'`)
  35346. boundaryGap: [0, 0],
  35347. // TODO
  35348. // min/max: [30, datamin, 60] or [20, datamin] or [datamin, 60]
  35349. // Min value of the axis. can be:
  35350. // + a number
  35351. // + 'dataMin': use the min value in data.
  35352. // + null/undefined: auto decide min value (consider pretty look and boundaryGap).
  35353. // min: null,
  35354. // Max value of the axis. can be:
  35355. // + a number
  35356. // + 'dataMax': use the max value in data.
  35357. // + null/undefined: auto decide max value (consider pretty look and boundaryGap).
  35358. // max: null,
  35359. // Readonly prop, specifies start value of the range when using data zoom.
  35360. // rangeStart: null
  35361. // Readonly prop, specifies end value of the range when using data zoom.
  35362. // rangeEnd: null
  35363. // Optional value can be:
  35364. // + `false`: always include value 0.
  35365. // + `true`: the extent do not consider value 0.
  35366. // scale: false,
  35367. // AxisTick and axisLabel and splitLine are caculated based on splitNumber.
  35368. splitNumber: 5,
  35369. // Interval specifies the span of the ticks is mandatorily.
  35370. // interval: null
  35371. // Specify min interval when auto calculate tick interval.
  35372. // minInterval: null
  35373. // Specify max interval when auto calculate tick interval.
  35374. // maxInterval: null
  35375. minorTick: {
  35376. // Minor tick, not available for cateogry axis.
  35377. show: false,
  35378. // Split number of minor ticks. The value should be in range of (0, 100)
  35379. splitNumber: 5,
  35380. // Lenght of minor tick
  35381. length: 3,
  35382. // Same inside with axisTick
  35383. // Line style
  35384. lineStyle: {
  35385. // Default to be same with axisTick
  35386. }
  35387. },
  35388. minorSplitLine: {
  35389. show: false,
  35390. lineStyle: {
  35391. color: '#eee',
  35392. width: 1
  35393. }
  35394. }
  35395. }, defaultOption);
  35396. axisDefault.timeAxis = defaults({
  35397. scale: true,
  35398. min: 'dataMin',
  35399. max: 'dataMax'
  35400. }, axisDefault.valueAxis);
  35401. axisDefault.logAxis = defaults({
  35402. scale: true,
  35403. logBase: 10
  35404. }, axisDefault.valueAxis);
  35405. /*
  35406. * Licensed to the Apache Software Foundation (ASF) under one
  35407. * or more contributor license agreements. See the NOTICE file
  35408. * distributed with this work for additional information
  35409. * regarding copyright ownership. The ASF licenses this file
  35410. * to you under the Apache License, Version 2.0 (the
  35411. * "License"); you may not use this file except in compliance
  35412. * with the License. You may obtain a copy of the License at
  35413. *
  35414. * http://www.apache.org/licenses/LICENSE-2.0
  35415. *
  35416. * Unless required by applicable law or agreed to in writing,
  35417. * software distributed under the License is distributed on an
  35418. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35419. * KIND, either express or implied. See the License for the
  35420. * specific language governing permissions and limitations
  35421. * under the License.
  35422. */
  35423. // FIXME axisType is fixed ?
  35424. var AXIS_TYPES = ['value', 'category', 'time', 'log'];
  35425. /**
  35426. * Generate sub axis model class
  35427. * @param {string} axisName 'x' 'y' 'radius' 'angle' 'parallel'
  35428. * @param {module:echarts/model/Component} BaseAxisModelClass
  35429. * @param {Function} axisTypeDefaulter
  35430. * @param {Object} [extraDefaultOption]
  35431. */
  35432. var axisModelCreator = function (axisName, BaseAxisModelClass, axisTypeDefaulter, extraDefaultOption) {
  35433. each$1(AXIS_TYPES, function (axisType) {
  35434. BaseAxisModelClass.extend({
  35435. /**
  35436. * @readOnly
  35437. */
  35438. type: axisName + 'Axis.' + axisType,
  35439. mergeDefaultAndTheme: function (option, ecModel) {
  35440. var layoutMode = this.layoutMode;
  35441. var inputPositionParams = layoutMode
  35442. ? getLayoutParams(option) : {};
  35443. var themeModel = ecModel.getTheme();
  35444. merge(option, themeModel.get(axisType + 'Axis'));
  35445. merge(option, this.getDefaultOption());
  35446. option.type = axisTypeDefaulter(axisName, option);
  35447. if (layoutMode) {
  35448. mergeLayoutParam(option, inputPositionParams, layoutMode);
  35449. }
  35450. },
  35451. /**
  35452. * @override
  35453. */
  35454. optionUpdated: function () {
  35455. var thisOption = this.option;
  35456. if (thisOption.type === 'category') {
  35457. this.__ordinalMeta = OrdinalMeta.createByAxisModel(this);
  35458. }
  35459. },
  35460. /**
  35461. * Should not be called before all of 'getInitailData' finished.
  35462. * Because categories are collected during initializing data.
  35463. */
  35464. getCategories: function (rawData) {
  35465. var option = this.option;
  35466. // FIXME
  35467. // warning if called before all of 'getInitailData' finished.
  35468. if (option.type === 'category') {
  35469. if (rawData) {
  35470. return option.data;
  35471. }
  35472. return this.__ordinalMeta.categories;
  35473. }
  35474. },
  35475. getOrdinalMeta: function () {
  35476. return this.__ordinalMeta;
  35477. },
  35478. defaultOption: mergeAll(
  35479. [
  35480. {},
  35481. axisDefault[axisType + 'Axis'],
  35482. extraDefaultOption
  35483. ],
  35484. true
  35485. )
  35486. });
  35487. });
  35488. ComponentModel.registerSubTypeDefaulter(
  35489. axisName + 'Axis',
  35490. curry(axisTypeDefaulter, axisName)
  35491. );
  35492. };
  35493. /*
  35494. * Licensed to the Apache Software Foundation (ASF) under one
  35495. * or more contributor license agreements. See the NOTICE file
  35496. * distributed with this work for additional information
  35497. * regarding copyright ownership. The ASF licenses this file
  35498. * to you under the Apache License, Version 2.0 (the
  35499. * "License"); you may not use this file except in compliance
  35500. * with the License. You may obtain a copy of the License at
  35501. *
  35502. * http://www.apache.org/licenses/LICENSE-2.0
  35503. *
  35504. * Unless required by applicable law or agreed to in writing,
  35505. * software distributed under the License is distributed on an
  35506. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35507. * KIND, either express or implied. See the License for the
  35508. * specific language governing permissions and limitations
  35509. * under the License.
  35510. */
  35511. var AxisModel = ComponentModel.extend({
  35512. type: 'cartesian2dAxis',
  35513. /**
  35514. * @type {module:echarts/coord/cartesian/Axis2D}
  35515. */
  35516. axis: null,
  35517. /**
  35518. * @override
  35519. */
  35520. init: function () {
  35521. AxisModel.superApply(this, 'init', arguments);
  35522. this.resetRange();
  35523. },
  35524. /**
  35525. * @override
  35526. */
  35527. mergeOption: function () {
  35528. AxisModel.superApply(this, 'mergeOption', arguments);
  35529. this.resetRange();
  35530. },
  35531. /**
  35532. * @override
  35533. */
  35534. restoreData: function () {
  35535. AxisModel.superApply(this, 'restoreData', arguments);
  35536. this.resetRange();
  35537. },
  35538. /**
  35539. * @override
  35540. * @return {module:echarts/model/Component}
  35541. */
  35542. getCoordSysModel: function () {
  35543. return this.ecModel.queryComponents({
  35544. mainType: 'grid',
  35545. index: this.option.gridIndex,
  35546. id: this.option.gridId
  35547. })[0];
  35548. }
  35549. });
  35550. function getAxisType(axisDim, option) {
  35551. // Default axis with data is category axis
  35552. return option.type || (option.data ? 'category' : 'value');
  35553. }
  35554. merge(AxisModel.prototype, axisModelCommonMixin);
  35555. var extraOption = {
  35556. // gridIndex: 0,
  35557. // gridId: '',
  35558. // Offset is for multiple axis on the same position
  35559. offset: 0
  35560. };
  35561. axisModelCreator('x', AxisModel, getAxisType, extraOption);
  35562. axisModelCreator('y', AxisModel, getAxisType, extraOption);
  35563. /*
  35564. * Licensed to the Apache Software Foundation (ASF) under one
  35565. * or more contributor license agreements. See the NOTICE file
  35566. * distributed with this work for additional information
  35567. * regarding copyright ownership. The ASF licenses this file
  35568. * to you under the Apache License, Version 2.0 (the
  35569. * "License"); you may not use this file except in compliance
  35570. * with the License. You may obtain a copy of the License at
  35571. *
  35572. * http://www.apache.org/licenses/LICENSE-2.0
  35573. *
  35574. * Unless required by applicable law or agreed to in writing,
  35575. * software distributed under the License is distributed on an
  35576. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35577. * KIND, either express or implied. See the License for the
  35578. * specific language governing permissions and limitations
  35579. * under the License.
  35580. */
  35581. // Grid 是在有直角坐标系的时候必须要存在的
  35582. // 所以这里也要被 Cartesian2D 依赖
  35583. ComponentModel.extend({
  35584. type: 'grid',
  35585. dependencies: ['xAxis', 'yAxis'],
  35586. layoutMode: 'box',
  35587. /**
  35588. * @type {module:echarts/coord/cartesian/Grid}
  35589. */
  35590. coordinateSystem: null,
  35591. defaultOption: {
  35592. show: false,
  35593. zlevel: 0,
  35594. z: 0,
  35595. left: '10%',
  35596. top: 60,
  35597. right: '10%',
  35598. bottom: 60,
  35599. // If grid size contain label
  35600. containLabel: false,
  35601. // width: {totalWidth} - left - right,
  35602. // height: {totalHeight} - top - bottom,
  35603. backgroundColor: 'rgba(0,0,0,0)',
  35604. borderWidth: 1,
  35605. borderColor: '#ccc'
  35606. }
  35607. });
  35608. /*
  35609. * Licensed to the Apache Software Foundation (ASF) under one
  35610. * or more contributor license agreements. See the NOTICE file
  35611. * distributed with this work for additional information
  35612. * regarding copyright ownership. The ASF licenses this file
  35613. * to you under the Apache License, Version 2.0 (the
  35614. * "License"); you may not use this file except in compliance
  35615. * with the License. You may obtain a copy of the License at
  35616. *
  35617. * http://www.apache.org/licenses/LICENSE-2.0
  35618. *
  35619. * Unless required by applicable law or agreed to in writing,
  35620. * software distributed under the License is distributed on an
  35621. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35622. * KIND, either express or implied. See the License for the
  35623. * specific language governing permissions and limitations
  35624. * under the License.
  35625. */
  35626. /**
  35627. * Grid is a region which contains at most 4 cartesian systems
  35628. *
  35629. * TODO Default cartesian
  35630. */
  35631. // Depends on GridModel, AxisModel, which performs preprocess.
  35632. /**
  35633. * Check if the axis is used in the specified grid
  35634. * @inner
  35635. */
  35636. function isAxisUsedInTheGrid(axisModel, gridModel, ecModel) {
  35637. return axisModel.getCoordSysModel() === gridModel;
  35638. }
  35639. function Grid(gridModel, ecModel, api) {
  35640. /**
  35641. * @type {Object.<string, module:echarts/coord/cartesian/Cartesian2D>}
  35642. * @private
  35643. */
  35644. this._coordsMap = {};
  35645. /**
  35646. * @type {Array.<module:echarts/coord/cartesian/Cartesian>}
  35647. * @private
  35648. */
  35649. this._coordsList = [];
  35650. /**
  35651. * @type {Object.<string, Array.<module:echarts/coord/cartesian/Axis2D>>}
  35652. * @private
  35653. */
  35654. this._axesMap = {};
  35655. /**
  35656. * @type {Array.<module:echarts/coord/cartesian/Axis2D>}
  35657. * @private
  35658. */
  35659. this._axesList = [];
  35660. this._initCartesian(gridModel, ecModel, api);
  35661. this.model = gridModel;
  35662. }
  35663. var gridProto = Grid.prototype;
  35664. gridProto.type = 'grid';
  35665. gridProto.axisPointerEnabled = true;
  35666. gridProto.getRect = function () {
  35667. return this._rect;
  35668. };
  35669. gridProto.update = function (ecModel, api) {
  35670. var axesMap = this._axesMap;
  35671. this._updateScale(ecModel, this.model);
  35672. each$1(axesMap.x, function (xAxis) {
  35673. niceScaleExtent(xAxis.scale, xAxis.model);
  35674. });
  35675. each$1(axesMap.y, function (yAxis) {
  35676. niceScaleExtent(yAxis.scale, yAxis.model);
  35677. });
  35678. // Key: axisDim_axisIndex, value: boolean, whether onZero target.
  35679. var onZeroRecords = {};
  35680. each$1(axesMap.x, function (xAxis) {
  35681. fixAxisOnZero(axesMap, 'y', xAxis, onZeroRecords);
  35682. });
  35683. each$1(axesMap.y, function (yAxis) {
  35684. fixAxisOnZero(axesMap, 'x', yAxis, onZeroRecords);
  35685. });
  35686. // Resize again if containLabel is enabled
  35687. // FIXME It may cause getting wrong grid size in data processing stage
  35688. this.resize(this.model, api);
  35689. };
  35690. function fixAxisOnZero(axesMap, otherAxisDim, axis, onZeroRecords) {
  35691. axis.getAxesOnZeroOf = function () {
  35692. // TODO: onZero of multiple axes.
  35693. return otherAxisOnZeroOf ? [otherAxisOnZeroOf] : [];
  35694. };
  35695. // onZero can not be enabled in these two situations:
  35696. // 1. When any other axis is a category axis.
  35697. // 2. When no axis is cross 0 point.
  35698. var otherAxes = axesMap[otherAxisDim];
  35699. var otherAxisOnZeroOf;
  35700. var axisModel = axis.model;
  35701. var onZero = axisModel.get('axisLine.onZero');
  35702. var onZeroAxisIndex = axisModel.get('axisLine.onZeroAxisIndex');
  35703. if (!onZero) {
  35704. return;
  35705. }
  35706. // If target axis is specified.
  35707. if (onZeroAxisIndex != null) {
  35708. if (canOnZeroToAxis(otherAxes[onZeroAxisIndex])) {
  35709. otherAxisOnZeroOf = otherAxes[onZeroAxisIndex];
  35710. }
  35711. }
  35712. else {
  35713. // Find the first available other axis.
  35714. for (var idx in otherAxes) {
  35715. if (otherAxes.hasOwnProperty(idx)
  35716. && canOnZeroToAxis(otherAxes[idx])
  35717. // Consider that two Y axes on one value axis,
  35718. // if both onZero, the two Y axes overlap.
  35719. && !onZeroRecords[getOnZeroRecordKey(otherAxes[idx])]
  35720. ) {
  35721. otherAxisOnZeroOf = otherAxes[idx];
  35722. break;
  35723. }
  35724. }
  35725. }
  35726. if (otherAxisOnZeroOf) {
  35727. onZeroRecords[getOnZeroRecordKey(otherAxisOnZeroOf)] = true;
  35728. }
  35729. function getOnZeroRecordKey(axis) {
  35730. return axis.dim + '_' + axis.index;
  35731. }
  35732. }
  35733. function canOnZeroToAxis(axis) {
  35734. return axis && axis.type !== 'category' && axis.type !== 'time' && ifAxisCrossZero(axis);
  35735. }
  35736. /**
  35737. * Resize the grid
  35738. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  35739. * @param {module:echarts/ExtensionAPI} api
  35740. */
  35741. gridProto.resize = function (gridModel, api, ignoreContainLabel) {
  35742. var gridRect = getLayoutRect(
  35743. gridModel.getBoxLayoutParams(), {
  35744. width: api.getWidth(),
  35745. height: api.getHeight()
  35746. });
  35747. this._rect = gridRect;
  35748. var axesList = this._axesList;
  35749. adjustAxes();
  35750. // Minus label size
  35751. if (!ignoreContainLabel && gridModel.get('containLabel')) {
  35752. each$1(axesList, function (axis) {
  35753. if (!axis.model.get('axisLabel.inside')) {
  35754. var labelUnionRect = estimateLabelUnionRect(axis);
  35755. if (labelUnionRect) {
  35756. var dim = axis.isHorizontal() ? 'height' : 'width';
  35757. var margin = axis.model.get('axisLabel.margin');
  35758. gridRect[dim] -= labelUnionRect[dim] + margin;
  35759. if (axis.position === 'top') {
  35760. gridRect.y += labelUnionRect.height + margin;
  35761. }
  35762. else if (axis.position === 'left') {
  35763. gridRect.x += labelUnionRect.width + margin;
  35764. }
  35765. }
  35766. }
  35767. });
  35768. adjustAxes();
  35769. }
  35770. function adjustAxes() {
  35771. each$1(axesList, function (axis) {
  35772. var isHorizontal = axis.isHorizontal();
  35773. var extent = isHorizontal ? [0, gridRect.width] : [0, gridRect.height];
  35774. var idx = axis.inverse ? 1 : 0;
  35775. axis.setExtent(extent[idx], extent[1 - idx]);
  35776. updateAxisTransform(axis, isHorizontal ? gridRect.x : gridRect.y);
  35777. });
  35778. }
  35779. };
  35780. /**
  35781. * @param {string} axisType
  35782. * @param {number} [axisIndex]
  35783. */
  35784. gridProto.getAxis = function (axisType, axisIndex) {
  35785. var axesMapOnDim = this._axesMap[axisType];
  35786. if (axesMapOnDim != null) {
  35787. if (axisIndex == null) {
  35788. // Find first axis
  35789. for (var name in axesMapOnDim) {
  35790. if (axesMapOnDim.hasOwnProperty(name)) {
  35791. return axesMapOnDim[name];
  35792. }
  35793. }
  35794. }
  35795. return axesMapOnDim[axisIndex];
  35796. }
  35797. };
  35798. /**
  35799. * @return {Array.<module:echarts/coord/Axis>}
  35800. */
  35801. gridProto.getAxes = function () {
  35802. return this._axesList.slice();
  35803. };
  35804. /**
  35805. * Usage:
  35806. * grid.getCartesian(xAxisIndex, yAxisIndex);
  35807. * grid.getCartesian(xAxisIndex);
  35808. * grid.getCartesian(null, yAxisIndex);
  35809. * grid.getCartesian({xAxisIndex: ..., yAxisIndex: ...});
  35810. *
  35811. * @param {number|Object} [xAxisIndex]
  35812. * @param {number} [yAxisIndex]
  35813. */
  35814. gridProto.getCartesian = function (xAxisIndex, yAxisIndex) {
  35815. if (xAxisIndex != null && yAxisIndex != null) {
  35816. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  35817. return this._coordsMap[key];
  35818. }
  35819. if (isObject$1(xAxisIndex)) {
  35820. yAxisIndex = xAxisIndex.yAxisIndex;
  35821. xAxisIndex = xAxisIndex.xAxisIndex;
  35822. }
  35823. // When only xAxisIndex or yAxisIndex given, find its first cartesian.
  35824. for (var i = 0, coordList = this._coordsList; i < coordList.length; i++) {
  35825. if (coordList[i].getAxis('x').index === xAxisIndex
  35826. || coordList[i].getAxis('y').index === yAxisIndex
  35827. ) {
  35828. return coordList[i];
  35829. }
  35830. }
  35831. };
  35832. gridProto.getCartesians = function () {
  35833. return this._coordsList.slice();
  35834. };
  35835. /**
  35836. * @implements
  35837. * see {module:echarts/CoodinateSystem}
  35838. */
  35839. gridProto.convertToPixel = function (ecModel, finder, value) {
  35840. var target = this._findConvertTarget(ecModel, finder);
  35841. return target.cartesian
  35842. ? target.cartesian.dataToPoint(value)
  35843. : target.axis
  35844. ? target.axis.toGlobalCoord(target.axis.dataToCoord(value))
  35845. : null;
  35846. };
  35847. /**
  35848. * @implements
  35849. * see {module:echarts/CoodinateSystem}
  35850. */
  35851. gridProto.convertFromPixel = function (ecModel, finder, value) {
  35852. var target = this._findConvertTarget(ecModel, finder);
  35853. return target.cartesian
  35854. ? target.cartesian.pointToData(value)
  35855. : target.axis
  35856. ? target.axis.coordToData(target.axis.toLocalCoord(value))
  35857. : null;
  35858. };
  35859. /**
  35860. * @inner
  35861. */
  35862. gridProto._findConvertTarget = function (ecModel, finder) {
  35863. var seriesModel = finder.seriesModel;
  35864. var xAxisModel = finder.xAxisModel
  35865. || (seriesModel && seriesModel.getReferringComponents('xAxis')[0]);
  35866. var yAxisModel = finder.yAxisModel
  35867. || (seriesModel && seriesModel.getReferringComponents('yAxis')[0]);
  35868. var gridModel = finder.gridModel;
  35869. var coordsList = this._coordsList;
  35870. var cartesian;
  35871. var axis;
  35872. if (seriesModel) {
  35873. cartesian = seriesModel.coordinateSystem;
  35874. indexOf(coordsList, cartesian) < 0 && (cartesian = null);
  35875. }
  35876. else if (xAxisModel && yAxisModel) {
  35877. cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  35878. }
  35879. else if (xAxisModel) {
  35880. axis = this.getAxis('x', xAxisModel.componentIndex);
  35881. }
  35882. else if (yAxisModel) {
  35883. axis = this.getAxis('y', yAxisModel.componentIndex);
  35884. }
  35885. // Lowest priority.
  35886. else if (gridModel) {
  35887. var grid = gridModel.coordinateSystem;
  35888. if (grid === this) {
  35889. cartesian = this._coordsList[0];
  35890. }
  35891. }
  35892. return {cartesian: cartesian, axis: axis};
  35893. };
  35894. /**
  35895. * @implements
  35896. * see {module:echarts/CoodinateSystem}
  35897. */
  35898. gridProto.containPoint = function (point) {
  35899. var coord = this._coordsList[0];
  35900. if (coord) {
  35901. return coord.containPoint(point);
  35902. }
  35903. };
  35904. /**
  35905. * Initialize cartesian coordinate systems
  35906. * @private
  35907. */
  35908. gridProto._initCartesian = function (gridModel, ecModel, api) {
  35909. var axisPositionUsed = {
  35910. left: false,
  35911. right: false,
  35912. top: false,
  35913. bottom: false
  35914. };
  35915. var axesMap = {
  35916. x: {},
  35917. y: {}
  35918. };
  35919. var axesCount = {
  35920. x: 0,
  35921. y: 0
  35922. };
  35923. /// Create axis
  35924. ecModel.eachComponent('xAxis', createAxisCreator('x'), this);
  35925. ecModel.eachComponent('yAxis', createAxisCreator('y'), this);
  35926. if (!axesCount.x || !axesCount.y) {
  35927. // Roll back when there no either x or y axis
  35928. this._axesMap = {};
  35929. this._axesList = [];
  35930. return;
  35931. }
  35932. this._axesMap = axesMap;
  35933. /// Create cartesian2d
  35934. each$1(axesMap.x, function (xAxis, xAxisIndex) {
  35935. each$1(axesMap.y, function (yAxis, yAxisIndex) {
  35936. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  35937. var cartesian = new Cartesian2D(key);
  35938. cartesian.grid = this;
  35939. cartesian.model = gridModel;
  35940. this._coordsMap[key] = cartesian;
  35941. this._coordsList.push(cartesian);
  35942. cartesian.addAxis(xAxis);
  35943. cartesian.addAxis(yAxis);
  35944. }, this);
  35945. }, this);
  35946. function createAxisCreator(axisType) {
  35947. return function (axisModel, idx) {
  35948. if (!isAxisUsedInTheGrid(axisModel, gridModel, ecModel)) {
  35949. return;
  35950. }
  35951. var axisPosition = axisModel.get('position');
  35952. if (axisType === 'x') {
  35953. // Fix position
  35954. if (axisPosition !== 'top' && axisPosition !== 'bottom') {
  35955. // Default bottom of X
  35956. axisPosition = axisPositionUsed.bottom ? 'top' : 'bottom';
  35957. }
  35958. }
  35959. else {
  35960. // Fix position
  35961. if (axisPosition !== 'left' && axisPosition !== 'right') {
  35962. // Default left of Y
  35963. axisPosition = axisPositionUsed.left ? 'right' : 'left';
  35964. }
  35965. }
  35966. axisPositionUsed[axisPosition] = true;
  35967. var axis = new Axis2D(
  35968. axisType, createScaleByModel(axisModel),
  35969. [0, 0],
  35970. axisModel.get('type'),
  35971. axisPosition
  35972. );
  35973. var isCategory = axis.type === 'category';
  35974. axis.onBand = isCategory && axisModel.get('boundaryGap');
  35975. axis.inverse = axisModel.get('inverse');
  35976. // Inject axis into axisModel
  35977. axisModel.axis = axis;
  35978. // Inject axisModel into axis
  35979. axis.model = axisModel;
  35980. // Inject grid info axis
  35981. axis.grid = this;
  35982. // Index of axis, can be used as key
  35983. axis.index = idx;
  35984. this._axesList.push(axis);
  35985. axesMap[axisType][idx] = axis;
  35986. axesCount[axisType]++;
  35987. };
  35988. }
  35989. };
  35990. /**
  35991. * Update cartesian properties from series
  35992. * @param {module:echarts/model/Option} option
  35993. * @private
  35994. */
  35995. gridProto._updateScale = function (ecModel, gridModel) {
  35996. // Reset scale
  35997. each$1(this._axesList, function (axis) {
  35998. axis.scale.setExtent(Infinity, -Infinity);
  35999. });
  36000. ecModel.eachSeries(function (seriesModel) {
  36001. if (isCartesian2D(seriesModel)) {
  36002. var axesModels = findAxesModels(seriesModel, ecModel);
  36003. var xAxisModel = axesModels[0];
  36004. var yAxisModel = axesModels[1];
  36005. if (!isAxisUsedInTheGrid(xAxisModel, gridModel, ecModel)
  36006. || !isAxisUsedInTheGrid(yAxisModel, gridModel, ecModel)
  36007. ) {
  36008. return;
  36009. }
  36010. var cartesian = this.getCartesian(
  36011. xAxisModel.componentIndex, yAxisModel.componentIndex
  36012. );
  36013. var data = seriesModel.getData();
  36014. var xAxis = cartesian.getAxis('x');
  36015. var yAxis = cartesian.getAxis('y');
  36016. if (data.type === 'list') {
  36017. unionExtent(data, xAxis, seriesModel);
  36018. unionExtent(data, yAxis, seriesModel);
  36019. }
  36020. }
  36021. }, this);
  36022. function unionExtent(data, axis, seriesModel) {
  36023. each$1(data.mapDimension(axis.dim, true), function (dim) {
  36024. axis.scale.unionExtentFromData(
  36025. // For example, the extent of the orginal dimension
  36026. // is [0.1, 0.5], the extent of the `stackResultDimension`
  36027. // is [7, 9], the final extent should not include [0.1, 0.5].
  36028. data, getStackedDimension(data, dim)
  36029. );
  36030. });
  36031. }
  36032. };
  36033. /**
  36034. * @param {string} [dim] 'x' or 'y' or 'auto' or null/undefined
  36035. * @return {Object} {baseAxes: [], otherAxes: []}
  36036. */
  36037. gridProto.getTooltipAxes = function (dim) {
  36038. var baseAxes = [];
  36039. var otherAxes = [];
  36040. each$1(this.getCartesians(), function (cartesian) {
  36041. var baseAxis = (dim != null && dim !== 'auto')
  36042. ? cartesian.getAxis(dim) : cartesian.getBaseAxis();
  36043. var otherAxis = cartesian.getOtherAxis(baseAxis);
  36044. indexOf(baseAxes, baseAxis) < 0 && baseAxes.push(baseAxis);
  36045. indexOf(otherAxes, otherAxis) < 0 && otherAxes.push(otherAxis);
  36046. });
  36047. return {baseAxes: baseAxes, otherAxes: otherAxes};
  36048. };
  36049. /**
  36050. * @inner
  36051. */
  36052. function updateAxisTransform(axis, coordBase) {
  36053. var axisExtent = axis.getExtent();
  36054. var axisExtentSum = axisExtent[0] + axisExtent[1];
  36055. // Fast transform
  36056. axis.toGlobalCoord = axis.dim === 'x'
  36057. ? function (coord) {
  36058. return coord + coordBase;
  36059. }
  36060. : function (coord) {
  36061. return axisExtentSum - coord + coordBase;
  36062. };
  36063. axis.toLocalCoord = axis.dim === 'x'
  36064. ? function (coord) {
  36065. return coord - coordBase;
  36066. }
  36067. : function (coord) {
  36068. return axisExtentSum - coord + coordBase;
  36069. };
  36070. }
  36071. var axesTypes = ['xAxis', 'yAxis'];
  36072. /**
  36073. * @inner
  36074. */
  36075. function findAxesModels(seriesModel, ecModel) {
  36076. return map(axesTypes, function (axisType) {
  36077. var axisModel = seriesModel.getReferringComponents(axisType)[0];
  36078. if (__DEV__) {
  36079. if (!axisModel) {
  36080. throw new Error(axisType + ' "' + retrieve(
  36081. seriesModel.get(axisType + 'Index'),
  36082. seriesModel.get(axisType + 'Id'),
  36083. 0
  36084. ) + '" not found');
  36085. }
  36086. }
  36087. return axisModel;
  36088. });
  36089. }
  36090. /**
  36091. * @inner
  36092. */
  36093. function isCartesian2D(seriesModel) {
  36094. return seriesModel.get('coordinateSystem') === 'cartesian2d';
  36095. }
  36096. Grid.create = function (ecModel, api) {
  36097. var grids = [];
  36098. ecModel.eachComponent('grid', function (gridModel, idx) {
  36099. var grid = new Grid(gridModel, ecModel, api);
  36100. grid.name = 'grid_' + idx;
  36101. // dataSampling requires axis extent, so resize
  36102. // should be performed in create stage.
  36103. grid.resize(gridModel, api, true);
  36104. gridModel.coordinateSystem = grid;
  36105. grids.push(grid);
  36106. });
  36107. // Inject the coordinateSystems into seriesModel
  36108. ecModel.eachSeries(function (seriesModel) {
  36109. if (!isCartesian2D(seriesModel)) {
  36110. return;
  36111. }
  36112. var axesModels = findAxesModels(seriesModel, ecModel);
  36113. var xAxisModel = axesModels[0];
  36114. var yAxisModel = axesModels[1];
  36115. var gridModel = xAxisModel.getCoordSysModel();
  36116. if (__DEV__) {
  36117. if (!gridModel) {
  36118. throw new Error(
  36119. 'Grid "' + retrieve(
  36120. xAxisModel.get('gridIndex'),
  36121. xAxisModel.get('gridId'),
  36122. 0
  36123. ) + '" not found'
  36124. );
  36125. }
  36126. if (xAxisModel.getCoordSysModel() !== yAxisModel.getCoordSysModel()) {
  36127. throw new Error('xAxis and yAxis must use the same grid');
  36128. }
  36129. }
  36130. var grid = gridModel.coordinateSystem;
  36131. seriesModel.coordinateSystem = grid.getCartesian(
  36132. xAxisModel.componentIndex, yAxisModel.componentIndex
  36133. );
  36134. });
  36135. return grids;
  36136. };
  36137. // For deciding which dimensions to use when creating list data
  36138. Grid.dimensions = Grid.prototype.dimensions = Cartesian2D.prototype.dimensions;
  36139. CoordinateSystemManager.register('cartesian2d', Grid);
  36140. /*
  36141. * Licensed to the Apache Software Foundation (ASF) under one
  36142. * or more contributor license agreements. See the NOTICE file
  36143. * distributed with this work for additional information
  36144. * regarding copyright ownership. The ASF licenses this file
  36145. * to you under the Apache License, Version 2.0 (the
  36146. * "License"); you may not use this file except in compliance
  36147. * with the License. You may obtain a copy of the License at
  36148. *
  36149. * http://www.apache.org/licenses/LICENSE-2.0
  36150. *
  36151. * Unless required by applicable law or agreed to in writing,
  36152. * software distributed under the License is distributed on an
  36153. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36154. * KIND, either express or implied. See the License for the
  36155. * specific language governing permissions and limitations
  36156. * under the License.
  36157. */
  36158. var PI$2 = Math.PI;
  36159. /**
  36160. * A final axis is translated and rotated from a "standard axis".
  36161. * So opt.position and opt.rotation is required.
  36162. *
  36163. * A standard axis is and axis from [0, 0] to [0, axisExtent[1]],
  36164. * for example: (0, 0) ------------> (0, 50)
  36165. *
  36166. * nameDirection or tickDirection or labelDirection is 1 means tick
  36167. * or label is below the standard axis, whereas is -1 means above
  36168. * the standard axis. labelOffset means offset between label and axis,
  36169. * which is useful when 'onZero', where axisLabel is in the grid and
  36170. * label in outside grid.
  36171. *
  36172. * Tips: like always,
  36173. * positive rotation represents anticlockwise, and negative rotation
  36174. * represents clockwise.
  36175. * The direction of position coordinate is the same as the direction
  36176. * of screen coordinate.
  36177. *
  36178. * Do not need to consider axis 'inverse', which is auto processed by
  36179. * axis extent.
  36180. *
  36181. * @param {module:zrender/container/Group} group
  36182. * @param {Object} axisModel
  36183. * @param {Object} opt Standard axis parameters.
  36184. * @param {Array.<number>} opt.position [x, y]
  36185. * @param {number} opt.rotation by radian
  36186. * @param {number} [opt.nameDirection=1] 1 or -1 Used when nameLocation is 'middle' or 'center'.
  36187. * @param {number} [opt.tickDirection=1] 1 or -1
  36188. * @param {number} [opt.labelDirection=1] 1 or -1
  36189. * @param {number} [opt.labelOffset=0] Usefull when onZero.
  36190. * @param {string} [opt.axisLabelShow] default get from axisModel.
  36191. * @param {string} [opt.axisName] default get from axisModel.
  36192. * @param {number} [opt.axisNameAvailableWidth]
  36193. * @param {number} [opt.labelRotate] by degree, default get from axisModel.
  36194. * @param {number} [opt.strokeContainThreshold] Default label interval when label
  36195. * @param {number} [opt.nameTruncateMaxWidth]
  36196. */
  36197. var AxisBuilder = function (axisModel, opt) {
  36198. /**
  36199. * @readOnly
  36200. */
  36201. this.opt = opt;
  36202. /**
  36203. * @readOnly
  36204. */
  36205. this.axisModel = axisModel;
  36206. // Default value
  36207. defaults(
  36208. opt,
  36209. {
  36210. labelOffset: 0,
  36211. nameDirection: 1,
  36212. tickDirection: 1,
  36213. labelDirection: 1,
  36214. silent: true
  36215. }
  36216. );
  36217. /**
  36218. * @readOnly
  36219. */
  36220. this.group = new Group();
  36221. // FIXME Not use a seperate text group?
  36222. var dumbGroup = new Group({
  36223. position: opt.position.slice(),
  36224. rotation: opt.rotation
  36225. });
  36226. // this.group.add(dumbGroup);
  36227. // this._dumbGroup = dumbGroup;
  36228. dumbGroup.updateTransform();
  36229. this._transform = dumbGroup.transform;
  36230. this._dumbGroup = dumbGroup;
  36231. };
  36232. AxisBuilder.prototype = {
  36233. constructor: AxisBuilder,
  36234. hasBuilder: function (name) {
  36235. return !!builders[name];
  36236. },
  36237. add: function (name) {
  36238. builders[name].call(this);
  36239. },
  36240. getGroup: function () {
  36241. return this.group;
  36242. }
  36243. };
  36244. var builders = {
  36245. /**
  36246. * @private
  36247. */
  36248. axisLine: function () {
  36249. var opt = this.opt;
  36250. var axisModel = this.axisModel;
  36251. if (!axisModel.get('axisLine.show')) {
  36252. return;
  36253. }
  36254. var extent = this.axisModel.axis.getExtent();
  36255. var matrix = this._transform;
  36256. var pt1 = [extent[0], 0];
  36257. var pt2 = [extent[1], 0];
  36258. if (matrix) {
  36259. applyTransform(pt1, pt1, matrix);
  36260. applyTransform(pt2, pt2, matrix);
  36261. }
  36262. var lineStyle = extend(
  36263. {
  36264. lineCap: 'round'
  36265. },
  36266. axisModel.getModel('axisLine.lineStyle').getLineStyle()
  36267. );
  36268. this.group.add(new Line({
  36269. // Id for animation
  36270. anid: 'line',
  36271. subPixelOptimize: true,
  36272. shape: {
  36273. x1: pt1[0],
  36274. y1: pt1[1],
  36275. x2: pt2[0],
  36276. y2: pt2[1]
  36277. },
  36278. style: lineStyle,
  36279. strokeContainThreshold: opt.strokeContainThreshold || 5,
  36280. silent: true,
  36281. z2: 1
  36282. }));
  36283. var arrows = axisModel.get('axisLine.symbol');
  36284. var arrowSize = axisModel.get('axisLine.symbolSize');
  36285. var arrowOffset = axisModel.get('axisLine.symbolOffset') || 0;
  36286. if (typeof arrowOffset === 'number') {
  36287. arrowOffset = [arrowOffset, arrowOffset];
  36288. }
  36289. if (arrows != null) {
  36290. if (typeof arrows === 'string') {
  36291. // Use the same arrow for start and end point
  36292. arrows = [arrows, arrows];
  36293. }
  36294. if (typeof arrowSize === 'string'
  36295. || typeof arrowSize === 'number'
  36296. ) {
  36297. // Use the same size for width and height
  36298. arrowSize = [arrowSize, arrowSize];
  36299. }
  36300. var symbolWidth = arrowSize[0];
  36301. var symbolHeight = arrowSize[1];
  36302. each$1([{
  36303. rotate: opt.rotation + Math.PI / 2,
  36304. offset: arrowOffset[0],
  36305. r: 0
  36306. }, {
  36307. rotate: opt.rotation - Math.PI / 2,
  36308. offset: arrowOffset[1],
  36309. r: Math.sqrt((pt1[0] - pt2[0]) * (pt1[0] - pt2[0])
  36310. + (pt1[1] - pt2[1]) * (pt1[1] - pt2[1]))
  36311. }], function (point, index) {
  36312. if (arrows[index] !== 'none' && arrows[index] != null) {
  36313. var symbol = createSymbol(
  36314. arrows[index],
  36315. -symbolWidth / 2,
  36316. -symbolHeight / 2,
  36317. symbolWidth,
  36318. symbolHeight,
  36319. lineStyle.stroke,
  36320. true
  36321. );
  36322. // Calculate arrow position with offset
  36323. var r = point.r + point.offset;
  36324. var pos = [
  36325. pt1[0] + r * Math.cos(opt.rotation),
  36326. pt1[1] - r * Math.sin(opt.rotation)
  36327. ];
  36328. symbol.attr({
  36329. rotation: point.rotate,
  36330. position: pos,
  36331. silent: true,
  36332. z2: 11
  36333. });
  36334. this.group.add(symbol);
  36335. }
  36336. }, this);
  36337. }
  36338. },
  36339. /**
  36340. * @private
  36341. */
  36342. axisTickLabel: function () {
  36343. var axisModel = this.axisModel;
  36344. var opt = this.opt;
  36345. var ticksEls = buildAxisMajorTicks(this, axisModel, opt);
  36346. var labelEls = buildAxisLabel(this, axisModel, opt);
  36347. fixMinMaxLabelShow(axisModel, labelEls, ticksEls);
  36348. buildAxisMinorTicks(this, axisModel, opt);
  36349. },
  36350. /**
  36351. * @private
  36352. */
  36353. axisName: function () {
  36354. var opt = this.opt;
  36355. var axisModel = this.axisModel;
  36356. var name = retrieve(opt.axisName, axisModel.get('name'));
  36357. if (!name) {
  36358. return;
  36359. }
  36360. var nameLocation = axisModel.get('nameLocation');
  36361. var nameDirection = opt.nameDirection;
  36362. var textStyleModel = axisModel.getModel('nameTextStyle');
  36363. var gap = axisModel.get('nameGap') || 0;
  36364. var extent = this.axisModel.axis.getExtent();
  36365. var gapSignal = extent[0] > extent[1] ? -1 : 1;
  36366. var pos = [
  36367. nameLocation === 'start'
  36368. ? extent[0] - gapSignal * gap
  36369. : nameLocation === 'end'
  36370. ? extent[1] + gapSignal * gap
  36371. : (extent[0] + extent[1]) / 2, // 'middle'
  36372. // Reuse labelOffset.
  36373. isNameLocationCenter(nameLocation) ? opt.labelOffset + nameDirection * gap : 0
  36374. ];
  36375. var labelLayout;
  36376. var nameRotation = axisModel.get('nameRotate');
  36377. if (nameRotation != null) {
  36378. nameRotation = nameRotation * PI$2 / 180; // To radian.
  36379. }
  36380. var axisNameAvailableWidth;
  36381. if (isNameLocationCenter(nameLocation)) {
  36382. labelLayout = innerTextLayout(
  36383. opt.rotation,
  36384. nameRotation != null ? nameRotation : opt.rotation, // Adapt to axis.
  36385. nameDirection
  36386. );
  36387. }
  36388. else {
  36389. labelLayout = endTextLayout(
  36390. opt, nameLocation, nameRotation || 0, extent
  36391. );
  36392. axisNameAvailableWidth = opt.axisNameAvailableWidth;
  36393. if (axisNameAvailableWidth != null) {
  36394. axisNameAvailableWidth = Math.abs(
  36395. axisNameAvailableWidth / Math.sin(labelLayout.rotation)
  36396. );
  36397. !isFinite(axisNameAvailableWidth) && (axisNameAvailableWidth = null);
  36398. }
  36399. }
  36400. var textFont = textStyleModel.getFont();
  36401. var truncateOpt = axisModel.get('nameTruncate', true) || {};
  36402. var ellipsis = truncateOpt.ellipsis;
  36403. var maxWidth = retrieve(
  36404. opt.nameTruncateMaxWidth, truncateOpt.maxWidth, axisNameAvailableWidth
  36405. );
  36406. // FIXME
  36407. // truncate rich text? (consider performance)
  36408. var truncatedText = (ellipsis != null && maxWidth != null)
  36409. ? truncateText$1(
  36410. name, maxWidth, textFont, ellipsis,
  36411. {minChar: 2, placeholder: truncateOpt.placeholder}
  36412. )
  36413. : name;
  36414. var tooltipOpt = axisModel.get('tooltip', true);
  36415. var mainType = axisModel.mainType;
  36416. var formatterParams = {
  36417. componentType: mainType,
  36418. name: name,
  36419. $vars: ['name']
  36420. };
  36421. formatterParams[mainType + 'Index'] = axisModel.componentIndex;
  36422. var textEl = new Text({
  36423. // Id for animation
  36424. anid: 'name',
  36425. __fullText: name,
  36426. __truncatedText: truncatedText,
  36427. position: pos,
  36428. rotation: labelLayout.rotation,
  36429. silent: isLabelSilent(axisModel),
  36430. z2: 1,
  36431. tooltip: (tooltipOpt && tooltipOpt.show)
  36432. ? extend({
  36433. content: name,
  36434. formatter: function () {
  36435. return name;
  36436. },
  36437. formatterParams: formatterParams
  36438. }, tooltipOpt)
  36439. : null
  36440. });
  36441. setTextStyle(textEl.style, textStyleModel, {
  36442. text: truncatedText,
  36443. textFont: textFont,
  36444. textFill: textStyleModel.getTextColor()
  36445. || axisModel.get('axisLine.lineStyle.color'),
  36446. textAlign: textStyleModel.get('align')
  36447. || labelLayout.textAlign,
  36448. textVerticalAlign: textStyleModel.get('verticalAlign')
  36449. || labelLayout.textVerticalAlign
  36450. });
  36451. if (axisModel.get('triggerEvent')) {
  36452. textEl.eventData = makeAxisEventDataBase(axisModel);
  36453. textEl.eventData.targetType = 'axisName';
  36454. textEl.eventData.name = name;
  36455. }
  36456. // FIXME
  36457. this._dumbGroup.add(textEl);
  36458. textEl.updateTransform();
  36459. this.group.add(textEl);
  36460. textEl.decomposeTransform();
  36461. }
  36462. };
  36463. var makeAxisEventDataBase = AxisBuilder.makeAxisEventDataBase = function (axisModel) {
  36464. var eventData = {
  36465. componentType: axisModel.mainType,
  36466. componentIndex: axisModel.componentIndex
  36467. };
  36468. eventData[axisModel.mainType + 'Index'] = axisModel.componentIndex;
  36469. return eventData;
  36470. };
  36471. /**
  36472. * @public
  36473. * @static
  36474. * @param {Object} opt
  36475. * @param {number} axisRotation in radian
  36476. * @param {number} textRotation in radian
  36477. * @param {number} direction
  36478. * @return {Object} {
  36479. * rotation, // according to axis
  36480. * textAlign,
  36481. * textVerticalAlign
  36482. * }
  36483. */
  36484. var innerTextLayout = AxisBuilder.innerTextLayout = function (axisRotation, textRotation, direction) {
  36485. var rotationDiff = remRadian(textRotation - axisRotation);
  36486. var textAlign;
  36487. var textVerticalAlign;
  36488. if (isRadianAroundZero(rotationDiff)) { // Label is parallel with axis line.
  36489. textVerticalAlign = direction > 0 ? 'top' : 'bottom';
  36490. textAlign = 'center';
  36491. }
  36492. else if (isRadianAroundZero(rotationDiff - PI$2)) { // Label is inverse parallel with axis line.
  36493. textVerticalAlign = direction > 0 ? 'bottom' : 'top';
  36494. textAlign = 'center';
  36495. }
  36496. else {
  36497. textVerticalAlign = 'middle';
  36498. if (rotationDiff > 0 && rotationDiff < PI$2) {
  36499. textAlign = direction > 0 ? 'right' : 'left';
  36500. }
  36501. else {
  36502. textAlign = direction > 0 ? 'left' : 'right';
  36503. }
  36504. }
  36505. return {
  36506. rotation: rotationDiff,
  36507. textAlign: textAlign,
  36508. textVerticalAlign: textVerticalAlign
  36509. };
  36510. };
  36511. function endTextLayout(opt, textPosition, textRotate, extent) {
  36512. var rotationDiff = remRadian(textRotate - opt.rotation);
  36513. var textAlign;
  36514. var textVerticalAlign;
  36515. var inverse = extent[0] > extent[1];
  36516. var onLeft = (textPosition === 'start' && !inverse)
  36517. || (textPosition !== 'start' && inverse);
  36518. if (isRadianAroundZero(rotationDiff - PI$2 / 2)) {
  36519. textVerticalAlign = onLeft ? 'bottom' : 'top';
  36520. textAlign = 'center';
  36521. }
  36522. else if (isRadianAroundZero(rotationDiff - PI$2 * 1.5)) {
  36523. textVerticalAlign = onLeft ? 'top' : 'bottom';
  36524. textAlign = 'center';
  36525. }
  36526. else {
  36527. textVerticalAlign = 'middle';
  36528. if (rotationDiff < PI$2 * 1.5 && rotationDiff > PI$2 / 2) {
  36529. textAlign = onLeft ? 'left' : 'right';
  36530. }
  36531. else {
  36532. textAlign = onLeft ? 'right' : 'left';
  36533. }
  36534. }
  36535. return {
  36536. rotation: rotationDiff,
  36537. textAlign: textAlign,
  36538. textVerticalAlign: textVerticalAlign
  36539. };
  36540. }
  36541. var isLabelSilent = AxisBuilder.isLabelSilent = function (axisModel) {
  36542. var tooltipOpt = axisModel.get('tooltip');
  36543. return axisModel.get('silent')
  36544. // Consider mouse cursor, add these restrictions.
  36545. || !(
  36546. axisModel.get('triggerEvent') || (tooltipOpt && tooltipOpt.show)
  36547. );
  36548. };
  36549. function fixMinMaxLabelShow(axisModel, labelEls, tickEls) {
  36550. if (shouldShowAllLabels(axisModel.axis)) {
  36551. return;
  36552. }
  36553. // If min or max are user set, we need to check
  36554. // If the tick on min(max) are overlap on their neighbour tick
  36555. // If they are overlapped, we need to hide the min(max) tick label
  36556. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  36557. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  36558. // FIXME
  36559. // Have not consider onBand yet, where tick els is more than label els.
  36560. labelEls = labelEls || [];
  36561. tickEls = tickEls || [];
  36562. var firstLabel = labelEls[0];
  36563. var nextLabel = labelEls[1];
  36564. var lastLabel = labelEls[labelEls.length - 1];
  36565. var prevLabel = labelEls[labelEls.length - 2];
  36566. var firstTick = tickEls[0];
  36567. var nextTick = tickEls[1];
  36568. var lastTick = tickEls[tickEls.length - 1];
  36569. var prevTick = tickEls[tickEls.length - 2];
  36570. if (showMinLabel === false) {
  36571. ignoreEl(firstLabel);
  36572. ignoreEl(firstTick);
  36573. }
  36574. else if (isTwoLabelOverlapped(firstLabel, nextLabel)) {
  36575. if (showMinLabel) {
  36576. ignoreEl(nextLabel);
  36577. ignoreEl(nextTick);
  36578. }
  36579. else {
  36580. ignoreEl(firstLabel);
  36581. ignoreEl(firstTick);
  36582. }
  36583. }
  36584. if (showMaxLabel === false) {
  36585. ignoreEl(lastLabel);
  36586. ignoreEl(lastTick);
  36587. }
  36588. else if (isTwoLabelOverlapped(prevLabel, lastLabel)) {
  36589. if (showMaxLabel) {
  36590. ignoreEl(prevLabel);
  36591. ignoreEl(prevTick);
  36592. }
  36593. else {
  36594. ignoreEl(lastLabel);
  36595. ignoreEl(lastTick);
  36596. }
  36597. }
  36598. }
  36599. function ignoreEl(el) {
  36600. el && (el.ignore = true);
  36601. }
  36602. function isTwoLabelOverlapped(current, next, labelLayout) {
  36603. // current and next has the same rotation.
  36604. var firstRect = current && current.getBoundingRect().clone();
  36605. var nextRect = next && next.getBoundingRect().clone();
  36606. if (!firstRect || !nextRect) {
  36607. return;
  36608. }
  36609. // When checking intersect of two rotated labels, we use mRotationBack
  36610. // to avoid that boundingRect is enlarge when using `boundingRect.applyTransform`.
  36611. var mRotationBack = identity([]);
  36612. rotate(mRotationBack, mRotationBack, -current.rotation);
  36613. firstRect.applyTransform(mul$1([], mRotationBack, current.getLocalTransform()));
  36614. nextRect.applyTransform(mul$1([], mRotationBack, next.getLocalTransform()));
  36615. return firstRect.intersect(nextRect);
  36616. }
  36617. function isNameLocationCenter(nameLocation) {
  36618. return nameLocation === 'middle' || nameLocation === 'center';
  36619. }
  36620. function createTicks(ticksCoords, tickTransform, tickEndCoord, tickLineStyle, aniid) {
  36621. var tickEls = [];
  36622. var pt1 = [];
  36623. var pt2 = [];
  36624. for (var i = 0; i < ticksCoords.length; i++) {
  36625. var tickCoord = ticksCoords[i].coord;
  36626. pt1[0] = tickCoord;
  36627. pt1[1] = 0;
  36628. pt2[0] = tickCoord;
  36629. pt2[1] = tickEndCoord;
  36630. if (tickTransform) {
  36631. applyTransform(pt1, pt1, tickTransform);
  36632. applyTransform(pt2, pt2, tickTransform);
  36633. }
  36634. // Tick line, Not use group transform to have better line draw
  36635. var tickEl = new Line({
  36636. // Id for animation
  36637. anid: aniid + '_' + ticksCoords[i].tickValue,
  36638. subPixelOptimize: true,
  36639. shape: {
  36640. x1: pt1[0],
  36641. y1: pt1[1],
  36642. x2: pt2[0],
  36643. y2: pt2[1]
  36644. },
  36645. style: tickLineStyle,
  36646. z2: 2,
  36647. silent: true
  36648. });
  36649. tickEls.push(tickEl);
  36650. }
  36651. return tickEls;
  36652. }
  36653. function buildAxisMajorTicks(axisBuilder, axisModel, opt) {
  36654. var axis = axisModel.axis;
  36655. var tickModel = axisModel.getModel('axisTick');
  36656. if (!tickModel.get('show') || axis.scale.isBlank()) {
  36657. return;
  36658. }
  36659. var lineStyleModel = tickModel.getModel('lineStyle');
  36660. var tickEndCoord = opt.tickDirection * tickModel.get('length');
  36661. var ticksCoords = axis.getTicksCoords();
  36662. var ticksEls = createTicks(ticksCoords, axisBuilder._transform, tickEndCoord, defaults(
  36663. lineStyleModel.getLineStyle(),
  36664. {
  36665. stroke: axisModel.get('axisLine.lineStyle.color')
  36666. }
  36667. ), 'ticks');
  36668. for (var i = 0; i < ticksEls.length; i++) {
  36669. axisBuilder.group.add(ticksEls[i]);
  36670. }
  36671. return ticksEls;
  36672. }
  36673. function buildAxisMinorTicks(axisBuilder, axisModel, opt) {
  36674. var axis = axisModel.axis;
  36675. var minorTickModel = axisModel.getModel('minorTick');
  36676. if (!minorTickModel.get('show') || axis.scale.isBlank()) {
  36677. return;
  36678. }
  36679. var minorTicksCoords = axis.getMinorTicksCoords();
  36680. if (!minorTicksCoords.length) {
  36681. return;
  36682. }
  36683. var lineStyleModel = minorTickModel.getModel('lineStyle');
  36684. var tickEndCoord = opt.tickDirection * minorTickModel.get('length');
  36685. var minorTickLineStyle = defaults(
  36686. lineStyleModel.getLineStyle(),
  36687. defaults(
  36688. axisModel.getModel('axisTick').getLineStyle(),
  36689. {
  36690. stroke: axisModel.get('axisLine.lineStyle.color')
  36691. }
  36692. )
  36693. );
  36694. for (var i = 0; i < minorTicksCoords.length; i++) {
  36695. var minorTicksEls = createTicks(
  36696. minorTicksCoords[i], axisBuilder._transform, tickEndCoord, minorTickLineStyle, 'minorticks_' + i
  36697. );
  36698. for (var k = 0; k < minorTicksEls.length; k++) {
  36699. axisBuilder.group.add(minorTicksEls[k]);
  36700. }
  36701. }
  36702. }
  36703. function buildAxisLabel(axisBuilder, axisModel, opt) {
  36704. var axis = axisModel.axis;
  36705. var show = retrieve(opt.axisLabelShow, axisModel.get('axisLabel.show'));
  36706. if (!show || axis.scale.isBlank()) {
  36707. return;
  36708. }
  36709. var labelModel = axisModel.getModel('axisLabel');
  36710. var labelMargin = labelModel.get('margin');
  36711. var labels = axis.getViewLabels();
  36712. // Special label rotate.
  36713. var labelRotation = (
  36714. retrieve(opt.labelRotate, labelModel.get('rotate')) || 0
  36715. ) * PI$2 / 180;
  36716. var labelLayout = innerTextLayout(opt.rotation, labelRotation, opt.labelDirection);
  36717. var rawCategoryData = axisModel.getCategories && axisModel.getCategories(true);
  36718. var labelEls = [];
  36719. var silent = isLabelSilent(axisModel);
  36720. var triggerEvent = axisModel.get('triggerEvent');
  36721. each$1(labels, function (labelItem, index) {
  36722. var tickValue = labelItem.tickValue;
  36723. var formattedLabel = labelItem.formattedLabel;
  36724. var rawLabel = labelItem.rawLabel;
  36725. var itemLabelModel = labelModel;
  36726. if (rawCategoryData && rawCategoryData[tickValue] && rawCategoryData[tickValue].textStyle) {
  36727. itemLabelModel = new Model(
  36728. rawCategoryData[tickValue].textStyle, labelModel, axisModel.ecModel
  36729. );
  36730. }
  36731. var textColor = itemLabelModel.getTextColor()
  36732. || axisModel.get('axisLine.lineStyle.color');
  36733. var tickCoord = axis.dataToCoord(tickValue);
  36734. var pos = [
  36735. tickCoord,
  36736. opt.labelOffset + opt.labelDirection * labelMargin
  36737. ];
  36738. var textEl = new Text({
  36739. // Id for animation
  36740. anid: 'label_' + tickValue,
  36741. position: pos,
  36742. rotation: labelLayout.rotation,
  36743. silent: silent,
  36744. z2: 10
  36745. });
  36746. setTextStyle(textEl.style, itemLabelModel, {
  36747. text: formattedLabel,
  36748. textAlign: itemLabelModel.getShallow('align', true)
  36749. || labelLayout.textAlign,
  36750. textVerticalAlign: itemLabelModel.getShallow('verticalAlign', true)
  36751. || itemLabelModel.getShallow('baseline', true)
  36752. || labelLayout.textVerticalAlign,
  36753. textFill: typeof textColor === 'function'
  36754. ? textColor(
  36755. // (1) In category axis with data zoom, tick is not the original
  36756. // index of axis.data. So tick should not be exposed to user
  36757. // in category axis.
  36758. // (2) Compatible with previous version, which always use formatted label as
  36759. // input. But in interval scale the formatted label is like '223,445', which
  36760. // maked user repalce ','. So we modify it to return original val but remain
  36761. // it as 'string' to avoid error in replacing.
  36762. axis.type === 'category'
  36763. ? rawLabel
  36764. : axis.type === 'value'
  36765. ? tickValue + ''
  36766. : tickValue,
  36767. index
  36768. )
  36769. : textColor
  36770. });
  36771. // Pack data for mouse event
  36772. if (triggerEvent) {
  36773. textEl.eventData = makeAxisEventDataBase(axisModel);
  36774. textEl.eventData.targetType = 'axisLabel';
  36775. textEl.eventData.value = rawLabel;
  36776. }
  36777. // FIXME
  36778. axisBuilder._dumbGroup.add(textEl);
  36779. textEl.updateTransform();
  36780. labelEls.push(textEl);
  36781. axisBuilder.group.add(textEl);
  36782. textEl.decomposeTransform();
  36783. });
  36784. return labelEls;
  36785. }
  36786. /*
  36787. * Licensed to the Apache Software Foundation (ASF) under one
  36788. * or more contributor license agreements. See the NOTICE file
  36789. * distributed with this work for additional information
  36790. * regarding copyright ownership. The ASF licenses this file
  36791. * to you under the Apache License, Version 2.0 (the
  36792. * "License"); you may not use this file except in compliance
  36793. * with the License. You may obtain a copy of the License at
  36794. *
  36795. * http://www.apache.org/licenses/LICENSE-2.0
  36796. *
  36797. * Unless required by applicable law or agreed to in writing,
  36798. * software distributed under the License is distributed on an
  36799. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36800. * KIND, either express or implied. See the License for the
  36801. * specific language governing permissions and limitations
  36802. * under the License.
  36803. */
  36804. var each$6 = each$1;
  36805. var curry$1 = curry;
  36806. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  36807. // allAxesInfo should be updated when setOption performed.
  36808. function collect(ecModel, api) {
  36809. var result = {
  36810. /**
  36811. * key: makeKey(axis.model)
  36812. * value: {
  36813. * axis,
  36814. * coordSys,
  36815. * axisPointerModel,
  36816. * triggerTooltip,
  36817. * involveSeries,
  36818. * snap,
  36819. * seriesModels,
  36820. * seriesDataCount
  36821. * }
  36822. */
  36823. axesInfo: {},
  36824. seriesInvolved: false,
  36825. /**
  36826. * key: makeKey(coordSys.model)
  36827. * value: Object: key makeKey(axis.model), value: axisInfo
  36828. */
  36829. coordSysAxesInfo: {},
  36830. coordSysMap: {}
  36831. };
  36832. collectAxesInfo(result, ecModel, api);
  36833. // Check seriesInvolved for performance, in case too many series in some chart.
  36834. result.seriesInvolved && collectSeriesInfo(result, ecModel);
  36835. return result;
  36836. }
  36837. function collectAxesInfo(result, ecModel, api) {
  36838. var globalTooltipModel = ecModel.getComponent('tooltip');
  36839. var globalAxisPointerModel = ecModel.getComponent('axisPointer');
  36840. // links can only be set on global.
  36841. var linksOption = globalAxisPointerModel.get('link', true) || [];
  36842. var linkGroups = [];
  36843. // Collect axes info.
  36844. each$6(api.getCoordinateSystems(), function (coordSys) {
  36845. // Some coordinate system do not support axes, like geo.
  36846. if (!coordSys.axisPointerEnabled) {
  36847. return;
  36848. }
  36849. var coordSysKey = makeKey(coordSys.model);
  36850. var axesInfoInCoordSys = result.coordSysAxesInfo[coordSysKey] = {};
  36851. result.coordSysMap[coordSysKey] = coordSys;
  36852. // Set tooltip (like 'cross') is a convienent way to show axisPointer
  36853. // for user. So we enable seting tooltip on coordSys model.
  36854. var coordSysModel = coordSys.model;
  36855. var baseTooltipModel = coordSysModel.getModel('tooltip', globalTooltipModel);
  36856. each$6(coordSys.getAxes(), curry$1(saveTooltipAxisInfo, false, null));
  36857. // If axis tooltip used, choose tooltip axis for each coordSys.
  36858. // Notice this case: coordSys is `grid` but not `cartesian2D` here.
  36859. if (coordSys.getTooltipAxes
  36860. && globalTooltipModel
  36861. // If tooltip.showContent is set as false, tooltip will not
  36862. // show but axisPointer will show as normal.
  36863. && baseTooltipModel.get('show')
  36864. ) {
  36865. // Compatible with previous logic. But series.tooltip.trigger: 'axis'
  36866. // or series.data[n].tooltip.trigger: 'axis' are not support any more.
  36867. var triggerAxis = baseTooltipModel.get('trigger') === 'axis';
  36868. var cross = baseTooltipModel.get('axisPointer.type') === 'cross';
  36869. var tooltipAxes = coordSys.getTooltipAxes(baseTooltipModel.get('axisPointer.axis'));
  36870. if (triggerAxis || cross) {
  36871. each$6(tooltipAxes.baseAxes, curry$1(
  36872. saveTooltipAxisInfo, cross ? 'cross' : true, triggerAxis
  36873. ));
  36874. }
  36875. if (cross) {
  36876. each$6(tooltipAxes.otherAxes, curry$1(saveTooltipAxisInfo, 'cross', false));
  36877. }
  36878. }
  36879. // fromTooltip: true | false | 'cross'
  36880. // triggerTooltip: true | false | null
  36881. function saveTooltipAxisInfo(fromTooltip, triggerTooltip, axis) {
  36882. var axisPointerModel = axis.model.getModel('axisPointer', globalAxisPointerModel);
  36883. var axisPointerShow = axisPointerModel.get('show');
  36884. if (!axisPointerShow || (
  36885. axisPointerShow === 'auto'
  36886. && !fromTooltip
  36887. && !isHandleTrigger(axisPointerModel)
  36888. )) {
  36889. return;
  36890. }
  36891. if (triggerTooltip == null) {
  36892. triggerTooltip = axisPointerModel.get('triggerTooltip');
  36893. }
  36894. axisPointerModel = fromTooltip
  36895. ? makeAxisPointerModel(
  36896. axis, baseTooltipModel, globalAxisPointerModel, ecModel,
  36897. fromTooltip, triggerTooltip
  36898. )
  36899. : axisPointerModel;
  36900. var snap = axisPointerModel.get('snap');
  36901. var key = makeKey(axis.model);
  36902. var involveSeries = triggerTooltip || snap || axis.type === 'category';
  36903. // If result.axesInfo[key] exist, override it (tooltip has higher priority).
  36904. var axisInfo = result.axesInfo[key] = {
  36905. key: key,
  36906. axis: axis,
  36907. coordSys: coordSys,
  36908. axisPointerModel: axisPointerModel,
  36909. triggerTooltip: triggerTooltip,
  36910. involveSeries: involveSeries,
  36911. snap: snap,
  36912. useHandle: isHandleTrigger(axisPointerModel),
  36913. seriesModels: []
  36914. };
  36915. axesInfoInCoordSys[key] = axisInfo;
  36916. result.seriesInvolved |= involveSeries;
  36917. var groupIndex = getLinkGroupIndex(linksOption, axis);
  36918. if (groupIndex != null) {
  36919. var linkGroup = linkGroups[groupIndex] || (linkGroups[groupIndex] = {axesInfo: {}});
  36920. linkGroup.axesInfo[key] = axisInfo;
  36921. linkGroup.mapper = linksOption[groupIndex].mapper;
  36922. axisInfo.linkGroup = linkGroup;
  36923. }
  36924. }
  36925. });
  36926. }
  36927. function makeAxisPointerModel(
  36928. axis, baseTooltipModel, globalAxisPointerModel, ecModel, fromTooltip, triggerTooltip
  36929. ) {
  36930. var tooltipAxisPointerModel = baseTooltipModel.getModel('axisPointer');
  36931. var volatileOption = {};
  36932. each$6(
  36933. [
  36934. 'type', 'snap', 'lineStyle', 'shadowStyle', 'label',
  36935. 'animation', 'animationDurationUpdate', 'animationEasingUpdate', 'z'
  36936. ],
  36937. function (field) {
  36938. volatileOption[field] = clone(tooltipAxisPointerModel.get(field));
  36939. }
  36940. );
  36941. // category axis do not auto snap, otherwise some tick that do not
  36942. // has value can not be hovered. value/time/log axis default snap if
  36943. // triggered from tooltip and trigger tooltip.
  36944. volatileOption.snap = axis.type !== 'category' && !!triggerTooltip;
  36945. // Compatibel with previous behavior, tooltip axis do not show label by default.
  36946. // Only these properties can be overrided from tooltip to axisPointer.
  36947. if (tooltipAxisPointerModel.get('type') === 'cross') {
  36948. volatileOption.type = 'line';
  36949. }
  36950. var labelOption = volatileOption.label || (volatileOption.label = {});
  36951. // Follow the convention, do not show label when triggered by tooltip by default.
  36952. labelOption.show == null && (labelOption.show = false);
  36953. if (fromTooltip === 'cross') {
  36954. // When 'cross', both axes show labels.
  36955. var tooltipAxisPointerLabelShow = tooltipAxisPointerModel.get('label.show');
  36956. labelOption.show = tooltipAxisPointerLabelShow != null ? tooltipAxisPointerLabelShow : true;
  36957. // If triggerTooltip, this is a base axis, which should better not use cross style
  36958. // (cross style is dashed by default)
  36959. if (!triggerTooltip) {
  36960. var crossStyle = volatileOption.lineStyle = tooltipAxisPointerModel.get('crossStyle');
  36961. crossStyle && defaults(labelOption, crossStyle.textStyle);
  36962. }
  36963. }
  36964. return axis.model.getModel(
  36965. 'axisPointer',
  36966. new Model(volatileOption, globalAxisPointerModel, ecModel)
  36967. );
  36968. }
  36969. function collectSeriesInfo(result, ecModel) {
  36970. // Prepare data for axis trigger
  36971. ecModel.eachSeries(function (seriesModel) {
  36972. // Notice this case: this coordSys is `cartesian2D` but not `grid`.
  36973. var coordSys = seriesModel.coordinateSystem;
  36974. var seriesTooltipTrigger = seriesModel.get('tooltip.trigger', true);
  36975. var seriesTooltipShow = seriesModel.get('tooltip.show', true);
  36976. if (!coordSys
  36977. || seriesTooltipTrigger === 'none'
  36978. || seriesTooltipTrigger === false
  36979. || seriesTooltipTrigger === 'item'
  36980. || seriesTooltipShow === false
  36981. || seriesModel.get('axisPointer.show', true) === false
  36982. ) {
  36983. return;
  36984. }
  36985. each$6(result.coordSysAxesInfo[makeKey(coordSys.model)], function (axisInfo) {
  36986. var axis = axisInfo.axis;
  36987. if (coordSys.getAxis(axis.dim) === axis) {
  36988. axisInfo.seriesModels.push(seriesModel);
  36989. axisInfo.seriesDataCount == null && (axisInfo.seriesDataCount = 0);
  36990. axisInfo.seriesDataCount += seriesModel.getData().count();
  36991. }
  36992. });
  36993. }, this);
  36994. }
  36995. /**
  36996. * For example:
  36997. * {
  36998. * axisPointer: {
  36999. * links: [{
  37000. * xAxisIndex: [2, 4],
  37001. * yAxisIndex: 'all'
  37002. * }, {
  37003. * xAxisId: ['a5', 'a7'],
  37004. * xAxisName: 'xxx'
  37005. * }]
  37006. * }
  37007. * }
  37008. */
  37009. function getLinkGroupIndex(linksOption, axis) {
  37010. var axisModel = axis.model;
  37011. var dim = axis.dim;
  37012. for (var i = 0; i < linksOption.length; i++) {
  37013. var linkOption = linksOption[i] || {};
  37014. if (checkPropInLink(linkOption[dim + 'AxisId'], axisModel.id)
  37015. || checkPropInLink(linkOption[dim + 'AxisIndex'], axisModel.componentIndex)
  37016. || checkPropInLink(linkOption[dim + 'AxisName'], axisModel.name)
  37017. ) {
  37018. return i;
  37019. }
  37020. }
  37021. }
  37022. function checkPropInLink(linkPropValue, axisPropValue) {
  37023. return linkPropValue === 'all'
  37024. || (isArray(linkPropValue) && indexOf(linkPropValue, axisPropValue) >= 0)
  37025. || linkPropValue === axisPropValue;
  37026. }
  37027. function fixValue(axisModel) {
  37028. var axisInfo = getAxisInfo(axisModel);
  37029. if (!axisInfo) {
  37030. return;
  37031. }
  37032. var axisPointerModel = axisInfo.axisPointerModel;
  37033. var scale = axisInfo.axis.scale;
  37034. var option = axisPointerModel.option;
  37035. var status = axisPointerModel.get('status');
  37036. var value = axisPointerModel.get('value');
  37037. // Parse init value for category and time axis.
  37038. if (value != null) {
  37039. value = scale.parse(value);
  37040. }
  37041. var useHandle = isHandleTrigger(axisPointerModel);
  37042. // If `handle` used, `axisPointer` will always be displayed, so value
  37043. // and status should be initialized.
  37044. if (status == null) {
  37045. option.status = useHandle ? 'show' : 'hide';
  37046. }
  37047. var extent = scale.getExtent().slice();
  37048. extent[0] > extent[1] && extent.reverse();
  37049. if (// Pick a value on axis when initializing.
  37050. value == null
  37051. // If both `handle` and `dataZoom` are used, value may be out of axis extent,
  37052. // where we should re-pick a value to keep `handle` displaying normally.
  37053. || value > extent[1]
  37054. ) {
  37055. // Make handle displayed on the end of the axis when init, which looks better.
  37056. value = extent[1];
  37057. }
  37058. if (value < extent[0]) {
  37059. value = extent[0];
  37060. }
  37061. option.value = value;
  37062. if (useHandle) {
  37063. option.status = axisInfo.axis.scale.isBlank() ? 'hide' : 'show';
  37064. }
  37065. }
  37066. function getAxisInfo(axisModel) {
  37067. var coordSysAxesInfo = (axisModel.ecModel.getComponent('axisPointer') || {}).coordSysAxesInfo;
  37068. return coordSysAxesInfo && coordSysAxesInfo.axesInfo[makeKey(axisModel)];
  37069. }
  37070. function getAxisPointerModel(axisModel) {
  37071. var axisInfo = getAxisInfo(axisModel);
  37072. return axisInfo && axisInfo.axisPointerModel;
  37073. }
  37074. function isHandleTrigger(axisPointerModel) {
  37075. return !!axisPointerModel.get('handle.show');
  37076. }
  37077. /**
  37078. * @param {module:echarts/model/Model} model
  37079. * @return {string} unique key
  37080. */
  37081. function makeKey(model) {
  37082. return model.type + '||' + model.id;
  37083. }
  37084. /*
  37085. * Licensed to the Apache Software Foundation (ASF) under one
  37086. * or more contributor license agreements. See the NOTICE file
  37087. * distributed with this work for additional information
  37088. * regarding copyright ownership. The ASF licenses this file
  37089. * to you under the Apache License, Version 2.0 (the
  37090. * "License"); you may not use this file except in compliance
  37091. * with the License. You may obtain a copy of the License at
  37092. *
  37093. * http://www.apache.org/licenses/LICENSE-2.0
  37094. *
  37095. * Unless required by applicable law or agreed to in writing,
  37096. * software distributed under the License is distributed on an
  37097. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37098. * KIND, either express or implied. See the License for the
  37099. * specific language governing permissions and limitations
  37100. * under the License.
  37101. */
  37102. /**
  37103. * Base class of AxisView.
  37104. */
  37105. var AxisView = extendComponentView({
  37106. type: 'axis',
  37107. /**
  37108. * @private
  37109. */
  37110. _axisPointer: null,
  37111. /**
  37112. * @protected
  37113. * @type {string}
  37114. */
  37115. axisPointerClass: null,
  37116. /**
  37117. * @override
  37118. */
  37119. render: function (axisModel, ecModel, api, payload) {
  37120. // FIXME
  37121. // This process should proformed after coordinate systems updated
  37122. // (axis scale updated), and should be performed each time update.
  37123. // So put it here temporarily, although it is not appropriate to
  37124. // put a model-writing procedure in `view`.
  37125. this.axisPointerClass && fixValue(axisModel);
  37126. AxisView.superApply(this, 'render', arguments);
  37127. updateAxisPointer(this, axisModel, ecModel, api, payload, true);
  37128. },
  37129. /**
  37130. * Action handler.
  37131. * @public
  37132. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  37133. * @param {module:echarts/model/Global} ecModel
  37134. * @param {module:echarts/ExtensionAPI} api
  37135. * @param {Object} payload
  37136. */
  37137. updateAxisPointer: function (axisModel, ecModel, api, payload, force) {
  37138. updateAxisPointer(this, axisModel, ecModel, api, payload, false);
  37139. },
  37140. /**
  37141. * @override
  37142. */
  37143. remove: function (ecModel, api) {
  37144. var axisPointer = this._axisPointer;
  37145. axisPointer && axisPointer.remove(api);
  37146. AxisView.superApply(this, 'remove', arguments);
  37147. },
  37148. /**
  37149. * @override
  37150. */
  37151. dispose: function (ecModel, api) {
  37152. disposeAxisPointer(this, api);
  37153. AxisView.superApply(this, 'dispose', arguments);
  37154. }
  37155. });
  37156. function updateAxisPointer(axisView, axisModel, ecModel, api, payload, forceRender) {
  37157. var Clazz = AxisView.getAxisPointerClass(axisView.axisPointerClass);
  37158. if (!Clazz) {
  37159. return;
  37160. }
  37161. var axisPointerModel = getAxisPointerModel(axisModel);
  37162. axisPointerModel
  37163. ? (axisView._axisPointer || (axisView._axisPointer = new Clazz()))
  37164. .render(axisModel, axisPointerModel, api, forceRender)
  37165. : disposeAxisPointer(axisView, api);
  37166. }
  37167. function disposeAxisPointer(axisView, ecModel, api) {
  37168. var axisPointer = axisView._axisPointer;
  37169. axisPointer && axisPointer.dispose(ecModel, api);
  37170. axisView._axisPointer = null;
  37171. }
  37172. var axisPointerClazz = [];
  37173. AxisView.registerAxisPointerClass = function (type, clazz) {
  37174. if (__DEV__) {
  37175. if (axisPointerClazz[type]) {
  37176. throw new Error('axisPointer ' + type + ' exists');
  37177. }
  37178. }
  37179. axisPointerClazz[type] = clazz;
  37180. };
  37181. AxisView.getAxisPointerClass = function (type) {
  37182. return type && axisPointerClazz[type];
  37183. };
  37184. /*
  37185. * Licensed to the Apache Software Foundation (ASF) under one
  37186. * or more contributor license agreements. See the NOTICE file
  37187. * distributed with this work for additional information
  37188. * regarding copyright ownership. The ASF licenses this file
  37189. * to you under the Apache License, Version 2.0 (the
  37190. * "License"); you may not use this file except in compliance
  37191. * with the License. You may obtain a copy of the License at
  37192. *
  37193. * http://www.apache.org/licenses/LICENSE-2.0
  37194. *
  37195. * Unless required by applicable law or agreed to in writing,
  37196. * software distributed under the License is distributed on an
  37197. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37198. * KIND, either express or implied. See the License for the
  37199. * specific language governing permissions and limitations
  37200. * under the License.
  37201. */
  37202. /**
  37203. * Can only be called after coordinate system creation stage.
  37204. * (Can be called before coordinate system update stage).
  37205. *
  37206. * @param {Object} opt {labelInside}
  37207. * @return {Object} {
  37208. * position, rotation, labelDirection, labelOffset,
  37209. * tickDirection, labelRotate, z2
  37210. * }
  37211. */
  37212. function layout$1(gridModel, axisModel, opt) {
  37213. opt = opt || {};
  37214. var grid = gridModel.coordinateSystem;
  37215. var axis = axisModel.axis;
  37216. var layout = {};
  37217. var otherAxisOnZeroOf = axis.getAxesOnZeroOf()[0];
  37218. var rawAxisPosition = axis.position;
  37219. var axisPosition = otherAxisOnZeroOf ? 'onZero' : rawAxisPosition;
  37220. var axisDim = axis.dim;
  37221. var rect = grid.getRect();
  37222. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  37223. var idx = {left: 0, right: 1, top: 0, bottom: 1, onZero: 2};
  37224. var axisOffset = axisModel.get('offset') || 0;
  37225. var posBound = axisDim === 'x'
  37226. ? [rectBound[2] - axisOffset, rectBound[3] + axisOffset]
  37227. : [rectBound[0] - axisOffset, rectBound[1] + axisOffset];
  37228. if (otherAxisOnZeroOf) {
  37229. var onZeroCoord = otherAxisOnZeroOf.toGlobalCoord(otherAxisOnZeroOf.dataToCoord(0));
  37230. posBound[idx.onZero] = Math.max(Math.min(onZeroCoord, posBound[1]), posBound[0]);
  37231. }
  37232. // Axis position
  37233. layout.position = [
  37234. axisDim === 'y' ? posBound[idx[axisPosition]] : rectBound[0],
  37235. axisDim === 'x' ? posBound[idx[axisPosition]] : rectBound[3]
  37236. ];
  37237. // Axis rotation
  37238. layout.rotation = Math.PI / 2 * (axisDim === 'x' ? 0 : 1);
  37239. // Tick and label direction, x y is axisDim
  37240. var dirMap = {top: -1, bottom: 1, left: -1, right: 1};
  37241. layout.labelDirection = layout.tickDirection = layout.nameDirection = dirMap[rawAxisPosition];
  37242. layout.labelOffset = otherAxisOnZeroOf ? posBound[idx[rawAxisPosition]] - posBound[idx.onZero] : 0;
  37243. if (axisModel.get('axisTick.inside')) {
  37244. layout.tickDirection = -layout.tickDirection;
  37245. }
  37246. if (retrieve(opt.labelInside, axisModel.get('axisLabel.inside'))) {
  37247. layout.labelDirection = -layout.labelDirection;
  37248. }
  37249. // Special label rotation
  37250. var labelRotate = axisModel.get('axisLabel.rotate');
  37251. layout.labelRotate = axisPosition === 'top' ? -labelRotate : labelRotate;
  37252. // Over splitLine and splitArea
  37253. layout.z2 = 1;
  37254. return layout;
  37255. }
  37256. /*
  37257. * Licensed to the Apache Software Foundation (ASF) under one
  37258. * or more contributor license agreements. See the NOTICE file
  37259. * distributed with this work for additional information
  37260. * regarding copyright ownership. The ASF licenses this file
  37261. * to you under the Apache License, Version 2.0 (the
  37262. * "License"); you may not use this file except in compliance
  37263. * with the License. You may obtain a copy of the License at
  37264. *
  37265. * http://www.apache.org/licenses/LICENSE-2.0
  37266. *
  37267. * Unless required by applicable law or agreed to in writing,
  37268. * software distributed under the License is distributed on an
  37269. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37270. * KIND, either express or implied. See the License for the
  37271. * specific language governing permissions and limitations
  37272. * under the License.
  37273. */
  37274. function rectCoordAxisBuildSplitArea(axisView, axisGroup, axisModel, gridModel) {
  37275. var axis = axisModel.axis;
  37276. if (axis.scale.isBlank()) {
  37277. return;
  37278. }
  37279. var splitAreaModel = axisModel.getModel('splitArea');
  37280. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  37281. var areaColors = areaStyleModel.get('color');
  37282. var gridRect = gridModel.coordinateSystem.getRect();
  37283. var ticksCoords = axis.getTicksCoords({
  37284. tickModel: splitAreaModel,
  37285. clamp: true
  37286. });
  37287. if (!ticksCoords.length) {
  37288. return;
  37289. }
  37290. // For Making appropriate splitArea animation, the color and anid
  37291. // should be corresponding to previous one if possible.
  37292. var areaColorsLen = areaColors.length;
  37293. var lastSplitAreaColors = axisView.__splitAreaColors;
  37294. var newSplitAreaColors = createHashMap();
  37295. var colorIndex = 0;
  37296. if (lastSplitAreaColors) {
  37297. for (var i = 0; i < ticksCoords.length; i++) {
  37298. var cIndex = lastSplitAreaColors.get(ticksCoords[i].tickValue);
  37299. if (cIndex != null) {
  37300. colorIndex = (cIndex + (areaColorsLen - 1) * i) % areaColorsLen;
  37301. break;
  37302. }
  37303. }
  37304. }
  37305. var prev = axis.toGlobalCoord(ticksCoords[0].coord);
  37306. var areaStyle = areaStyleModel.getAreaStyle();
  37307. areaColors = isArray(areaColors) ? areaColors : [areaColors];
  37308. for (var i = 1; i < ticksCoords.length; i++) {
  37309. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  37310. var x;
  37311. var y;
  37312. var width;
  37313. var height;
  37314. if (axis.isHorizontal()) {
  37315. x = prev;
  37316. y = gridRect.y;
  37317. width = tickCoord - x;
  37318. height = gridRect.height;
  37319. prev = x + width;
  37320. }
  37321. else {
  37322. x = gridRect.x;
  37323. y = prev;
  37324. width = gridRect.width;
  37325. height = tickCoord - y;
  37326. prev = y + height;
  37327. }
  37328. var tickValue = ticksCoords[i - 1].tickValue;
  37329. tickValue != null && newSplitAreaColors.set(tickValue, colorIndex);
  37330. axisGroup.add(new Rect({
  37331. anid: tickValue != null ? 'area_' + tickValue : null,
  37332. shape: {
  37333. x: x,
  37334. y: y,
  37335. width: width,
  37336. height: height
  37337. },
  37338. style: defaults({
  37339. fill: areaColors[colorIndex]
  37340. }, areaStyle),
  37341. silent: true
  37342. }));
  37343. colorIndex = (colorIndex + 1) % areaColorsLen;
  37344. }
  37345. axisView.__splitAreaColors = newSplitAreaColors;
  37346. }
  37347. function rectCoordAxisHandleRemove(axisView) {
  37348. axisView.__splitAreaColors = null;
  37349. }
  37350. /*
  37351. * Licensed to the Apache Software Foundation (ASF) under one
  37352. * or more contributor license agreements. See the NOTICE file
  37353. * distributed with this work for additional information
  37354. * regarding copyright ownership. The ASF licenses this file
  37355. * to you under the Apache License, Version 2.0 (the
  37356. * "License"); you may not use this file except in compliance
  37357. * with the License. You may obtain a copy of the License at
  37358. *
  37359. * http://www.apache.org/licenses/LICENSE-2.0
  37360. *
  37361. * Unless required by applicable law or agreed to in writing,
  37362. * software distributed under the License is distributed on an
  37363. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37364. * KIND, either express or implied. See the License for the
  37365. * specific language governing permissions and limitations
  37366. * under the License.
  37367. */
  37368. var axisBuilderAttrs = [
  37369. 'axisLine', 'axisTickLabel', 'axisName'
  37370. ];
  37371. var selfBuilderAttrs = [
  37372. 'splitArea', 'splitLine', 'minorSplitLine'
  37373. ];
  37374. var CartesianAxisView = AxisView.extend({
  37375. type: 'cartesianAxis',
  37376. axisPointerClass: 'CartesianAxisPointer',
  37377. /**
  37378. * @override
  37379. */
  37380. render: function (axisModel, ecModel, api, payload) {
  37381. this.group.removeAll();
  37382. var oldAxisGroup = this._axisGroup;
  37383. this._axisGroup = new Group();
  37384. this.group.add(this._axisGroup);
  37385. if (!axisModel.get('show')) {
  37386. return;
  37387. }
  37388. var gridModel = axisModel.getCoordSysModel();
  37389. var layout = layout$1(gridModel, axisModel);
  37390. var axisBuilder = new AxisBuilder(axisModel, layout);
  37391. each$1(axisBuilderAttrs, axisBuilder.add, axisBuilder);
  37392. this._axisGroup.add(axisBuilder.getGroup());
  37393. each$1(selfBuilderAttrs, function (name) {
  37394. if (axisModel.get(name + '.show')) {
  37395. this['_' + name](axisModel, gridModel);
  37396. }
  37397. }, this);
  37398. groupTransition(oldAxisGroup, this._axisGroup, axisModel);
  37399. CartesianAxisView.superCall(this, 'render', axisModel, ecModel, api, payload);
  37400. },
  37401. remove: function () {
  37402. rectCoordAxisHandleRemove(this);
  37403. },
  37404. /**
  37405. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  37406. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  37407. * @private
  37408. */
  37409. _splitLine: function (axisModel, gridModel) {
  37410. var axis = axisModel.axis;
  37411. if (axis.scale.isBlank()) {
  37412. return;
  37413. }
  37414. var splitLineModel = axisModel.getModel('splitLine');
  37415. var lineStyleModel = splitLineModel.getModel('lineStyle');
  37416. var lineColors = lineStyleModel.get('color');
  37417. lineColors = isArray(lineColors) ? lineColors : [lineColors];
  37418. var gridRect = gridModel.coordinateSystem.getRect();
  37419. var isHorizontal = axis.isHorizontal();
  37420. var lineCount = 0;
  37421. var ticksCoords = axis.getTicksCoords({
  37422. tickModel: splitLineModel
  37423. });
  37424. var p1 = [];
  37425. var p2 = [];
  37426. var lineStyle = lineStyleModel.getLineStyle();
  37427. for (var i = 0; i < ticksCoords.length; i++) {
  37428. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  37429. if (isHorizontal) {
  37430. p1[0] = tickCoord;
  37431. p1[1] = gridRect.y;
  37432. p2[0] = tickCoord;
  37433. p2[1] = gridRect.y + gridRect.height;
  37434. }
  37435. else {
  37436. p1[0] = gridRect.x;
  37437. p1[1] = tickCoord;
  37438. p2[0] = gridRect.x + gridRect.width;
  37439. p2[1] = tickCoord;
  37440. }
  37441. var colorIndex = (lineCount++) % lineColors.length;
  37442. var tickValue = ticksCoords[i].tickValue;
  37443. this._axisGroup.add(new Line({
  37444. anid: tickValue != null ? 'line_' + ticksCoords[i].tickValue : null,
  37445. subPixelOptimize: true,
  37446. shape: {
  37447. x1: p1[0],
  37448. y1: p1[1],
  37449. x2: p2[0],
  37450. y2: p2[1]
  37451. },
  37452. style: defaults({
  37453. stroke: lineColors[colorIndex]
  37454. }, lineStyle),
  37455. silent: true
  37456. }));
  37457. }
  37458. },
  37459. /**
  37460. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  37461. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  37462. * @private
  37463. */
  37464. _minorSplitLine: function (axisModel, gridModel) {
  37465. var axis = axisModel.axis;
  37466. var minorSplitLineModel = axisModel.getModel('minorSplitLine');
  37467. var lineStyleModel = minorSplitLineModel.getModel('lineStyle');
  37468. var gridRect = gridModel.coordinateSystem.getRect();
  37469. var isHorizontal = axis.isHorizontal();
  37470. var minorTicksCoords = axis.getMinorTicksCoords();
  37471. if (!minorTicksCoords.length) {
  37472. return;
  37473. }
  37474. var p1 = [];
  37475. var p2 = [];
  37476. var lineStyle = lineStyleModel.getLineStyle();
  37477. for (var i = 0; i < minorTicksCoords.length; i++) {
  37478. for (var k = 0; k < minorTicksCoords[i].length; k++) {
  37479. var tickCoord = axis.toGlobalCoord(minorTicksCoords[i][k].coord);
  37480. if (isHorizontal) {
  37481. p1[0] = tickCoord;
  37482. p1[1] = gridRect.y;
  37483. p2[0] = tickCoord;
  37484. p2[1] = gridRect.y + gridRect.height;
  37485. }
  37486. else {
  37487. p1[0] = gridRect.x;
  37488. p1[1] = tickCoord;
  37489. p2[0] = gridRect.x + gridRect.width;
  37490. p2[1] = tickCoord;
  37491. }
  37492. this._axisGroup.add(new Line({
  37493. anid: 'minor_line_' + minorTicksCoords[i][k].tickValue,
  37494. subPixelOptimize: true,
  37495. shape: {
  37496. x1: p1[0],
  37497. y1: p1[1],
  37498. x2: p2[0],
  37499. y2: p2[1]
  37500. },
  37501. style: lineStyle,
  37502. silent: true
  37503. }));
  37504. }
  37505. }
  37506. },
  37507. /**
  37508. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  37509. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  37510. * @private
  37511. */
  37512. _splitArea: function (axisModel, gridModel) {
  37513. rectCoordAxisBuildSplitArea(this, this._axisGroup, axisModel, gridModel);
  37514. }
  37515. });
  37516. CartesianAxisView.extend({
  37517. type: 'xAxis'
  37518. });
  37519. CartesianAxisView.extend({
  37520. type: 'yAxis'
  37521. });
  37522. /*
  37523. * Licensed to the Apache Software Foundation (ASF) under one
  37524. * or more contributor license agreements. See the NOTICE file
  37525. * distributed with this work for additional information
  37526. * regarding copyright ownership. The ASF licenses this file
  37527. * to you under the Apache License, Version 2.0 (the
  37528. * "License"); you may not use this file except in compliance
  37529. * with the License. You may obtain a copy of the License at
  37530. *
  37531. * http://www.apache.org/licenses/LICENSE-2.0
  37532. *
  37533. * Unless required by applicable law or agreed to in writing,
  37534. * software distributed under the License is distributed on an
  37535. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37536. * KIND, either express or implied. See the License for the
  37537. * specific language governing permissions and limitations
  37538. * under the License.
  37539. */
  37540. /*
  37541. * Licensed to the Apache Software Foundation (ASF) under one
  37542. * or more contributor license agreements. See the NOTICE file
  37543. * distributed with this work for additional information
  37544. * regarding copyright ownership. The ASF licenses this file
  37545. * to you under the Apache License, Version 2.0 (the
  37546. * "License"); you may not use this file except in compliance
  37547. * with the License. You may obtain a copy of the License at
  37548. *
  37549. * http://www.apache.org/licenses/LICENSE-2.0
  37550. *
  37551. * Unless required by applicable law or agreed to in writing,
  37552. * software distributed under the License is distributed on an
  37553. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37554. * KIND, either express or implied. See the License for the
  37555. * specific language governing permissions and limitations
  37556. * under the License.
  37557. */
  37558. // Grid view
  37559. extendComponentView({
  37560. type: 'grid',
  37561. render: function (gridModel, ecModel) {
  37562. this.group.removeAll();
  37563. if (gridModel.get('show')) {
  37564. this.group.add(new Rect({
  37565. shape: gridModel.coordinateSystem.getRect(),
  37566. style: defaults({
  37567. fill: gridModel.get('backgroundColor')
  37568. }, gridModel.getItemStyle()),
  37569. silent: true,
  37570. z2: -1
  37571. }));
  37572. }
  37573. }
  37574. });
  37575. registerPreprocessor(function (option) {
  37576. // Only create grid when need
  37577. if (option.xAxis && option.yAxis && !option.grid) {
  37578. option.grid = {};
  37579. }
  37580. });
  37581. /*
  37582. * Licensed to the Apache Software Foundation (ASF) under one
  37583. * or more contributor license agreements. See the NOTICE file
  37584. * distributed with this work for additional information
  37585. * regarding copyright ownership. The ASF licenses this file
  37586. * to you under the Apache License, Version 2.0 (the
  37587. * "License"); you may not use this file except in compliance
  37588. * with the License. You may obtain a copy of the License at
  37589. *
  37590. * http://www.apache.org/licenses/LICENSE-2.0
  37591. *
  37592. * Unless required by applicable law or agreed to in writing,
  37593. * software distributed under the License is distributed on an
  37594. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37595. * KIND, either express or implied. See the License for the
  37596. * specific language governing permissions and limitations
  37597. * under the License.
  37598. */
  37599. // In case developer forget to include grid component
  37600. registerVisual(visualSymbol('line', 'circle', 'line'));
  37601. registerLayout(pointsLayout('line'));
  37602. // Down sample after filter
  37603. registerProcessor(
  37604. PRIORITY.PROCESSOR.STATISTIC,
  37605. dataSample('line')
  37606. );
  37607. /*
  37608. * Licensed to the Apache Software Foundation (ASF) under one
  37609. * or more contributor license agreements. See the NOTICE file
  37610. * distributed with this work for additional information
  37611. * regarding copyright ownership. The ASF licenses this file
  37612. * to you under the Apache License, Version 2.0 (the
  37613. * "License"); you may not use this file except in compliance
  37614. * with the License. You may obtain a copy of the License at
  37615. *
  37616. * http://www.apache.org/licenses/LICENSE-2.0
  37617. *
  37618. * Unless required by applicable law or agreed to in writing,
  37619. * software distributed under the License is distributed on an
  37620. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37621. * KIND, either express or implied. See the License for the
  37622. * specific language governing permissions and limitations
  37623. * under the License.
  37624. */
  37625. var BaseBarSeries = SeriesModel.extend({
  37626. type: 'series.__base_bar__',
  37627. getInitialData: function (option, ecModel) {
  37628. return createListFromArray(this.getSource(), this, {useEncodeDefaulter: true});
  37629. },
  37630. getMarkerPosition: function (value) {
  37631. var coordSys = this.coordinateSystem;
  37632. if (coordSys) {
  37633. // PENDING if clamp ?
  37634. var pt = coordSys.dataToPoint(coordSys.clampData(value));
  37635. var data = this.getData();
  37636. var offset = data.getLayout('offset');
  37637. var size = data.getLayout('size');
  37638. var offsetIndex = coordSys.getBaseAxis().isHorizontal() ? 0 : 1;
  37639. pt[offsetIndex] += offset + size / 2;
  37640. return pt;
  37641. }
  37642. return [NaN, NaN];
  37643. },
  37644. defaultOption: {
  37645. zlevel: 0, // 一级层叠
  37646. z: 2, // 二级层叠
  37647. coordinateSystem: 'cartesian2d',
  37648. legendHoverLink: true,
  37649. // stack: null
  37650. // Cartesian coordinate system
  37651. // xAxisIndex: 0,
  37652. // yAxisIndex: 0,
  37653. // 最小高度改为0
  37654. barMinHeight: 0,
  37655. // 最小角度为0,仅对极坐标系下的柱状图有效
  37656. barMinAngle: 0,
  37657. // cursor: null,
  37658. large: false,
  37659. largeThreshold: 400,
  37660. progressive: 3e3,
  37661. progressiveChunkMode: 'mod',
  37662. // barMaxWidth: null,
  37663. // In cartesian, the default value is 1. Otherwise null.
  37664. // barMinWidth: null,
  37665. // 默认自适应
  37666. // barWidth: null,
  37667. // 柱间距离,默认为柱形宽度的30%,可设固定值
  37668. // barGap: '30%',
  37669. // 类目间柱形距离,默认为类目间距的20%,可设固定值
  37670. // barCategoryGap: '20%',
  37671. // label: {
  37672. // show: false
  37673. // },
  37674. itemStyle: {},
  37675. emphasis: {}
  37676. }
  37677. });
  37678. /*
  37679. * Licensed to the Apache Software Foundation (ASF) under one
  37680. * or more contributor license agreements. See the NOTICE file
  37681. * distributed with this work for additional information
  37682. * regarding copyright ownership. The ASF licenses this file
  37683. * to you under the Apache License, Version 2.0 (the
  37684. * "License"); you may not use this file except in compliance
  37685. * with the License. You may obtain a copy of the License at
  37686. *
  37687. * http://www.apache.org/licenses/LICENSE-2.0
  37688. *
  37689. * Unless required by applicable law or agreed to in writing,
  37690. * software distributed under the License is distributed on an
  37691. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37692. * KIND, either express or implied. See the License for the
  37693. * specific language governing permissions and limitations
  37694. * under the License.
  37695. */
  37696. BaseBarSeries.extend({
  37697. type: 'series.bar',
  37698. dependencies: ['grid', 'polar'],
  37699. brushSelector: 'rect',
  37700. /**
  37701. * @override
  37702. */
  37703. getProgressive: function () {
  37704. // Do not support progressive in normal mode.
  37705. return this.get('large')
  37706. ? this.get('progressive')
  37707. : false;
  37708. },
  37709. /**
  37710. * @override
  37711. */
  37712. getProgressiveThreshold: function () {
  37713. // Do not support progressive in normal mode.
  37714. var progressiveThreshold = this.get('progressiveThreshold');
  37715. var largeThreshold = this.get('largeThreshold');
  37716. if (largeThreshold > progressiveThreshold) {
  37717. progressiveThreshold = largeThreshold;
  37718. }
  37719. return progressiveThreshold;
  37720. },
  37721. defaultOption: {
  37722. // If clipped
  37723. // Only available on cartesian2d
  37724. clip: true,
  37725. // If use caps on two sides of bars
  37726. // Only available on tangential polar bar
  37727. roundCap: false,
  37728. showBackground: false,
  37729. backgroundStyle: {
  37730. color: 'rgba(180, 180, 180, 0.2)',
  37731. borderColor: null,
  37732. borderWidth: 0,
  37733. borderType: 'solid',
  37734. borderRadius: 0,
  37735. shadowBlur: 0,
  37736. shadowColor: null,
  37737. shadowOffsetX: 0,
  37738. shadowOffsetY: 0,
  37739. opacity: 1
  37740. }
  37741. }
  37742. });
  37743. /*
  37744. * Licensed to the Apache Software Foundation (ASF) under one
  37745. * or more contributor license agreements. See the NOTICE file
  37746. * distributed with this work for additional information
  37747. * regarding copyright ownership. The ASF licenses this file
  37748. * to you under the Apache License, Version 2.0 (the
  37749. * "License"); you may not use this file except in compliance
  37750. * with the License. You may obtain a copy of the License at
  37751. *
  37752. * http://www.apache.org/licenses/LICENSE-2.0
  37753. *
  37754. * Unless required by applicable law or agreed to in writing,
  37755. * software distributed under the License is distributed on an
  37756. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37757. * KIND, either express or implied. See the License for the
  37758. * specific language governing permissions and limitations
  37759. * under the License.
  37760. */
  37761. function setLabel(
  37762. normalStyle, hoverStyle, itemModel, color, seriesModel, dataIndex, labelPositionOutside
  37763. ) {
  37764. var labelModel = itemModel.getModel('label');
  37765. var hoverLabelModel = itemModel.getModel('emphasis.label');
  37766. setLabelStyle(
  37767. normalStyle, hoverStyle, labelModel, hoverLabelModel,
  37768. {
  37769. labelFetcher: seriesModel,
  37770. labelDataIndex: dataIndex,
  37771. defaultText: getDefaultLabel(seriesModel.getData(), dataIndex),
  37772. isRectText: true,
  37773. autoColor: color
  37774. }
  37775. );
  37776. fixPosition(normalStyle);
  37777. fixPosition(hoverStyle);
  37778. }
  37779. function fixPosition(style, labelPositionOutside) {
  37780. if (style.textPosition === 'outside') {
  37781. style.textPosition = labelPositionOutside;
  37782. }
  37783. }
  37784. /*
  37785. * Licensed to the Apache Software Foundation (ASF) under one
  37786. * or more contributor license agreements. See the NOTICE file
  37787. * distributed with this work for additional information
  37788. * regarding copyright ownership. The ASF licenses this file
  37789. * to you under the Apache License, Version 2.0 (the
  37790. * "License"); you may not use this file except in compliance
  37791. * with the License. You may obtain a copy of the License at
  37792. *
  37793. * http://www.apache.org/licenses/LICENSE-2.0
  37794. *
  37795. * Unless required by applicable law or agreed to in writing,
  37796. * software distributed under the License is distributed on an
  37797. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37798. * KIND, either express or implied. See the License for the
  37799. * specific language governing permissions and limitations
  37800. * under the License.
  37801. */
  37802. var getBarItemStyle = makeStyleMapper(
  37803. [
  37804. ['fill', 'color'],
  37805. ['stroke', 'borderColor'],
  37806. ['lineWidth', 'borderWidth'],
  37807. // Compatitable with 2
  37808. ['stroke', 'barBorderColor'],
  37809. ['lineWidth', 'barBorderWidth'],
  37810. ['opacity'],
  37811. ['shadowBlur'],
  37812. ['shadowOffsetX'],
  37813. ['shadowOffsetY'],
  37814. ['shadowColor']
  37815. ]
  37816. );
  37817. var barItemStyle = {
  37818. getBarItemStyle: function (excludes) {
  37819. var style = getBarItemStyle(this, excludes);
  37820. if (this.getBorderLineDash) {
  37821. var lineDash = this.getBorderLineDash();
  37822. lineDash && (style.lineDash = lineDash);
  37823. }
  37824. return style;
  37825. }
  37826. };
  37827. /*
  37828. * Licensed to the Apache Software Foundation (ASF) under one
  37829. * or more contributor license agreements. See the NOTICE file
  37830. * distributed with this work for additional information
  37831. * regarding copyright ownership. The ASF licenses this file
  37832. * to you under the Apache License, Version 2.0 (the
  37833. * "License"); you may not use this file except in compliance
  37834. * with the License. You may obtain a copy of the License at
  37835. *
  37836. * http://www.apache.org/licenses/LICENSE-2.0
  37837. *
  37838. * Unless required by applicable law or agreed to in writing,
  37839. * software distributed under the License is distributed on an
  37840. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37841. * KIND, either express or implied. See the License for the
  37842. * specific language governing permissions and limitations
  37843. * under the License.
  37844. */
  37845. /**
  37846. * Sausage: similar to sector, but have half circle on both sides
  37847. * @public
  37848. */
  37849. var Sausage = extendShape({
  37850. type: 'sausage',
  37851. shape: {
  37852. cx: 0,
  37853. cy: 0,
  37854. r0: 0,
  37855. r: 0,
  37856. startAngle: 0,
  37857. endAngle: Math.PI * 2,
  37858. clockwise: true
  37859. },
  37860. buildPath: function (ctx, shape) {
  37861. var x = shape.cx;
  37862. var y = shape.cy;
  37863. var r0 = Math.max(shape.r0 || 0, 0);
  37864. var r = Math.max(shape.r, 0);
  37865. var dr = (r - r0) * 0.5;
  37866. var rCenter = r0 + dr;
  37867. var startAngle = shape.startAngle;
  37868. var endAngle = shape.endAngle;
  37869. var clockwise = shape.clockwise;
  37870. var unitStartX = Math.cos(startAngle);
  37871. var unitStartY = Math.sin(startAngle);
  37872. var unitEndX = Math.cos(endAngle);
  37873. var unitEndY = Math.sin(endAngle);
  37874. var lessThanCircle = clockwise
  37875. ? endAngle - startAngle < Math.PI * 2
  37876. : startAngle - endAngle < Math.PI * 2;
  37877. if (lessThanCircle) {
  37878. ctx.moveTo(unitStartX * r0 + x, unitStartY * r0 + y);
  37879. ctx.arc(
  37880. unitStartX * rCenter + x, unitStartY * rCenter + y, dr,
  37881. -Math.PI + startAngle, startAngle, !clockwise
  37882. );
  37883. }
  37884. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  37885. ctx.moveTo(unitEndX * r + x, unitEndY * r + y);
  37886. ctx.arc(
  37887. unitEndX * rCenter + x, unitEndY * rCenter + y, dr,
  37888. endAngle - Math.PI * 2, endAngle - Math.PI, !clockwise
  37889. );
  37890. if (r0 !== 0) {
  37891. ctx.arc(x, y, r0, endAngle, startAngle, clockwise);
  37892. ctx.moveTo(unitStartX * r0 + x, unitEndY * r0 + y);
  37893. }
  37894. ctx.closePath();
  37895. }
  37896. });
  37897. /*
  37898. * Licensed to the Apache Software Foundation (ASF) under one
  37899. * or more contributor license agreements. See the NOTICE file
  37900. * distributed with this work for additional information
  37901. * regarding copyright ownership. The ASF licenses this file
  37902. * to you under the Apache License, Version 2.0 (the
  37903. * "License"); you may not use this file except in compliance
  37904. * with the License. You may obtain a copy of the License at
  37905. *
  37906. * http://www.apache.org/licenses/LICENSE-2.0
  37907. *
  37908. * Unless required by applicable law or agreed to in writing,
  37909. * software distributed under the License is distributed on an
  37910. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37911. * KIND, either express or implied. See the License for the
  37912. * specific language governing permissions and limitations
  37913. * under the License.
  37914. */
  37915. var BAR_BORDER_WIDTH_QUERY = ['itemStyle', 'barBorderWidth'];
  37916. var _eventPos = [0, 0];
  37917. // FIXME
  37918. // Just for compatible with ec2.
  37919. extend(Model.prototype, barItemStyle);
  37920. function getClipArea(coord, data) {
  37921. var coordSysClipArea = coord.getArea && coord.getArea();
  37922. if (coord.type === 'cartesian2d') {
  37923. var baseAxis = coord.getBaseAxis();
  37924. // When boundaryGap is false or using time axis. bar may exceed the grid.
  37925. // We should not clip this part.
  37926. // See test/bar2.html
  37927. if (baseAxis.type !== 'category' || !baseAxis.onBand) {
  37928. var expandWidth = data.getLayout('bandWidth');
  37929. if (baseAxis.isHorizontal()) {
  37930. coordSysClipArea.x -= expandWidth;
  37931. coordSysClipArea.width += expandWidth * 2;
  37932. }
  37933. else {
  37934. coordSysClipArea.y -= expandWidth;
  37935. coordSysClipArea.height += expandWidth * 2;
  37936. }
  37937. }
  37938. }
  37939. return coordSysClipArea;
  37940. }
  37941. extendChartView({
  37942. type: 'bar',
  37943. render: function (seriesModel, ecModel, api) {
  37944. this._updateDrawMode(seriesModel);
  37945. var coordinateSystemType = seriesModel.get('coordinateSystem');
  37946. if (coordinateSystemType === 'cartesian2d'
  37947. || coordinateSystemType === 'polar'
  37948. ) {
  37949. this._isLargeDraw
  37950. ? this._renderLarge(seriesModel, ecModel, api)
  37951. : this._renderNormal(seriesModel, ecModel, api);
  37952. }
  37953. else if (__DEV__) {
  37954. console.warn('Only cartesian2d and polar supported for bar.');
  37955. }
  37956. return this.group;
  37957. },
  37958. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  37959. this._clear();
  37960. this._updateDrawMode(seriesModel);
  37961. },
  37962. incrementalRender: function (params, seriesModel, ecModel, api) {
  37963. // Do not support progressive in normal mode.
  37964. this._incrementalRenderLarge(params, seriesModel);
  37965. },
  37966. _updateDrawMode: function (seriesModel) {
  37967. var isLargeDraw = seriesModel.pipelineContext.large;
  37968. if (this._isLargeDraw == null || isLargeDraw ^ this._isLargeDraw) {
  37969. this._isLargeDraw = isLargeDraw;
  37970. this._clear();
  37971. }
  37972. },
  37973. _renderNormal: function (seriesModel, ecModel, api) {
  37974. var group = this.group;
  37975. var data = seriesModel.getData();
  37976. var oldData = this._data;
  37977. var coord = seriesModel.coordinateSystem;
  37978. var baseAxis = coord.getBaseAxis();
  37979. var isHorizontalOrRadial;
  37980. if (coord.type === 'cartesian2d') {
  37981. isHorizontalOrRadial = baseAxis.isHorizontal();
  37982. }
  37983. else if (coord.type === 'polar') {
  37984. isHorizontalOrRadial = baseAxis.dim === 'angle';
  37985. }
  37986. var animationModel = seriesModel.isAnimationEnabled() ? seriesModel : null;
  37987. var needsClip = seriesModel.get('clip', true);
  37988. var coordSysClipArea = getClipArea(coord, data);
  37989. // If there is clipPath created in large mode. Remove it.
  37990. group.removeClipPath();
  37991. // We don't use clipPath in normal mode because we needs a perfect animation
  37992. // And don't want the label are clipped.
  37993. var roundCap = seriesModel.get('roundCap', true);
  37994. var drawBackground = seriesModel.get('showBackground', true);
  37995. var backgroundModel = seriesModel.getModel('backgroundStyle');
  37996. var barBorderRadius = backgroundModel.get('barBorderRadius') || 0;
  37997. var bgEls = [];
  37998. var oldBgEls = this._backgroundEls || [];
  37999. data.diff(oldData)
  38000. .add(function (dataIndex) {
  38001. var itemModel = data.getItemModel(dataIndex);
  38002. var layout = getLayout[coord.type](data, dataIndex, itemModel);
  38003. if (drawBackground) {
  38004. var bgLayout = getLayout[coord.type](data, dataIndex);
  38005. var bgEl = createBackgroundEl(coord, isHorizontalOrRadial, bgLayout);
  38006. bgEl.useStyle(backgroundModel.getBarItemStyle());
  38007. // Only cartesian2d support borderRadius.
  38008. if (coord.type === 'cartesian2d') {
  38009. bgEl.setShape('r', barBorderRadius);
  38010. }
  38011. bgEls[dataIndex] = bgEl;
  38012. }
  38013. // If dataZoom in filteMode: 'empty', the baseValue can be set as NaN in "axisProxy".
  38014. if (!data.hasValue(dataIndex)) {
  38015. return;
  38016. }
  38017. if (needsClip) {
  38018. // Clip will modify the layout params.
  38019. // And return a boolean to determine if the shape are fully clipped.
  38020. var isClipped = clip[coord.type](coordSysClipArea, layout);
  38021. if (isClipped) {
  38022. group.remove(el);
  38023. return;
  38024. }
  38025. }
  38026. var el = elementCreator[coord.type](
  38027. dataIndex, layout, isHorizontalOrRadial, animationModel, false, roundCap
  38028. );
  38029. data.setItemGraphicEl(dataIndex, el);
  38030. group.add(el);
  38031. updateStyle(
  38032. el, data, dataIndex, itemModel, layout,
  38033. seriesModel, isHorizontalOrRadial, coord.type === 'polar'
  38034. );
  38035. })
  38036. .update(function (newIndex, oldIndex) {
  38037. var itemModel = data.getItemModel(newIndex);
  38038. var layout = getLayout[coord.type](data, newIndex, itemModel);
  38039. if (drawBackground) {
  38040. var bgEl = oldBgEls[oldIndex];
  38041. bgEl.useStyle(backgroundModel.getBarItemStyle());
  38042. // Only cartesian2d support borderRadius.
  38043. if (coord.type === 'cartesian2d') {
  38044. bgEl.setShape('r', barBorderRadius);
  38045. }
  38046. bgEls[newIndex] = bgEl;
  38047. var bgLayout = getLayout[coord.type](data, newIndex);
  38048. var shape = createBackgroundShape(isHorizontalOrRadial, bgLayout, coord);
  38049. updateProps(bgEl, { shape: shape }, animationModel, newIndex);
  38050. }
  38051. var el = oldData.getItemGraphicEl(oldIndex);
  38052. if (!data.hasValue(newIndex)) {
  38053. group.remove(el);
  38054. return;
  38055. }
  38056. if (needsClip) {
  38057. var isClipped = clip[coord.type](coordSysClipArea, layout);
  38058. if (isClipped) {
  38059. group.remove(el);
  38060. return;
  38061. }
  38062. }
  38063. if (el) {
  38064. updateProps(el, {shape: layout}, animationModel, newIndex);
  38065. }
  38066. else {
  38067. el = elementCreator[coord.type](
  38068. newIndex, layout, isHorizontalOrRadial, animationModel, true, roundCap
  38069. );
  38070. }
  38071. data.setItemGraphicEl(newIndex, el);
  38072. // Add back
  38073. group.add(el);
  38074. updateStyle(
  38075. el, data, newIndex, itemModel, layout,
  38076. seriesModel, isHorizontalOrRadial, coord.type === 'polar'
  38077. );
  38078. })
  38079. .remove(function (dataIndex) {
  38080. var el = oldData.getItemGraphicEl(dataIndex);
  38081. if (coord.type === 'cartesian2d') {
  38082. el && removeRect(dataIndex, animationModel, el);
  38083. }
  38084. else {
  38085. el && removeSector(dataIndex, animationModel, el);
  38086. }
  38087. })
  38088. .execute();
  38089. var bgGroup = this._backgroundGroup || (this._backgroundGroup = new Group());
  38090. bgGroup.removeAll();
  38091. for (var i = 0; i < bgEls.length; ++i) {
  38092. bgGroup.add(bgEls[i]);
  38093. }
  38094. group.add(bgGroup);
  38095. this._backgroundEls = bgEls;
  38096. this._data = data;
  38097. },
  38098. _renderLarge: function (seriesModel, ecModel, api) {
  38099. this._clear();
  38100. createLarge(seriesModel, this.group);
  38101. // Use clipPath in large mode.
  38102. var clipPath = seriesModel.get('clip', true)
  38103. ? createClipPath(seriesModel.coordinateSystem, false, seriesModel)
  38104. : null;
  38105. if (clipPath) {
  38106. this.group.setClipPath(clipPath);
  38107. }
  38108. else {
  38109. this.group.removeClipPath();
  38110. }
  38111. },
  38112. _incrementalRenderLarge: function (params, seriesModel) {
  38113. this._removeBackground();
  38114. createLarge(seriesModel, this.group, true);
  38115. },
  38116. dispose: noop,
  38117. remove: function (ecModel) {
  38118. this._clear(ecModel);
  38119. },
  38120. _clear: function (ecModel) {
  38121. var group = this.group;
  38122. var data = this._data;
  38123. if (ecModel && ecModel.get('animation') && data && !this._isLargeDraw) {
  38124. this._removeBackground();
  38125. this._backgroundEls = [];
  38126. data.eachItemGraphicEl(function (el) {
  38127. if (el.type === 'sector') {
  38128. removeSector(el.dataIndex, ecModel, el);
  38129. }
  38130. else {
  38131. removeRect(el.dataIndex, ecModel, el);
  38132. }
  38133. });
  38134. }
  38135. else {
  38136. group.removeAll();
  38137. }
  38138. this._data = null;
  38139. },
  38140. _removeBackground: function () {
  38141. this.group.remove(this._backgroundGroup);
  38142. this._backgroundGroup = null;
  38143. }
  38144. });
  38145. var mathMax$4 = Math.max;
  38146. var mathMin$4 = Math.min;
  38147. var clip = {
  38148. cartesian2d: function (coordSysBoundingRect, layout) {
  38149. var signWidth = layout.width < 0 ? -1 : 1;
  38150. var signHeight = layout.height < 0 ? -1 : 1;
  38151. // Needs positive width and height
  38152. if (signWidth < 0) {
  38153. layout.x += layout.width;
  38154. layout.width = -layout.width;
  38155. }
  38156. if (signHeight < 0) {
  38157. layout.y += layout.height;
  38158. layout.height = -layout.height;
  38159. }
  38160. var x = mathMax$4(layout.x, coordSysBoundingRect.x);
  38161. var x2 = mathMin$4(layout.x + layout.width, coordSysBoundingRect.x + coordSysBoundingRect.width);
  38162. var y = mathMax$4(layout.y, coordSysBoundingRect.y);
  38163. var y2 = mathMin$4(layout.y + layout.height, coordSysBoundingRect.y + coordSysBoundingRect.height);
  38164. layout.x = x;
  38165. layout.y = y;
  38166. layout.width = x2 - x;
  38167. layout.height = y2 - y;
  38168. var clipped = layout.width < 0 || layout.height < 0;
  38169. // Reverse back
  38170. if (signWidth < 0) {
  38171. layout.x += layout.width;
  38172. layout.width = -layout.width;
  38173. }
  38174. if (signHeight < 0) {
  38175. layout.y += layout.height;
  38176. layout.height = -layout.height;
  38177. }
  38178. return clipped;
  38179. },
  38180. polar: function (coordSysClipArea) {
  38181. return false;
  38182. }
  38183. };
  38184. var elementCreator = {
  38185. cartesian2d: function (
  38186. dataIndex, layout, isHorizontal,
  38187. animationModel, isUpdate
  38188. ) {
  38189. var rect = new Rect({
  38190. shape: extend({}, layout),
  38191. z2: 1
  38192. });
  38193. rect.name = 'item';
  38194. // Animation
  38195. if (animationModel) {
  38196. var rectShape = rect.shape;
  38197. var animateProperty = isHorizontal ? 'height' : 'width';
  38198. var animateTarget = {};
  38199. rectShape[animateProperty] = 0;
  38200. animateTarget[animateProperty] = layout[animateProperty];
  38201. graphic[isUpdate ? 'updateProps' : 'initProps'](rect, {
  38202. shape: animateTarget
  38203. }, animationModel, dataIndex);
  38204. }
  38205. return rect;
  38206. },
  38207. polar: function (
  38208. dataIndex, layout, isRadial,
  38209. animationModel, isUpdate, roundCap
  38210. ) {
  38211. // Keep the same logic with bar in catesion: use end value to control
  38212. // direction. Notice that if clockwise is true (by default), the sector
  38213. // will always draw clockwisely, no matter whether endAngle is greater
  38214. // or less than startAngle.
  38215. var clockwise = layout.startAngle < layout.endAngle;
  38216. var ShapeClass = (!isRadial && roundCap) ? Sausage : Sector;
  38217. var sector = new ShapeClass({
  38218. shape: defaults({clockwise: clockwise}, layout),
  38219. z2: 1
  38220. });
  38221. sector.name = 'item';
  38222. // Animation
  38223. if (animationModel) {
  38224. var sectorShape = sector.shape;
  38225. var animateProperty = isRadial ? 'r' : 'endAngle';
  38226. var animateTarget = {};
  38227. sectorShape[animateProperty] = isRadial ? 0 : layout.startAngle;
  38228. animateTarget[animateProperty] = layout[animateProperty];
  38229. graphic[isUpdate ? 'updateProps' : 'initProps'](sector, {
  38230. shape: animateTarget
  38231. }, animationModel, dataIndex);
  38232. }
  38233. return sector;
  38234. }
  38235. };
  38236. function removeRect(dataIndex, animationModel, el) {
  38237. // Not show text when animating
  38238. el.style.text = null;
  38239. updateProps(el, {
  38240. shape: {
  38241. width: 0
  38242. }
  38243. }, animationModel, dataIndex, function () {
  38244. el.parent && el.parent.remove(el);
  38245. });
  38246. }
  38247. function removeSector(dataIndex, animationModel, el) {
  38248. // Not show text when animating
  38249. el.style.text = null;
  38250. updateProps(el, {
  38251. shape: {
  38252. r: el.shape.r0
  38253. }
  38254. }, animationModel, dataIndex, function () {
  38255. el.parent && el.parent.remove(el);
  38256. });
  38257. }
  38258. var getLayout = {
  38259. // itemModel is only used to get borderWidth, which is not needed
  38260. // when calculating bar background layout.
  38261. cartesian2d: function (data, dataIndex, itemModel) {
  38262. var layout = data.getItemLayout(dataIndex);
  38263. var fixedLineWidth = itemModel ? getLineWidth(itemModel, layout) : 0;
  38264. // fix layout with lineWidth
  38265. var signX = layout.width > 0 ? 1 : -1;
  38266. var signY = layout.height > 0 ? 1 : -1;
  38267. return {
  38268. x: layout.x + signX * fixedLineWidth / 2,
  38269. y: layout.y + signY * fixedLineWidth / 2,
  38270. width: layout.width - signX * fixedLineWidth,
  38271. height: layout.height - signY * fixedLineWidth
  38272. };
  38273. },
  38274. polar: function (data, dataIndex, itemModel) {
  38275. var layout = data.getItemLayout(dataIndex);
  38276. return {
  38277. cx: layout.cx,
  38278. cy: layout.cy,
  38279. r0: layout.r0,
  38280. r: layout.r,
  38281. startAngle: layout.startAngle,
  38282. endAngle: layout.endAngle
  38283. };
  38284. }
  38285. };
  38286. function isZeroOnPolar(layout) {
  38287. return layout.startAngle != null
  38288. && layout.endAngle != null
  38289. && layout.startAngle === layout.endAngle;
  38290. }
  38291. function updateStyle(
  38292. el, data, dataIndex, itemModel, layout, seriesModel, isHorizontal, isPolar
  38293. ) {
  38294. var color = data.getItemVisual(dataIndex, 'color');
  38295. var opacity = data.getItemVisual(dataIndex, 'opacity');
  38296. var stroke = data.getVisual('borderColor');
  38297. var itemStyleModel = itemModel.getModel('itemStyle');
  38298. var hoverStyle = itemModel.getModel('emphasis.itemStyle').getBarItemStyle();
  38299. if (!isPolar) {
  38300. el.setShape('r', itemStyleModel.get('barBorderRadius') || 0);
  38301. }
  38302. el.useStyle(defaults(
  38303. {
  38304. stroke: isZeroOnPolar(layout) ? 'none' : stroke,
  38305. fill: isZeroOnPolar(layout) ? 'none' : color,
  38306. opacity: opacity
  38307. },
  38308. itemStyleModel.getBarItemStyle()
  38309. ));
  38310. var cursorStyle = itemModel.getShallow('cursor');
  38311. cursorStyle && el.attr('cursor', cursorStyle);
  38312. var labelPositionOutside = isHorizontal
  38313. ? (layout.height > 0 ? 'bottom' : 'top')
  38314. : (layout.width > 0 ? 'left' : 'right');
  38315. if (!isPolar) {
  38316. setLabel(
  38317. el.style, hoverStyle, itemModel, color,
  38318. seriesModel, dataIndex, labelPositionOutside
  38319. );
  38320. }
  38321. if (isZeroOnPolar(layout)) {
  38322. hoverStyle.fill = hoverStyle.stroke = 'none';
  38323. }
  38324. setHoverStyle(el, hoverStyle);
  38325. }
  38326. // In case width or height are too small.
  38327. function getLineWidth(itemModel, rawLayout) {
  38328. var lineWidth = itemModel.get(BAR_BORDER_WIDTH_QUERY) || 0;
  38329. // width or height may be NaN for empty data
  38330. var width = isNaN(rawLayout.width) ? Number.MAX_VALUE : Math.abs(rawLayout.width);
  38331. var height = isNaN(rawLayout.height) ? Number.MAX_VALUE : Math.abs(rawLayout.height);
  38332. return Math.min(lineWidth, width, height);
  38333. }
  38334. var LargePath = Path.extend({
  38335. type: 'largeBar',
  38336. shape: {points: []},
  38337. buildPath: function (ctx, shape) {
  38338. // Drawing lines is more efficient than drawing
  38339. // a whole line or drawing rects.
  38340. var points = shape.points;
  38341. var startPoint = this.__startPoint;
  38342. var baseDimIdx = this.__baseDimIdx;
  38343. for (var i = 0; i < points.length; i += 2) {
  38344. startPoint[baseDimIdx] = points[i + baseDimIdx];
  38345. ctx.moveTo(startPoint[0], startPoint[1]);
  38346. ctx.lineTo(points[i], points[i + 1]);
  38347. }
  38348. }
  38349. });
  38350. function createLarge(seriesModel, group, incremental) {
  38351. // TODO support polar
  38352. var data = seriesModel.getData();
  38353. var startPoint = [];
  38354. var baseDimIdx = data.getLayout('valueAxisHorizontal') ? 1 : 0;
  38355. startPoint[1 - baseDimIdx] = data.getLayout('valueAxisStart');
  38356. var largeDataIndices = data.getLayout('largeDataIndices');
  38357. var barWidth = data.getLayout('barWidth');
  38358. var backgroundModel = seriesModel.getModel('backgroundStyle');
  38359. var drawBackground = seriesModel.get('showBackground', true);
  38360. if (drawBackground) {
  38361. var points = data.getLayout('largeBackgroundPoints');
  38362. var backgroundStartPoint = [];
  38363. backgroundStartPoint[1 - baseDimIdx] = data.getLayout('backgroundStart');
  38364. var bgEl = new LargePath({
  38365. shape: {points: points},
  38366. incremental: !!incremental,
  38367. __startPoint: backgroundStartPoint,
  38368. __baseDimIdx: baseDimIdx,
  38369. __largeDataIndices: largeDataIndices,
  38370. __barWidth: barWidth,
  38371. silent: true,
  38372. z2: 0
  38373. });
  38374. setLargeBackgroundStyle(bgEl, backgroundModel, data);
  38375. group.add(bgEl);
  38376. }
  38377. var el = new LargePath({
  38378. shape: {points: data.getLayout('largePoints')},
  38379. incremental: !!incremental,
  38380. __startPoint: startPoint,
  38381. __baseDimIdx: baseDimIdx,
  38382. __largeDataIndices: largeDataIndices,
  38383. __barWidth: barWidth
  38384. });
  38385. group.add(el);
  38386. setLargeStyle(el, seriesModel, data);
  38387. // Enable tooltip and user mouse/touch event handlers.
  38388. el.seriesIndex = seriesModel.seriesIndex;
  38389. if (!seriesModel.get('silent')) {
  38390. el.on('mousedown', largePathUpdateDataIndex);
  38391. el.on('mousemove', largePathUpdateDataIndex);
  38392. }
  38393. }
  38394. // Use throttle to avoid frequently traverse to find dataIndex.
  38395. var largePathUpdateDataIndex = throttle(function (event) {
  38396. var largePath = this;
  38397. var dataIndex = largePathFindDataIndex(largePath, event.offsetX, event.offsetY);
  38398. largePath.dataIndex = dataIndex >= 0 ? dataIndex : null;
  38399. }, 30, false);
  38400. function largePathFindDataIndex(largePath, x, y) {
  38401. var baseDimIdx = largePath.__baseDimIdx;
  38402. var valueDimIdx = 1 - baseDimIdx;
  38403. var points = largePath.shape.points;
  38404. var largeDataIndices = largePath.__largeDataIndices;
  38405. var barWidthHalf = Math.abs(largePath.__barWidth / 2);
  38406. var startValueVal = largePath.__startPoint[valueDimIdx];
  38407. _eventPos[0] = x;
  38408. _eventPos[1] = y;
  38409. var pointerBaseVal = _eventPos[baseDimIdx];
  38410. var pointerValueVal = _eventPos[1 - baseDimIdx];
  38411. var baseLowerBound = pointerBaseVal - barWidthHalf;
  38412. var baseUpperBound = pointerBaseVal + barWidthHalf;
  38413. for (var i = 0, len = points.length / 2; i < len; i++) {
  38414. var ii = i * 2;
  38415. var barBaseVal = points[ii + baseDimIdx];
  38416. var barValueVal = points[ii + valueDimIdx];
  38417. if (
  38418. barBaseVal >= baseLowerBound && barBaseVal <= baseUpperBound
  38419. && (
  38420. startValueVal <= barValueVal
  38421. ? (pointerValueVal >= startValueVal && pointerValueVal <= barValueVal)
  38422. : (pointerValueVal >= barValueVal && pointerValueVal <= startValueVal)
  38423. )
  38424. ) {
  38425. return largeDataIndices[i];
  38426. }
  38427. }
  38428. return -1;
  38429. }
  38430. function setLargeStyle(el, seriesModel, data) {
  38431. var borderColor = data.getVisual('borderColor') || data.getVisual('color');
  38432. var itemStyle = seriesModel.getModel('itemStyle').getItemStyle(['color', 'borderColor']);
  38433. el.useStyle(itemStyle);
  38434. el.style.fill = null;
  38435. el.style.stroke = borderColor;
  38436. el.style.lineWidth = data.getLayout('barWidth');
  38437. }
  38438. function setLargeBackgroundStyle(el, backgroundModel, data) {
  38439. var borderColor = backgroundModel.get('borderColor') || backgroundModel.get('color');
  38440. var itemStyle = backgroundModel.getItemStyle(['color', 'borderColor']);
  38441. el.useStyle(itemStyle);
  38442. el.style.fill = null;
  38443. el.style.stroke = borderColor;
  38444. el.style.lineWidth = data.getLayout('barWidth');
  38445. }
  38446. function createBackgroundShape(isHorizontalOrRadial, layout, coord) {
  38447. var coordLayout;
  38448. var isPolar = coord.type === 'polar';
  38449. if (isPolar) {
  38450. coordLayout = coord.getArea();
  38451. }
  38452. else {
  38453. coordLayout = coord.grid.getRect();
  38454. }
  38455. if (isPolar) {
  38456. return {
  38457. cx: coordLayout.cx,
  38458. cy: coordLayout.cy,
  38459. r0: isHorizontalOrRadial ? coordLayout.r0 : layout.r0,
  38460. r: isHorizontalOrRadial ? coordLayout.r : layout.r,
  38461. startAngle: isHorizontalOrRadial ? layout.startAngle : 0,
  38462. endAngle: isHorizontalOrRadial ? layout.endAngle : Math.PI * 2
  38463. };
  38464. }
  38465. else {
  38466. return {
  38467. x: isHorizontalOrRadial ? layout.x : coordLayout.x,
  38468. y: isHorizontalOrRadial ? coordLayout.y : layout.y,
  38469. width: isHorizontalOrRadial ? layout.width : coordLayout.width,
  38470. height: isHorizontalOrRadial ? coordLayout.height : layout.height
  38471. };
  38472. }
  38473. }
  38474. function createBackgroundEl(coord, isHorizontalOrRadial, layout) {
  38475. var ElementClz = coord.type === 'polar' ? Sector : Rect;
  38476. return new ElementClz({
  38477. shape: createBackgroundShape(isHorizontalOrRadial, layout, coord),
  38478. silent: true,
  38479. z2: 0
  38480. });
  38481. }
  38482. /*
  38483. * Licensed to the Apache Software Foundation (ASF) under one
  38484. * or more contributor license agreements. See the NOTICE file
  38485. * distributed with this work for additional information
  38486. * regarding copyright ownership. The ASF licenses this file
  38487. * to you under the Apache License, Version 2.0 (the
  38488. * "License"); you may not use this file except in compliance
  38489. * with the License. You may obtain a copy of the License at
  38490. *
  38491. * http://www.apache.org/licenses/LICENSE-2.0
  38492. *
  38493. * Unless required by applicable law or agreed to in writing,
  38494. * software distributed under the License is distributed on an
  38495. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38496. * KIND, either express or implied. See the License for the
  38497. * specific language governing permissions and limitations
  38498. * under the License.
  38499. */
  38500. // In case developer forget to include grid component
  38501. registerLayout(PRIORITY.VISUAL.LAYOUT, curry(layout, 'bar'));
  38502. // Use higher prority to avoid to be blocked by other overall layout, which do not
  38503. // only exist in this module, but probably also exist in other modules, like `barPolar`.
  38504. registerLayout(PRIORITY.VISUAL.PROGRESSIVE_LAYOUT, largeLayout);
  38505. registerVisual({
  38506. seriesType: 'bar',
  38507. reset: function (seriesModel) {
  38508. // Visual coding for legend
  38509. seriesModel.getData().setVisual('legendSymbol', 'roundRect');
  38510. }
  38511. });
  38512. /*
  38513. * Licensed to the Apache Software Foundation (ASF) under one
  38514. * or more contributor license agreements. See the NOTICE file
  38515. * distributed with this work for additional information
  38516. * regarding copyright ownership. The ASF licenses this file
  38517. * to you under the Apache License, Version 2.0 (the
  38518. * "License"); you may not use this file except in compliance
  38519. * with the License. You may obtain a copy of the License at
  38520. *
  38521. * http://www.apache.org/licenses/LICENSE-2.0
  38522. *
  38523. * Unless required by applicable law or agreed to in writing,
  38524. * software distributed under the License is distributed on an
  38525. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38526. * KIND, either express or implied. See the License for the
  38527. * specific language governing permissions and limitations
  38528. * under the License.
  38529. */
  38530. /**
  38531. * [Usage]:
  38532. * (1)
  38533. * createListSimply(seriesModel, ['value']);
  38534. * (2)
  38535. * createListSimply(seriesModel, {
  38536. * coordDimensions: ['value'],
  38537. * dimensionsCount: 5
  38538. * });
  38539. *
  38540. * @param {module:echarts/model/Series} seriesModel
  38541. * @param {Object|Array.<string|Object>} opt opt or coordDimensions
  38542. * The options in opt, see `echarts/data/helper/createDimensions`
  38543. * @param {Array.<string>} [nameList]
  38544. * @return {module:echarts/data/List}
  38545. */
  38546. var createListSimply = function (seriesModel, opt, nameList) {
  38547. opt = isArray(opt) && {coordDimensions: opt} || extend({}, opt);
  38548. var source = seriesModel.getSource();
  38549. var dimensionsInfo = createDimensions(source, opt);
  38550. var list = new List(dimensionsInfo, seriesModel);
  38551. list.initData(source, nameList);
  38552. return list;
  38553. };
  38554. /*
  38555. * Licensed to the Apache Software Foundation (ASF) under one
  38556. * or more contributor license agreements. See the NOTICE file
  38557. * distributed with this work for additional information
  38558. * regarding copyright ownership. The ASF licenses this file
  38559. * to you under the Apache License, Version 2.0 (the
  38560. * "License"); you may not use this file except in compliance
  38561. * with the License. You may obtain a copy of the License at
  38562. *
  38563. * http://www.apache.org/licenses/LICENSE-2.0
  38564. *
  38565. * Unless required by applicable law or agreed to in writing,
  38566. * software distributed under the License is distributed on an
  38567. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38568. * KIND, either express or implied. See the License for the
  38569. * specific language governing permissions and limitations
  38570. * under the License.
  38571. */
  38572. /**
  38573. * Data selectable mixin for chart series.
  38574. * To eanble data select, option of series must have `selectedMode`.
  38575. * And each data item will use `selected` to toggle itself selected status
  38576. */
  38577. var selectableMixin = {
  38578. /**
  38579. * @param {Array.<Object>} targetList [{name, value, selected}, ...]
  38580. * If targetList is an array, it should like [{name: ..., value: ...}, ...].
  38581. * If targetList is a "List", it must have coordDim: 'value' dimension and name.
  38582. */
  38583. updateSelectedMap: function (targetList) {
  38584. this._targetList = isArray(targetList) ? targetList.slice() : [];
  38585. this._selectTargetMap = reduce(targetList || [], function (targetMap, target) {
  38586. targetMap.set(target.name, target);
  38587. return targetMap;
  38588. }, createHashMap());
  38589. },
  38590. /**
  38591. * Either name or id should be passed as input here.
  38592. * If both of them are defined, id is used.
  38593. *
  38594. * @param {string|undefined} name name of data
  38595. * @param {number|undefined} id dataIndex of data
  38596. */
  38597. // PENGING If selectedMode is null ?
  38598. select: function (name, id) {
  38599. var target = id != null
  38600. ? this._targetList[id]
  38601. : this._selectTargetMap.get(name);
  38602. var selectedMode = this.get('selectedMode');
  38603. if (selectedMode === 'single') {
  38604. this._selectTargetMap.each(function (target) {
  38605. target.selected = false;
  38606. });
  38607. }
  38608. target && (target.selected = true);
  38609. },
  38610. /**
  38611. * Either name or id should be passed as input here.
  38612. * If both of them are defined, id is used.
  38613. *
  38614. * @param {string|undefined} name name of data
  38615. * @param {number|undefined} id dataIndex of data
  38616. */
  38617. unSelect: function (name, id) {
  38618. var target = id != null
  38619. ? this._targetList[id]
  38620. : this._selectTargetMap.get(name);
  38621. // var selectedMode = this.get('selectedMode');
  38622. // selectedMode !== 'single' && target && (target.selected = false);
  38623. target && (target.selected = false);
  38624. },
  38625. /**
  38626. * Either name or id should be passed as input here.
  38627. * If both of them are defined, id is used.
  38628. *
  38629. * @param {string|undefined} name name of data
  38630. * @param {number|undefined} id dataIndex of data
  38631. */
  38632. toggleSelected: function (name, id) {
  38633. var target = id != null
  38634. ? this._targetList[id]
  38635. : this._selectTargetMap.get(name);
  38636. if (target != null) {
  38637. this[target.selected ? 'unSelect' : 'select'](name, id);
  38638. return target.selected;
  38639. }
  38640. },
  38641. /**
  38642. * Either name or id should be passed as input here.
  38643. * If both of them are defined, id is used.
  38644. *
  38645. * @param {string|undefined} name name of data
  38646. * @param {number|undefined} id dataIndex of data
  38647. */
  38648. isSelected: function (name, id) {
  38649. var target = id != null
  38650. ? this._targetList[id]
  38651. : this._selectTargetMap.get(name);
  38652. return target && target.selected;
  38653. }
  38654. };
  38655. /*
  38656. * Licensed to the Apache Software Foundation (ASF) under one
  38657. * or more contributor license agreements. See the NOTICE file
  38658. * distributed with this work for additional information
  38659. * regarding copyright ownership. The ASF licenses this file
  38660. * to you under the Apache License, Version 2.0 (the
  38661. * "License"); you may not use this file except in compliance
  38662. * with the License. You may obtain a copy of the License at
  38663. *
  38664. * http://www.apache.org/licenses/LICENSE-2.0
  38665. *
  38666. * Unless required by applicable law or agreed to in writing,
  38667. * software distributed under the License is distributed on an
  38668. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38669. * KIND, either express or implied. See the License for the
  38670. * specific language governing permissions and limitations
  38671. * under the License.
  38672. */
  38673. /**
  38674. * LegendVisualProvider is an bridge that pick encoded color from data and
  38675. * provide to the legend component.
  38676. * @param {Function} getDataWithEncodedVisual Function to get data after filtered. It stores all the encoding info
  38677. * @param {Function} getRawData Function to get raw data before filtered.
  38678. */
  38679. function LegendVisualProvider(getDataWithEncodedVisual, getRawData) {
  38680. this.getAllNames = function () {
  38681. var rawData = getRawData();
  38682. // We find the name from the raw data. In case it's filtered by the legend component.
  38683. // Normally, the name can be found in rawData, but can't be found in filtered data will display as gray.
  38684. return rawData.mapArray(rawData.getName);
  38685. };
  38686. this.containName = function (name) {
  38687. var rawData = getRawData();
  38688. return rawData.indexOfName(name) >= 0;
  38689. };
  38690. this.indexOfName = function (name) {
  38691. // Only get data when necessary.
  38692. // Because LegendVisualProvider constructor may be new in the stage that data is not prepared yet.
  38693. // Invoking Series#getData immediately will throw an error.
  38694. var dataWithEncodedVisual = getDataWithEncodedVisual();
  38695. return dataWithEncodedVisual.indexOfName(name);
  38696. };
  38697. this.getItemVisual = function (dataIndex, key) {
  38698. // Get encoded visual properties from final filtered data.
  38699. var dataWithEncodedVisual = getDataWithEncodedVisual();
  38700. return dataWithEncodedVisual.getItemVisual(dataIndex, key);
  38701. };
  38702. }
  38703. /*
  38704. * Licensed to the Apache Software Foundation (ASF) under one
  38705. * or more contributor license agreements. See the NOTICE file
  38706. * distributed with this work for additional information
  38707. * regarding copyright ownership. The ASF licenses this file
  38708. * to you under the Apache License, Version 2.0 (the
  38709. * "License"); you may not use this file except in compliance
  38710. * with the License. You may obtain a copy of the License at
  38711. *
  38712. * http://www.apache.org/licenses/LICENSE-2.0
  38713. *
  38714. * Unless required by applicable law or agreed to in writing,
  38715. * software distributed under the License is distributed on an
  38716. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38717. * KIND, either express or implied. See the License for the
  38718. * specific language governing permissions and limitations
  38719. * under the License.
  38720. */
  38721. var PieSeries = extendSeriesModel({
  38722. type: 'series.pie',
  38723. // Overwrite
  38724. init: function (option) {
  38725. PieSeries.superApply(this, 'init', arguments);
  38726. // Enable legend selection for each data item
  38727. // Use a function instead of direct access because data reference may changed
  38728. this.legendVisualProvider = new LegendVisualProvider(
  38729. bind(this.getData, this), bind(this.getRawData, this)
  38730. );
  38731. this.updateSelectedMap(this._createSelectableList());
  38732. this._defaultLabelLine(option);
  38733. },
  38734. // Overwrite
  38735. mergeOption: function (newOption) {
  38736. PieSeries.superCall(this, 'mergeOption', newOption);
  38737. this.updateSelectedMap(this._createSelectableList());
  38738. },
  38739. getInitialData: function (option, ecModel) {
  38740. return createListSimply(this, {
  38741. coordDimensions: ['value'],
  38742. encodeDefaulter: curry(makeSeriesEncodeForNameBased, this)
  38743. });
  38744. },
  38745. _createSelectableList: function () {
  38746. var data = this.getRawData();
  38747. var valueDim = data.mapDimension('value');
  38748. var targetList = [];
  38749. for (var i = 0, len = data.count(); i < len; i++) {
  38750. targetList.push({
  38751. name: data.getName(i),
  38752. value: data.get(valueDim, i),
  38753. selected: retrieveRawAttr(data, i, 'selected')
  38754. });
  38755. }
  38756. return targetList;
  38757. },
  38758. // Overwrite
  38759. getDataParams: function (dataIndex) {
  38760. var data = this.getData();
  38761. var params = PieSeries.superCall(this, 'getDataParams', dataIndex);
  38762. // FIXME toFixed?
  38763. var valueList = [];
  38764. data.each(data.mapDimension('value'), function (value) {
  38765. valueList.push(value);
  38766. });
  38767. params.percent = getPercentWithPrecision(
  38768. valueList,
  38769. dataIndex,
  38770. data.hostModel.get('percentPrecision')
  38771. );
  38772. params.$vars.push('percent');
  38773. return params;
  38774. },
  38775. _defaultLabelLine: function (option) {
  38776. // Extend labelLine emphasis
  38777. defaultEmphasis(option, 'labelLine', ['show']);
  38778. var labelLineNormalOpt = option.labelLine;
  38779. var labelLineEmphasisOpt = option.emphasis.labelLine;
  38780. // Not show label line if `label.normal.show = false`
  38781. labelLineNormalOpt.show = labelLineNormalOpt.show
  38782. && option.label.show;
  38783. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show
  38784. && option.emphasis.label.show;
  38785. },
  38786. defaultOption: {
  38787. zlevel: 0,
  38788. z: 2,
  38789. legendHoverLink: true,
  38790. hoverAnimation: true,
  38791. // 默认全局居中
  38792. center: ['50%', '50%'],
  38793. radius: [0, '75%'],
  38794. // 默认顺时针
  38795. clockwise: true,
  38796. startAngle: 90,
  38797. // 最小角度改为0
  38798. minAngle: 0,
  38799. // If the angle of a sector less than `minShowLabelAngle`,
  38800. // the label will not be displayed.
  38801. minShowLabelAngle: 0,
  38802. // 选中时扇区偏移量
  38803. selectedOffset: 10,
  38804. // 高亮扇区偏移量
  38805. hoverOffset: 10,
  38806. // If use strategy to avoid label overlapping
  38807. avoidLabelOverlap: true,
  38808. // 选择模式,默认关闭,可选single,multiple
  38809. // selectedMode: false,
  38810. // 南丁格尔玫瑰图模式,'radius'(半径) | 'area'(面积)
  38811. // roseType: null,
  38812. percentPrecision: 2,
  38813. // If still show when all data zero.
  38814. stillShowZeroSum: true,
  38815. // cursor: null,
  38816. left: 0,
  38817. top: 0,
  38818. right: 0,
  38819. bottom: 0,
  38820. width: null,
  38821. height: null,
  38822. label: {
  38823. // If rotate around circle
  38824. rotate: false,
  38825. show: true,
  38826. // 'outer', 'inside', 'center'
  38827. position: 'outer',
  38828. // 'none', 'labelLine', 'edge'. Works only when position is 'outer'
  38829. alignTo: 'none',
  38830. // Closest distance between label and chart edge.
  38831. // Works only position is 'outer' and alignTo is 'edge'.
  38832. margin: '25%',
  38833. // Works only position is 'outer' and alignTo is not 'edge'.
  38834. bleedMargin: 10,
  38835. // Distance between text and label line.
  38836. distanceToLabelLine: 5
  38837. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  38838. // 默认使用全局文本样式,详见TEXTSTYLE
  38839. // distance: 当position为inner时有效,为label位置到圆心的距离与圆半径(环状图为内外半径和)的比例系数
  38840. },
  38841. // Enabled when label.normal.position is 'outer'
  38842. labelLine: {
  38843. show: true,
  38844. // 引导线两段中的第一段长度
  38845. length: 15,
  38846. // 引导线两段中的第二段长度
  38847. length2: 15,
  38848. smooth: false,
  38849. lineStyle: {
  38850. // color: 各异,
  38851. width: 1,
  38852. type: 'solid'
  38853. }
  38854. },
  38855. itemStyle: {
  38856. borderWidth: 1
  38857. },
  38858. // Animation type. Valid values: expansion, scale
  38859. animationType: 'expansion',
  38860. // Animation type when update. Valid values: transition, expansion
  38861. animationTypeUpdate: 'transition',
  38862. animationEasing: 'cubicOut'
  38863. }
  38864. });
  38865. mixin(PieSeries, selectableMixin);
  38866. /*
  38867. * Licensed to the Apache Software Foundation (ASF) under one
  38868. * or more contributor license agreements. See the NOTICE file
  38869. * distributed with this work for additional information
  38870. * regarding copyright ownership. The ASF licenses this file
  38871. * to you under the Apache License, Version 2.0 (the
  38872. * "License"); you may not use this file except in compliance
  38873. * with the License. You may obtain a copy of the License at
  38874. *
  38875. * http://www.apache.org/licenses/LICENSE-2.0
  38876. *
  38877. * Unless required by applicable law or agreed to in writing,
  38878. * software distributed under the License is distributed on an
  38879. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38880. * KIND, either express or implied. See the License for the
  38881. * specific language governing permissions and limitations
  38882. * under the License.
  38883. */
  38884. /**
  38885. * @param {module:echarts/model/Series} seriesModel
  38886. * @param {boolean} hasAnimation
  38887. * @inner
  38888. */
  38889. function updateDataSelected(uid, seriesModel, hasAnimation, api) {
  38890. var data = seriesModel.getData();
  38891. var dataIndex = this.dataIndex;
  38892. var name = data.getName(dataIndex);
  38893. var selectedOffset = seriesModel.get('selectedOffset');
  38894. api.dispatchAction({
  38895. type: 'pieToggleSelect',
  38896. from: uid,
  38897. name: name,
  38898. seriesId: seriesModel.id
  38899. });
  38900. data.each(function (idx) {
  38901. toggleItemSelected(
  38902. data.getItemGraphicEl(idx),
  38903. data.getItemLayout(idx),
  38904. seriesModel.isSelected(data.getName(idx)),
  38905. selectedOffset,
  38906. hasAnimation
  38907. );
  38908. });
  38909. }
  38910. /**
  38911. * @param {module:zrender/graphic/Sector} el
  38912. * @param {Object} layout
  38913. * @param {boolean} isSelected
  38914. * @param {number} selectedOffset
  38915. * @param {boolean} hasAnimation
  38916. * @inner
  38917. */
  38918. function toggleItemSelected(el, layout, isSelected, selectedOffset, hasAnimation) {
  38919. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  38920. var dx = Math.cos(midAngle);
  38921. var dy = Math.sin(midAngle);
  38922. var offset = isSelected ? selectedOffset : 0;
  38923. var position = [dx * offset, dy * offset];
  38924. hasAnimation
  38925. // animateTo will stop revious animation like update transition
  38926. ? el.animate()
  38927. .when(200, {
  38928. position: position
  38929. })
  38930. .start('bounceOut')
  38931. : el.attr('position', position);
  38932. }
  38933. /**
  38934. * Piece of pie including Sector, Label, LabelLine
  38935. * @constructor
  38936. * @extends {module:zrender/graphic/Group}
  38937. */
  38938. function PiePiece(data, idx) {
  38939. Group.call(this);
  38940. var sector = new Sector({
  38941. z2: 2
  38942. });
  38943. var polyline = new Polyline();
  38944. var text = new Text();
  38945. this.add(sector);
  38946. this.add(polyline);
  38947. this.add(text);
  38948. this.updateData(data, idx, true);
  38949. }
  38950. var piePieceProto = PiePiece.prototype;
  38951. piePieceProto.updateData = function (data, idx, firstCreate) {
  38952. var sector = this.childAt(0);
  38953. var labelLine = this.childAt(1);
  38954. var labelText = this.childAt(2);
  38955. var seriesModel = data.hostModel;
  38956. var itemModel = data.getItemModel(idx);
  38957. var layout = data.getItemLayout(idx);
  38958. var sectorShape = extend({}, layout);
  38959. sectorShape.label = null;
  38960. var animationTypeUpdate = seriesModel.getShallow('animationTypeUpdate');
  38961. if (firstCreate) {
  38962. sector.setShape(sectorShape);
  38963. var animationType = seriesModel.getShallow('animationType');
  38964. if (animationType === 'scale') {
  38965. sector.shape.r = layout.r0;
  38966. initProps(sector, {
  38967. shape: {
  38968. r: layout.r
  38969. }
  38970. }, seriesModel, idx);
  38971. }
  38972. // Expansion
  38973. else {
  38974. sector.shape.endAngle = layout.startAngle;
  38975. updateProps(sector, {
  38976. shape: {
  38977. endAngle: layout.endAngle
  38978. }
  38979. }, seriesModel, idx);
  38980. }
  38981. }
  38982. else {
  38983. if (animationTypeUpdate === 'expansion') {
  38984. // Sectors are set to be target shape and an overlaying clipPath is used for animation
  38985. sector.setShape(sectorShape);
  38986. }
  38987. else {
  38988. // Transition animation from the old shape
  38989. updateProps(sector, {
  38990. shape: sectorShape
  38991. }, seriesModel, idx);
  38992. }
  38993. }
  38994. // Update common style
  38995. var visualColor = data.getItemVisual(idx, 'color');
  38996. sector.useStyle(
  38997. defaults(
  38998. {
  38999. lineJoin: 'bevel',
  39000. fill: visualColor
  39001. },
  39002. itemModel.getModel('itemStyle').getItemStyle()
  39003. )
  39004. );
  39005. sector.hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  39006. var cursorStyle = itemModel.getShallow('cursor');
  39007. cursorStyle && sector.attr('cursor', cursorStyle);
  39008. // Toggle selected
  39009. toggleItemSelected(
  39010. this,
  39011. data.getItemLayout(idx),
  39012. seriesModel.isSelected(data.getName(idx)),
  39013. seriesModel.get('selectedOffset'),
  39014. seriesModel.get('animation')
  39015. );
  39016. // Label and text animation should be applied only for transition type animation when update
  39017. var withAnimation = !firstCreate && animationTypeUpdate === 'transition';
  39018. this._updateLabel(data, idx, withAnimation);
  39019. this.highDownOnUpdate = !seriesModel.get('silent')
  39020. ? function (fromState, toState) {
  39021. var hasAnimation = seriesModel.isAnimationEnabled() && itemModel.get('hoverAnimation');
  39022. if (toState === 'emphasis') {
  39023. labelLine.ignore = labelLine.hoverIgnore;
  39024. labelText.ignore = labelText.hoverIgnore;
  39025. // Sector may has animation of updating data. Force to move to the last frame
  39026. // Or it may stopped on the wrong shape
  39027. if (hasAnimation) {
  39028. sector.stopAnimation(true);
  39029. sector.animateTo({
  39030. shape: {
  39031. r: layout.r + seriesModel.get('hoverOffset')
  39032. }
  39033. }, 300, 'elasticOut');
  39034. }
  39035. }
  39036. else {
  39037. labelLine.ignore = labelLine.normalIgnore;
  39038. labelText.ignore = labelText.normalIgnore;
  39039. if (hasAnimation) {
  39040. sector.stopAnimation(true);
  39041. sector.animateTo({
  39042. shape: {
  39043. r: layout.r
  39044. }
  39045. }, 300, 'elasticOut');
  39046. }
  39047. }
  39048. }
  39049. : null;
  39050. setHoverStyle(this);
  39051. };
  39052. piePieceProto._updateLabel = function (data, idx, withAnimation) {
  39053. var labelLine = this.childAt(1);
  39054. var labelText = this.childAt(2);
  39055. var seriesModel = data.hostModel;
  39056. var itemModel = data.getItemModel(idx);
  39057. var layout = data.getItemLayout(idx);
  39058. var labelLayout = layout.label;
  39059. var visualColor = data.getItemVisual(idx, 'color');
  39060. if (!labelLayout || isNaN(labelLayout.x) || isNaN(labelLayout.y)) {
  39061. labelText.ignore = labelText.normalIgnore = labelText.hoverIgnore =
  39062. labelLine.ignore = labelLine.normalIgnore = labelLine.hoverIgnore = true;
  39063. return;
  39064. }
  39065. var targetLineShape = {
  39066. points: labelLayout.linePoints || [
  39067. [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y]
  39068. ]
  39069. };
  39070. var targetTextStyle = {
  39071. x: labelLayout.x,
  39072. y: labelLayout.y
  39073. };
  39074. if (withAnimation) {
  39075. updateProps(labelLine, {
  39076. shape: targetLineShape
  39077. }, seriesModel, idx);
  39078. updateProps(labelText, {
  39079. style: targetTextStyle
  39080. }, seriesModel, idx);
  39081. }
  39082. else {
  39083. labelLine.attr({
  39084. shape: targetLineShape
  39085. });
  39086. labelText.attr({
  39087. style: targetTextStyle
  39088. });
  39089. }
  39090. labelText.attr({
  39091. rotation: labelLayout.rotation,
  39092. origin: [labelLayout.x, labelLayout.y],
  39093. z2: 10
  39094. });
  39095. var labelModel = itemModel.getModel('label');
  39096. var labelHoverModel = itemModel.getModel('emphasis.label');
  39097. var labelLineModel = itemModel.getModel('labelLine');
  39098. var labelLineHoverModel = itemModel.getModel('emphasis.labelLine');
  39099. var visualColor = data.getItemVisual(idx, 'color');
  39100. setLabelStyle(
  39101. labelText.style, labelText.hoverStyle = {}, labelModel, labelHoverModel,
  39102. {
  39103. labelFetcher: data.hostModel,
  39104. labelDataIndex: idx,
  39105. defaultText: labelLayout.text,
  39106. autoColor: visualColor,
  39107. useInsideStyle: !!labelLayout.inside
  39108. },
  39109. {
  39110. textAlign: labelLayout.textAlign,
  39111. textVerticalAlign: labelLayout.verticalAlign,
  39112. opacity: data.getItemVisual(idx, 'opacity')
  39113. }
  39114. );
  39115. labelText.ignore = labelText.normalIgnore = !labelModel.get('show');
  39116. labelText.hoverIgnore = !labelHoverModel.get('show');
  39117. labelLine.ignore = labelLine.normalIgnore = !labelLineModel.get('show');
  39118. labelLine.hoverIgnore = !labelLineHoverModel.get('show');
  39119. // Default use item visual color
  39120. labelLine.setStyle({
  39121. stroke: visualColor,
  39122. opacity: data.getItemVisual(idx, 'opacity')
  39123. });
  39124. labelLine.setStyle(labelLineModel.getModel('lineStyle').getLineStyle());
  39125. labelLine.hoverStyle = labelLineHoverModel.getModel('lineStyle').getLineStyle();
  39126. var smooth = labelLineModel.get('smooth');
  39127. if (smooth && smooth === true) {
  39128. smooth = 0.4;
  39129. }
  39130. labelLine.setShape({
  39131. smooth: smooth
  39132. });
  39133. };
  39134. inherits(PiePiece, Group);
  39135. // Pie view
  39136. var PieView = Chart.extend({
  39137. type: 'pie',
  39138. init: function () {
  39139. var sectorGroup = new Group();
  39140. this._sectorGroup = sectorGroup;
  39141. },
  39142. render: function (seriesModel, ecModel, api, payload) {
  39143. if (payload && (payload.from === this.uid)) {
  39144. return;
  39145. }
  39146. var data = seriesModel.getData();
  39147. var oldData = this._data;
  39148. var group = this.group;
  39149. var hasAnimation = ecModel.get('animation');
  39150. var isFirstRender = !oldData;
  39151. var animationType = seriesModel.get('animationType');
  39152. var animationTypeUpdate = seriesModel.get('animationTypeUpdate');
  39153. var onSectorClick = curry(
  39154. updateDataSelected, this.uid, seriesModel, hasAnimation, api
  39155. );
  39156. var selectedMode = seriesModel.get('selectedMode');
  39157. data.diff(oldData)
  39158. .add(function (idx) {
  39159. var piePiece = new PiePiece(data, idx);
  39160. // Default expansion animation
  39161. if (isFirstRender && animationType !== 'scale') {
  39162. piePiece.eachChild(function (child) {
  39163. child.stopAnimation(true);
  39164. });
  39165. }
  39166. selectedMode && piePiece.on('click', onSectorClick);
  39167. data.setItemGraphicEl(idx, piePiece);
  39168. group.add(piePiece);
  39169. })
  39170. .update(function (newIdx, oldIdx) {
  39171. var piePiece = oldData.getItemGraphicEl(oldIdx);
  39172. if (!isFirstRender && animationTypeUpdate !== 'transition') {
  39173. piePiece.eachChild(function (child) {
  39174. child.stopAnimation(true);
  39175. });
  39176. }
  39177. piePiece.updateData(data, newIdx);
  39178. piePiece.off('click');
  39179. selectedMode && piePiece.on('click', onSectorClick);
  39180. group.add(piePiece);
  39181. data.setItemGraphicEl(newIdx, piePiece);
  39182. })
  39183. .remove(function (idx) {
  39184. var piePiece = oldData.getItemGraphicEl(idx);
  39185. group.remove(piePiece);
  39186. })
  39187. .execute();
  39188. if (
  39189. hasAnimation && data.count() > 0
  39190. && (isFirstRender ? animationType !== 'scale' : animationTypeUpdate !== 'transition')
  39191. ) {
  39192. var shape = data.getItemLayout(0);
  39193. for (var s = 1; isNaN(shape.startAngle) && s < data.count(); ++s) {
  39194. shape = data.getItemLayout(s);
  39195. }
  39196. var r = Math.max(api.getWidth(), api.getHeight()) / 2;
  39197. var removeClipPath = bind(group.removeClipPath, group);
  39198. group.setClipPath(this._createClipPath(
  39199. shape.cx, shape.cy, r, shape.startAngle, shape.clockwise, removeClipPath, seriesModel, isFirstRender
  39200. ));
  39201. }
  39202. else {
  39203. // clipPath is used in first-time animation, so remove it when otherwise. See: #8994
  39204. group.removeClipPath();
  39205. }
  39206. this._data = data;
  39207. },
  39208. dispose: function () {},
  39209. _createClipPath: function (
  39210. cx, cy, r, startAngle, clockwise, cb, seriesModel, isFirstRender
  39211. ) {
  39212. var clipPath = new Sector({
  39213. shape: {
  39214. cx: cx,
  39215. cy: cy,
  39216. r0: 0,
  39217. r: r,
  39218. startAngle: startAngle,
  39219. endAngle: startAngle,
  39220. clockwise: clockwise
  39221. }
  39222. });
  39223. var initOrUpdate = isFirstRender ? initProps : updateProps;
  39224. initOrUpdate(clipPath, {
  39225. shape: {
  39226. endAngle: startAngle + (clockwise ? 1 : -1) * Math.PI * 2
  39227. }
  39228. }, seriesModel, cb);
  39229. return clipPath;
  39230. },
  39231. /**
  39232. * @implement
  39233. */
  39234. containPoint: function (point, seriesModel) {
  39235. var data = seriesModel.getData();
  39236. var itemLayout = data.getItemLayout(0);
  39237. if (itemLayout) {
  39238. var dx = point[0] - itemLayout.cx;
  39239. var dy = point[1] - itemLayout.cy;
  39240. var radius = Math.sqrt(dx * dx + dy * dy);
  39241. return radius <= itemLayout.r && radius >= itemLayout.r0;
  39242. }
  39243. }
  39244. });
  39245. /*
  39246. * Licensed to the Apache Software Foundation (ASF) under one
  39247. * or more contributor license agreements. See the NOTICE file
  39248. * distributed with this work for additional information
  39249. * regarding copyright ownership. The ASF licenses this file
  39250. * to you under the Apache License, Version 2.0 (the
  39251. * "License"); you may not use this file except in compliance
  39252. * with the License. You may obtain a copy of the License at
  39253. *
  39254. * http://www.apache.org/licenses/LICENSE-2.0
  39255. *
  39256. * Unless required by applicable law or agreed to in writing,
  39257. * software distributed under the License is distributed on an
  39258. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39259. * KIND, either express or implied. See the License for the
  39260. * specific language governing permissions and limitations
  39261. * under the License.
  39262. */
  39263. var createDataSelectAction = function (seriesType, actionInfos) {
  39264. each$1(actionInfos, function (actionInfo) {
  39265. actionInfo.update = 'updateView';
  39266. /**
  39267. * @payload
  39268. * @property {string} seriesName
  39269. * @property {string} name
  39270. */
  39271. registerAction(actionInfo, function (payload, ecModel) {
  39272. var selected = {};
  39273. ecModel.eachComponent(
  39274. {mainType: 'series', subType: seriesType, query: payload},
  39275. function (seriesModel) {
  39276. if (seriesModel[actionInfo.method]) {
  39277. seriesModel[actionInfo.method](
  39278. payload.name,
  39279. payload.dataIndex
  39280. );
  39281. }
  39282. var data = seriesModel.getData();
  39283. // Create selected map
  39284. data.each(function (idx) {
  39285. var name = data.getName(idx);
  39286. selected[name] = seriesModel.isSelected(name)
  39287. || false;
  39288. });
  39289. }
  39290. );
  39291. return {
  39292. name: payload.name,
  39293. selected: selected,
  39294. seriesId: payload.seriesId
  39295. };
  39296. });
  39297. });
  39298. };
  39299. /*
  39300. * Licensed to the Apache Software Foundation (ASF) under one
  39301. * or more contributor license agreements. See the NOTICE file
  39302. * distributed with this work for additional information
  39303. * regarding copyright ownership. The ASF licenses this file
  39304. * to you under the Apache License, Version 2.0 (the
  39305. * "License"); you may not use this file except in compliance
  39306. * with the License. You may obtain a copy of the License at
  39307. *
  39308. * http://www.apache.org/licenses/LICENSE-2.0
  39309. *
  39310. * Unless required by applicable law or agreed to in writing,
  39311. * software distributed under the License is distributed on an
  39312. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39313. * KIND, either express or implied. See the License for the
  39314. * specific language governing permissions and limitations
  39315. * under the License.
  39316. */
  39317. // Pick color from palette for each data item.
  39318. // Applicable for charts that require applying color palette
  39319. // in data level (like pie, funnel, chord).
  39320. var dataColor = function (seriesType) {
  39321. return {
  39322. getTargetSeries: function (ecModel) {
  39323. // Pie and funnel may use diferrent scope
  39324. var paletteScope = {};
  39325. var seiresModelMap = createHashMap();
  39326. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  39327. seriesModel.__paletteScope = paletteScope;
  39328. seiresModelMap.set(seriesModel.uid, seriesModel);
  39329. });
  39330. return seiresModelMap;
  39331. },
  39332. reset: function (seriesModel, ecModel) {
  39333. var dataAll = seriesModel.getRawData();
  39334. var idxMap = {};
  39335. var data = seriesModel.getData();
  39336. data.each(function (idx) {
  39337. var rawIdx = data.getRawIndex(idx);
  39338. idxMap[rawIdx] = idx;
  39339. });
  39340. dataAll.each(function (rawIdx) {
  39341. var filteredIdx = idxMap[rawIdx];
  39342. // If series.itemStyle.normal.color is a function. itemVisual may be encoded
  39343. var singleDataColor = filteredIdx != null
  39344. && data.getItemVisual(filteredIdx, 'color', true);
  39345. var singleDataBorderColor = filteredIdx != null
  39346. && data.getItemVisual(filteredIdx, 'borderColor', true);
  39347. var itemModel;
  39348. if (!singleDataColor || !singleDataBorderColor) {
  39349. // FIXME Performance
  39350. itemModel = dataAll.getItemModel(rawIdx);
  39351. }
  39352. if (!singleDataColor) {
  39353. var color = itemModel.get('itemStyle.color')
  39354. || seriesModel.getColorFromPalette(
  39355. dataAll.getName(rawIdx) || (rawIdx + ''), seriesModel.__paletteScope,
  39356. dataAll.count()
  39357. );
  39358. // Data is not filtered
  39359. if (filteredIdx != null) {
  39360. data.setItemVisual(filteredIdx, 'color', color);
  39361. }
  39362. }
  39363. if (!singleDataBorderColor) {
  39364. var borderColor = itemModel.get('itemStyle.borderColor');
  39365. // Data is not filtered
  39366. if (filteredIdx != null) {
  39367. data.setItemVisual(filteredIdx, 'borderColor', borderColor);
  39368. }
  39369. }
  39370. });
  39371. }
  39372. };
  39373. };
  39374. /*
  39375. * Licensed to the Apache Software Foundation (ASF) under one
  39376. * or more contributor license agreements. See the NOTICE file
  39377. * distributed with this work for additional information
  39378. * regarding copyright ownership. The ASF licenses this file
  39379. * to you under the Apache License, Version 2.0 (the
  39380. * "License"); you may not use this file except in compliance
  39381. * with the License. You may obtain a copy of the License at
  39382. *
  39383. * http://www.apache.org/licenses/LICENSE-2.0
  39384. *
  39385. * Unless required by applicable law or agreed to in writing,
  39386. * software distributed under the License is distributed on an
  39387. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39388. * KIND, either express or implied. See the License for the
  39389. * specific language governing permissions and limitations
  39390. * under the License.
  39391. */
  39392. // FIXME emphasis label position is not same with normal label position
  39393. var RADIAN$1 = Math.PI / 180;
  39394. function adjustSingleSide(list, cx, cy, r, dir, viewWidth, viewHeight, viewLeft, viewTop, farthestX) {
  39395. list.sort(function (a, b) {
  39396. return a.y - b.y;
  39397. });
  39398. function shiftDown(start, end, delta, dir) {
  39399. for (var j = start; j < end; j++) {
  39400. if (list[j].y + delta > viewTop + viewHeight) {
  39401. break;
  39402. }
  39403. list[j].y += delta;
  39404. if (j > start
  39405. && j + 1 < end
  39406. && list[j + 1].y > list[j].y + list[j].height
  39407. ) {
  39408. shiftUp(j, delta / 2);
  39409. return;
  39410. }
  39411. }
  39412. shiftUp(end - 1, delta / 2);
  39413. }
  39414. function shiftUp(end, delta) {
  39415. for (var j = end; j >= 0; j--) {
  39416. if (list[j].y - delta < viewTop) {
  39417. break;
  39418. }
  39419. list[j].y -= delta;
  39420. if (j > 0
  39421. && list[j].y > list[j - 1].y + list[j - 1].height
  39422. ) {
  39423. break;
  39424. }
  39425. }
  39426. }
  39427. function changeX(list, isDownList, cx, cy, r, dir) {
  39428. var lastDeltaX = dir > 0
  39429. ? isDownList // right-side
  39430. ? Number.MAX_VALUE // down
  39431. : 0 // up
  39432. : isDownList // left-side
  39433. ? Number.MAX_VALUE // down
  39434. : 0; // up
  39435. for (var i = 0, l = list.length; i < l; i++) {
  39436. if (list[i].labelAlignTo !== 'none') {
  39437. continue;
  39438. }
  39439. var deltaY = Math.abs(list[i].y - cy);
  39440. var length = list[i].len;
  39441. var length2 = list[i].len2;
  39442. var deltaX = (deltaY < r + length)
  39443. ? Math.sqrt(
  39444. (r + length + length2) * (r + length + length2)
  39445. - deltaY * deltaY
  39446. )
  39447. : Math.abs(list[i].x - cx);
  39448. if (isDownList && deltaX >= lastDeltaX) {
  39449. // right-down, left-down
  39450. deltaX = lastDeltaX - 10;
  39451. }
  39452. if (!isDownList && deltaX <= lastDeltaX) {
  39453. // right-up, left-up
  39454. deltaX = lastDeltaX + 10;
  39455. }
  39456. list[i].x = cx + deltaX * dir;
  39457. lastDeltaX = deltaX;
  39458. }
  39459. }
  39460. var lastY = 0;
  39461. var delta;
  39462. var len = list.length;
  39463. var upList = [];
  39464. var downList = [];
  39465. for (var i = 0; i < len; i++) {
  39466. if (list[i].position === 'outer' && list[i].labelAlignTo === 'labelLine') {
  39467. var dx = list[i].x - farthestX;
  39468. list[i].linePoints[1][0] += dx;
  39469. list[i].x = farthestX;
  39470. }
  39471. delta = list[i].y - lastY;
  39472. if (delta < 0) {
  39473. shiftDown(i, len, -delta, dir);
  39474. }
  39475. lastY = list[i].y + list[i].height;
  39476. }
  39477. if (viewHeight - lastY < 0) {
  39478. shiftUp(len - 1, lastY - viewHeight);
  39479. }
  39480. for (var i = 0; i < len; i++) {
  39481. if (list[i].y >= cy) {
  39482. downList.push(list[i]);
  39483. }
  39484. else {
  39485. upList.push(list[i]);
  39486. }
  39487. }
  39488. changeX(upList, false, cx, cy, r, dir);
  39489. changeX(downList, true, cx, cy, r, dir);
  39490. }
  39491. function avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight, viewLeft, viewTop) {
  39492. var leftList = [];
  39493. var rightList = [];
  39494. var leftmostX = Number.MAX_VALUE;
  39495. var rightmostX = -Number.MAX_VALUE;
  39496. for (var i = 0; i < labelLayoutList.length; i++) {
  39497. if (isPositionCenter(labelLayoutList[i])) {
  39498. continue;
  39499. }
  39500. if (labelLayoutList[i].x < cx) {
  39501. leftmostX = Math.min(leftmostX, labelLayoutList[i].x);
  39502. leftList.push(labelLayoutList[i]);
  39503. }
  39504. else {
  39505. rightmostX = Math.max(rightmostX, labelLayoutList[i].x);
  39506. rightList.push(labelLayoutList[i]);
  39507. }
  39508. }
  39509. adjustSingleSide(rightList, cx, cy, r, 1, viewWidth, viewHeight, viewLeft, viewTop, rightmostX);
  39510. adjustSingleSide(leftList, cx, cy, r, -1, viewWidth, viewHeight, viewLeft, viewTop, leftmostX);
  39511. for (var i = 0; i < labelLayoutList.length; i++) {
  39512. var layout = labelLayoutList[i];
  39513. if (isPositionCenter(layout)) {
  39514. continue;
  39515. }
  39516. var linePoints = layout.linePoints;
  39517. if (linePoints) {
  39518. var isAlignToEdge = layout.labelAlignTo === 'edge';
  39519. var realTextWidth = layout.textRect.width;
  39520. var targetTextWidth;
  39521. if (isAlignToEdge) {
  39522. if (layout.x < cx) {
  39523. targetTextWidth = linePoints[2][0] - layout.labelDistance
  39524. - viewLeft - layout.labelMargin;
  39525. }
  39526. else {
  39527. targetTextWidth = viewLeft + viewWidth - layout.labelMargin
  39528. - linePoints[2][0] - layout.labelDistance;
  39529. }
  39530. }
  39531. else {
  39532. if (layout.x < cx) {
  39533. targetTextWidth = layout.x - viewLeft - layout.bleedMargin;
  39534. }
  39535. else {
  39536. targetTextWidth = viewLeft + viewWidth - layout.x - layout.bleedMargin;
  39537. }
  39538. }
  39539. if (targetTextWidth < layout.textRect.width) {
  39540. layout.text = truncateText(layout.text, targetTextWidth, layout.font);
  39541. if (layout.labelAlignTo === 'edge') {
  39542. realTextWidth = getWidth(layout.text, layout.font);
  39543. }
  39544. }
  39545. var dist = linePoints[1][0] - linePoints[2][0];
  39546. if (isAlignToEdge) {
  39547. if (layout.x < cx) {
  39548. linePoints[2][0] = viewLeft + layout.labelMargin + realTextWidth + layout.labelDistance;
  39549. }
  39550. else {
  39551. linePoints[2][0] = viewLeft + viewWidth - layout.labelMargin
  39552. - realTextWidth - layout.labelDistance;
  39553. }
  39554. }
  39555. else {
  39556. if (layout.x < cx) {
  39557. linePoints[2][0] = layout.x + layout.labelDistance;
  39558. }
  39559. else {
  39560. linePoints[2][0] = layout.x - layout.labelDistance;
  39561. }
  39562. linePoints[1][0] = linePoints[2][0] + dist;
  39563. }
  39564. linePoints[1][1] = linePoints[2][1] = layout.y;
  39565. }
  39566. }
  39567. }
  39568. function isPositionCenter(layout) {
  39569. // Not change x for center label
  39570. return layout.position === 'center';
  39571. }
  39572. var labelLayout = function (seriesModel, r, viewWidth, viewHeight, viewLeft, viewTop) {
  39573. var data = seriesModel.getData();
  39574. var labelLayoutList = [];
  39575. var cx;
  39576. var cy;
  39577. var hasLabelRotate = false;
  39578. var minShowLabelRadian = (seriesModel.get('minShowLabelAngle') || 0) * RADIAN$1;
  39579. data.each(function (idx) {
  39580. var layout = data.getItemLayout(idx);
  39581. var itemModel = data.getItemModel(idx);
  39582. var labelModel = itemModel.getModel('label');
  39583. // Use position in normal or emphasis
  39584. var labelPosition = labelModel.get('position') || itemModel.get('emphasis.label.position');
  39585. var labelDistance = labelModel.get('distanceToLabelLine');
  39586. var labelAlignTo = labelModel.get('alignTo');
  39587. var labelMargin = parsePercent$1(labelModel.get('margin'), viewWidth);
  39588. var bleedMargin = labelModel.get('bleedMargin');
  39589. var font = labelModel.getFont();
  39590. var labelLineModel = itemModel.getModel('labelLine');
  39591. var labelLineLen = labelLineModel.get('length');
  39592. labelLineLen = parsePercent$1(labelLineLen, viewWidth);
  39593. var labelLineLen2 = labelLineModel.get('length2');
  39594. labelLineLen2 = parsePercent$1(labelLineLen2, viewWidth);
  39595. if (layout.angle < minShowLabelRadian) {
  39596. return;
  39597. }
  39598. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  39599. var dx = Math.cos(midAngle);
  39600. var dy = Math.sin(midAngle);
  39601. var textX;
  39602. var textY;
  39603. var linePoints;
  39604. var textAlign;
  39605. cx = layout.cx;
  39606. cy = layout.cy;
  39607. var text = seriesModel.getFormattedLabel(idx, 'normal')
  39608. || data.getName(idx);
  39609. var textRect = getBoundingRect(
  39610. text, font, textAlign, 'top'
  39611. );
  39612. var isLabelInside = labelPosition === 'inside' || labelPosition === 'inner';
  39613. if (labelPosition === 'center') {
  39614. textX = layout.cx;
  39615. textY = layout.cy;
  39616. textAlign = 'center';
  39617. }
  39618. else {
  39619. var x1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dx : layout.r * dx) + cx;
  39620. var y1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dy : layout.r * dy) + cy;
  39621. textX = x1 + dx * 3;
  39622. textY = y1 + dy * 3;
  39623. if (!isLabelInside) {
  39624. // For roseType
  39625. var x2 = x1 + dx * (labelLineLen + r - layout.r);
  39626. var y2 = y1 + dy * (labelLineLen + r - layout.r);
  39627. var x3 = x2 + ((dx < 0 ? -1 : 1) * labelLineLen2);
  39628. var y3 = y2;
  39629. if (labelAlignTo === 'edge') {
  39630. // Adjust textX because text align of edge is opposite
  39631. textX = dx < 0
  39632. ? viewLeft + labelMargin
  39633. : viewLeft + viewWidth - labelMargin;
  39634. }
  39635. else {
  39636. textX = x3 + (dx < 0 ? -labelDistance : labelDistance);
  39637. }
  39638. textY = y3;
  39639. linePoints = [[x1, y1], [x2, y2], [x3, y3]];
  39640. }
  39641. textAlign = isLabelInside
  39642. ? 'center'
  39643. : (labelAlignTo === 'edge'
  39644. ? (dx > 0 ? 'right' : 'left')
  39645. : (dx > 0 ? 'left' : 'right'));
  39646. }
  39647. var labelRotate;
  39648. var rotate = labelModel.get('rotate');
  39649. if (typeof rotate === 'number') {
  39650. labelRotate = rotate * (Math.PI / 180);
  39651. }
  39652. else {
  39653. labelRotate = rotate
  39654. ? (dx < 0 ? -midAngle + Math.PI : -midAngle)
  39655. : 0;
  39656. }
  39657. hasLabelRotate = !!labelRotate;
  39658. layout.label = {
  39659. x: textX,
  39660. y: textY,
  39661. position: labelPosition,
  39662. height: textRect.height,
  39663. len: labelLineLen,
  39664. len2: labelLineLen2,
  39665. linePoints: linePoints,
  39666. textAlign: textAlign,
  39667. verticalAlign: 'middle',
  39668. rotation: labelRotate,
  39669. inside: isLabelInside,
  39670. labelDistance: labelDistance,
  39671. labelAlignTo: labelAlignTo,
  39672. labelMargin: labelMargin,
  39673. bleedMargin: bleedMargin,
  39674. textRect: textRect,
  39675. text: text,
  39676. font: font
  39677. };
  39678. // Not layout the inside label
  39679. if (!isLabelInside) {
  39680. labelLayoutList.push(layout.label);
  39681. }
  39682. });
  39683. if (!hasLabelRotate && seriesModel.get('avoidLabelOverlap')) {
  39684. avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight, viewLeft, viewTop);
  39685. }
  39686. };
  39687. /*
  39688. * Licensed to the Apache Software Foundation (ASF) under one
  39689. * or more contributor license agreements. See the NOTICE file
  39690. * distributed with this work for additional information
  39691. * regarding copyright ownership. The ASF licenses this file
  39692. * to you under the Apache License, Version 2.0 (the
  39693. * "License"); you may not use this file except in compliance
  39694. * with the License. You may obtain a copy of the License at
  39695. *
  39696. * http://www.apache.org/licenses/LICENSE-2.0
  39697. *
  39698. * Unless required by applicable law or agreed to in writing,
  39699. * software distributed under the License is distributed on an
  39700. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39701. * KIND, either express or implied. See the License for the
  39702. * specific language governing permissions and limitations
  39703. * under the License.
  39704. */
  39705. var PI2$4 = Math.PI * 2;
  39706. var RADIAN = Math.PI / 180;
  39707. function getViewRect(seriesModel, api) {
  39708. return getLayoutRect(
  39709. seriesModel.getBoxLayoutParams(), {
  39710. width: api.getWidth(),
  39711. height: api.getHeight()
  39712. }
  39713. );
  39714. }
  39715. var pieLayout = function (seriesType, ecModel, api, payload) {
  39716. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  39717. var data = seriesModel.getData();
  39718. var valueDim = data.mapDimension('value');
  39719. var viewRect = getViewRect(seriesModel, api);
  39720. var center = seriesModel.get('center');
  39721. var radius = seriesModel.get('radius');
  39722. if (!isArray(radius)) {
  39723. radius = [0, radius];
  39724. }
  39725. if (!isArray(center)) {
  39726. center = [center, center];
  39727. }
  39728. var width = parsePercent$1(viewRect.width, api.getWidth());
  39729. var height = parsePercent$1(viewRect.height, api.getHeight());
  39730. var size = Math.min(width, height);
  39731. var cx = parsePercent$1(center[0], width) + viewRect.x;
  39732. var cy = parsePercent$1(center[1], height) + viewRect.y;
  39733. var r0 = parsePercent$1(radius[0], size / 2);
  39734. var r = parsePercent$1(radius[1], size / 2);
  39735. var startAngle = -seriesModel.get('startAngle') * RADIAN;
  39736. var minAngle = seriesModel.get('minAngle') * RADIAN;
  39737. var validDataCount = 0;
  39738. data.each(valueDim, function (value) {
  39739. !isNaN(value) && validDataCount++;
  39740. });
  39741. var sum = data.getSum(valueDim);
  39742. // Sum may be 0
  39743. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  39744. var clockwise = seriesModel.get('clockwise');
  39745. var roseType = seriesModel.get('roseType');
  39746. var stillShowZeroSum = seriesModel.get('stillShowZeroSum');
  39747. // [0...max]
  39748. var extent = data.getDataExtent(valueDim);
  39749. extent[0] = 0;
  39750. // In the case some sector angle is smaller than minAngle
  39751. var restAngle = PI2$4;
  39752. var valueSumLargerThanMinAngle = 0;
  39753. var currentAngle = startAngle;
  39754. var dir = clockwise ? 1 : -1;
  39755. data.each(valueDim, function (value, idx) {
  39756. var angle;
  39757. if (isNaN(value)) {
  39758. data.setItemLayout(idx, {
  39759. angle: NaN,
  39760. startAngle: NaN,
  39761. endAngle: NaN,
  39762. clockwise: clockwise,
  39763. cx: cx,
  39764. cy: cy,
  39765. r0: r0,
  39766. r: roseType
  39767. ? NaN
  39768. : r,
  39769. viewRect: viewRect
  39770. });
  39771. return;
  39772. }
  39773. // FIXME 兼容 2.0 但是 roseType 是 area 的时候才是这样?
  39774. if (roseType !== 'area') {
  39775. angle = (sum === 0 && stillShowZeroSum)
  39776. ? unitRadian : (value * unitRadian);
  39777. }
  39778. else {
  39779. angle = PI2$4 / validDataCount;
  39780. }
  39781. if (angle < minAngle) {
  39782. angle = minAngle;
  39783. restAngle -= minAngle;
  39784. }
  39785. else {
  39786. valueSumLargerThanMinAngle += value;
  39787. }
  39788. var endAngle = currentAngle + dir * angle;
  39789. data.setItemLayout(idx, {
  39790. angle: angle,
  39791. startAngle: currentAngle,
  39792. endAngle: endAngle,
  39793. clockwise: clockwise,
  39794. cx: cx,
  39795. cy: cy,
  39796. r0: r0,
  39797. r: roseType
  39798. ? linearMap(value, extent, [r0, r])
  39799. : r,
  39800. viewRect: viewRect
  39801. });
  39802. currentAngle = endAngle;
  39803. });
  39804. // Some sector is constrained by minAngle
  39805. // Rest sectors needs recalculate angle
  39806. if (restAngle < PI2$4 && validDataCount) {
  39807. // Average the angle if rest angle is not enough after all angles is
  39808. // Constrained by minAngle
  39809. if (restAngle <= 1e-3) {
  39810. var angle = PI2$4 / validDataCount;
  39811. data.each(valueDim, function (value, idx) {
  39812. if (!isNaN(value)) {
  39813. var layout = data.getItemLayout(idx);
  39814. layout.angle = angle;
  39815. layout.startAngle = startAngle + dir * idx * angle;
  39816. layout.endAngle = startAngle + dir * (idx + 1) * angle;
  39817. }
  39818. });
  39819. }
  39820. else {
  39821. unitRadian = restAngle / valueSumLargerThanMinAngle;
  39822. currentAngle = startAngle;
  39823. data.each(valueDim, function (value, idx) {
  39824. if (!isNaN(value)) {
  39825. var layout = data.getItemLayout(idx);
  39826. var angle = layout.angle === minAngle
  39827. ? minAngle : value * unitRadian;
  39828. layout.startAngle = currentAngle;
  39829. layout.endAngle = currentAngle + dir * angle;
  39830. currentAngle += dir * angle;
  39831. }
  39832. });
  39833. }
  39834. }
  39835. labelLayout(seriesModel, r, viewRect.width, viewRect.height, viewRect.x, viewRect.y);
  39836. });
  39837. };
  39838. /*
  39839. * Licensed to the Apache Software Foundation (ASF) under one
  39840. * or more contributor license agreements. See the NOTICE file
  39841. * distributed with this work for additional information
  39842. * regarding copyright ownership. The ASF licenses this file
  39843. * to you under the Apache License, Version 2.0 (the
  39844. * "License"); you may not use this file except in compliance
  39845. * with the License. You may obtain a copy of the License at
  39846. *
  39847. * http://www.apache.org/licenses/LICENSE-2.0
  39848. *
  39849. * Unless required by applicable law or agreed to in writing,
  39850. * software distributed under the License is distributed on an
  39851. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39852. * KIND, either express or implied. See the License for the
  39853. * specific language governing permissions and limitations
  39854. * under the License.
  39855. */
  39856. var dataFilter = function (seriesType) {
  39857. return {
  39858. seriesType: seriesType,
  39859. reset: function (seriesModel, ecModel) {
  39860. var legendModels = ecModel.findComponents({
  39861. mainType: 'legend'
  39862. });
  39863. if (!legendModels || !legendModels.length) {
  39864. return;
  39865. }
  39866. var data = seriesModel.getData();
  39867. data.filterSelf(function (idx) {
  39868. var name = data.getName(idx);
  39869. // If in any legend component the status is not selected.
  39870. for (var i = 0; i < legendModels.length; i++) {
  39871. if (!legendModels[i].isSelected(name)) {
  39872. return false;
  39873. }
  39874. }
  39875. return true;
  39876. });
  39877. }
  39878. };
  39879. };
  39880. /*
  39881. * Licensed to the Apache Software Foundation (ASF) under one
  39882. * or more contributor license agreements. See the NOTICE file
  39883. * distributed with this work for additional information
  39884. * regarding copyright ownership. The ASF licenses this file
  39885. * to you under the Apache License, Version 2.0 (the
  39886. * "License"); you may not use this file except in compliance
  39887. * with the License. You may obtain a copy of the License at
  39888. *
  39889. * http://www.apache.org/licenses/LICENSE-2.0
  39890. *
  39891. * Unless required by applicable law or agreed to in writing,
  39892. * software distributed under the License is distributed on an
  39893. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39894. * KIND, either express or implied. See the License for the
  39895. * specific language governing permissions and limitations
  39896. * under the License.
  39897. */
  39898. createDataSelectAction('pie', [{
  39899. type: 'pieToggleSelect',
  39900. event: 'pieselectchanged',
  39901. method: 'toggleSelected'
  39902. }, {
  39903. type: 'pieSelect',
  39904. event: 'pieselected',
  39905. method: 'select'
  39906. }, {
  39907. type: 'pieUnSelect',
  39908. event: 'pieunselected',
  39909. method: 'unSelect'
  39910. }]);
  39911. registerVisual(dataColor('pie'));
  39912. registerLayout(curry(pieLayout, 'pie'));
  39913. registerProcessor(dataFilter('pie'));
  39914. /*
  39915. * Licensed to the Apache Software Foundation (ASF) under one
  39916. * or more contributor license agreements. See the NOTICE file
  39917. * distributed with this work for additional information
  39918. * regarding copyright ownership. The ASF licenses this file
  39919. * to you under the Apache License, Version 2.0 (the
  39920. * "License"); you may not use this file except in compliance
  39921. * with the License. You may obtain a copy of the License at
  39922. *
  39923. * http://www.apache.org/licenses/LICENSE-2.0
  39924. *
  39925. * Unless required by applicable law or agreed to in writing,
  39926. * software distributed under the License is distributed on an
  39927. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39928. * KIND, either express or implied. See the License for the
  39929. * specific language governing permissions and limitations
  39930. * under the License.
  39931. */
  39932. SeriesModel.extend({
  39933. type: 'series.scatter',
  39934. dependencies: ['grid', 'polar', 'geo', 'singleAxis', 'calendar'],
  39935. getInitialData: function (option, ecModel) {
  39936. return createListFromArray(this.getSource(), this, {useEncodeDefaulter: true});
  39937. },
  39938. brushSelector: 'point',
  39939. getProgressive: function () {
  39940. var progressive = this.option.progressive;
  39941. if (progressive == null) {
  39942. // PENDING
  39943. return this.option.large ? 5e3 : this.get('progressive');
  39944. }
  39945. return progressive;
  39946. },
  39947. getProgressiveThreshold: function () {
  39948. var progressiveThreshold = this.option.progressiveThreshold;
  39949. if (progressiveThreshold == null) {
  39950. // PENDING
  39951. return this.option.large ? 1e4 : this.get('progressiveThreshold');
  39952. }
  39953. return progressiveThreshold;
  39954. },
  39955. defaultOption: {
  39956. coordinateSystem: 'cartesian2d',
  39957. zlevel: 0,
  39958. z: 2,
  39959. legendHoverLink: true,
  39960. hoverAnimation: true,
  39961. // Cartesian coordinate system
  39962. // xAxisIndex: 0,
  39963. // yAxisIndex: 0,
  39964. // Polar coordinate system
  39965. // polarIndex: 0,
  39966. // Geo coordinate system
  39967. // geoIndex: 0,
  39968. // symbol: null, // 图形类型
  39969. symbolSize: 10, // 图形大小,半宽(半径)参数,当图形为方向或菱形则总宽度为symbolSize * 2
  39970. // symbolRotate: null, // 图形旋转控制
  39971. large: false,
  39972. // Available when large is true
  39973. largeThreshold: 2000,
  39974. // cursor: null,
  39975. // label: {
  39976. // show: false
  39977. // distance: 5,
  39978. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  39979. // position: 默认自适应,水平布局为'top',垂直布局为'right',可选为
  39980. // 'inside'|'left'|'right'|'top'|'bottom'
  39981. // 默认使用全局文本样式,详见TEXTSTYLE
  39982. // },
  39983. itemStyle: {
  39984. opacity: 0.8
  39985. // color: 各异
  39986. },
  39987. // If clip the overflow graphics
  39988. // Works on cartesian / polar series
  39989. clip: true
  39990. // progressive: null
  39991. }
  39992. });
  39993. /*
  39994. * Licensed to the Apache Software Foundation (ASF) under one
  39995. * or more contributor license agreements. See the NOTICE file
  39996. * distributed with this work for additional information
  39997. * regarding copyright ownership. The ASF licenses this file
  39998. * to you under the Apache License, Version 2.0 (the
  39999. * "License"); you may not use this file except in compliance
  40000. * with the License. You may obtain a copy of the License at
  40001. *
  40002. * http://www.apache.org/licenses/LICENSE-2.0
  40003. *
  40004. * Unless required by applicable law or agreed to in writing,
  40005. * software distributed under the License is distributed on an
  40006. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40007. * KIND, either express or implied. See the License for the
  40008. * specific language governing permissions and limitations
  40009. * under the License.
  40010. */
  40011. /* global Float32Array */
  40012. // TODO Batch by color
  40013. var BOOST_SIZE_THRESHOLD = 4;
  40014. var LargeSymbolPath = extendShape({
  40015. shape: {
  40016. points: null
  40017. },
  40018. symbolProxy: null,
  40019. softClipShape: null,
  40020. buildPath: function (path, shape) {
  40021. var points = shape.points;
  40022. var size = shape.size;
  40023. var symbolProxy = this.symbolProxy;
  40024. var symbolProxyShape = symbolProxy.shape;
  40025. var ctx = path.getContext ? path.getContext() : path;
  40026. var canBoost = ctx && size[0] < BOOST_SIZE_THRESHOLD;
  40027. // Do draw in afterBrush.
  40028. if (canBoost) {
  40029. return;
  40030. }
  40031. for (var i = 0; i < points.length;) {
  40032. var x = points[i++];
  40033. var y = points[i++];
  40034. if (isNaN(x) || isNaN(y)) {
  40035. continue;
  40036. }
  40037. if (this.softClipShape && !this.softClipShape.contain(x, y)) {
  40038. continue;
  40039. }
  40040. symbolProxyShape.x = x - size[0] / 2;
  40041. symbolProxyShape.y = y - size[1] / 2;
  40042. symbolProxyShape.width = size[0];
  40043. symbolProxyShape.height = size[1];
  40044. symbolProxy.buildPath(path, symbolProxyShape, true);
  40045. }
  40046. },
  40047. afterBrush: function (ctx) {
  40048. var shape = this.shape;
  40049. var points = shape.points;
  40050. var size = shape.size;
  40051. var canBoost = size[0] < BOOST_SIZE_THRESHOLD;
  40052. if (!canBoost) {
  40053. return;
  40054. }
  40055. this.setTransform(ctx);
  40056. // PENDING If style or other canvas status changed?
  40057. for (var i = 0; i < points.length;) {
  40058. var x = points[i++];
  40059. var y = points[i++];
  40060. if (isNaN(x) || isNaN(y)) {
  40061. continue;
  40062. }
  40063. if (this.softClipShape && !this.softClipShape.contain(x, y)) {
  40064. continue;
  40065. }
  40066. // fillRect is faster than building a rect path and draw.
  40067. // And it support light globalCompositeOperation.
  40068. ctx.fillRect(
  40069. x - size[0] / 2, y - size[1] / 2,
  40070. size[0], size[1]
  40071. );
  40072. }
  40073. this.restoreTransform(ctx);
  40074. },
  40075. findDataIndex: function (x, y) {
  40076. // TODO ???
  40077. // Consider transform
  40078. var shape = this.shape;
  40079. var points = shape.points;
  40080. var size = shape.size;
  40081. var w = Math.max(size[0], 4);
  40082. var h = Math.max(size[1], 4);
  40083. // Not consider transform
  40084. // Treat each element as a rect
  40085. // top down traverse
  40086. for (var idx = points.length / 2 - 1; idx >= 0; idx--) {
  40087. var i = idx * 2;
  40088. var x0 = points[i] - w / 2;
  40089. var y0 = points[i + 1] - h / 2;
  40090. if (x >= x0 && y >= y0 && x <= x0 + w && y <= y0 + h) {
  40091. return idx;
  40092. }
  40093. }
  40094. return -1;
  40095. }
  40096. });
  40097. function LargeSymbolDraw() {
  40098. this.group = new Group();
  40099. }
  40100. var largeSymbolProto = LargeSymbolDraw.prototype;
  40101. largeSymbolProto.isPersistent = function () {
  40102. return !this._incremental;
  40103. };
  40104. /**
  40105. * Update symbols draw by new data
  40106. * @param {module:echarts/data/List} data
  40107. * @param {Object} opt
  40108. * @param {Object} [opt.clipShape]
  40109. */
  40110. largeSymbolProto.updateData = function (data, opt) {
  40111. this.group.removeAll();
  40112. var symbolEl = new LargeSymbolPath({
  40113. rectHover: true,
  40114. cursor: 'default'
  40115. });
  40116. symbolEl.setShape({
  40117. points: data.getLayout('symbolPoints')
  40118. });
  40119. this._setCommon(symbolEl, data, false, opt);
  40120. this.group.add(symbolEl);
  40121. this._incremental = null;
  40122. };
  40123. largeSymbolProto.updateLayout = function (data) {
  40124. if (this._incremental) {
  40125. return;
  40126. }
  40127. var points = data.getLayout('symbolPoints');
  40128. this.group.eachChild(function (child) {
  40129. if (child.startIndex != null) {
  40130. var len = (child.endIndex - child.startIndex) * 2;
  40131. var byteOffset = child.startIndex * 4 * 2;
  40132. points = new Float32Array(points.buffer, byteOffset, len);
  40133. }
  40134. child.setShape('points', points);
  40135. });
  40136. };
  40137. largeSymbolProto.incrementalPrepareUpdate = function (data) {
  40138. this.group.removeAll();
  40139. this._clearIncremental();
  40140. // Only use incremental displayables when data amount is larger than 2 million.
  40141. // PENDING Incremental data?
  40142. if (data.count() > 2e6) {
  40143. if (!this._incremental) {
  40144. this._incremental = new IncrementalDisplayble({
  40145. silent: true
  40146. });
  40147. }
  40148. this.group.add(this._incremental);
  40149. }
  40150. else {
  40151. this._incremental = null;
  40152. }
  40153. };
  40154. largeSymbolProto.incrementalUpdate = function (taskParams, data, opt) {
  40155. var symbolEl;
  40156. if (this._incremental) {
  40157. symbolEl = new LargeSymbolPath();
  40158. this._incremental.addDisplayable(symbolEl, true);
  40159. }
  40160. else {
  40161. symbolEl = new LargeSymbolPath({
  40162. rectHover: true,
  40163. cursor: 'default',
  40164. startIndex: taskParams.start,
  40165. endIndex: taskParams.end
  40166. });
  40167. symbolEl.incremental = true;
  40168. this.group.add(symbolEl);
  40169. }
  40170. symbolEl.setShape({
  40171. points: data.getLayout('symbolPoints')
  40172. });
  40173. this._setCommon(symbolEl, data, !!this._incremental, opt);
  40174. };
  40175. largeSymbolProto._setCommon = function (symbolEl, data, isIncremental, opt) {
  40176. var hostModel = data.hostModel;
  40177. opt = opt || {};
  40178. // TODO
  40179. // if (data.hasItemVisual.symbolSize) {
  40180. // // TODO typed array?
  40181. // symbolEl.setShape('sizes', data.mapArray(
  40182. // function (idx) {
  40183. // var size = data.getItemVisual(idx, 'symbolSize');
  40184. // return (size instanceof Array) ? size : [size, size];
  40185. // }
  40186. // ));
  40187. // }
  40188. // else {
  40189. var size = data.getVisual('symbolSize');
  40190. symbolEl.setShape('size', (size instanceof Array) ? size : [size, size]);
  40191. // }
  40192. symbolEl.softClipShape = opt.clipShape || null;
  40193. // Create symbolProxy to build path for each data
  40194. symbolEl.symbolProxy = createSymbol(
  40195. data.getVisual('symbol'), 0, 0, 0, 0
  40196. );
  40197. // Use symbolProxy setColor method
  40198. symbolEl.setColor = symbolEl.symbolProxy.setColor;
  40199. var extrudeShadow = symbolEl.shape.size[0] < BOOST_SIZE_THRESHOLD;
  40200. symbolEl.useStyle(
  40201. // Draw shadow when doing fillRect is extremely slow.
  40202. hostModel.getModel('itemStyle').getItemStyle(extrudeShadow ? ['color', 'shadowBlur', 'shadowColor'] : ['color'])
  40203. );
  40204. var visualColor = data.getVisual('color');
  40205. if (visualColor) {
  40206. symbolEl.setColor(visualColor);
  40207. }
  40208. if (!isIncremental) {
  40209. // Enable tooltip
  40210. // PENDING May have performance issue when path is extremely large
  40211. symbolEl.seriesIndex = hostModel.seriesIndex;
  40212. symbolEl.on('mousemove', function (e) {
  40213. symbolEl.dataIndex = null;
  40214. var dataIndex = symbolEl.findDataIndex(e.offsetX, e.offsetY);
  40215. if (dataIndex >= 0) {
  40216. // Provide dataIndex for tooltip
  40217. symbolEl.dataIndex = dataIndex + (symbolEl.startIndex || 0);
  40218. }
  40219. });
  40220. }
  40221. };
  40222. largeSymbolProto.remove = function () {
  40223. this._clearIncremental();
  40224. this._incremental = null;
  40225. this.group.removeAll();
  40226. };
  40227. largeSymbolProto._clearIncremental = function () {
  40228. var incremental = this._incremental;
  40229. if (incremental) {
  40230. incremental.clearDisplaybles();
  40231. }
  40232. };
  40233. /*
  40234. * Licensed to the Apache Software Foundation (ASF) under one
  40235. * or more contributor license agreements. See the NOTICE file
  40236. * distributed with this work for additional information
  40237. * regarding copyright ownership. The ASF licenses this file
  40238. * to you under the Apache License, Version 2.0 (the
  40239. * "License"); you may not use this file except in compliance
  40240. * with the License. You may obtain a copy of the License at
  40241. *
  40242. * http://www.apache.org/licenses/LICENSE-2.0
  40243. *
  40244. * Unless required by applicable law or agreed to in writing,
  40245. * software distributed under the License is distributed on an
  40246. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40247. * KIND, either express or implied. See the License for the
  40248. * specific language governing permissions and limitations
  40249. * under the License.
  40250. */
  40251. extendChartView({
  40252. type: 'scatter',
  40253. render: function (seriesModel, ecModel, api) {
  40254. var data = seriesModel.getData();
  40255. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  40256. symbolDraw.updateData(data, {
  40257. // TODO
  40258. // If this parameter should be a shape or a bounding volume
  40259. // shape will be more general.
  40260. // But bounding volume like bounding rect will be much faster in the contain calculation
  40261. clipShape: this._getClipShape(seriesModel)
  40262. });
  40263. this._finished = true;
  40264. },
  40265. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  40266. var data = seriesModel.getData();
  40267. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  40268. symbolDraw.incrementalPrepareUpdate(data);
  40269. this._finished = false;
  40270. },
  40271. incrementalRender: function (taskParams, seriesModel, ecModel) {
  40272. this._symbolDraw.incrementalUpdate(taskParams, seriesModel.getData(), {
  40273. clipShape: this._getClipShape(seriesModel)
  40274. });
  40275. this._finished = taskParams.end === seriesModel.getData().count();
  40276. },
  40277. updateTransform: function (seriesModel, ecModel, api) {
  40278. var data = seriesModel.getData();
  40279. // Must mark group dirty and make sure the incremental layer will be cleared
  40280. // PENDING
  40281. this.group.dirty();
  40282. if (!this._finished || data.count() > 1e4 || !this._symbolDraw.isPersistent()) {
  40283. return {
  40284. update: true
  40285. };
  40286. }
  40287. else {
  40288. var res = pointsLayout().reset(seriesModel);
  40289. if (res.progress) {
  40290. res.progress({ start: 0, end: data.count() }, data);
  40291. }
  40292. this._symbolDraw.updateLayout(data);
  40293. }
  40294. },
  40295. _getClipShape: function (seriesModel) {
  40296. var coordSys = seriesModel.coordinateSystem;
  40297. var clipArea = coordSys && coordSys.getArea && coordSys.getArea();
  40298. return seriesModel.get('clip', true) ? clipArea : null;
  40299. },
  40300. _updateSymbolDraw: function (data, seriesModel) {
  40301. var symbolDraw = this._symbolDraw;
  40302. var pipelineContext = seriesModel.pipelineContext;
  40303. var isLargeDraw = pipelineContext.large;
  40304. if (!symbolDraw || isLargeDraw !== this._isLargeDraw) {
  40305. symbolDraw && symbolDraw.remove();
  40306. symbolDraw = this._symbolDraw = isLargeDraw
  40307. ? new LargeSymbolDraw()
  40308. : new SymbolDraw();
  40309. this._isLargeDraw = isLargeDraw;
  40310. this.group.removeAll();
  40311. }
  40312. this.group.add(symbolDraw.group);
  40313. return symbolDraw;
  40314. },
  40315. remove: function (ecModel, api) {
  40316. this._symbolDraw && this._symbolDraw.remove(true);
  40317. this._symbolDraw = null;
  40318. },
  40319. dispose: function () {}
  40320. });
  40321. /*
  40322. * Licensed to the Apache Software Foundation (ASF) under one
  40323. * or more contributor license agreements. See the NOTICE file
  40324. * distributed with this work for additional information
  40325. * regarding copyright ownership. The ASF licenses this file
  40326. * to you under the Apache License, Version 2.0 (the
  40327. * "License"); you may not use this file except in compliance
  40328. * with the License. You may obtain a copy of the License at
  40329. *
  40330. * http://www.apache.org/licenses/LICENSE-2.0
  40331. *
  40332. * Unless required by applicable law or agreed to in writing,
  40333. * software distributed under the License is distributed on an
  40334. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40335. * KIND, either express or implied. See the License for the
  40336. * specific language governing permissions and limitations
  40337. * under the License.
  40338. */
  40339. // import * as zrUtil from 'zrender/src/core/util';
  40340. // In case developer forget to include grid component
  40341. registerVisual(visualSymbol('scatter', 'circle'));
  40342. registerLayout(pointsLayout('scatter'));
  40343. // echarts.registerProcessor(function (ecModel, api) {
  40344. // ecModel.eachSeriesByType('scatter', function (seriesModel) {
  40345. // var data = seriesModel.getData();
  40346. // var coordSys = seriesModel.coordinateSystem;
  40347. // if (coordSys.type !== 'geo') {
  40348. // return;
  40349. // }
  40350. // var startPt = coordSys.pointToData([0, 0]);
  40351. // var endPt = coordSys.pointToData([api.getWidth(), api.getHeight()]);
  40352. // var dims = zrUtil.map(coordSys.dimensions, function (dim) {
  40353. // return data.mapDimension(dim);
  40354. // });
  40355. // var range = {};
  40356. // range[dims[0]] = [Math.min(startPt[0], endPt[0]), Math.max(startPt[0], endPt[0])];
  40357. // range[dims[1]] = [Math.min(startPt[1], endPt[1]), Math.max(startPt[1], endPt[1])];
  40358. // data.selectRange(range);
  40359. // });
  40360. // });
  40361. /*
  40362. * Licensed to the Apache Software Foundation (ASF) under one
  40363. * or more contributor license agreements. See the NOTICE file
  40364. * distributed with this work for additional information
  40365. * regarding copyright ownership. The ASF licenses this file
  40366. * to you under the Apache License, Version 2.0 (the
  40367. * "License"); you may not use this file except in compliance
  40368. * with the License. You may obtain a copy of the License at
  40369. *
  40370. * http://www.apache.org/licenses/LICENSE-2.0
  40371. *
  40372. * Unless required by applicable law or agreed to in writing,
  40373. * software distributed under the License is distributed on an
  40374. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40375. * KIND, either express or implied. See the License for the
  40376. * specific language governing permissions and limitations
  40377. * under the License.
  40378. */
  40379. function IndicatorAxis(dim, scale, radiusExtent) {
  40380. Axis.call(this, dim, scale, radiusExtent);
  40381. /**
  40382. * Axis type
  40383. * - 'category'
  40384. * - 'value'
  40385. * - 'time'
  40386. * - 'log'
  40387. * @type {string}
  40388. */
  40389. this.type = 'value';
  40390. this.angle = 0;
  40391. /**
  40392. * Indicator name
  40393. * @type {string}
  40394. */
  40395. this.name = '';
  40396. /**
  40397. * @type {module:echarts/model/Model}
  40398. */
  40399. this.model;
  40400. }
  40401. inherits(IndicatorAxis, Axis);
  40402. /*
  40403. * Licensed to the Apache Software Foundation (ASF) under one
  40404. * or more contributor license agreements. See the NOTICE file
  40405. * distributed with this work for additional information
  40406. * regarding copyright ownership. The ASF licenses this file
  40407. * to you under the Apache License, Version 2.0 (the
  40408. * "License"); you may not use this file except in compliance
  40409. * with the License. You may obtain a copy of the License at
  40410. *
  40411. * http://www.apache.org/licenses/LICENSE-2.0
  40412. *
  40413. * Unless required by applicable law or agreed to in writing,
  40414. * software distributed under the License is distributed on an
  40415. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40416. * KIND, either express or implied. See the License for the
  40417. * specific language governing permissions and limitations
  40418. * under the License.
  40419. */
  40420. // TODO clockwise
  40421. function Radar(radarModel, ecModel, api) {
  40422. this._model = radarModel;
  40423. /**
  40424. * Radar dimensions
  40425. * @type {Array.<string>}
  40426. */
  40427. this.dimensions = [];
  40428. this._indicatorAxes = map(radarModel.getIndicatorModels(), function (indicatorModel, idx) {
  40429. var dim = 'indicator_' + idx;
  40430. var indicatorAxis = new IndicatorAxis(dim,
  40431. (indicatorModel.get('axisType') === 'log') ? new LogScale() : new IntervalScale());
  40432. indicatorAxis.name = indicatorModel.get('name');
  40433. // Inject model and axis
  40434. indicatorAxis.model = indicatorModel;
  40435. indicatorModel.axis = indicatorAxis;
  40436. this.dimensions.push(dim);
  40437. return indicatorAxis;
  40438. }, this);
  40439. this.resize(radarModel, api);
  40440. /**
  40441. * @type {number}
  40442. * @readOnly
  40443. */
  40444. this.cx;
  40445. /**
  40446. * @type {number}
  40447. * @readOnly
  40448. */
  40449. this.cy;
  40450. /**
  40451. * @type {number}
  40452. * @readOnly
  40453. */
  40454. this.r;
  40455. /**
  40456. * @type {number}
  40457. * @readOnly
  40458. */
  40459. this.r0;
  40460. /**
  40461. * @type {number}
  40462. * @readOnly
  40463. */
  40464. this.startAngle;
  40465. }
  40466. Radar.prototype.getIndicatorAxes = function () {
  40467. return this._indicatorAxes;
  40468. };
  40469. Radar.prototype.dataToPoint = function (value, indicatorIndex) {
  40470. var indicatorAxis = this._indicatorAxes[indicatorIndex];
  40471. return this.coordToPoint(indicatorAxis.dataToCoord(value), indicatorIndex);
  40472. };
  40473. Radar.prototype.coordToPoint = function (coord, indicatorIndex) {
  40474. var indicatorAxis = this._indicatorAxes[indicatorIndex];
  40475. var angle = indicatorAxis.angle;
  40476. var x = this.cx + coord * Math.cos(angle);
  40477. var y = this.cy - coord * Math.sin(angle);
  40478. return [x, y];
  40479. };
  40480. Radar.prototype.pointToData = function (pt) {
  40481. var dx = pt[0] - this.cx;
  40482. var dy = pt[1] - this.cy;
  40483. var radius = Math.sqrt(dx * dx + dy * dy);
  40484. dx /= radius;
  40485. dy /= radius;
  40486. var radian = Math.atan2(-dy, dx);
  40487. // Find the closest angle
  40488. // FIXME index can calculated directly
  40489. var minRadianDiff = Infinity;
  40490. var closestAxis;
  40491. var closestAxisIdx = -1;
  40492. for (var i = 0; i < this._indicatorAxes.length; i++) {
  40493. var indicatorAxis = this._indicatorAxes[i];
  40494. var diff = Math.abs(radian - indicatorAxis.angle);
  40495. if (diff < minRadianDiff) {
  40496. closestAxis = indicatorAxis;
  40497. closestAxisIdx = i;
  40498. minRadianDiff = diff;
  40499. }
  40500. }
  40501. return [closestAxisIdx, +(closestAxis && closestAxis.coordToData(radius))];
  40502. };
  40503. Radar.prototype.resize = function (radarModel, api) {
  40504. var center = radarModel.get('center');
  40505. var viewWidth = api.getWidth();
  40506. var viewHeight = api.getHeight();
  40507. var viewSize = Math.min(viewWidth, viewHeight) / 2;
  40508. this.cx = parsePercent$1(center[0], viewWidth);
  40509. this.cy = parsePercent$1(center[1], viewHeight);
  40510. this.startAngle = radarModel.get('startAngle') * Math.PI / 180;
  40511. // radius may be single value like `20`, `'80%'`, or array like `[10, '80%']`
  40512. var radius = radarModel.get('radius');
  40513. if (typeof radius === 'string' || typeof radius === 'number') {
  40514. radius = [0, radius];
  40515. }
  40516. this.r0 = parsePercent$1(radius[0], viewSize);
  40517. this.r = parsePercent$1(radius[1], viewSize);
  40518. each$1(this._indicatorAxes, function (indicatorAxis, idx) {
  40519. indicatorAxis.setExtent(this.r0, this.r);
  40520. var angle = (this.startAngle + idx * Math.PI * 2 / this._indicatorAxes.length);
  40521. // Normalize to [-PI, PI]
  40522. angle = Math.atan2(Math.sin(angle), Math.cos(angle));
  40523. indicatorAxis.angle = angle;
  40524. }, this);
  40525. };
  40526. Radar.prototype.update = function (ecModel, api) {
  40527. var indicatorAxes = this._indicatorAxes;
  40528. var radarModel = this._model;
  40529. each$1(indicatorAxes, function (indicatorAxis) {
  40530. indicatorAxis.scale.setExtent(Infinity, -Infinity);
  40531. });
  40532. ecModel.eachSeriesByType('radar', function (radarSeries, idx) {
  40533. if (radarSeries.get('coordinateSystem') !== 'radar'
  40534. || ecModel.getComponent('radar', radarSeries.get('radarIndex')) !== radarModel
  40535. ) {
  40536. return;
  40537. }
  40538. var data = radarSeries.getData();
  40539. each$1(indicatorAxes, function (indicatorAxis) {
  40540. indicatorAxis.scale.unionExtentFromData(data, data.mapDimension(indicatorAxis.dim));
  40541. });
  40542. }, this);
  40543. var splitNumber = radarModel.get('splitNumber');
  40544. function increaseInterval(interval) {
  40545. var exp10 = Math.pow(10, Math.floor(Math.log(interval) / Math.LN10));
  40546. // Increase interval
  40547. var f = interval / exp10;
  40548. if (f === 2) {
  40549. f = 5;
  40550. }
  40551. else { // f is 2 or 5
  40552. f *= 2;
  40553. }
  40554. return f * exp10;
  40555. }
  40556. // Force all the axis fixing the maxSplitNumber.
  40557. each$1(indicatorAxes, function (indicatorAxis, idx) {
  40558. var rawExtent = getScaleExtent(indicatorAxis.scale, indicatorAxis.model).extent;
  40559. niceScaleExtent(indicatorAxis.scale, indicatorAxis.model);
  40560. var axisModel = indicatorAxis.model;
  40561. var scale = indicatorAxis.scale;
  40562. var fixedMin = axisModel.getMin();
  40563. var fixedMax = axisModel.getMax();
  40564. var interval = scale.getInterval();
  40565. if (fixedMin != null && fixedMax != null) {
  40566. // User set min, max, divide to get new interval
  40567. scale.setExtent(+fixedMin, +fixedMax);
  40568. scale.setInterval(
  40569. (fixedMax - fixedMin) / splitNumber
  40570. );
  40571. }
  40572. else if (fixedMin != null) {
  40573. var max;
  40574. // User set min, expand extent on the other side
  40575. do {
  40576. max = fixedMin + interval * splitNumber;
  40577. scale.setExtent(+fixedMin, max);
  40578. // Interval must been set after extent
  40579. // FIXME
  40580. scale.setInterval(interval);
  40581. interval = increaseInterval(interval);
  40582. } while (max < rawExtent[1] && isFinite(max) && isFinite(rawExtent[1]));
  40583. }
  40584. else if (fixedMax != null) {
  40585. var min;
  40586. // User set min, expand extent on the other side
  40587. do {
  40588. min = fixedMax - interval * splitNumber;
  40589. scale.setExtent(min, +fixedMax);
  40590. scale.setInterval(interval);
  40591. interval = increaseInterval(interval);
  40592. } while (min > rawExtent[0] && isFinite(min) && isFinite(rawExtent[0]));
  40593. }
  40594. else {
  40595. var nicedSplitNumber = scale.getTicks().length - 1;
  40596. if (nicedSplitNumber > splitNumber) {
  40597. interval = increaseInterval(interval);
  40598. }
  40599. // TODO
  40600. var max = Math.ceil(rawExtent[1] / interval) * interval;
  40601. var min = round$1(max - interval * splitNumber);
  40602. scale.setExtent(min, max);
  40603. scale.setInterval(interval);
  40604. }
  40605. });
  40606. };
  40607. /**
  40608. * Radar dimensions is based on the data
  40609. * @type {Array}
  40610. */
  40611. Radar.dimensions = [];
  40612. Radar.create = function (ecModel, api) {
  40613. var radarList = [];
  40614. ecModel.eachComponent('radar', function (radarModel) {
  40615. var radar = new Radar(radarModel, ecModel, api);
  40616. radarList.push(radar);
  40617. radarModel.coordinateSystem = radar;
  40618. });
  40619. ecModel.eachSeriesByType('radar', function (radarSeries) {
  40620. if (radarSeries.get('coordinateSystem') === 'radar') {
  40621. // Inject coordinate system
  40622. radarSeries.coordinateSystem = radarList[radarSeries.get('radarIndex') || 0];
  40623. }
  40624. });
  40625. return radarList;
  40626. };
  40627. CoordinateSystemManager.register('radar', Radar);
  40628. /*
  40629. * Licensed to the Apache Software Foundation (ASF) under one
  40630. * or more contributor license agreements. See the NOTICE file
  40631. * distributed with this work for additional information
  40632. * regarding copyright ownership. The ASF licenses this file
  40633. * to you under the Apache License, Version 2.0 (the
  40634. * "License"); you may not use this file except in compliance
  40635. * with the License. You may obtain a copy of the License at
  40636. *
  40637. * http://www.apache.org/licenses/LICENSE-2.0
  40638. *
  40639. * Unless required by applicable law or agreed to in writing,
  40640. * software distributed under the License is distributed on an
  40641. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40642. * KIND, either express or implied. See the License for the
  40643. * specific language governing permissions and limitations
  40644. * under the License.
  40645. */
  40646. var valueAxisDefault = axisDefault.valueAxis;
  40647. function defaultsShow(opt, show) {
  40648. return defaults({
  40649. show: show
  40650. }, opt);
  40651. }
  40652. var RadarModel = extendComponentModel({
  40653. type: 'radar',
  40654. optionUpdated: function () {
  40655. var boundaryGap = this.get('boundaryGap');
  40656. var splitNumber = this.get('splitNumber');
  40657. var scale = this.get('scale');
  40658. var axisLine = this.get('axisLine');
  40659. var axisTick = this.get('axisTick');
  40660. var axisType = this.get('axisType');
  40661. var axisLabel = this.get('axisLabel');
  40662. var nameTextStyle = this.get('name');
  40663. var showName = this.get('name.show');
  40664. var nameFormatter = this.get('name.formatter');
  40665. var nameGap = this.get('nameGap');
  40666. var triggerEvent = this.get('triggerEvent');
  40667. var indicatorModels = map(this.get('indicator') || [], function (indicatorOpt) {
  40668. // PENDING
  40669. if (indicatorOpt.max != null && indicatorOpt.max > 0 && !indicatorOpt.min) {
  40670. indicatorOpt.min = 0;
  40671. }
  40672. else if (indicatorOpt.min != null && indicatorOpt.min < 0 && !indicatorOpt.max) {
  40673. indicatorOpt.max = 0;
  40674. }
  40675. var iNameTextStyle = nameTextStyle;
  40676. if (indicatorOpt.color != null) {
  40677. iNameTextStyle = defaults({color: indicatorOpt.color}, nameTextStyle);
  40678. }
  40679. // Use same configuration
  40680. indicatorOpt = merge(clone(indicatorOpt), {
  40681. boundaryGap: boundaryGap,
  40682. splitNumber: splitNumber,
  40683. scale: scale,
  40684. axisLine: axisLine,
  40685. axisTick: axisTick,
  40686. axisType: axisType,
  40687. axisLabel: axisLabel,
  40688. // Compatible with 2 and use text
  40689. name: indicatorOpt.text,
  40690. nameLocation: 'end',
  40691. nameGap: nameGap,
  40692. // min: 0,
  40693. nameTextStyle: iNameTextStyle,
  40694. triggerEvent: triggerEvent
  40695. }, false);
  40696. if (!showName) {
  40697. indicatorOpt.name = '';
  40698. }
  40699. if (typeof nameFormatter === 'string') {
  40700. var indName = indicatorOpt.name;
  40701. indicatorOpt.name = nameFormatter.replace('{value}', indName != null ? indName : '');
  40702. }
  40703. else if (typeof nameFormatter === 'function') {
  40704. indicatorOpt.name = nameFormatter(
  40705. indicatorOpt.name, indicatorOpt
  40706. );
  40707. }
  40708. var model = extend(
  40709. new Model(indicatorOpt, null, this.ecModel),
  40710. axisModelCommonMixin
  40711. );
  40712. // For triggerEvent.
  40713. model.mainType = 'radar';
  40714. model.componentIndex = this.componentIndex;
  40715. return model;
  40716. }, this);
  40717. this.getIndicatorModels = function () {
  40718. return indicatorModels;
  40719. };
  40720. },
  40721. defaultOption: {
  40722. zlevel: 0,
  40723. z: 0,
  40724. center: ['50%', '50%'],
  40725. radius: '75%',
  40726. startAngle: 90,
  40727. name: {
  40728. show: true
  40729. // formatter: null
  40730. // textStyle: {}
  40731. },
  40732. boundaryGap: [0, 0],
  40733. splitNumber: 5,
  40734. nameGap: 15,
  40735. scale: false,
  40736. // Polygon or circle
  40737. shape: 'polygon',
  40738. axisLine: merge(
  40739. {
  40740. lineStyle: {
  40741. color: '#bbb'
  40742. }
  40743. },
  40744. valueAxisDefault.axisLine
  40745. ),
  40746. axisLabel: defaultsShow(valueAxisDefault.axisLabel, false),
  40747. axisTick: defaultsShow(valueAxisDefault.axisTick, false),
  40748. axisType: 'interval',
  40749. splitLine: defaultsShow(valueAxisDefault.splitLine, true),
  40750. splitArea: defaultsShow(valueAxisDefault.splitArea, true),
  40751. // {text, min, max}
  40752. indicator: []
  40753. }
  40754. });
  40755. /*
  40756. * Licensed to the Apache Software Foundation (ASF) under one
  40757. * or more contributor license agreements. See the NOTICE file
  40758. * distributed with this work for additional information
  40759. * regarding copyright ownership. The ASF licenses this file
  40760. * to you under the Apache License, Version 2.0 (the
  40761. * "License"); you may not use this file except in compliance
  40762. * with the License. You may obtain a copy of the License at
  40763. *
  40764. * http://www.apache.org/licenses/LICENSE-2.0
  40765. *
  40766. * Unless required by applicable law or agreed to in writing,
  40767. * software distributed under the License is distributed on an
  40768. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40769. * KIND, either express or implied. See the License for the
  40770. * specific language governing permissions and limitations
  40771. * under the License.
  40772. */
  40773. var axisBuilderAttrs$1 = [
  40774. 'axisLine', 'axisTickLabel', 'axisName'
  40775. ];
  40776. extendComponentView({
  40777. type: 'radar',
  40778. render: function (radarModel, ecModel, api) {
  40779. var group = this.group;
  40780. group.removeAll();
  40781. this._buildAxes(radarModel);
  40782. this._buildSplitLineAndArea(radarModel);
  40783. },
  40784. _buildAxes: function (radarModel) {
  40785. var radar = radarModel.coordinateSystem;
  40786. var indicatorAxes = radar.getIndicatorAxes();
  40787. var axisBuilders = map(indicatorAxes, function (indicatorAxis) {
  40788. var axisBuilder = new AxisBuilder(indicatorAxis.model, {
  40789. position: [radar.cx, radar.cy],
  40790. rotation: indicatorAxis.angle,
  40791. labelDirection: -1,
  40792. tickDirection: -1,
  40793. nameDirection: 1
  40794. });
  40795. return axisBuilder;
  40796. });
  40797. each$1(axisBuilders, function (axisBuilder) {
  40798. each$1(axisBuilderAttrs$1, axisBuilder.add, axisBuilder);
  40799. this.group.add(axisBuilder.getGroup());
  40800. }, this);
  40801. },
  40802. _buildSplitLineAndArea: function (radarModel) {
  40803. var radar = radarModel.coordinateSystem;
  40804. var indicatorAxes = radar.getIndicatorAxes();
  40805. if (!indicatorAxes.length) {
  40806. return;
  40807. }
  40808. var shape = radarModel.get('shape');
  40809. var splitLineModel = radarModel.getModel('splitLine');
  40810. var splitAreaModel = radarModel.getModel('splitArea');
  40811. var lineStyleModel = splitLineModel.getModel('lineStyle');
  40812. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  40813. var showSplitLine = splitLineModel.get('show');
  40814. var showSplitArea = splitAreaModel.get('show');
  40815. var splitLineColors = lineStyleModel.get('color');
  40816. var splitAreaColors = areaStyleModel.get('color');
  40817. splitLineColors = isArray(splitLineColors) ? splitLineColors : [splitLineColors];
  40818. splitAreaColors = isArray(splitAreaColors) ? splitAreaColors : [splitAreaColors];
  40819. var splitLines = [];
  40820. var splitAreas = [];
  40821. function getColorIndex(areaOrLine, areaOrLineColorList, idx) {
  40822. var colorIndex = idx % areaOrLineColorList.length;
  40823. areaOrLine[colorIndex] = areaOrLine[colorIndex] || [];
  40824. return colorIndex;
  40825. }
  40826. if (shape === 'circle') {
  40827. var ticksRadius = indicatorAxes[0].getTicksCoords();
  40828. var cx = radar.cx;
  40829. var cy = radar.cy;
  40830. for (var i = 0; i < ticksRadius.length; i++) {
  40831. if (showSplitLine) {
  40832. var colorIndex = getColorIndex(splitLines, splitLineColors, i);
  40833. splitLines[colorIndex].push(new Circle({
  40834. shape: {
  40835. cx: cx,
  40836. cy: cy,
  40837. r: ticksRadius[i].coord
  40838. }
  40839. }));
  40840. }
  40841. if (showSplitArea && i < ticksRadius.length - 1) {
  40842. var colorIndex = getColorIndex(splitAreas, splitAreaColors, i);
  40843. splitAreas[colorIndex].push(new Ring({
  40844. shape: {
  40845. cx: cx,
  40846. cy: cy,
  40847. r0: ticksRadius[i].coord,
  40848. r: ticksRadius[i + 1].coord
  40849. }
  40850. }));
  40851. }
  40852. }
  40853. }
  40854. // Polyyon
  40855. else {
  40856. var realSplitNumber;
  40857. var axesTicksPoints = map(indicatorAxes, function (indicatorAxis, idx) {
  40858. var ticksCoords = indicatorAxis.getTicksCoords();
  40859. realSplitNumber = realSplitNumber == null
  40860. ? ticksCoords.length - 1
  40861. : Math.min(ticksCoords.length - 1, realSplitNumber);
  40862. return map(ticksCoords, function (tickCoord) {
  40863. return radar.coordToPoint(tickCoord.coord, idx);
  40864. });
  40865. });
  40866. var prevPoints = [];
  40867. for (var i = 0; i <= realSplitNumber; i++) {
  40868. var points = [];
  40869. for (var j = 0; j < indicatorAxes.length; j++) {
  40870. points.push(axesTicksPoints[j][i]);
  40871. }
  40872. // Close
  40873. if (points[0]) {
  40874. points.push(points[0].slice());
  40875. }
  40876. else {
  40877. if (__DEV__) {
  40878. console.error('Can\'t draw value axis ' + i);
  40879. }
  40880. }
  40881. if (showSplitLine) {
  40882. var colorIndex = getColorIndex(splitLines, splitLineColors, i);
  40883. splitLines[colorIndex].push(new Polyline({
  40884. shape: {
  40885. points: points
  40886. }
  40887. }));
  40888. }
  40889. if (showSplitArea && prevPoints) {
  40890. var colorIndex = getColorIndex(splitAreas, splitAreaColors, i - 1);
  40891. splitAreas[colorIndex].push(new Polygon({
  40892. shape: {
  40893. points: points.concat(prevPoints)
  40894. }
  40895. }));
  40896. }
  40897. prevPoints = points.slice().reverse();
  40898. }
  40899. }
  40900. var lineStyle = lineStyleModel.getLineStyle();
  40901. var areaStyle = areaStyleModel.getAreaStyle();
  40902. // Add splitArea before splitLine
  40903. each$1(splitAreas, function (splitAreas, idx) {
  40904. this.group.add(mergePath(
  40905. splitAreas, {
  40906. style: defaults({
  40907. stroke: 'none',
  40908. fill: splitAreaColors[idx % splitAreaColors.length]
  40909. }, areaStyle),
  40910. silent: true
  40911. }
  40912. ));
  40913. }, this);
  40914. each$1(splitLines, function (splitLines, idx) {
  40915. this.group.add(mergePath(
  40916. splitLines, {
  40917. style: defaults({
  40918. fill: 'none',
  40919. stroke: splitLineColors[idx % splitLineColors.length]
  40920. }, lineStyle),
  40921. silent: true
  40922. }
  40923. ));
  40924. }, this);
  40925. }
  40926. });
  40927. /*
  40928. * Licensed to the Apache Software Foundation (ASF) under one
  40929. * or more contributor license agreements. See the NOTICE file
  40930. * distributed with this work for additional information
  40931. * regarding copyright ownership. The ASF licenses this file
  40932. * to you under the Apache License, Version 2.0 (the
  40933. * "License"); you may not use this file except in compliance
  40934. * with the License. You may obtain a copy of the License at
  40935. *
  40936. * http://www.apache.org/licenses/LICENSE-2.0
  40937. *
  40938. * Unless required by applicable law or agreed to in writing,
  40939. * software distributed under the License is distributed on an
  40940. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40941. * KIND, either express or implied. See the License for the
  40942. * specific language governing permissions and limitations
  40943. * under the License.
  40944. */
  40945. /*
  40946. * Licensed to the Apache Software Foundation (ASF) under one
  40947. * or more contributor license agreements. See the NOTICE file
  40948. * distributed with this work for additional information
  40949. * regarding copyright ownership. The ASF licenses this file
  40950. * to you under the Apache License, Version 2.0 (the
  40951. * "License"); you may not use this file except in compliance
  40952. * with the License. You may obtain a copy of the License at
  40953. *
  40954. * http://www.apache.org/licenses/LICENSE-2.0
  40955. *
  40956. * Unless required by applicable law or agreed to in writing,
  40957. * software distributed under the License is distributed on an
  40958. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40959. * KIND, either express or implied. See the License for the
  40960. * specific language governing permissions and limitations
  40961. * under the License.
  40962. */
  40963. var RadarSeries = SeriesModel.extend({
  40964. type: 'series.radar',
  40965. dependencies: ['radar'],
  40966. // Overwrite
  40967. init: function (option) {
  40968. RadarSeries.superApply(this, 'init', arguments);
  40969. // Enable legend selection for each data item
  40970. // Use a function instead of direct access because data reference may changed
  40971. this.legendVisualProvider = new LegendVisualProvider(
  40972. bind(this.getData, this), bind(this.getRawData, this)
  40973. );
  40974. },
  40975. getInitialData: function (option, ecModel) {
  40976. return createListSimply(this, {
  40977. generateCoord: 'indicator_',
  40978. generateCoordCount: Infinity
  40979. });
  40980. },
  40981. formatTooltip: function (dataIndex) {
  40982. var data = this.getData();
  40983. var coordSys = this.coordinateSystem;
  40984. var indicatorAxes = coordSys.getIndicatorAxes();
  40985. var name = this.getData().getName(dataIndex);
  40986. return encodeHTML(name === '' ? this.name : name) + '<br/>'
  40987. + map(indicatorAxes, function (axis, idx) {
  40988. var val = data.get(data.mapDimension(axis.dim), dataIndex);
  40989. return encodeHTML(axis.name + ' : ' + val);
  40990. }).join('<br />');
  40991. },
  40992. /**
  40993. * @implement
  40994. */
  40995. getTooltipPosition: function (dataIndex) {
  40996. if (dataIndex != null) {
  40997. var data = this.getData();
  40998. var coordSys = this.coordinateSystem;
  40999. var values = data.getValues(
  41000. map(coordSys.dimensions, function (dim) {
  41001. return data.mapDimension(dim);
  41002. }), dataIndex, true
  41003. );
  41004. for (var i = 0, len = values.length; i < len; i++) {
  41005. if (!isNaN(values[i])) {
  41006. var indicatorAxes = coordSys.getIndicatorAxes();
  41007. return coordSys.coordToPoint(indicatorAxes[i].dataToCoord(values[i]), i);
  41008. }
  41009. }
  41010. }
  41011. },
  41012. defaultOption: {
  41013. zlevel: 0,
  41014. z: 2,
  41015. coordinateSystem: 'radar',
  41016. legendHoverLink: true,
  41017. radarIndex: 0,
  41018. lineStyle: {
  41019. width: 2,
  41020. type: 'solid'
  41021. },
  41022. label: {
  41023. position: 'top'
  41024. },
  41025. // areaStyle: {
  41026. // },
  41027. // itemStyle: {}
  41028. symbol: 'emptyCircle',
  41029. symbolSize: 4
  41030. // symbolRotate: null
  41031. }
  41032. });
  41033. /*
  41034. * Licensed to the Apache Software Foundation (ASF) under one
  41035. * or more contributor license agreements. See the NOTICE file
  41036. * distributed with this work for additional information
  41037. * regarding copyright ownership. The ASF licenses this file
  41038. * to you under the Apache License, Version 2.0 (the
  41039. * "License"); you may not use this file except in compliance
  41040. * with the License. You may obtain a copy of the License at
  41041. *
  41042. * http://www.apache.org/licenses/LICENSE-2.0
  41043. *
  41044. * Unless required by applicable law or agreed to in writing,
  41045. * software distributed under the License is distributed on an
  41046. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41047. * KIND, either express or implied. See the License for the
  41048. * specific language governing permissions and limitations
  41049. * under the License.
  41050. */
  41051. function normalizeSymbolSize(symbolSize) {
  41052. if (!isArray(symbolSize)) {
  41053. symbolSize = [+symbolSize, +symbolSize];
  41054. }
  41055. return symbolSize;
  41056. }
  41057. extendChartView({
  41058. type: 'radar',
  41059. render: function (seriesModel, ecModel, api) {
  41060. var polar = seriesModel.coordinateSystem;
  41061. var group = this.group;
  41062. var data = seriesModel.getData();
  41063. var oldData = this._data;
  41064. function createSymbol$$1(data, idx) {
  41065. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  41066. var color = data.getItemVisual(idx, 'color');
  41067. if (symbolType === 'none') {
  41068. return;
  41069. }
  41070. var symbolSize = normalizeSymbolSize(
  41071. data.getItemVisual(idx, 'symbolSize')
  41072. );
  41073. var symbolPath = createSymbol(
  41074. symbolType, -1, -1, 2, 2, color
  41075. );
  41076. symbolPath.attr({
  41077. style: {
  41078. strokeNoScale: true
  41079. },
  41080. z2: 100,
  41081. scale: [symbolSize[0] / 2, symbolSize[1] / 2]
  41082. });
  41083. return symbolPath;
  41084. }
  41085. function updateSymbols(oldPoints, newPoints, symbolGroup, data, idx, isInit) {
  41086. // Simply rerender all
  41087. symbolGroup.removeAll();
  41088. for (var i = 0; i < newPoints.length - 1; i++) {
  41089. var symbolPath = createSymbol$$1(data, idx);
  41090. if (symbolPath) {
  41091. symbolPath.__dimIdx = i;
  41092. if (oldPoints[i]) {
  41093. symbolPath.attr('position', oldPoints[i]);
  41094. graphic[isInit ? 'initProps' : 'updateProps'](
  41095. symbolPath, {
  41096. position: newPoints[i]
  41097. }, seriesModel, idx
  41098. );
  41099. }
  41100. else {
  41101. symbolPath.attr('position', newPoints[i]);
  41102. }
  41103. symbolGroup.add(symbolPath);
  41104. }
  41105. }
  41106. }
  41107. function getInitialPoints(points) {
  41108. return map(points, function (pt) {
  41109. return [polar.cx, polar.cy];
  41110. });
  41111. }
  41112. data.diff(oldData)
  41113. .add(function (idx) {
  41114. var points = data.getItemLayout(idx);
  41115. if (!points) {
  41116. return;
  41117. }
  41118. var polygon = new Polygon();
  41119. var polyline = new Polyline();
  41120. var target = {
  41121. shape: {
  41122. points: points
  41123. }
  41124. };
  41125. polygon.shape.points = getInitialPoints(points);
  41126. polyline.shape.points = getInitialPoints(points);
  41127. initProps(polygon, target, seriesModel, idx);
  41128. initProps(polyline, target, seriesModel, idx);
  41129. var itemGroup = new Group();
  41130. var symbolGroup = new Group();
  41131. itemGroup.add(polyline);
  41132. itemGroup.add(polygon);
  41133. itemGroup.add(symbolGroup);
  41134. updateSymbols(
  41135. polyline.shape.points, points, symbolGroup, data, idx, true
  41136. );
  41137. data.setItemGraphicEl(idx, itemGroup);
  41138. })
  41139. .update(function (newIdx, oldIdx) {
  41140. var itemGroup = oldData.getItemGraphicEl(oldIdx);
  41141. var polyline = itemGroup.childAt(0);
  41142. var polygon = itemGroup.childAt(1);
  41143. var symbolGroup = itemGroup.childAt(2);
  41144. var target = {
  41145. shape: {
  41146. points: data.getItemLayout(newIdx)
  41147. }
  41148. };
  41149. if (!target.shape.points) {
  41150. return;
  41151. }
  41152. updateSymbols(
  41153. polyline.shape.points, target.shape.points, symbolGroup, data, newIdx, false
  41154. );
  41155. updateProps(polyline, target, seriesModel);
  41156. updateProps(polygon, target, seriesModel);
  41157. data.setItemGraphicEl(newIdx, itemGroup);
  41158. })
  41159. .remove(function (idx) {
  41160. group.remove(oldData.getItemGraphicEl(idx));
  41161. })
  41162. .execute();
  41163. data.eachItemGraphicEl(function (itemGroup, idx) {
  41164. var itemModel = data.getItemModel(idx);
  41165. var polyline = itemGroup.childAt(0);
  41166. var polygon = itemGroup.childAt(1);
  41167. var symbolGroup = itemGroup.childAt(2);
  41168. var color = data.getItemVisual(idx, 'color');
  41169. group.add(itemGroup);
  41170. polyline.useStyle(
  41171. defaults(
  41172. itemModel.getModel('lineStyle').getLineStyle(),
  41173. {
  41174. fill: 'none',
  41175. stroke: color
  41176. }
  41177. )
  41178. );
  41179. polyline.hoverStyle = itemModel.getModel('emphasis.lineStyle').getLineStyle();
  41180. var areaStyleModel = itemModel.getModel('areaStyle');
  41181. var hoverAreaStyleModel = itemModel.getModel('emphasis.areaStyle');
  41182. var polygonIgnore = areaStyleModel.isEmpty() && areaStyleModel.parentModel.isEmpty();
  41183. var hoverPolygonIgnore = hoverAreaStyleModel.isEmpty() && hoverAreaStyleModel.parentModel.isEmpty();
  41184. hoverPolygonIgnore = hoverPolygonIgnore && polygonIgnore;
  41185. polygon.ignore = polygonIgnore;
  41186. polygon.useStyle(
  41187. defaults(
  41188. areaStyleModel.getAreaStyle(),
  41189. {
  41190. fill: color,
  41191. opacity: 0.7
  41192. }
  41193. )
  41194. );
  41195. polygon.hoverStyle = hoverAreaStyleModel.getAreaStyle();
  41196. var itemStyle = itemModel.getModel('itemStyle').getItemStyle(['color']);
  41197. var itemHoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  41198. var labelModel = itemModel.getModel('label');
  41199. var labelHoverModel = itemModel.getModel('emphasis.label');
  41200. symbolGroup.eachChild(function (symbolPath) {
  41201. symbolPath.setStyle(itemStyle);
  41202. symbolPath.hoverStyle = clone(itemHoverStyle);
  41203. var defaultText = data.get(data.dimensions[symbolPath.__dimIdx], idx);
  41204. (defaultText == null || isNaN(defaultText)) && (defaultText = '');
  41205. setLabelStyle(
  41206. symbolPath.style, symbolPath.hoverStyle, labelModel, labelHoverModel,
  41207. {
  41208. labelFetcher: data.hostModel,
  41209. labelDataIndex: idx,
  41210. labelDimIndex: symbolPath.__dimIdx,
  41211. defaultText: defaultText,
  41212. autoColor: color,
  41213. isRectText: true
  41214. }
  41215. );
  41216. });
  41217. itemGroup.highDownOnUpdate = function (fromState, toState) {
  41218. polygon.attr('ignore', toState === 'emphasis' ? hoverPolygonIgnore : polygonIgnore);
  41219. };
  41220. setHoverStyle(itemGroup);
  41221. });
  41222. this._data = data;
  41223. },
  41224. remove: function () {
  41225. this.group.removeAll();
  41226. this._data = null;
  41227. },
  41228. dispose: function () {}
  41229. });
  41230. /*
  41231. * Licensed to the Apache Software Foundation (ASF) under one
  41232. * or more contributor license agreements. See the NOTICE file
  41233. * distributed with this work for additional information
  41234. * regarding copyright ownership. The ASF licenses this file
  41235. * to you under the Apache License, Version 2.0 (the
  41236. * "License"); you may not use this file except in compliance
  41237. * with the License. You may obtain a copy of the License at
  41238. *
  41239. * http://www.apache.org/licenses/LICENSE-2.0
  41240. *
  41241. * Unless required by applicable law or agreed to in writing,
  41242. * software distributed under the License is distributed on an
  41243. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41244. * KIND, either express or implied. See the License for the
  41245. * specific language governing permissions and limitations
  41246. * under the License.
  41247. */
  41248. var radarLayout = function (ecModel) {
  41249. ecModel.eachSeriesByType('radar', function (seriesModel) {
  41250. var data = seriesModel.getData();
  41251. var points = [];
  41252. var coordSys = seriesModel.coordinateSystem;
  41253. if (!coordSys) {
  41254. return;
  41255. }
  41256. var axes = coordSys.getIndicatorAxes();
  41257. each$1(axes, function (axis, axisIndex) {
  41258. data.each(data.mapDimension(axes[axisIndex].dim), function (val, dataIndex) {
  41259. points[dataIndex] = points[dataIndex] || [];
  41260. var point = coordSys.dataToPoint(val, axisIndex);
  41261. points[dataIndex][axisIndex] = isValidPoint(point)
  41262. ? point : getValueMissingPoint(coordSys);
  41263. });
  41264. });
  41265. // Close polygon
  41266. data.each(function (idx) {
  41267. // TODO
  41268. // Is it appropriate to connect to the next data when some data is missing?
  41269. // Or, should trade it like `connectNull` in line chart?
  41270. var firstPoint = find(points[idx], function (point) {
  41271. return isValidPoint(point);
  41272. }) || getValueMissingPoint(coordSys);
  41273. // Copy the first actual point to the end of the array
  41274. points[idx].push(firstPoint.slice());
  41275. data.setItemLayout(idx, points[idx]);
  41276. });
  41277. });
  41278. };
  41279. function isValidPoint(point) {
  41280. return !isNaN(point[0]) && !isNaN(point[1]);
  41281. }
  41282. function getValueMissingPoint(coordSys) {
  41283. // It is error-prone to input [NaN, NaN] into polygon, polygon.
  41284. // (probably cause problem when refreshing or animating)
  41285. return [coordSys.cx, coordSys.cy];
  41286. }
  41287. /*
  41288. * Licensed to the Apache Software Foundation (ASF) under one
  41289. * or more contributor license agreements. See the NOTICE file
  41290. * distributed with this work for additional information
  41291. * regarding copyright ownership. The ASF licenses this file
  41292. * to you under the Apache License, Version 2.0 (the
  41293. * "License"); you may not use this file except in compliance
  41294. * with the License. You may obtain a copy of the License at
  41295. *
  41296. * http://www.apache.org/licenses/LICENSE-2.0
  41297. *
  41298. * Unless required by applicable law or agreed to in writing,
  41299. * software distributed under the License is distributed on an
  41300. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41301. * KIND, either express or implied. See the License for the
  41302. * specific language governing permissions and limitations
  41303. * under the License.
  41304. */
  41305. // Backward compat for radar chart in 2
  41306. var backwardCompat$1 = function (option) {
  41307. var polarOptArr = option.polar;
  41308. if (polarOptArr) {
  41309. if (!isArray(polarOptArr)) {
  41310. polarOptArr = [polarOptArr];
  41311. }
  41312. var polarNotRadar = [];
  41313. each$1(polarOptArr, function (polarOpt, idx) {
  41314. if (polarOpt.indicator) {
  41315. if (polarOpt.type && !polarOpt.shape) {
  41316. polarOpt.shape = polarOpt.type;
  41317. }
  41318. option.radar = option.radar || [];
  41319. if (!isArray(option.radar)) {
  41320. option.radar = [option.radar];
  41321. }
  41322. option.radar.push(polarOpt);
  41323. }
  41324. else {
  41325. polarNotRadar.push(polarOpt);
  41326. }
  41327. });
  41328. option.polar = polarNotRadar;
  41329. }
  41330. each$1(option.series, function (seriesOpt) {
  41331. if (seriesOpt && seriesOpt.type === 'radar' && seriesOpt.polarIndex) {
  41332. seriesOpt.radarIndex = seriesOpt.polarIndex;
  41333. }
  41334. });
  41335. };
  41336. /*
  41337. * Licensed to the Apache Software Foundation (ASF) under one
  41338. * or more contributor license agreements. See the NOTICE file
  41339. * distributed with this work for additional information
  41340. * regarding copyright ownership. The ASF licenses this file
  41341. * to you under the Apache License, Version 2.0 (the
  41342. * "License"); you may not use this file except in compliance
  41343. * with the License. You may obtain a copy of the License at
  41344. *
  41345. * http://www.apache.org/licenses/LICENSE-2.0
  41346. *
  41347. * Unless required by applicable law or agreed to in writing,
  41348. * software distributed under the License is distributed on an
  41349. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41350. * KIND, either express or implied. See the License for the
  41351. * specific language governing permissions and limitations
  41352. * under the License.
  41353. */
  41354. // Must use radar component
  41355. registerVisual(dataColor('radar'));
  41356. registerVisual(visualSymbol('radar', 'circle'));
  41357. registerLayout(radarLayout);
  41358. registerProcessor(dataFilter('radar'));
  41359. registerPreprocessor(backwardCompat$1);
  41360. /*
  41361. * Licensed to the Apache Software Foundation (ASF) under one
  41362. * or more contributor license agreements. See the NOTICE file
  41363. * distributed with this work for additional information
  41364. * regarding copyright ownership. The ASF licenses this file
  41365. * to you under the Apache License, Version 2.0 (the
  41366. * "License"); you may not use this file except in compliance
  41367. * with the License. You may obtain a copy of the License at
  41368. *
  41369. * http://www.apache.org/licenses/LICENSE-2.0
  41370. *
  41371. * Unless required by applicable law or agreed to in writing,
  41372. * software distributed under the License is distributed on an
  41373. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41374. * KIND, either express or implied. See the License for the
  41375. * specific language governing permissions and limitations
  41376. * under the License.
  41377. */
  41378. // Fix for 南海诸岛
  41379. var geoCoord = [126, 25];
  41380. var points$1 = [
  41381. [[0, 3.5], [7, 11.2], [15, 11.9], [30, 7], [42, 0.7], [52, 0.7],
  41382. [56, 7.7], [59, 0.7], [64, 0.7], [64, 0], [5, 0], [0, 3.5]],
  41383. [[13, 16.1], [19, 14.7], [16, 21.7], [11, 23.1], [13, 16.1]],
  41384. [[12, 32.2], [14, 38.5], [15, 38.5], [13, 32.2], [12, 32.2]],
  41385. [[16, 47.6], [12, 53.2], [13, 53.2], [18, 47.6], [16, 47.6]],
  41386. [[6, 64.4], [8, 70], [9, 70], [8, 64.4], [6, 64.4]],
  41387. [[23, 82.6], [29, 79.8], [30, 79.8], [25, 82.6], [23, 82.6]],
  41388. [[37, 70.7], [43, 62.3], [44, 62.3], [39, 70.7], [37, 70.7]],
  41389. [[48, 51.1], [51, 45.5], [53, 45.5], [50, 51.1], [48, 51.1]],
  41390. [[51, 35], [51, 28.7], [53, 28.7], [53, 35], [51, 35]],
  41391. [[52, 22.4], [55, 17.5], [56, 17.5], [53, 22.4], [52, 22.4]],
  41392. [[58, 12.6], [62, 7], [63, 7], [60, 12.6], [58, 12.6]],
  41393. [[0, 3.5], [0, 93.1], [64, 93.1], [64, 0], [63, 0], [63, 92.4],
  41394. [1, 92.4], [1, 3.5], [0, 3.5]]
  41395. ];
  41396. for (var i$1 = 0; i$1 < points$1.length; i$1++) {
  41397. for (var k = 0; k < points$1[i$1].length; k++) {
  41398. points$1[i$1][k][0] /= 10.5;
  41399. points$1[i$1][k][1] /= -10.5 / 0.75;
  41400. points$1[i$1][k][0] += geoCoord[0];
  41401. points$1[i$1][k][1] += geoCoord[1];
  41402. }
  41403. }
  41404. var fixNanhai = function (mapType, regions) {
  41405. if (mapType === 'china') {
  41406. regions.push(new Region(
  41407. '南海诸岛',
  41408. map(points$1, function (exterior) {
  41409. return {
  41410. type: 'polygon',
  41411. exterior: exterior
  41412. };
  41413. }), geoCoord
  41414. ));
  41415. }
  41416. };
  41417. /*
  41418. * Licensed to the Apache Software Foundation (ASF) under one
  41419. * or more contributor license agreements. See the NOTICE file
  41420. * distributed with this work for additional information
  41421. * regarding copyright ownership. The ASF licenses this file
  41422. * to you under the Apache License, Version 2.0 (the
  41423. * "License"); you may not use this file except in compliance
  41424. * with the License. You may obtain a copy of the License at
  41425. *
  41426. * http://www.apache.org/licenses/LICENSE-2.0
  41427. *
  41428. * Unless required by applicable law or agreed to in writing,
  41429. * software distributed under the License is distributed on an
  41430. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41431. * KIND, either express or implied. See the License for the
  41432. * specific language governing permissions and limitations
  41433. * under the License.
  41434. */
  41435. var coordsOffsetMap = {
  41436. '南海诸岛': [32, 80],
  41437. // 全国
  41438. '广东': [0, -10],
  41439. '香港': [10, 5],
  41440. '澳门': [-10, 10],
  41441. //'北京': [-10, 0],
  41442. '天津': [5, 5]
  41443. };
  41444. var fixTextCoord = function (mapType, region) {
  41445. if (mapType === 'china') {
  41446. var coordFix = coordsOffsetMap[region.name];
  41447. if (coordFix) {
  41448. var cp = region.center;
  41449. cp[0] += coordFix[0] / 10.5;
  41450. cp[1] += -coordFix[1] / (10.5 / 0.75);
  41451. }
  41452. }
  41453. };
  41454. /*
  41455. * Licensed to the Apache Software Foundation (ASF) under one
  41456. * or more contributor license agreements. See the NOTICE file
  41457. * distributed with this work for additional information
  41458. * regarding copyright ownership. The ASF licenses this file
  41459. * to you under the Apache License, Version 2.0 (the
  41460. * "License"); you may not use this file except in compliance
  41461. * with the License. You may obtain a copy of the License at
  41462. *
  41463. * http://www.apache.org/licenses/LICENSE-2.0
  41464. *
  41465. * Unless required by applicable law or agreed to in writing,
  41466. * software distributed under the License is distributed on an
  41467. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41468. * KIND, either express or implied. See the License for the
  41469. * specific language governing permissions and limitations
  41470. * under the License.
  41471. */
  41472. var geoCoordMap = {
  41473. 'Russia': [100, 60],
  41474. 'United States': [-99, 38],
  41475. 'United States of America': [-99, 38]
  41476. };
  41477. var fixGeoCoord = function (mapType, region) {
  41478. if (mapType === 'world') {
  41479. var geoCoord = geoCoordMap[region.name];
  41480. if (geoCoord) {
  41481. var cp = region.center;
  41482. cp[0] = geoCoord[0];
  41483. cp[1] = geoCoord[1];
  41484. }
  41485. }
  41486. };
  41487. /*
  41488. * Licensed to the Apache Software Foundation (ASF) under one
  41489. * or more contributor license agreements. See the NOTICE file
  41490. * distributed with this work for additional information
  41491. * regarding copyright ownership. The ASF licenses this file
  41492. * to you under the Apache License, Version 2.0 (the
  41493. * "License"); you may not use this file except in compliance
  41494. * with the License. You may obtain a copy of the License at
  41495. *
  41496. * http://www.apache.org/licenses/LICENSE-2.0
  41497. *
  41498. * Unless required by applicable law or agreed to in writing,
  41499. * software distributed under the License is distributed on an
  41500. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41501. * KIND, either express or implied. See the License for the
  41502. * specific language governing permissions and limitations
  41503. * under the License.
  41504. */
  41505. // Fix for 钓鱼岛
  41506. // var Region = require('../Region');
  41507. // var zrUtil = require('zrender/src/core/util');
  41508. // var geoCoord = [126, 25];
  41509. var points$2 = [
  41510. [
  41511. [123.45165252685547, 25.73527164402261],
  41512. [123.49731445312499, 25.73527164402261],
  41513. [123.49731445312499, 25.750734064600884],
  41514. [123.45165252685547, 25.750734064600884],
  41515. [123.45165252685547, 25.73527164402261]
  41516. ]
  41517. ];
  41518. var fixDiaoyuIsland = function (mapType, region) {
  41519. if (mapType === 'china' && region.name === '台湾') {
  41520. region.geometries.push({
  41521. type: 'polygon',
  41522. exterior: points$2[0]
  41523. });
  41524. }
  41525. };
  41526. /*
  41527. * Licensed to the Apache Software Foundation (ASF) under one
  41528. * or more contributor license agreements. See the NOTICE file
  41529. * distributed with this work for additional information
  41530. * regarding copyright ownership. The ASF licenses this file
  41531. * to you under the Apache License, Version 2.0 (the
  41532. * "License"); you may not use this file except in compliance
  41533. * with the License. You may obtain a copy of the License at
  41534. *
  41535. * http://www.apache.org/licenses/LICENSE-2.0
  41536. *
  41537. * Unless required by applicable law or agreed to in writing,
  41538. * software distributed under the License is distributed on an
  41539. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41540. * KIND, either express or implied. See the License for the
  41541. * specific language governing permissions and limitations
  41542. * under the License.
  41543. */
  41544. // Built-in GEO fixer.
  41545. var inner$7 = makeInner();
  41546. var geoJSONLoader = {
  41547. /**
  41548. * @param {string} mapName
  41549. * @param {Object} mapRecord {specialAreas, geoJSON}
  41550. * @param {string} nameProperty
  41551. * @return {Object} {regions, boundingRect}
  41552. */
  41553. load: function (mapName, mapRecord, nameProperty) {
  41554. var parsed = inner$7(mapRecord).parsed;
  41555. if (parsed) {
  41556. return parsed;
  41557. }
  41558. var specialAreas = mapRecord.specialAreas || {};
  41559. var geoJSON = mapRecord.geoJSON;
  41560. var regions;
  41561. // https://jsperf.com/try-catch-performance-overhead
  41562. try {
  41563. regions = geoJSON ? parseGeoJson$1(geoJSON, nameProperty) : [];
  41564. }
  41565. catch (e) {
  41566. throw new Error('Invalid geoJson format\n' + e.message);
  41567. }
  41568. fixNanhai(mapName, regions);
  41569. each$1(regions, function (region) {
  41570. var regionName = region.name;
  41571. fixTextCoord(mapName, region);
  41572. fixGeoCoord(mapName, region);
  41573. fixDiaoyuIsland(mapName, region);
  41574. // Some area like Alaska in USA map needs to be tansformed
  41575. // to look better
  41576. var specialArea = specialAreas[regionName];
  41577. if (specialArea) {
  41578. region.transformTo(
  41579. specialArea.left, specialArea.top, specialArea.width, specialArea.height
  41580. );
  41581. }
  41582. });
  41583. return (inner$7(mapRecord).parsed = {
  41584. regions: regions,
  41585. boundingRect: getBoundingRect$1(regions)
  41586. });
  41587. }
  41588. };
  41589. function getBoundingRect$1(regions) {
  41590. var rect;
  41591. for (var i = 0; i < regions.length; i++) {
  41592. var regionRect = regions[i].getBoundingRect();
  41593. rect = rect || regionRect.clone();
  41594. rect.union(regionRect);
  41595. }
  41596. return rect;
  41597. }
  41598. /*
  41599. * Licensed to the Apache Software Foundation (ASF) under one
  41600. * or more contributor license agreements. See the NOTICE file
  41601. * distributed with this work for additional information
  41602. * regarding copyright ownership. The ASF licenses this file
  41603. * to you under the Apache License, Version 2.0 (the
  41604. * "License"); you may not use this file except in compliance
  41605. * with the License. You may obtain a copy of the License at
  41606. *
  41607. * http://www.apache.org/licenses/LICENSE-2.0
  41608. *
  41609. * Unless required by applicable law or agreed to in writing,
  41610. * software distributed under the License is distributed on an
  41611. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41612. * KIND, either express or implied. See the License for the
  41613. * specific language governing permissions and limitations
  41614. * under the License.
  41615. */
  41616. var inner$8 = makeInner();
  41617. var geoSVGLoader = {
  41618. /**
  41619. * @param {string} mapName
  41620. * @param {Object} mapRecord {specialAreas, geoJSON}
  41621. * @return {Object} {root, boundingRect}
  41622. */
  41623. load: function (mapName, mapRecord) {
  41624. var originRoot = inner$8(mapRecord).originRoot;
  41625. if (originRoot) {
  41626. return {
  41627. root: originRoot,
  41628. boundingRect: inner$8(mapRecord).boundingRect
  41629. };
  41630. }
  41631. var graphic = buildGraphic(mapRecord);
  41632. inner$8(mapRecord).originRoot = graphic.root;
  41633. inner$8(mapRecord).boundingRect = graphic.boundingRect;
  41634. return graphic;
  41635. },
  41636. makeGraphic: function (mapName, mapRecord, hostKey) {
  41637. // For performance consideration (in large SVG), graphic only maked
  41638. // when necessary and reuse them according to hostKey.
  41639. var field = inner$8(mapRecord);
  41640. var rootMap = field.rootMap || (field.rootMap = createHashMap());
  41641. var root = rootMap.get(hostKey);
  41642. if (root) {
  41643. return root;
  41644. }
  41645. var originRoot = field.originRoot;
  41646. var boundingRect = field.boundingRect;
  41647. // For performance, if originRoot is not used by a view,
  41648. // assign it to a view, but not reproduce graphic elements.
  41649. if (!field.originRootHostKey) {
  41650. field.originRootHostKey = hostKey;
  41651. root = originRoot;
  41652. }
  41653. else {
  41654. root = buildGraphic(mapRecord, boundingRect).root;
  41655. }
  41656. return rootMap.set(hostKey, root);
  41657. },
  41658. removeGraphic: function (mapName, mapRecord, hostKey) {
  41659. var field = inner$8(mapRecord);
  41660. var rootMap = field.rootMap;
  41661. rootMap && rootMap.removeKey(hostKey);
  41662. if (hostKey === field.originRootHostKey) {
  41663. field.originRootHostKey = null;
  41664. }
  41665. }
  41666. };
  41667. function buildGraphic(mapRecord, boundingRect) {
  41668. var svgXML = mapRecord.svgXML;
  41669. var result;
  41670. var root;
  41671. try {
  41672. result = svgXML && parseSVG(svgXML, {
  41673. ignoreViewBox: true,
  41674. ignoreRootClip: true
  41675. }) || {};
  41676. root = result.root;
  41677. assert$1(root != null);
  41678. }
  41679. catch (e) {
  41680. throw new Error('Invalid svg format\n' + e.message);
  41681. }
  41682. var svgWidth = result.width;
  41683. var svgHeight = result.height;
  41684. var viewBoxRect = result.viewBoxRect;
  41685. if (!boundingRect) {
  41686. boundingRect = (svgWidth == null || svgHeight == null)
  41687. // If svg width / height not specified, calculate
  41688. // bounding rect as the width / height
  41689. ? root.getBoundingRect()
  41690. : new BoundingRect(0, 0, 0, 0);
  41691. if (svgWidth != null) {
  41692. boundingRect.width = svgWidth;
  41693. }
  41694. if (svgHeight != null) {
  41695. boundingRect.height = svgHeight;
  41696. }
  41697. }
  41698. if (viewBoxRect) {
  41699. var viewBoxTransform = makeViewBoxTransform(viewBoxRect, boundingRect.width, boundingRect.height);
  41700. var elRoot = root;
  41701. root = new Group();
  41702. root.add(elRoot);
  41703. elRoot.scale = viewBoxTransform.scale;
  41704. elRoot.position = viewBoxTransform.position;
  41705. }
  41706. root.setClipPath(new Rect({
  41707. shape: boundingRect.plain()
  41708. }));
  41709. return {
  41710. root: root,
  41711. boundingRect: boundingRect
  41712. };
  41713. }
  41714. /*
  41715. * Licensed to the Apache Software Foundation (ASF) under one
  41716. * or more contributor license agreements. See the NOTICE file
  41717. * distributed with this work for additional information
  41718. * regarding copyright ownership. The ASF licenses this file
  41719. * to you under the Apache License, Version 2.0 (the
  41720. * "License"); you may not use this file except in compliance
  41721. * with the License. You may obtain a copy of the License at
  41722. *
  41723. * http://www.apache.org/licenses/LICENSE-2.0
  41724. *
  41725. * Unless required by applicable law or agreed to in writing,
  41726. * software distributed under the License is distributed on an
  41727. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41728. * KIND, either express or implied. See the License for the
  41729. * specific language governing permissions and limitations
  41730. * under the License.
  41731. */
  41732. var loaders = {
  41733. geoJSON: geoJSONLoader,
  41734. svg: geoSVGLoader
  41735. };
  41736. var geoSourceManager = {
  41737. /**
  41738. * @param {string} mapName
  41739. * @param {Object} nameMap
  41740. * @param {string} nameProperty
  41741. * @return {Object} source {regions, regionsMap, nameCoordMap, boundingRect}
  41742. */
  41743. load: function (mapName, nameMap, nameProperty) {
  41744. var regions = [];
  41745. var regionsMap = createHashMap();
  41746. var nameCoordMap = createHashMap();
  41747. var boundingRect;
  41748. var mapRecords = retrieveMap(mapName);
  41749. each$1(mapRecords, function (record) {
  41750. var singleSource = loaders[record.type].load(mapName, record, nameProperty);
  41751. each$1(singleSource.regions, function (region) {
  41752. var regionName = region.name;
  41753. // Try use the alias in geoNameMap
  41754. if (nameMap && nameMap.hasOwnProperty(regionName)) {
  41755. region = region.cloneShallow(regionName = nameMap[regionName]);
  41756. }
  41757. regions.push(region);
  41758. regionsMap.set(regionName, region);
  41759. nameCoordMap.set(regionName, region.center);
  41760. });
  41761. var rect = singleSource.boundingRect;
  41762. if (rect) {
  41763. boundingRect
  41764. ? boundingRect.union(rect)
  41765. : (boundingRect = rect.clone());
  41766. }
  41767. });
  41768. return {
  41769. regions: regions,
  41770. regionsMap: regionsMap,
  41771. nameCoordMap: nameCoordMap,
  41772. // FIXME Always return new ?
  41773. boundingRect: boundingRect || new BoundingRect(0, 0, 0, 0)
  41774. };
  41775. },
  41776. /**
  41777. * @param {string} mapName
  41778. * @param {string} hostKey For cache.
  41779. * @return {Array.<module:zrender/Element>} Roots.
  41780. */
  41781. makeGraphic: makeInvoker('makeGraphic'),
  41782. /**
  41783. * @param {string} mapName
  41784. * @param {string} hostKey For cache.
  41785. */
  41786. removeGraphic: makeInvoker('removeGraphic')
  41787. };
  41788. function makeInvoker(methodName) {
  41789. return function (mapName, hostKey) {
  41790. var mapRecords = retrieveMap(mapName);
  41791. var results = [];
  41792. each$1(mapRecords, function (record) {
  41793. var method = loaders[record.type][methodName];
  41794. method && results.push(method(mapName, record, hostKey));
  41795. });
  41796. return results;
  41797. };
  41798. }
  41799. function mapNotExistsError(mapName) {
  41800. if (__DEV__) {
  41801. console.error(
  41802. 'Map ' + mapName + ' not exists. The GeoJSON of the map must be provided.'
  41803. );
  41804. }
  41805. }
  41806. function retrieveMap(mapName) {
  41807. var mapRecords = mapDataStorage.retrieveMap(mapName) || [];
  41808. if (__DEV__) {
  41809. if (!mapRecords.length) {
  41810. mapNotExistsError(mapName);
  41811. }
  41812. }
  41813. return mapRecords;
  41814. }
  41815. /*
  41816. * Licensed to the Apache Software Foundation (ASF) under one
  41817. * or more contributor license agreements. See the NOTICE file
  41818. * distributed with this work for additional information
  41819. * regarding copyright ownership. The ASF licenses this file
  41820. * to you under the Apache License, Version 2.0 (the
  41821. * "License"); you may not use this file except in compliance
  41822. * with the License. You may obtain a copy of the License at
  41823. *
  41824. * http://www.apache.org/licenses/LICENSE-2.0
  41825. *
  41826. * Unless required by applicable law or agreed to in writing,
  41827. * software distributed under the License is distributed on an
  41828. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41829. * KIND, either express or implied. See the License for the
  41830. * specific language governing permissions and limitations
  41831. * under the License.
  41832. */
  41833. var MapSeries = SeriesModel.extend({
  41834. type: 'series.map',
  41835. dependencies: ['geo'],
  41836. layoutMode: 'box',
  41837. /**
  41838. * Only first map series of same mapType will drawMap
  41839. * @type {boolean}
  41840. */
  41841. needsDrawMap: false,
  41842. /**
  41843. * Group of all map series with same mapType
  41844. * @type {boolean}
  41845. */
  41846. seriesGroup: [],
  41847. getInitialData: function (option) {
  41848. var data = createListSimply(this, {
  41849. coordDimensions: ['value'],
  41850. encodeDefaulter: curry(makeSeriesEncodeForNameBased, this)
  41851. });
  41852. var valueDim = data.mapDimension('value');
  41853. var dataNameMap = createHashMap();
  41854. var selectTargetList = [];
  41855. var toAppendNames = [];
  41856. for (var i = 0, len = data.count(); i < len; i++) {
  41857. var name = data.getName(i);
  41858. dataNameMap.set(name, true);
  41859. selectTargetList.push({
  41860. name: name,
  41861. value: data.get(valueDim, i),
  41862. selected: retrieveRawAttr(data, i, 'selected')
  41863. });
  41864. }
  41865. var geoSource = geoSourceManager.load(this.getMapType(), this.option.nameMap, this.option.nameProperty);
  41866. each$1(geoSource.regions, function (region) {
  41867. var name = region.name;
  41868. if (!dataNameMap.get(name)) {
  41869. selectTargetList.push({name: name});
  41870. toAppendNames.push(name);
  41871. }
  41872. });
  41873. this.updateSelectedMap(selectTargetList);
  41874. // Complete data with missing regions. The consequent processes (like visual
  41875. // map and render) can not be performed without a "full data". For example,
  41876. // find `dataIndex` by name.
  41877. data.appendValues([], toAppendNames);
  41878. return data;
  41879. },
  41880. /**
  41881. * If no host geo model, return null, which means using a
  41882. * inner exclusive geo model.
  41883. */
  41884. getHostGeoModel: function () {
  41885. var geoIndex = this.option.geoIndex;
  41886. return geoIndex != null
  41887. ? this.dependentModels.geo[geoIndex]
  41888. : null;
  41889. },
  41890. getMapType: function () {
  41891. return (this.getHostGeoModel() || this).option.map;
  41892. },
  41893. // _fillOption: function (option, mapName) {
  41894. // Shallow clone
  41895. // option = zrUtil.extend({}, option);
  41896. // option.data = geoCreator.getFilledRegions(option.data, mapName, option.nameMap);
  41897. // return option;
  41898. // },
  41899. getRawValue: function (dataIndex) {
  41900. // Use value stored in data instead because it is calculated from multiple series
  41901. // FIXME Provide all value of multiple series ?
  41902. var data = this.getData();
  41903. return data.get(data.mapDimension('value'), dataIndex);
  41904. },
  41905. /**
  41906. * Get model of region
  41907. * @param {string} name
  41908. * @return {module:echarts/model/Model}
  41909. */
  41910. getRegionModel: function (regionName) {
  41911. var data = this.getData();
  41912. return data.getItemModel(data.indexOfName(regionName));
  41913. },
  41914. /**
  41915. * Map tooltip formatter
  41916. *
  41917. * @param {number} dataIndex
  41918. */
  41919. formatTooltip: function (dataIndex) {
  41920. // FIXME orignalData and data is a bit confusing
  41921. var data = this.getData();
  41922. var formattedValue = addCommas(this.getRawValue(dataIndex));
  41923. var name = data.getName(dataIndex);
  41924. var seriesGroup = this.seriesGroup;
  41925. var seriesNames = [];
  41926. for (var i = 0; i < seriesGroup.length; i++) {
  41927. var otherIndex = seriesGroup[i].originalData.indexOfName(name);
  41928. var valueDim = data.mapDimension('value');
  41929. if (!isNaN(seriesGroup[i].originalData.get(valueDim, otherIndex))) {
  41930. seriesNames.push(
  41931. encodeHTML(seriesGroup[i].name)
  41932. );
  41933. }
  41934. }
  41935. return seriesNames.join(', ') + '<br />'
  41936. + encodeHTML(name + ' : ' + formattedValue);
  41937. },
  41938. /**
  41939. * @implement
  41940. */
  41941. getTooltipPosition: function (dataIndex) {
  41942. if (dataIndex != null) {
  41943. var name = this.getData().getName(dataIndex);
  41944. var geo = this.coordinateSystem;
  41945. var region = geo.getRegion(name);
  41946. return region && geo.dataToPoint(region.center);
  41947. }
  41948. },
  41949. setZoom: function (zoom) {
  41950. this.option.zoom = zoom;
  41951. },
  41952. setCenter: function (center) {
  41953. this.option.center = center;
  41954. },
  41955. defaultOption: {
  41956. // 一级层叠
  41957. zlevel: 0,
  41958. // 二级层叠
  41959. z: 2,
  41960. coordinateSystem: 'geo',
  41961. // map should be explicitly specified since ec3.
  41962. map: '',
  41963. // If `geoIndex` is not specified, a exclusive geo will be
  41964. // created. Otherwise use the specified geo component, and
  41965. // `map` and `mapType` are ignored.
  41966. // geoIndex: 0,
  41967. // 'center' | 'left' | 'right' | 'x%' | {number}
  41968. left: 'center',
  41969. // 'center' | 'top' | 'bottom' | 'x%' | {number}
  41970. top: 'center',
  41971. // right
  41972. // bottom
  41973. // width:
  41974. // height
  41975. // Aspect is width / height. Inited to be geoJson bbox aspect
  41976. // This parameter is used for scale this aspect
  41977. aspectScale: 0.75,
  41978. ///// Layout with center and size
  41979. // If you wan't to put map in a fixed size box with right aspect ratio
  41980. // This two properties may more conveninet
  41981. // layoutCenter: [50%, 50%]
  41982. // layoutSize: 100
  41983. // 数值合并方式,默认加和,可选为:
  41984. // 'sum' | 'average' | 'max' | 'min'
  41985. // mapValueCalculation: 'sum',
  41986. // 地图数值计算结果小数精度
  41987. // mapValuePrecision: 0,
  41988. // 显示图例颜色标识(系列标识的小圆点),图例开启时有效
  41989. showLegendSymbol: true,
  41990. // 选择模式,默认关闭,可选single,multiple
  41991. // selectedMode: false,
  41992. dataRangeHoverLink: true,
  41993. // 是否开启缩放及漫游模式
  41994. // roam: false,
  41995. // Define left-top, right-bottom coords to control view
  41996. // For example, [ [180, 90], [-180, -90] ],
  41997. // higher priority than center and zoom
  41998. boundingCoords: null,
  41999. // Default on center of map
  42000. center: null,
  42001. zoom: 1,
  42002. scaleLimit: null,
  42003. label: {
  42004. show: false,
  42005. color: '#000'
  42006. },
  42007. // scaleLimit: null,
  42008. itemStyle: {
  42009. borderWidth: 0.5,
  42010. borderColor: '#444',
  42011. areaColor: '#eee'
  42012. },
  42013. emphasis: {
  42014. label: {
  42015. show: true,
  42016. color: 'rgb(100,0,0)'
  42017. },
  42018. itemStyle: {
  42019. areaColor: 'rgba(255,215,0,0.8)'
  42020. }
  42021. },
  42022. nameProperty: 'name'
  42023. }
  42024. });
  42025. mixin(MapSeries, selectableMixin);
  42026. /*
  42027. * Licensed to the Apache Software Foundation (ASF) under one
  42028. * or more contributor license agreements. See the NOTICE file
  42029. * distributed with this work for additional information
  42030. * regarding copyright ownership. The ASF licenses this file
  42031. * to you under the Apache License, Version 2.0 (the
  42032. * "License"); you may not use this file except in compliance
  42033. * with the License. You may obtain a copy of the License at
  42034. *
  42035. * http://www.apache.org/licenses/LICENSE-2.0
  42036. *
  42037. * Unless required by applicable law or agreed to in writing,
  42038. * software distributed under the License is distributed on an
  42039. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42040. * KIND, either express or implied. See the License for the
  42041. * specific language governing permissions and limitations
  42042. * under the License.
  42043. */
  42044. var ATTR = '\0_ec_interaction_mutex';
  42045. function take(zr, resourceKey, userKey) {
  42046. var store = getStore(zr);
  42047. store[resourceKey] = userKey;
  42048. }
  42049. function release(zr, resourceKey, userKey) {
  42050. var store = getStore(zr);
  42051. var uKey = store[resourceKey];
  42052. if (uKey === userKey) {
  42053. store[resourceKey] = null;
  42054. }
  42055. }
  42056. function isTaken(zr, resourceKey) {
  42057. return !!getStore(zr)[resourceKey];
  42058. }
  42059. function getStore(zr) {
  42060. return zr[ATTR] || (zr[ATTR] = {});
  42061. }
  42062. /**
  42063. * payload: {
  42064. * type: 'takeGlobalCursor',
  42065. * key: 'dataZoomSelect', or 'brush', or ...,
  42066. * If no userKey, release global cursor.
  42067. * }
  42068. */
  42069. registerAction(
  42070. {type: 'takeGlobalCursor', event: 'globalCursorTaken', update: 'update'},
  42071. function () {}
  42072. );
  42073. /*
  42074. * Licensed to the Apache Software Foundation (ASF) under one
  42075. * or more contributor license agreements. See the NOTICE file
  42076. * distributed with this work for additional information
  42077. * regarding copyright ownership. The ASF licenses this file
  42078. * to you under the Apache License, Version 2.0 (the
  42079. * "License"); you may not use this file except in compliance
  42080. * with the License. You may obtain a copy of the License at
  42081. *
  42082. * http://www.apache.org/licenses/LICENSE-2.0
  42083. *
  42084. * Unless required by applicable law or agreed to in writing,
  42085. * software distributed under the License is distributed on an
  42086. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42087. * KIND, either express or implied. See the License for the
  42088. * specific language governing permissions and limitations
  42089. * under the License.
  42090. */
  42091. /**
  42092. * @alias module:echarts/component/helper/RoamController
  42093. * @constructor
  42094. * @mixin {module:zrender/mixin/Eventful}
  42095. *
  42096. * @param {module:zrender/zrender~ZRender} zr
  42097. */
  42098. function RoamController(zr) {
  42099. /**
  42100. * @type {Function}
  42101. */
  42102. this.pointerChecker;
  42103. /**
  42104. * @type {module:zrender}
  42105. */
  42106. this._zr = zr;
  42107. /**
  42108. * @type {Object}
  42109. */
  42110. this._opt = {};
  42111. // Avoid two roamController bind the same handler
  42112. var bind$$1 = bind;
  42113. var mousedownHandler = bind$$1(mousedown, this);
  42114. var mousemoveHandler = bind$$1(mousemove, this);
  42115. var mouseupHandler = bind$$1(mouseup, this);
  42116. var mousewheelHandler = bind$$1(mousewheel, this);
  42117. var pinchHandler = bind$$1(pinch, this);
  42118. Eventful.call(this);
  42119. /**
  42120. * @param {Function} pointerChecker
  42121. * input: x, y
  42122. * output: boolean
  42123. */
  42124. this.setPointerChecker = function (pointerChecker) {
  42125. this.pointerChecker = pointerChecker;
  42126. };
  42127. /**
  42128. * Notice: only enable needed types. For example, if 'zoom'
  42129. * is not needed, 'zoom' should not be enabled, otherwise
  42130. * default mousewheel behaviour (scroll page) will be disabled.
  42131. *
  42132. * @param {boolean|string} [controlType=true] Specify the control type,
  42133. * which can be null/undefined or true/false
  42134. * or 'pan/move' or 'zoom'/'scale'
  42135. * @param {Object} [opt]
  42136. * @param {Object} [opt.zoomOnMouseWheel=true] The value can be: true / false / 'shift' / 'ctrl' / 'alt'.
  42137. * @param {Object} [opt.moveOnMouseMove=true] The value can be: true / false / 'shift' / 'ctrl' / 'alt'.
  42138. * @param {Object} [opt.moveOnMouseWheel=false] The value can be: true / false / 'shift' / 'ctrl' / 'alt'.
  42139. * @param {Object} [opt.preventDefaultMouseMove=true] When pan.
  42140. */
  42141. this.enable = function (controlType, opt) {
  42142. // Disable previous first
  42143. this.disable();
  42144. this._opt = defaults(clone(opt) || {}, {
  42145. zoomOnMouseWheel: true,
  42146. moveOnMouseMove: true,
  42147. // By default, wheel do not trigger move.
  42148. moveOnMouseWheel: false,
  42149. preventDefaultMouseMove: true
  42150. });
  42151. if (controlType == null) {
  42152. controlType = true;
  42153. }
  42154. if (controlType === true || (controlType === 'move' || controlType === 'pan')) {
  42155. zr.on('mousedown', mousedownHandler);
  42156. zr.on('mousemove', mousemoveHandler);
  42157. zr.on('mouseup', mouseupHandler);
  42158. }
  42159. if (controlType === true || (controlType === 'scale' || controlType === 'zoom')) {
  42160. zr.on('mousewheel', mousewheelHandler);
  42161. zr.on('pinch', pinchHandler);
  42162. }
  42163. };
  42164. this.disable = function () {
  42165. zr.off('mousedown', mousedownHandler);
  42166. zr.off('mousemove', mousemoveHandler);
  42167. zr.off('mouseup', mouseupHandler);
  42168. zr.off('mousewheel', mousewheelHandler);
  42169. zr.off('pinch', pinchHandler);
  42170. };
  42171. this.dispose = this.disable;
  42172. this.isDragging = function () {
  42173. return this._dragging;
  42174. };
  42175. this.isPinching = function () {
  42176. return this._pinching;
  42177. };
  42178. }
  42179. mixin(RoamController, Eventful);
  42180. function mousedown(e) {
  42181. if (isMiddleOrRightButtonOnMouseUpDown(e)
  42182. || (e.target && e.target.draggable)
  42183. ) {
  42184. return;
  42185. }
  42186. var x = e.offsetX;
  42187. var y = e.offsetY;
  42188. // Only check on mosedown, but not mousemove.
  42189. // Mouse can be out of target when mouse moving.
  42190. if (this.pointerChecker && this.pointerChecker(e, x, y)) {
  42191. this._x = x;
  42192. this._y = y;
  42193. this._dragging = true;
  42194. }
  42195. }
  42196. function mousemove(e) {
  42197. if (!this._dragging
  42198. || !isAvailableBehavior('moveOnMouseMove', e, this._opt)
  42199. || e.gestureEvent === 'pinch'
  42200. || isTaken(this._zr, 'globalPan')
  42201. ) {
  42202. return;
  42203. }
  42204. var x = e.offsetX;
  42205. var y = e.offsetY;
  42206. var oldX = this._x;
  42207. var oldY = this._y;
  42208. var dx = x - oldX;
  42209. var dy = y - oldY;
  42210. this._x = x;
  42211. this._y = y;
  42212. this._opt.preventDefaultMouseMove && stop(e.event);
  42213. trigger(this, 'pan', 'moveOnMouseMove', e, {
  42214. dx: dx, dy: dy, oldX: oldX, oldY: oldY, newX: x, newY: y
  42215. });
  42216. }
  42217. function mouseup(e) {
  42218. if (!isMiddleOrRightButtonOnMouseUpDown(e)) {
  42219. this._dragging = false;
  42220. }
  42221. }
  42222. function mousewheel(e) {
  42223. var shouldZoom = isAvailableBehavior('zoomOnMouseWheel', e, this._opt);
  42224. var shouldMove = isAvailableBehavior('moveOnMouseWheel', e, this._opt);
  42225. var wheelDelta = e.wheelDelta;
  42226. var absWheelDeltaDelta = Math.abs(wheelDelta);
  42227. var originX = e.offsetX;
  42228. var originY = e.offsetY;
  42229. // wheelDelta maybe -0 in chrome mac.
  42230. if (wheelDelta === 0 || (!shouldZoom && !shouldMove)) {
  42231. return;
  42232. }
  42233. // If both `shouldZoom` and `shouldMove` is true, trigger
  42234. // their event both, and the final behavior is determined
  42235. // by event listener themselves.
  42236. if (shouldZoom) {
  42237. // Convenience:
  42238. // Mac and VM Windows on Mac: scroll up: zoom out.
  42239. // Windows: scroll up: zoom in.
  42240. // FIXME: Should do more test in different environment.
  42241. // wheelDelta is too complicated in difference nvironment
  42242. // (https://developer.mozilla.org/en-US/docs/Web/Events/mousewheel),
  42243. // although it has been normallized by zrender.
  42244. // wheelDelta of mouse wheel is bigger than touch pad.
  42245. var factor = absWheelDeltaDelta > 3 ? 1.4 : absWheelDeltaDelta > 1 ? 1.2 : 1.1;
  42246. var scale = wheelDelta > 0 ? factor : 1 / factor;
  42247. checkPointerAndTrigger(this, 'zoom', 'zoomOnMouseWheel', e, {
  42248. scale: scale, originX: originX, originY: originY
  42249. });
  42250. }
  42251. if (shouldMove) {
  42252. // FIXME: Should do more test in different environment.
  42253. var absDelta = Math.abs(wheelDelta);
  42254. // wheelDelta of mouse wheel is bigger than touch pad.
  42255. var scrollDelta = (wheelDelta > 0 ? 1 : -1) * (absDelta > 3 ? 0.4 : absDelta > 1 ? 0.15 : 0.05);
  42256. checkPointerAndTrigger(this, 'scrollMove', 'moveOnMouseWheel', e, {
  42257. scrollDelta: scrollDelta, originX: originX, originY: originY
  42258. });
  42259. }
  42260. }
  42261. function pinch(e) {
  42262. if (isTaken(this._zr, 'globalPan')) {
  42263. return;
  42264. }
  42265. var scale = e.pinchScale > 1 ? 1.1 : 1 / 1.1;
  42266. checkPointerAndTrigger(this, 'zoom', null, e, {
  42267. scale: scale, originX: e.pinchX, originY: e.pinchY
  42268. });
  42269. }
  42270. function checkPointerAndTrigger(controller, eventName, behaviorToCheck, e, contollerEvent) {
  42271. if (controller.pointerChecker
  42272. && controller.pointerChecker(e, contollerEvent.originX, contollerEvent.originY)
  42273. ) {
  42274. // When mouse is out of roamController rect,
  42275. // default befavoius should not be be disabled, otherwise
  42276. // page sliding is disabled, contrary to expectation.
  42277. stop(e.event);
  42278. trigger(controller, eventName, behaviorToCheck, e, contollerEvent);
  42279. }
  42280. }
  42281. function trigger(controller, eventName, behaviorToCheck, e, contollerEvent) {
  42282. // Also provide behavior checker for event listener, for some case that
  42283. // multiple components share one listener.
  42284. contollerEvent.isAvailableBehavior = bind(isAvailableBehavior, null, behaviorToCheck, e);
  42285. controller.trigger(eventName, contollerEvent);
  42286. }
  42287. // settings: {
  42288. // zoomOnMouseWheel
  42289. // moveOnMouseMove
  42290. // moveOnMouseWheel
  42291. // }
  42292. // The value can be: true / false / 'shift' / 'ctrl' / 'alt'.
  42293. function isAvailableBehavior(behaviorToCheck, e, settings) {
  42294. var setting = settings[behaviorToCheck];
  42295. return !behaviorToCheck || (
  42296. setting && (!isString(setting) || e.event[setting + 'Key'])
  42297. );
  42298. }
  42299. /*
  42300. * Licensed to the Apache Software Foundation (ASF) under one
  42301. * or more contributor license agreements. See the NOTICE file
  42302. * distributed with this work for additional information
  42303. * regarding copyright ownership. The ASF licenses this file
  42304. * to you under the Apache License, Version 2.0 (the
  42305. * "License"); you may not use this file except in compliance
  42306. * with the License. You may obtain a copy of the License at
  42307. *
  42308. * http://www.apache.org/licenses/LICENSE-2.0
  42309. *
  42310. * Unless required by applicable law or agreed to in writing,
  42311. * software distributed under the License is distributed on an
  42312. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42313. * KIND, either express or implied. See the License for the
  42314. * specific language governing permissions and limitations
  42315. * under the License.
  42316. */
  42317. /**
  42318. * For geo and graph.
  42319. *
  42320. * @param {Object} controllerHost
  42321. * @param {module:zrender/Element} controllerHost.target
  42322. */
  42323. function updateViewOnPan(controllerHost, dx, dy) {
  42324. var target = controllerHost.target;
  42325. var pos = target.position;
  42326. pos[0] += dx;
  42327. pos[1] += dy;
  42328. target.dirty();
  42329. }
  42330. /**
  42331. * For geo and graph.
  42332. *
  42333. * @param {Object} controllerHost
  42334. * @param {module:zrender/Element} controllerHost.target
  42335. * @param {number} controllerHost.zoom
  42336. * @param {number} controllerHost.zoomLimit like: {min: 1, max: 2}
  42337. */
  42338. function updateViewOnZoom(controllerHost, zoomDelta, zoomX, zoomY) {
  42339. var target = controllerHost.target;
  42340. var zoomLimit = controllerHost.zoomLimit;
  42341. var pos = target.position;
  42342. var scale = target.scale;
  42343. var newZoom = controllerHost.zoom = controllerHost.zoom || 1;
  42344. newZoom *= zoomDelta;
  42345. if (zoomLimit) {
  42346. var zoomMin = zoomLimit.min || 0;
  42347. var zoomMax = zoomLimit.max || Infinity;
  42348. newZoom = Math.max(
  42349. Math.min(zoomMax, newZoom),
  42350. zoomMin
  42351. );
  42352. }
  42353. var zoomScale = newZoom / controllerHost.zoom;
  42354. controllerHost.zoom = newZoom;
  42355. // Keep the mouse center when scaling
  42356. pos[0] -= (zoomX - pos[0]) * (zoomScale - 1);
  42357. pos[1] -= (zoomY - pos[1]) * (zoomScale - 1);
  42358. scale[0] *= zoomScale;
  42359. scale[1] *= zoomScale;
  42360. target.dirty();
  42361. }
  42362. /*
  42363. * Licensed to the Apache Software Foundation (ASF) under one
  42364. * or more contributor license agreements. See the NOTICE file
  42365. * distributed with this work for additional information
  42366. * regarding copyright ownership. The ASF licenses this file
  42367. * to you under the Apache License, Version 2.0 (the
  42368. * "License"); you may not use this file except in compliance
  42369. * with the License. You may obtain a copy of the License at
  42370. *
  42371. * http://www.apache.org/licenses/LICENSE-2.0
  42372. *
  42373. * Unless required by applicable law or agreed to in writing,
  42374. * software distributed under the License is distributed on an
  42375. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42376. * KIND, either express or implied. See the License for the
  42377. * specific language governing permissions and limitations
  42378. * under the License.
  42379. */
  42380. var IRRELEVANT_EXCLUDES = {'axisPointer': 1, 'tooltip': 1, 'brush': 1};
  42381. /**
  42382. * Avoid that: mouse click on a elements that is over geo or graph,
  42383. * but roam is triggered.
  42384. */
  42385. function onIrrelevantElement(e, api, targetCoordSysModel) {
  42386. var model = api.getComponentByElement(e.topTarget);
  42387. // If model is axisModel, it works only if it is injected with coordinateSystem.
  42388. var coordSys = model && model.coordinateSystem;
  42389. return model
  42390. && model !== targetCoordSysModel
  42391. && !IRRELEVANT_EXCLUDES[model.mainType]
  42392. && (coordSys && coordSys.model !== targetCoordSysModel);
  42393. }
  42394. /*
  42395. * Licensed to the Apache Software Foundation (ASF) under one
  42396. * or more contributor license agreements. See the NOTICE file
  42397. * distributed with this work for additional information
  42398. * regarding copyright ownership. The ASF licenses this file
  42399. * to you under the Apache License, Version 2.0 (the
  42400. * "License"); you may not use this file except in compliance
  42401. * with the License. You may obtain a copy of the License at
  42402. *
  42403. * http://www.apache.org/licenses/LICENSE-2.0
  42404. *
  42405. * Unless required by applicable law or agreed to in writing,
  42406. * software distributed under the License is distributed on an
  42407. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42408. * KIND, either express or implied. See the License for the
  42409. * specific language governing permissions and limitations
  42410. * under the License.
  42411. */
  42412. function getFixedItemStyle(model) {
  42413. var itemStyle = model.getItemStyle();
  42414. var areaColor = model.get('areaColor');
  42415. // If user want the color not to be changed when hover,
  42416. // they should both set areaColor and color to be null.
  42417. if (areaColor != null) {
  42418. itemStyle.fill = areaColor;
  42419. }
  42420. return itemStyle;
  42421. }
  42422. function updateMapSelectHandler(mapDraw, mapOrGeoModel, regionsGroup, api, fromView) {
  42423. regionsGroup.off('click');
  42424. regionsGroup.off('mousedown');
  42425. if (mapOrGeoModel.get('selectedMode')) {
  42426. regionsGroup.on('mousedown', function () {
  42427. mapDraw._mouseDownFlag = true;
  42428. });
  42429. regionsGroup.on('click', function (e) {
  42430. if (!mapDraw._mouseDownFlag) {
  42431. return;
  42432. }
  42433. mapDraw._mouseDownFlag = false;
  42434. var el = e.target;
  42435. while (!el.__regions) {
  42436. el = el.parent;
  42437. }
  42438. if (!el) {
  42439. return;
  42440. }
  42441. var action = {
  42442. type: (mapOrGeoModel.mainType === 'geo' ? 'geo' : 'map') + 'ToggleSelect',
  42443. batch: map(el.__regions, function (region) {
  42444. return {
  42445. name: region.name,
  42446. from: fromView.uid
  42447. };
  42448. })
  42449. };
  42450. action[mapOrGeoModel.mainType + 'Id'] = mapOrGeoModel.id;
  42451. api.dispatchAction(action);
  42452. updateMapSelected(mapOrGeoModel, regionsGroup);
  42453. });
  42454. }
  42455. }
  42456. function updateMapSelected(mapOrGeoModel, regionsGroup) {
  42457. // FIXME
  42458. regionsGroup.eachChild(function (otherRegionEl) {
  42459. each$1(otherRegionEl.__regions, function (region) {
  42460. otherRegionEl.trigger(mapOrGeoModel.isSelected(region.name) ? 'emphasis' : 'normal');
  42461. });
  42462. });
  42463. }
  42464. /**
  42465. * @alias module:echarts/component/helper/MapDraw
  42466. * @param {module:echarts/ExtensionAPI} api
  42467. * @param {boolean} updateGroup
  42468. */
  42469. function MapDraw(api, updateGroup) {
  42470. var group = new Group();
  42471. /**
  42472. * @type {string}
  42473. * @private
  42474. */
  42475. this.uid = getUID('ec_map_draw');
  42476. /**
  42477. * @type {module:echarts/component/helper/RoamController}
  42478. * @private
  42479. */
  42480. this._controller = new RoamController(api.getZr());
  42481. /**
  42482. * @type {Object} {target, zoom, zoomLimit}
  42483. * @private
  42484. */
  42485. this._controllerHost = {target: updateGroup ? group : null};
  42486. /**
  42487. * @type {module:zrender/container/Group}
  42488. * @readOnly
  42489. */
  42490. this.group = group;
  42491. /**
  42492. * @type {boolean}
  42493. * @private
  42494. */
  42495. this._updateGroup = updateGroup;
  42496. /**
  42497. * This flag is used to make sure that only one among
  42498. * `pan`, `zoom`, `click` can occurs, otherwise 'selected'
  42499. * action may be triggered when `pan`, which is unexpected.
  42500. * @type {booelan}
  42501. */
  42502. this._mouseDownFlag;
  42503. /**
  42504. * @type {string}
  42505. */
  42506. this._mapName;
  42507. /**
  42508. * @type {boolean}
  42509. */
  42510. this._initialized;
  42511. /**
  42512. * @type {module:zrender/container/Group}
  42513. */
  42514. group.add(this._regionsGroup = new Group());
  42515. /**
  42516. * @type {module:zrender/container/Group}
  42517. */
  42518. group.add(this._backgroundGroup = new Group());
  42519. }
  42520. MapDraw.prototype = {
  42521. constructor: MapDraw,
  42522. draw: function (mapOrGeoModel, ecModel, api, fromView, payload) {
  42523. var isGeo = mapOrGeoModel.mainType === 'geo';
  42524. // Map series has data. GEO model that controlled by map series
  42525. // will be assigned with map data. Other GEO model has no data.
  42526. var data = mapOrGeoModel.getData && mapOrGeoModel.getData();
  42527. isGeo && ecModel.eachComponent({mainType: 'series', subType: 'map'}, function (mapSeries) {
  42528. if (!data && mapSeries.getHostGeoModel() === mapOrGeoModel) {
  42529. data = mapSeries.getData();
  42530. }
  42531. });
  42532. var geo = mapOrGeoModel.coordinateSystem;
  42533. this._updateBackground(geo);
  42534. var regionsGroup = this._regionsGroup;
  42535. var group = this.group;
  42536. var transformInfo = geo.getTransformInfo();
  42537. // No animation when first draw or in action
  42538. var isFirstDraw = !regionsGroup.childAt(0) || payload;
  42539. var targetScale;
  42540. if (isFirstDraw) {
  42541. group.transform = transformInfo.roamTransform;
  42542. group.decomposeTransform();
  42543. group.dirty();
  42544. }
  42545. else {
  42546. var target = new Transformable();
  42547. target.transform = transformInfo.roamTransform;
  42548. target.decomposeTransform();
  42549. var props = {
  42550. scale: target.scale,
  42551. position: target.position
  42552. };
  42553. targetScale = target.scale;
  42554. updateProps(group, props, mapOrGeoModel);
  42555. }
  42556. var scale = transformInfo.rawScale;
  42557. var position = transformInfo.rawPosition;
  42558. regionsGroup.removeAll();
  42559. var itemStyleAccessPath = ['itemStyle'];
  42560. var hoverItemStyleAccessPath = ['emphasis', 'itemStyle'];
  42561. var labelAccessPath = ['label'];
  42562. var hoverLabelAccessPath = ['emphasis', 'label'];
  42563. var nameMap = createHashMap();
  42564. each$1(geo.regions, function (region) {
  42565. // Consider in GeoJson properties.name may be duplicated, for example,
  42566. // there is multiple region named "United Kindom" or "France" (so many
  42567. // colonies). And it is not appropriate to merge them in geo, which
  42568. // will make them share the same label and bring trouble in label
  42569. // location calculation.
  42570. var regionGroup = nameMap.get(region.name)
  42571. || nameMap.set(region.name, new Group());
  42572. var compoundPath = new CompoundPath({
  42573. segmentIgnoreThreshold: 1,
  42574. shape: {
  42575. paths: []
  42576. }
  42577. });
  42578. regionGroup.add(compoundPath);
  42579. var regionModel = mapOrGeoModel.getRegionModel(region.name) || mapOrGeoModel;
  42580. var itemStyleModel = regionModel.getModel(itemStyleAccessPath);
  42581. var hoverItemStyleModel = regionModel.getModel(hoverItemStyleAccessPath);
  42582. var itemStyle = getFixedItemStyle(itemStyleModel);
  42583. var hoverItemStyle = getFixedItemStyle(hoverItemStyleModel);
  42584. var labelModel = regionModel.getModel(labelAccessPath);
  42585. var hoverLabelModel = regionModel.getModel(hoverLabelAccessPath);
  42586. var dataIdx;
  42587. // Use the itemStyle in data if has data
  42588. if (data) {
  42589. dataIdx = data.indexOfName(region.name);
  42590. // Only visual color of each item will be used. It can be encoded by dataRange
  42591. // But visual color of series is used in symbol drawing
  42592. //
  42593. // Visual color for each series is for the symbol draw
  42594. var visualColor = data.getItemVisual(dataIdx, 'color', true);
  42595. if (visualColor) {
  42596. itemStyle.fill = visualColor;
  42597. }
  42598. }
  42599. var transformPoint = function (point) {
  42600. return [
  42601. point[0] * scale[0] + position[0],
  42602. point[1] * scale[1] + position[1]
  42603. ];
  42604. };
  42605. each$1(region.geometries, function (geometry) {
  42606. if (geometry.type !== 'polygon') {
  42607. return;
  42608. }
  42609. var points = [];
  42610. for (var i = 0; i < geometry.exterior.length; ++i) {
  42611. points.push(transformPoint(geometry.exterior[i]));
  42612. }
  42613. compoundPath.shape.paths.push(new Polygon({
  42614. segmentIgnoreThreshold: 1,
  42615. shape: {
  42616. points: points
  42617. }
  42618. }));
  42619. for (var i = 0; i < (geometry.interiors ? geometry.interiors.length : 0); ++i) {
  42620. var interior = geometry.interiors[i];
  42621. var points = [];
  42622. for (var j = 0; j < interior.length; ++j) {
  42623. points.push(transformPoint(interior[j]));
  42624. }
  42625. compoundPath.shape.paths.push(new Polygon({
  42626. segmentIgnoreThreshold: 1,
  42627. shape: {
  42628. points: points
  42629. }
  42630. }));
  42631. }
  42632. });
  42633. compoundPath.setStyle(itemStyle);
  42634. compoundPath.style.strokeNoScale = true;
  42635. compoundPath.culling = true;
  42636. // Label
  42637. var showLabel = labelModel.get('show');
  42638. var hoverShowLabel = hoverLabelModel.get('show');
  42639. var isDataNaN = data && isNaN(data.get(data.mapDimension('value'), dataIdx));
  42640. var itemLayout = data && data.getItemLayout(dataIdx);
  42641. // In the following cases label will be drawn
  42642. // 1. In map series and data value is NaN
  42643. // 2. In geo component
  42644. // 4. Region has no series legendSymbol, which will be add a showLabel flag in mapSymbolLayout
  42645. if (
  42646. (isGeo || isDataNaN && (showLabel || hoverShowLabel))
  42647. || (itemLayout && itemLayout.showLabel)
  42648. ) {
  42649. var query = !isGeo ? dataIdx : region.name;
  42650. var labelFetcher;
  42651. // Consider dataIdx not found.
  42652. if (!data || dataIdx >= 0) {
  42653. labelFetcher = mapOrGeoModel;
  42654. }
  42655. var textEl = new Text({
  42656. position: transformPoint(region.center.slice()),
  42657. // FIXME
  42658. // label rotation is not support yet in geo or regions of series-map
  42659. // that has no data. The rotation will be effected by this `scale`.
  42660. // So needed to change to RectText?
  42661. scale: [1 / group.scale[0], 1 / group.scale[1]],
  42662. z2: 10,
  42663. silent: true
  42664. });
  42665. setLabelStyle(
  42666. textEl.style, textEl.hoverStyle = {}, labelModel, hoverLabelModel,
  42667. {
  42668. labelFetcher: labelFetcher,
  42669. labelDataIndex: query,
  42670. defaultText: region.name,
  42671. useInsideStyle: false
  42672. },
  42673. {
  42674. textAlign: 'center',
  42675. textVerticalAlign: 'middle'
  42676. }
  42677. );
  42678. if (!isFirstDraw) {
  42679. // Text animation
  42680. var textScale = [1 / targetScale[0], 1 / targetScale[1]];
  42681. updateProps(textEl, { scale: textScale }, mapOrGeoModel);
  42682. }
  42683. regionGroup.add(textEl);
  42684. }
  42685. // setItemGraphicEl, setHoverStyle after all polygons and labels
  42686. // are added to the rigionGroup
  42687. if (data) {
  42688. data.setItemGraphicEl(dataIdx, regionGroup);
  42689. }
  42690. else {
  42691. var regionModel = mapOrGeoModel.getRegionModel(region.name);
  42692. // Package custom mouse event for geo component
  42693. compoundPath.eventData = {
  42694. componentType: 'geo',
  42695. componentIndex: mapOrGeoModel.componentIndex,
  42696. geoIndex: mapOrGeoModel.componentIndex,
  42697. name: region.name,
  42698. region: (regionModel && regionModel.option) || {}
  42699. };
  42700. }
  42701. var groupRegions = regionGroup.__regions || (regionGroup.__regions = []);
  42702. groupRegions.push(region);
  42703. regionGroup.highDownSilentOnTouch = !!mapOrGeoModel.get('selectedMode');
  42704. setHoverStyle(regionGroup, hoverItemStyle);
  42705. regionsGroup.add(regionGroup);
  42706. });
  42707. this._updateController(mapOrGeoModel, ecModel, api);
  42708. updateMapSelectHandler(this, mapOrGeoModel, regionsGroup, api, fromView);
  42709. updateMapSelected(mapOrGeoModel, regionsGroup);
  42710. },
  42711. remove: function () {
  42712. this._regionsGroup.removeAll();
  42713. this._backgroundGroup.removeAll();
  42714. this._controller.dispose();
  42715. this._mapName && geoSourceManager.removeGraphic(this._mapName, this.uid);
  42716. this._mapName = null;
  42717. this._controllerHost = {};
  42718. },
  42719. _updateBackground: function (geo) {
  42720. var mapName = geo.map;
  42721. if (this._mapName !== mapName) {
  42722. each$1(geoSourceManager.makeGraphic(mapName, this.uid), function (root) {
  42723. this._backgroundGroup.add(root);
  42724. }, this);
  42725. }
  42726. this._mapName = mapName;
  42727. },
  42728. _updateController: function (mapOrGeoModel, ecModel, api) {
  42729. var geo = mapOrGeoModel.coordinateSystem;
  42730. var controller = this._controller;
  42731. var controllerHost = this._controllerHost;
  42732. controllerHost.zoomLimit = mapOrGeoModel.get('scaleLimit');
  42733. controllerHost.zoom = geo.getZoom();
  42734. // roamType is will be set default true if it is null
  42735. controller.enable(mapOrGeoModel.get('roam') || false);
  42736. var mainType = mapOrGeoModel.mainType;
  42737. function makeActionBase() {
  42738. var action = {
  42739. type: 'geoRoam',
  42740. componentType: mainType
  42741. };
  42742. action[mainType + 'Id'] = mapOrGeoModel.id;
  42743. return action;
  42744. }
  42745. controller.off('pan').on('pan', function (e) {
  42746. this._mouseDownFlag = false;
  42747. updateViewOnPan(controllerHost, e.dx, e.dy);
  42748. api.dispatchAction(extend(makeActionBase(), {
  42749. dx: e.dx,
  42750. dy: e.dy
  42751. }));
  42752. }, this);
  42753. controller.off('zoom').on('zoom', function (e) {
  42754. this._mouseDownFlag = false;
  42755. updateViewOnZoom(controllerHost, e.scale, e.originX, e.originY);
  42756. api.dispatchAction(extend(makeActionBase(), {
  42757. zoom: e.scale,
  42758. originX: e.originX,
  42759. originY: e.originY
  42760. }));
  42761. if (this._updateGroup) {
  42762. var scale = this.group.scale;
  42763. this._regionsGroup.traverse(function (el) {
  42764. if (el.type === 'text') {
  42765. el.attr('scale', [1 / scale[0], 1 / scale[1]]);
  42766. }
  42767. });
  42768. }
  42769. }, this);
  42770. controller.setPointerChecker(function (e, x, y) {
  42771. return geo.getViewRectAfterRoam().contain(x, y)
  42772. && !onIrrelevantElement(e, api, mapOrGeoModel);
  42773. });
  42774. }
  42775. };
  42776. /*
  42777. * Licensed to the Apache Software Foundation (ASF) under one
  42778. * or more contributor license agreements. See the NOTICE file
  42779. * distributed with this work for additional information
  42780. * regarding copyright ownership. The ASF licenses this file
  42781. * to you under the Apache License, Version 2.0 (the
  42782. * "License"); you may not use this file except in compliance
  42783. * with the License. You may obtain a copy of the License at
  42784. *
  42785. * http://www.apache.org/licenses/LICENSE-2.0
  42786. *
  42787. * Unless required by applicable law or agreed to in writing,
  42788. * software distributed under the License is distributed on an
  42789. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42790. * KIND, either express or implied. See the License for the
  42791. * specific language governing permissions and limitations
  42792. * under the License.
  42793. */
  42794. var HIGH_DOWN_PROP = '__seriesMapHighDown';
  42795. var RECORD_VERSION_PROP = '__seriesMapCallKey';
  42796. extendChartView({
  42797. type: 'map',
  42798. render: function (mapModel, ecModel, api, payload) {
  42799. // Not render if it is an toggleSelect action from self
  42800. if (payload && payload.type === 'mapToggleSelect'
  42801. && payload.from === this.uid
  42802. ) {
  42803. return;
  42804. }
  42805. var group = this.group;
  42806. group.removeAll();
  42807. if (mapModel.getHostGeoModel()) {
  42808. return;
  42809. }
  42810. // Not update map if it is an roam action from self
  42811. if (!(payload && payload.type === 'geoRoam'
  42812. && payload.componentType === 'series'
  42813. && payload.seriesId === mapModel.id
  42814. )
  42815. ) {
  42816. if (mapModel.needsDrawMap) {
  42817. var mapDraw = this._mapDraw || new MapDraw(api, true);
  42818. group.add(mapDraw.group);
  42819. mapDraw.draw(mapModel, ecModel, api, this, payload);
  42820. this._mapDraw = mapDraw;
  42821. }
  42822. else {
  42823. // Remove drawed map
  42824. this._mapDraw && this._mapDraw.remove();
  42825. this._mapDraw = null;
  42826. }
  42827. }
  42828. else {
  42829. var mapDraw = this._mapDraw;
  42830. mapDraw && group.add(mapDraw.group);
  42831. }
  42832. mapModel.get('showLegendSymbol') && ecModel.getComponent('legend')
  42833. && this._renderSymbols(mapModel, ecModel, api);
  42834. },
  42835. remove: function () {
  42836. this._mapDraw && this._mapDraw.remove();
  42837. this._mapDraw = null;
  42838. this.group.removeAll();
  42839. },
  42840. dispose: function () {
  42841. this._mapDraw && this._mapDraw.remove();
  42842. this._mapDraw = null;
  42843. },
  42844. _renderSymbols: function (mapModel, ecModel, api) {
  42845. var originalData = mapModel.originalData;
  42846. var group = this.group;
  42847. originalData.each(originalData.mapDimension('value'), function (value, originalDataIndex) {
  42848. if (isNaN(value)) {
  42849. return;
  42850. }
  42851. var layout = originalData.getItemLayout(originalDataIndex);
  42852. if (!layout || !layout.point) {
  42853. // Not exists in map
  42854. return;
  42855. }
  42856. var point = layout.point;
  42857. var offset = layout.offset;
  42858. var circle = new Circle({
  42859. style: {
  42860. // Because the special of map draw.
  42861. // Which needs statistic of multiple series and draw on one map.
  42862. // And each series also need a symbol with legend color
  42863. //
  42864. // Layout and visual are put one the different data
  42865. fill: mapModel.getData().getVisual('color')
  42866. },
  42867. shape: {
  42868. cx: point[0] + offset * 9,
  42869. cy: point[1],
  42870. r: 3
  42871. },
  42872. silent: true,
  42873. // Do not overlap the first series, on which labels are displayed.
  42874. z2: 8 + (!offset ? Z2_EMPHASIS_LIFT + 1 : 0)
  42875. });
  42876. // Only the series that has the first value on the same region is in charge of rendering the label.
  42877. // But consider the case:
  42878. // series: [
  42879. // {id: 'X', type: 'map', map: 'm', {data: [{name: 'A', value: 11}, {name: 'B', {value: 22}]},
  42880. // {id: 'Y', type: 'map', map: 'm', {data: [{name: 'A', value: 21}, {name: 'C', {value: 33}]}
  42881. // ]
  42882. // The offset `0` of item `A` is at series `X`, but of item `C` is at series `Y`.
  42883. // For backward compatibility, we follow the rule that render label `A` by the
  42884. // settings on series `X` but render label `C` by the settings on series `Y`.
  42885. if (!offset) {
  42886. var fullData = mapModel.mainSeries.getData();
  42887. var name = originalData.getName(originalDataIndex);
  42888. var fullIndex = fullData.indexOfName(name);
  42889. var itemModel = originalData.getItemModel(originalDataIndex);
  42890. var labelModel = itemModel.getModel('label');
  42891. var hoverLabelModel = itemModel.getModel('emphasis.label');
  42892. var regionGroup = fullData.getItemGraphicEl(fullIndex);
  42893. // `getFormattedLabel` needs to use `getData` inside. Here
  42894. // `mapModel.getData()` is shallow cloned from `mainSeries.getData()`.
  42895. // FIXME
  42896. // If this is not the `mainSeries`, the item model (like label formatter)
  42897. // set on original data item will never get. But it has been working
  42898. // like that from the begining, and this scenario is rarely encountered.
  42899. // So it won't be fixed until have to.
  42900. var normalText = retrieve2(
  42901. mapModel.getFormattedLabel(fullIndex, 'normal'),
  42902. name
  42903. );
  42904. var emphasisText = retrieve2(
  42905. mapModel.getFormattedLabel(fullIndex, 'emphasis'),
  42906. normalText
  42907. );
  42908. var highDownRecord = regionGroup[HIGH_DOWN_PROP];
  42909. var recordVersion = Math.random();
  42910. // Prevent from register listeners duplicatedly when roaming.
  42911. if (!highDownRecord) {
  42912. highDownRecord = regionGroup[HIGH_DOWN_PROP] = {};
  42913. var onEmphasis = curry(onRegionHighDown, true);
  42914. var onNormal = curry(onRegionHighDown, false);
  42915. regionGroup.on('mouseover', onEmphasis)
  42916. .on('mouseout', onNormal)
  42917. .on('emphasis', onEmphasis)
  42918. .on('normal', onNormal);
  42919. }
  42920. // Prevent removed regions effect current grapics.
  42921. regionGroup[RECORD_VERSION_PROP] = recordVersion;
  42922. extend(highDownRecord, {
  42923. recordVersion: recordVersion,
  42924. circle: circle,
  42925. labelModel: labelModel,
  42926. hoverLabelModel: hoverLabelModel,
  42927. emphasisText: emphasisText,
  42928. normalText: normalText
  42929. });
  42930. // FIXME
  42931. // Consider set option when emphasis.
  42932. enterRegionHighDown(highDownRecord, false);
  42933. }
  42934. group.add(circle);
  42935. });
  42936. }
  42937. });
  42938. function onRegionHighDown(toHighOrDown) {
  42939. var highDownRecord = this[HIGH_DOWN_PROP];
  42940. if (highDownRecord && highDownRecord.recordVersion === this[RECORD_VERSION_PROP]) {
  42941. enterRegionHighDown(highDownRecord, toHighOrDown);
  42942. }
  42943. }
  42944. function enterRegionHighDown(highDownRecord, toHighOrDown) {
  42945. var circle = highDownRecord.circle;
  42946. var labelModel = highDownRecord.labelModel;
  42947. var hoverLabelModel = highDownRecord.hoverLabelModel;
  42948. var emphasisText = highDownRecord.emphasisText;
  42949. var normalText = highDownRecord.normalText;
  42950. if (toHighOrDown) {
  42951. circle.style.extendFrom(
  42952. setTextStyle({}, hoverLabelModel, {
  42953. text: hoverLabelModel.get('show') ? emphasisText : null
  42954. }, {isRectText: true, useInsideStyle: false}, true)
  42955. );
  42956. // Make label upper than others if overlaps.
  42957. circle.__mapOriginalZ2 = circle.z2;
  42958. circle.z2 += Z2_EMPHASIS_LIFT;
  42959. }
  42960. else {
  42961. setTextStyle(circle.style, labelModel, {
  42962. text: labelModel.get('show') ? normalText : null,
  42963. textPosition: labelModel.getShallow('position') || 'bottom'
  42964. }, {isRectText: true, useInsideStyle: false});
  42965. // Trigger normalize style like padding.
  42966. circle.dirty(false);
  42967. if (circle.__mapOriginalZ2 != null) {
  42968. circle.z2 = circle.__mapOriginalZ2;
  42969. circle.__mapOriginalZ2 = null;
  42970. }
  42971. }
  42972. }
  42973. /*
  42974. * Licensed to the Apache Software Foundation (ASF) under one
  42975. * or more contributor license agreements. See the NOTICE file
  42976. * distributed with this work for additional information
  42977. * regarding copyright ownership. The ASF licenses this file
  42978. * to you under the Apache License, Version 2.0 (the
  42979. * "License"); you may not use this file except in compliance
  42980. * with the License. You may obtain a copy of the License at
  42981. *
  42982. * http://www.apache.org/licenses/LICENSE-2.0
  42983. *
  42984. * Unless required by applicable law or agreed to in writing,
  42985. * software distributed under the License is distributed on an
  42986. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42987. * KIND, either express or implied. See the License for the
  42988. * specific language governing permissions and limitations
  42989. * under the License.
  42990. */
  42991. /**
  42992. * @param {module:echarts/coord/View} view
  42993. * @param {Object} payload
  42994. * @param {Object} [zoomLimit]
  42995. */
  42996. function updateCenterAndZoom(
  42997. view, payload, zoomLimit
  42998. ) {
  42999. var previousZoom = view.getZoom();
  43000. var center = view.getCenter();
  43001. var zoom = payload.zoom;
  43002. var point = view.dataToPoint(center);
  43003. if (payload.dx != null && payload.dy != null) {
  43004. point[0] -= payload.dx;
  43005. point[1] -= payload.dy;
  43006. var center = view.pointToData(point);
  43007. view.setCenter(center);
  43008. }
  43009. if (zoom != null) {
  43010. if (zoomLimit) {
  43011. var zoomMin = zoomLimit.min || 0;
  43012. var zoomMax = zoomLimit.max || Infinity;
  43013. zoom = Math.max(
  43014. Math.min(previousZoom * zoom, zoomMax),
  43015. zoomMin
  43016. ) / previousZoom;
  43017. }
  43018. // Zoom on given point(originX, originY)
  43019. view.scale[0] *= zoom;
  43020. view.scale[1] *= zoom;
  43021. var position = view.position;
  43022. var fixX = (payload.originX - position[0]) * (zoom - 1);
  43023. var fixY = (payload.originY - position[1]) * (zoom - 1);
  43024. position[0] -= fixX;
  43025. position[1] -= fixY;
  43026. view.updateTransform();
  43027. // Get the new center
  43028. var center = view.pointToData(point);
  43029. view.setCenter(center);
  43030. view.setZoom(zoom * previousZoom);
  43031. }
  43032. return {
  43033. center: view.getCenter(),
  43034. zoom: view.getZoom()
  43035. };
  43036. }
  43037. /*
  43038. * Licensed to the Apache Software Foundation (ASF) under one
  43039. * or more contributor license agreements. See the NOTICE file
  43040. * distributed with this work for additional information
  43041. * regarding copyright ownership. The ASF licenses this file
  43042. * to you under the Apache License, Version 2.0 (the
  43043. * "License"); you may not use this file except in compliance
  43044. * with the License. You may obtain a copy of the License at
  43045. *
  43046. * http://www.apache.org/licenses/LICENSE-2.0
  43047. *
  43048. * Unless required by applicable law or agreed to in writing,
  43049. * software distributed under the License is distributed on an
  43050. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43051. * KIND, either express or implied. See the License for the
  43052. * specific language governing permissions and limitations
  43053. * under the License.
  43054. */
  43055. /**
  43056. * @payload
  43057. * @property {string} [componentType=series]
  43058. * @property {number} [dx]
  43059. * @property {number} [dy]
  43060. * @property {number} [zoom]
  43061. * @property {number} [originX]
  43062. * @property {number} [originY]
  43063. */
  43064. registerAction({
  43065. type: 'geoRoam',
  43066. event: 'geoRoam',
  43067. update: 'updateTransform'
  43068. }, function (payload, ecModel) {
  43069. var componentType = payload.componentType || 'series';
  43070. ecModel.eachComponent(
  43071. { mainType: componentType, query: payload },
  43072. function (componentModel) {
  43073. var geo = componentModel.coordinateSystem;
  43074. if (geo.type !== 'geo') {
  43075. return;
  43076. }
  43077. var res = updateCenterAndZoom(
  43078. geo, payload, componentModel.get('scaleLimit')
  43079. );
  43080. componentModel.setCenter
  43081. && componentModel.setCenter(res.center);
  43082. componentModel.setZoom
  43083. && componentModel.setZoom(res.zoom);
  43084. // All map series with same `map` use the same geo coordinate system
  43085. // So the center and zoom must be in sync. Include the series not selected by legend
  43086. if (componentType === 'series') {
  43087. each$1(componentModel.seriesGroup, function (seriesModel) {
  43088. seriesModel.setCenter(res.center);
  43089. seriesModel.setZoom(res.zoom);
  43090. });
  43091. }
  43092. }
  43093. );
  43094. });
  43095. /*
  43096. * Licensed to the Apache Software Foundation (ASF) under one
  43097. * or more contributor license agreements. See the NOTICE file
  43098. * distributed with this work for additional information
  43099. * regarding copyright ownership. The ASF licenses this file
  43100. * to you under the Apache License, Version 2.0 (the
  43101. * "License"); you may not use this file except in compliance
  43102. * with the License. You may obtain a copy of the License at
  43103. *
  43104. * http://www.apache.org/licenses/LICENSE-2.0
  43105. *
  43106. * Unless required by applicable law or agreed to in writing,
  43107. * software distributed under the License is distributed on an
  43108. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43109. * KIND, either express or implied. See the License for the
  43110. * specific language governing permissions and limitations
  43111. * under the License.
  43112. */
  43113. /**
  43114. * Simple view coordinate system
  43115. * Mapping given x, y to transformd view x, y
  43116. */
  43117. var v2ApplyTransform$1 = applyTransform;
  43118. // Dummy transform node
  43119. function TransformDummy() {
  43120. Transformable.call(this);
  43121. }
  43122. mixin(TransformDummy, Transformable);
  43123. function View(name) {
  43124. /**
  43125. * @type {string}
  43126. */
  43127. this.name = name;
  43128. /**
  43129. * @type {Object}
  43130. */
  43131. this.zoomLimit;
  43132. Transformable.call(this);
  43133. this._roamTransformable = new TransformDummy();
  43134. this._rawTransformable = new TransformDummy();
  43135. this._center;
  43136. this._zoom;
  43137. }
  43138. View.prototype = {
  43139. constructor: View,
  43140. type: 'view',
  43141. /**
  43142. * @param {Array.<string>}
  43143. * @readOnly
  43144. */
  43145. dimensions: ['x', 'y'],
  43146. /**
  43147. * Set bounding rect
  43148. * @param {number} x
  43149. * @param {number} y
  43150. * @param {number} width
  43151. * @param {number} height
  43152. */
  43153. // PENDING to getRect
  43154. setBoundingRect: function (x, y, width, height) {
  43155. this._rect = new BoundingRect(x, y, width, height);
  43156. return this._rect;
  43157. },
  43158. /**
  43159. * @return {module:zrender/core/BoundingRect}
  43160. */
  43161. // PENDING to getRect
  43162. getBoundingRect: function () {
  43163. return this._rect;
  43164. },
  43165. /**
  43166. * @param {number} x
  43167. * @param {number} y
  43168. * @param {number} width
  43169. * @param {number} height
  43170. */
  43171. setViewRect: function (x, y, width, height) {
  43172. this.transformTo(x, y, width, height);
  43173. this._viewRect = new BoundingRect(x, y, width, height);
  43174. },
  43175. /**
  43176. * Transformed to particular position and size
  43177. * @param {number} x
  43178. * @param {number} y
  43179. * @param {number} width
  43180. * @param {number} height
  43181. */
  43182. transformTo: function (x, y, width, height) {
  43183. var rect = this.getBoundingRect();
  43184. var rawTransform = this._rawTransformable;
  43185. rawTransform.transform = rect.calculateTransform(
  43186. new BoundingRect(x, y, width, height)
  43187. );
  43188. rawTransform.decomposeTransform();
  43189. this._updateTransform();
  43190. },
  43191. /**
  43192. * Set center of view
  43193. * @param {Array.<number>} [centerCoord]
  43194. */
  43195. setCenter: function (centerCoord) {
  43196. if (!centerCoord) {
  43197. return;
  43198. }
  43199. this._center = centerCoord;
  43200. this._updateCenterAndZoom();
  43201. },
  43202. /**
  43203. * @param {number} zoom
  43204. */
  43205. setZoom: function (zoom) {
  43206. zoom = zoom || 1;
  43207. var zoomLimit = this.zoomLimit;
  43208. if (zoomLimit) {
  43209. if (zoomLimit.max != null) {
  43210. zoom = Math.min(zoomLimit.max, zoom);
  43211. }
  43212. if (zoomLimit.min != null) {
  43213. zoom = Math.max(zoomLimit.min, zoom);
  43214. }
  43215. }
  43216. this._zoom = zoom;
  43217. this._updateCenterAndZoom();
  43218. },
  43219. /**
  43220. * Get default center without roam
  43221. */
  43222. getDefaultCenter: function () {
  43223. // Rect before any transform
  43224. var rawRect = this.getBoundingRect();
  43225. var cx = rawRect.x + rawRect.width / 2;
  43226. var cy = rawRect.y + rawRect.height / 2;
  43227. return [cx, cy];
  43228. },
  43229. getCenter: function () {
  43230. return this._center || this.getDefaultCenter();
  43231. },
  43232. getZoom: function () {
  43233. return this._zoom || 1;
  43234. },
  43235. /**
  43236. * @return {Array.<number}
  43237. */
  43238. getRoamTransform: function () {
  43239. return this._roamTransformable.getLocalTransform();
  43240. },
  43241. /**
  43242. * Remove roam
  43243. */
  43244. _updateCenterAndZoom: function () {
  43245. // Must update after view transform updated
  43246. var rawTransformMatrix = this._rawTransformable.getLocalTransform();
  43247. var roamTransform = this._roamTransformable;
  43248. var defaultCenter = this.getDefaultCenter();
  43249. var center = this.getCenter();
  43250. var zoom = this.getZoom();
  43251. center = applyTransform([], center, rawTransformMatrix);
  43252. defaultCenter = applyTransform([], defaultCenter, rawTransformMatrix);
  43253. roamTransform.origin = center;
  43254. roamTransform.position = [
  43255. defaultCenter[0] - center[0],
  43256. defaultCenter[1] - center[1]
  43257. ];
  43258. roamTransform.scale = [zoom, zoom];
  43259. this._updateTransform();
  43260. },
  43261. /**
  43262. * Update transform from roam and mapLocation
  43263. * @private
  43264. */
  43265. _updateTransform: function () {
  43266. var roamTransformable = this._roamTransformable;
  43267. var rawTransformable = this._rawTransformable;
  43268. rawTransformable.parent = roamTransformable;
  43269. roamTransformable.updateTransform();
  43270. rawTransformable.updateTransform();
  43271. copy$1(this.transform || (this.transform = []), rawTransformable.transform || create$1());
  43272. this._rawTransform = rawTransformable.getLocalTransform();
  43273. this.invTransform = this.invTransform || [];
  43274. invert(this.invTransform, this.transform);
  43275. this.decomposeTransform();
  43276. },
  43277. getTransformInfo: function () {
  43278. var roamTransform = this._roamTransformable.transform;
  43279. var rawTransformable = this._rawTransformable;
  43280. return {
  43281. roamTransform: roamTransform ? slice(roamTransform) : create$1(),
  43282. rawScale: slice(rawTransformable.scale),
  43283. rawPosition: slice(rawTransformable.position)
  43284. };
  43285. },
  43286. /**
  43287. * @return {module:zrender/core/BoundingRect}
  43288. */
  43289. getViewRect: function () {
  43290. return this._viewRect;
  43291. },
  43292. /**
  43293. * Get view rect after roam transform
  43294. * @return {module:zrender/core/BoundingRect}
  43295. */
  43296. getViewRectAfterRoam: function () {
  43297. var rect = this.getBoundingRect().clone();
  43298. rect.applyTransform(this.transform);
  43299. return rect;
  43300. },
  43301. /**
  43302. * Convert a single (lon, lat) data item to (x, y) point.
  43303. * @param {Array.<number>} data
  43304. * @param {boolean} noRoam
  43305. * @param {Array.<number>} [out]
  43306. * @return {Array.<number>}
  43307. */
  43308. dataToPoint: function (data, noRoam, out) {
  43309. var transform = noRoam ? this._rawTransform : this.transform;
  43310. out = out || [];
  43311. return transform
  43312. ? v2ApplyTransform$1(out, data, transform)
  43313. : copy(out, data);
  43314. },
  43315. /**
  43316. * Convert a (x, y) point to (lon, lat) data
  43317. * @param {Array.<number>} point
  43318. * @return {Array.<number>}
  43319. */
  43320. pointToData: function (point) {
  43321. var invTransform = this.invTransform;
  43322. return invTransform
  43323. ? v2ApplyTransform$1([], point, invTransform)
  43324. : [point[0], point[1]];
  43325. },
  43326. /**
  43327. * @implements
  43328. * see {module:echarts/CoodinateSystem}
  43329. */
  43330. convertToPixel: curry(doConvert$1, 'dataToPoint'),
  43331. /**
  43332. * @implements
  43333. * see {module:echarts/CoodinateSystem}
  43334. */
  43335. convertFromPixel: curry(doConvert$1, 'pointToData'),
  43336. /**
  43337. * @implements
  43338. * see {module:echarts/CoodinateSystem}
  43339. */
  43340. containPoint: function (point) {
  43341. return this.getViewRectAfterRoam().contain(point[0], point[1]);
  43342. }
  43343. /**
  43344. * @return {number}
  43345. */
  43346. // getScalarScale: function () {
  43347. // // Use determinant square root of transform to mutiply scalar
  43348. // var m = this.transform;
  43349. // var det = Math.sqrt(Math.abs(m[0] * m[3] - m[2] * m[1]));
  43350. // return det;
  43351. // }
  43352. };
  43353. mixin(View, Transformable);
  43354. function doConvert$1(methodName, ecModel, finder, value) {
  43355. var seriesModel = finder.seriesModel;
  43356. var coordSys = seriesModel ? seriesModel.coordinateSystem : null; // e.g., graph.
  43357. return coordSys === this ? coordSys[methodName](value) : null;
  43358. }
  43359. /*
  43360. * Licensed to the Apache Software Foundation (ASF) under one
  43361. * or more contributor license agreements. See the NOTICE file
  43362. * distributed with this work for additional information
  43363. * regarding copyright ownership. The ASF licenses this file
  43364. * to you under the Apache License, Version 2.0 (the
  43365. * "License"); you may not use this file except in compliance
  43366. * with the License. You may obtain a copy of the License at
  43367. *
  43368. * http://www.apache.org/licenses/LICENSE-2.0
  43369. *
  43370. * Unless required by applicable law or agreed to in writing,
  43371. * software distributed under the License is distributed on an
  43372. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43373. * KIND, either express or implied. See the License for the
  43374. * specific language governing permissions and limitations
  43375. * under the License.
  43376. */
  43377. /**
  43378. * [Geo description]
  43379. * For backward compatibility, the orginal interface:
  43380. * `name, map, geoJson, specialAreas, nameMap` is kept.
  43381. *
  43382. * @param {string|Object} name
  43383. * @param {string} map Map type
  43384. * Specify the positioned areas by left, top, width, height
  43385. * @param {Object.<string, string>} [nameMap]
  43386. * Specify name alias
  43387. * @param {boolean} [invertLongitute=true]
  43388. */
  43389. function Geo(name, map$$1, nameMap, invertLongitute) {
  43390. View.call(this, name);
  43391. /**
  43392. * Map type
  43393. * @type {string}
  43394. */
  43395. this.map = map$$1;
  43396. var source = geoSourceManager.load(map$$1, nameMap);
  43397. this._nameCoordMap = source.nameCoordMap;
  43398. this._regionsMap = source.regionsMap;
  43399. this._invertLongitute = invertLongitute == null ? true : invertLongitute;
  43400. /**
  43401. * @readOnly
  43402. */
  43403. this.regions = source.regions;
  43404. /**
  43405. * @type {module:zrender/src/core/BoundingRect}
  43406. */
  43407. this._rect = source.boundingRect;
  43408. }
  43409. Geo.prototype = {
  43410. constructor: Geo,
  43411. type: 'geo',
  43412. /**
  43413. * @param {Array.<string>}
  43414. * @readOnly
  43415. */
  43416. dimensions: ['lng', 'lat'],
  43417. /**
  43418. * If contain given lng,lat coord
  43419. * @param {Array.<number>}
  43420. * @readOnly
  43421. */
  43422. containCoord: function (coord) {
  43423. var regions = this.regions;
  43424. for (var i = 0; i < regions.length; i++) {
  43425. if (regions[i].contain(coord)) {
  43426. return true;
  43427. }
  43428. }
  43429. return false;
  43430. },
  43431. /**
  43432. * @override
  43433. */
  43434. transformTo: function (x, y, width, height) {
  43435. var rect = this.getBoundingRect();
  43436. var invertLongitute = this._invertLongitute;
  43437. rect = rect.clone();
  43438. if (invertLongitute) {
  43439. // Longitute is inverted
  43440. rect.y = -rect.y - rect.height;
  43441. }
  43442. var rawTransformable = this._rawTransformable;
  43443. rawTransformable.transform = rect.calculateTransform(
  43444. new BoundingRect(x, y, width, height)
  43445. );
  43446. rawTransformable.decomposeTransform();
  43447. if (invertLongitute) {
  43448. var scale = rawTransformable.scale;
  43449. scale[1] = -scale[1];
  43450. }
  43451. rawTransformable.updateTransform();
  43452. this._updateTransform();
  43453. },
  43454. /**
  43455. * @param {string} name
  43456. * @return {module:echarts/coord/geo/Region}
  43457. */
  43458. getRegion: function (name) {
  43459. return this._regionsMap.get(name);
  43460. },
  43461. getRegionByCoord: function (coord) {
  43462. var regions = this.regions;
  43463. for (var i = 0; i < regions.length; i++) {
  43464. if (regions[i].contain(coord)) {
  43465. return regions[i];
  43466. }
  43467. }
  43468. },
  43469. /**
  43470. * Add geoCoord for indexing by name
  43471. * @param {string} name
  43472. * @param {Array.<number>} geoCoord
  43473. */
  43474. addGeoCoord: function (name, geoCoord) {
  43475. this._nameCoordMap.set(name, geoCoord);
  43476. },
  43477. /**
  43478. * Get geoCoord by name
  43479. * @param {string} name
  43480. * @return {Array.<number>}
  43481. */
  43482. getGeoCoord: function (name) {
  43483. return this._nameCoordMap.get(name);
  43484. },
  43485. /**
  43486. * @override
  43487. */
  43488. getBoundingRect: function () {
  43489. return this._rect;
  43490. },
  43491. /**
  43492. * @param {string|Array.<number>} data
  43493. * @param {boolean} noRoam
  43494. * @param {Array.<number>} [out]
  43495. * @return {Array.<number>}
  43496. */
  43497. dataToPoint: function (data, noRoam, out) {
  43498. if (typeof data === 'string') {
  43499. // Map area name to geoCoord
  43500. data = this.getGeoCoord(data);
  43501. }
  43502. if (data) {
  43503. return View.prototype.dataToPoint.call(this, data, noRoam, out);
  43504. }
  43505. },
  43506. /**
  43507. * @override
  43508. */
  43509. convertToPixel: curry(doConvert, 'dataToPoint'),
  43510. /**
  43511. * @override
  43512. */
  43513. convertFromPixel: curry(doConvert, 'pointToData')
  43514. };
  43515. mixin(Geo, View);
  43516. function doConvert(methodName, ecModel, finder, value) {
  43517. var geoModel = finder.geoModel;
  43518. var seriesModel = finder.seriesModel;
  43519. var coordSys = geoModel
  43520. ? geoModel.coordinateSystem
  43521. : seriesModel
  43522. ? (
  43523. seriesModel.coordinateSystem // For map.
  43524. || (seriesModel.getReferringComponents('geo')[0] || {}).coordinateSystem
  43525. )
  43526. : null;
  43527. return coordSys === this ? coordSys[methodName](value) : null;
  43528. }
  43529. /*
  43530. * Licensed to the Apache Software Foundation (ASF) under one
  43531. * or more contributor license agreements. See the NOTICE file
  43532. * distributed with this work for additional information
  43533. * regarding copyright ownership. The ASF licenses this file
  43534. * to you under the Apache License, Version 2.0 (the
  43535. * "License"); you may not use this file except in compliance
  43536. * with the License. You may obtain a copy of the License at
  43537. *
  43538. * http://www.apache.org/licenses/LICENSE-2.0
  43539. *
  43540. * Unless required by applicable law or agreed to in writing,
  43541. * software distributed under the License is distributed on an
  43542. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43543. * KIND, either express or implied. See the License for the
  43544. * specific language governing permissions and limitations
  43545. * under the License.
  43546. */
  43547. /**
  43548. * Resize method bound to the geo
  43549. * @param {module:echarts/coord/geo/GeoModel|module:echarts/chart/map/MapModel} geoModel
  43550. * @param {module:echarts/ExtensionAPI} api
  43551. */
  43552. function resizeGeo(geoModel, api) {
  43553. var boundingCoords = geoModel.get('boundingCoords');
  43554. if (boundingCoords != null) {
  43555. var leftTop = boundingCoords[0];
  43556. var rightBottom = boundingCoords[1];
  43557. if (isNaN(leftTop[0]) || isNaN(leftTop[1]) || isNaN(rightBottom[0]) || isNaN(rightBottom[1])) {
  43558. if (__DEV__) {
  43559. console.error('Invalid boundingCoords');
  43560. }
  43561. }
  43562. else {
  43563. this.setBoundingRect(leftTop[0], leftTop[1], rightBottom[0] - leftTop[0], rightBottom[1] - leftTop[1]);
  43564. }
  43565. }
  43566. var rect = this.getBoundingRect();
  43567. var boxLayoutOption;
  43568. var center = geoModel.get('layoutCenter');
  43569. var size = geoModel.get('layoutSize');
  43570. var viewWidth = api.getWidth();
  43571. var viewHeight = api.getHeight();
  43572. var aspect = rect.width / rect.height * this.aspectScale;
  43573. var useCenterAndSize = false;
  43574. if (center && size) {
  43575. center = [
  43576. parsePercent$1(center[0], viewWidth),
  43577. parsePercent$1(center[1], viewHeight)
  43578. ];
  43579. size = parsePercent$1(size, Math.min(viewWidth, viewHeight));
  43580. if (!isNaN(center[0]) && !isNaN(center[1]) && !isNaN(size)) {
  43581. useCenterAndSize = true;
  43582. }
  43583. else {
  43584. if (__DEV__) {
  43585. console.warn('Given layoutCenter or layoutSize data are invalid. Use left/top/width/height instead.');
  43586. }
  43587. }
  43588. }
  43589. var viewRect;
  43590. if (useCenterAndSize) {
  43591. var viewRect = {};
  43592. if (aspect > 1) {
  43593. // Width is same with size
  43594. viewRect.width = size;
  43595. viewRect.height = size / aspect;
  43596. }
  43597. else {
  43598. viewRect.height = size;
  43599. viewRect.width = size * aspect;
  43600. }
  43601. viewRect.y = center[1] - viewRect.height / 2;
  43602. viewRect.x = center[0] - viewRect.width / 2;
  43603. }
  43604. else {
  43605. // Use left/top/width/height
  43606. boxLayoutOption = geoModel.getBoxLayoutParams();
  43607. // 0.75 rate
  43608. boxLayoutOption.aspect = aspect;
  43609. viewRect = getLayoutRect(boxLayoutOption, {
  43610. width: viewWidth,
  43611. height: viewHeight
  43612. });
  43613. }
  43614. this.setViewRect(viewRect.x, viewRect.y, viewRect.width, viewRect.height);
  43615. this.setCenter(geoModel.get('center'));
  43616. this.setZoom(geoModel.get('zoom'));
  43617. }
  43618. /**
  43619. * @param {module:echarts/coord/Geo} geo
  43620. * @param {module:echarts/model/Model} model
  43621. * @inner
  43622. */
  43623. function setGeoCoords(geo, model) {
  43624. each$1(model.get('geoCoord'), function (geoCoord, name) {
  43625. geo.addGeoCoord(name, geoCoord);
  43626. });
  43627. }
  43628. var geoCreator = {
  43629. // For deciding which dimensions to use when creating list data
  43630. dimensions: Geo.prototype.dimensions,
  43631. create: function (ecModel, api) {
  43632. var geoList = [];
  43633. // FIXME Create each time may be slow
  43634. ecModel.eachComponent('geo', function (geoModel, idx) {
  43635. var name = geoModel.get('map');
  43636. var aspectScale = geoModel.get('aspectScale');
  43637. var invertLongitute = true;
  43638. var mapRecords = mapDataStorage.retrieveMap(name);
  43639. if (mapRecords && mapRecords[0] && mapRecords[0].type === 'svg') {
  43640. aspectScale == null && (aspectScale = 1);
  43641. invertLongitute = false;
  43642. }
  43643. else {
  43644. aspectScale == null && (aspectScale = 0.75);
  43645. }
  43646. var geo = new Geo(name + idx, name, geoModel.get('nameMap'), invertLongitute);
  43647. geo.aspectScale = aspectScale;
  43648. geo.zoomLimit = geoModel.get('scaleLimit');
  43649. geoList.push(geo);
  43650. setGeoCoords(geo, geoModel);
  43651. geoModel.coordinateSystem = geo;
  43652. geo.model = geoModel;
  43653. // Inject resize method
  43654. geo.resize = resizeGeo;
  43655. geo.resize(geoModel, api);
  43656. });
  43657. ecModel.eachSeries(function (seriesModel) {
  43658. var coordSys = seriesModel.get('coordinateSystem');
  43659. if (coordSys === 'geo') {
  43660. var geoIndex = seriesModel.get('geoIndex') || 0;
  43661. seriesModel.coordinateSystem = geoList[geoIndex];
  43662. }
  43663. });
  43664. // If has map series
  43665. var mapModelGroupBySeries = {};
  43666. ecModel.eachSeriesByType('map', function (seriesModel) {
  43667. if (!seriesModel.getHostGeoModel()) {
  43668. var mapType = seriesModel.getMapType();
  43669. mapModelGroupBySeries[mapType] = mapModelGroupBySeries[mapType] || [];
  43670. mapModelGroupBySeries[mapType].push(seriesModel);
  43671. }
  43672. });
  43673. each$1(mapModelGroupBySeries, function (mapSeries, mapType) {
  43674. var nameMapList = map(mapSeries, function (singleMapSeries) {
  43675. return singleMapSeries.get('nameMap');
  43676. });
  43677. var geo = new Geo(mapType, mapType, mergeAll(nameMapList));
  43678. geo.zoomLimit = retrieve.apply(null, map(mapSeries, function (singleMapSeries) {
  43679. return singleMapSeries.get('scaleLimit');
  43680. }));
  43681. geoList.push(geo);
  43682. // Inject resize method
  43683. geo.resize = resizeGeo;
  43684. geo.aspectScale = mapSeries[0].get('aspectScale');
  43685. geo.resize(mapSeries[0], api);
  43686. each$1(mapSeries, function (singleMapSeries) {
  43687. singleMapSeries.coordinateSystem = geo;
  43688. setGeoCoords(geo, singleMapSeries);
  43689. });
  43690. });
  43691. return geoList;
  43692. },
  43693. /**
  43694. * Fill given regions array
  43695. * @param {Array.<Object>} originRegionArr
  43696. * @param {string} mapName
  43697. * @param {Object} [nameMap]
  43698. * @return {Array}
  43699. */
  43700. getFilledRegions: function (originRegionArr, mapName, nameMap) {
  43701. // Not use the original
  43702. var regionsArr = (originRegionArr || []).slice();
  43703. var dataNameMap = createHashMap();
  43704. for (var i = 0; i < regionsArr.length; i++) {
  43705. dataNameMap.set(regionsArr[i].name, regionsArr[i]);
  43706. }
  43707. var source = geoSourceManager.load(mapName, nameMap);
  43708. each$1(source.regions, function (region) {
  43709. var name = region.name;
  43710. !dataNameMap.get(name) && regionsArr.push({name: name});
  43711. });
  43712. return regionsArr;
  43713. }
  43714. };
  43715. registerCoordinateSystem('geo', geoCreator);
  43716. /*
  43717. * Licensed to the Apache Software Foundation (ASF) under one
  43718. * or more contributor license agreements. See the NOTICE file
  43719. * distributed with this work for additional information
  43720. * regarding copyright ownership. The ASF licenses this file
  43721. * to you under the Apache License, Version 2.0 (the
  43722. * "License"); you may not use this file except in compliance
  43723. * with the License. You may obtain a copy of the License at
  43724. *
  43725. * http://www.apache.org/licenses/LICENSE-2.0
  43726. *
  43727. * Unless required by applicable law or agreed to in writing,
  43728. * software distributed under the License is distributed on an
  43729. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43730. * KIND, either express or implied. See the License for the
  43731. * specific language governing permissions and limitations
  43732. * under the License.
  43733. */
  43734. var mapSymbolLayout = function (ecModel) {
  43735. var processedMapType = {};
  43736. ecModel.eachSeriesByType('map', function (mapSeries) {
  43737. var mapType = mapSeries.getMapType();
  43738. if (mapSeries.getHostGeoModel() || processedMapType[mapType]) {
  43739. return;
  43740. }
  43741. var mapSymbolOffsets = {};
  43742. each$1(mapSeries.seriesGroup, function (subMapSeries) {
  43743. var geo = subMapSeries.coordinateSystem;
  43744. var data = subMapSeries.originalData;
  43745. if (subMapSeries.get('showLegendSymbol') && ecModel.getComponent('legend')) {
  43746. data.each(data.mapDimension('value'), function (value, idx) {
  43747. var name = data.getName(idx);
  43748. var region = geo.getRegion(name);
  43749. // If input series.data is [11, 22, '-'/null/undefined, 44],
  43750. // it will be filled with NaN: [11, 22, NaN, 44] and NaN will
  43751. // not be drawn. So here must validate if value is NaN.
  43752. if (!region || isNaN(value)) {
  43753. return;
  43754. }
  43755. var offset = mapSymbolOffsets[name] || 0;
  43756. var point = geo.dataToPoint(region.center);
  43757. mapSymbolOffsets[name] = offset + 1;
  43758. data.setItemLayout(idx, {
  43759. point: point,
  43760. offset: offset
  43761. });
  43762. });
  43763. }
  43764. });
  43765. // Show label of those region not has legendSymbol(which is offset 0)
  43766. var data = mapSeries.getData();
  43767. data.each(function (idx) {
  43768. var name = data.getName(idx);
  43769. var layout = data.getItemLayout(idx) || {};
  43770. layout.showLabel = !mapSymbolOffsets[name];
  43771. data.setItemLayout(idx, layout);
  43772. });
  43773. processedMapType[mapType] = true;
  43774. });
  43775. };
  43776. /*
  43777. * Licensed to the Apache Software Foundation (ASF) under one
  43778. * or more contributor license agreements. See the NOTICE file
  43779. * distributed with this work for additional information
  43780. * regarding copyright ownership. The ASF licenses this file
  43781. * to you under the Apache License, Version 2.0 (the
  43782. * "License"); you may not use this file except in compliance
  43783. * with the License. You may obtain a copy of the License at
  43784. *
  43785. * http://www.apache.org/licenses/LICENSE-2.0
  43786. *
  43787. * Unless required by applicable law or agreed to in writing,
  43788. * software distributed under the License is distributed on an
  43789. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43790. * KIND, either express or implied. See the License for the
  43791. * specific language governing permissions and limitations
  43792. * under the License.
  43793. */
  43794. var mapVisual = function (ecModel) {
  43795. ecModel.eachSeriesByType('map', function (seriesModel) {
  43796. var colorList = seriesModel.get('color');
  43797. var itemStyleModel = seriesModel.getModel('itemStyle');
  43798. var areaColor = itemStyleModel.get('areaColor');
  43799. var color = itemStyleModel.get('color')
  43800. || colorList[seriesModel.seriesIndex % colorList.length];
  43801. seriesModel.getData().setVisual({
  43802. 'areaColor': areaColor,
  43803. 'color': color
  43804. });
  43805. });
  43806. };
  43807. /*
  43808. * Licensed to the Apache Software Foundation (ASF) under one
  43809. * or more contributor license agreements. See the NOTICE file
  43810. * distributed with this work for additional information
  43811. * regarding copyright ownership. The ASF licenses this file
  43812. * to you under the Apache License, Version 2.0 (the
  43813. * "License"); you may not use this file except in compliance
  43814. * with the License. You may obtain a copy of the License at
  43815. *
  43816. * http://www.apache.org/licenses/LICENSE-2.0
  43817. *
  43818. * Unless required by applicable law or agreed to in writing,
  43819. * software distributed under the License is distributed on an
  43820. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43821. * KIND, either express or implied. See the License for the
  43822. * specific language governing permissions and limitations
  43823. * under the License.
  43824. */
  43825. // FIXME 公用?
  43826. /**
  43827. * @param {Array.<module:echarts/data/List>} datas
  43828. * @param {string} statisticType 'average' 'sum'
  43829. * @inner
  43830. */
  43831. function dataStatistics(datas, statisticType) {
  43832. var dataNameMap = {};
  43833. each$1(datas, function (data) {
  43834. data.each(data.mapDimension('value'), function (value, idx) {
  43835. // Add prefix to avoid conflict with Object.prototype.
  43836. var mapKey = 'ec-' + data.getName(idx);
  43837. dataNameMap[mapKey] = dataNameMap[mapKey] || [];
  43838. if (!isNaN(value)) {
  43839. dataNameMap[mapKey].push(value);
  43840. }
  43841. });
  43842. });
  43843. return datas[0].map(datas[0].mapDimension('value'), function (value, idx) {
  43844. var mapKey = 'ec-' + datas[0].getName(idx);
  43845. var sum = 0;
  43846. var min = Infinity;
  43847. var max = -Infinity;
  43848. var len = dataNameMap[mapKey].length;
  43849. for (var i = 0; i < len; i++) {
  43850. min = Math.min(min, dataNameMap[mapKey][i]);
  43851. max = Math.max(max, dataNameMap[mapKey][i]);
  43852. sum += dataNameMap[mapKey][i];
  43853. }
  43854. var result;
  43855. if (statisticType === 'min') {
  43856. result = min;
  43857. }
  43858. else if (statisticType === 'max') {
  43859. result = max;
  43860. }
  43861. else if (statisticType === 'average') {
  43862. result = sum / len;
  43863. }
  43864. else {
  43865. result = sum;
  43866. }
  43867. return len === 0 ? NaN : result;
  43868. });
  43869. }
  43870. var mapDataStatistic = function (ecModel) {
  43871. var seriesGroups = {};
  43872. ecModel.eachSeriesByType('map', function (seriesModel) {
  43873. var hostGeoModel = seriesModel.getHostGeoModel();
  43874. var key = hostGeoModel ? 'o' + hostGeoModel.id : 'i' + seriesModel.getMapType();
  43875. (seriesGroups[key] = seriesGroups[key] || []).push(seriesModel);
  43876. });
  43877. each$1(seriesGroups, function (seriesList, key) {
  43878. var data = dataStatistics(
  43879. map(seriesList, function (seriesModel) {
  43880. return seriesModel.getData();
  43881. }),
  43882. seriesList[0].get('mapValueCalculation')
  43883. );
  43884. for (var i = 0; i < seriesList.length; i++) {
  43885. seriesList[i].originalData = seriesList[i].getData();
  43886. }
  43887. // FIXME Put where?
  43888. for (var i = 0; i < seriesList.length; i++) {
  43889. seriesList[i].seriesGroup = seriesList;
  43890. seriesList[i].needsDrawMap = i === 0 && !seriesList[i].getHostGeoModel();
  43891. seriesList[i].setData(data.cloneShallow());
  43892. seriesList[i].mainSeries = seriesList[0];
  43893. }
  43894. });
  43895. };
  43896. /*
  43897. * Licensed to the Apache Software Foundation (ASF) under one
  43898. * or more contributor license agreements. See the NOTICE file
  43899. * distributed with this work for additional information
  43900. * regarding copyright ownership. The ASF licenses this file
  43901. * to you under the Apache License, Version 2.0 (the
  43902. * "License"); you may not use this file except in compliance
  43903. * with the License. You may obtain a copy of the License at
  43904. *
  43905. * http://www.apache.org/licenses/LICENSE-2.0
  43906. *
  43907. * Unless required by applicable law or agreed to in writing,
  43908. * software distributed under the License is distributed on an
  43909. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43910. * KIND, either express or implied. See the License for the
  43911. * specific language governing permissions and limitations
  43912. * under the License.
  43913. */
  43914. var backwardCompat$2 = function (option) {
  43915. // Save geoCoord
  43916. var mapSeries = [];
  43917. each$1(option.series, function (seriesOpt) {
  43918. if (seriesOpt && seriesOpt.type === 'map') {
  43919. mapSeries.push(seriesOpt);
  43920. seriesOpt.map = seriesOpt.map || seriesOpt.mapType;
  43921. // Put x, y, width, height, x2, y2 in the top level
  43922. defaults(seriesOpt, seriesOpt.mapLocation);
  43923. }
  43924. });
  43925. };
  43926. /*
  43927. * Licensed to the Apache Software Foundation (ASF) under one
  43928. * or more contributor license agreements. See the NOTICE file
  43929. * distributed with this work for additional information
  43930. * regarding copyright ownership. The ASF licenses this file
  43931. * to you under the Apache License, Version 2.0 (the
  43932. * "License"); you may not use this file except in compliance
  43933. * with the License. You may obtain a copy of the License at
  43934. *
  43935. * http://www.apache.org/licenses/LICENSE-2.0
  43936. *
  43937. * Unless required by applicable law or agreed to in writing,
  43938. * software distributed under the License is distributed on an
  43939. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43940. * KIND, either express or implied. See the License for the
  43941. * specific language governing permissions and limitations
  43942. * under the License.
  43943. */
  43944. registerLayout(mapSymbolLayout);
  43945. registerVisual(mapVisual);
  43946. registerProcessor(PRIORITY.PROCESSOR.STATISTIC, mapDataStatistic);
  43947. registerPreprocessor(backwardCompat$2);
  43948. createDataSelectAction('map', [{
  43949. type: 'mapToggleSelect',
  43950. event: 'mapselectchanged',
  43951. method: 'toggleSelected'
  43952. }, {
  43953. type: 'mapSelect',
  43954. event: 'mapselected',
  43955. method: 'select'
  43956. }, {
  43957. type: 'mapUnSelect',
  43958. event: 'mapunselected',
  43959. method: 'unSelect'
  43960. }]);
  43961. /*
  43962. * Licensed to the Apache Software Foundation (ASF) under one
  43963. * or more contributor license agreements. See the NOTICE file
  43964. * distributed with this work for additional information
  43965. * regarding copyright ownership. The ASF licenses this file
  43966. * to you under the Apache License, Version 2.0 (the
  43967. * "License"); you may not use this file except in compliance
  43968. * with the License. You may obtain a copy of the License at
  43969. *
  43970. * http://www.apache.org/licenses/LICENSE-2.0
  43971. *
  43972. * Unless required by applicable law or agreed to in writing,
  43973. * software distributed under the License is distributed on an
  43974. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43975. * KIND, either express or implied. See the License for the
  43976. * specific language governing permissions and limitations
  43977. * under the License.
  43978. */
  43979. /**
  43980. * Link lists and struct (graph or tree)
  43981. */
  43982. var each$7 = each$1;
  43983. var DATAS = '\0__link_datas';
  43984. var MAIN_DATA = '\0__link_mainData';
  43985. // Caution:
  43986. // In most case, either list or its shallow clones (see list.cloneShallow)
  43987. // is active in echarts process. So considering heap memory consumption,
  43988. // we do not clone tree or graph, but share them among list and its shallow clones.
  43989. // But in some rare case, we have to keep old list (like do animation in chart). So
  43990. // please take care that both the old list and the new list share the same tree/graph.
  43991. /**
  43992. * @param {Object} opt
  43993. * @param {module:echarts/data/List} opt.mainData
  43994. * @param {Object} [opt.struct] For example, instance of Graph or Tree.
  43995. * @param {string} [opt.structAttr] designation: list[structAttr] = struct;
  43996. * @param {Object} [opt.datas] {dataType: data},
  43997. * like: {node: nodeList, edge: edgeList}.
  43998. * Should contain mainData.
  43999. * @param {Object} [opt.datasAttr] {dataType: attr},
  44000. * designation: struct[datasAttr[dataType]] = list;
  44001. */
  44002. function linkList(opt) {
  44003. var mainData = opt.mainData;
  44004. var datas = opt.datas;
  44005. if (!datas) {
  44006. datas = {main: mainData};
  44007. opt.datasAttr = {main: 'data'};
  44008. }
  44009. opt.datas = opt.mainData = null;
  44010. linkAll(mainData, datas, opt);
  44011. // Porxy data original methods.
  44012. each$7(datas, function (data) {
  44013. each$7(mainData.TRANSFERABLE_METHODS, function (methodName) {
  44014. data.wrapMethod(methodName, curry(transferInjection, opt));
  44015. });
  44016. });
  44017. // Beyond transfer, additional features should be added to `cloneShallow`.
  44018. mainData.wrapMethod('cloneShallow', curry(cloneShallowInjection, opt));
  44019. // Only mainData trigger change, because struct.update may trigger
  44020. // another changable methods, which may bring about dead lock.
  44021. each$7(mainData.CHANGABLE_METHODS, function (methodName) {
  44022. mainData.wrapMethod(methodName, curry(changeInjection, opt));
  44023. });
  44024. // Make sure datas contains mainData.
  44025. assert$1(datas[mainData.dataType] === mainData);
  44026. }
  44027. function transferInjection(opt, res) {
  44028. if (isMainData(this)) {
  44029. // Transfer datas to new main data.
  44030. var datas = extend({}, this[DATAS]);
  44031. datas[this.dataType] = res;
  44032. linkAll(res, datas, opt);
  44033. }
  44034. else {
  44035. // Modify the reference in main data to point newData.
  44036. linkSingle(res, this.dataType, this[MAIN_DATA], opt);
  44037. }
  44038. return res;
  44039. }
  44040. function changeInjection(opt, res) {
  44041. opt.struct && opt.struct.update(this);
  44042. return res;
  44043. }
  44044. function cloneShallowInjection(opt, res) {
  44045. // cloneShallow, which brings about some fragilities, may be inappropriate
  44046. // to be exposed as an API. So for implementation simplicity we can make
  44047. // the restriction that cloneShallow of not-mainData should not be invoked
  44048. // outside, but only be invoked here.
  44049. each$7(res[DATAS], function (data, dataType) {
  44050. data !== res && linkSingle(data.cloneShallow(), dataType, res, opt);
  44051. });
  44052. return res;
  44053. }
  44054. /**
  44055. * Supplement method to List.
  44056. *
  44057. * @public
  44058. * @param {string} [dataType] If not specified, return mainData.
  44059. * @return {module:echarts/data/List}
  44060. */
  44061. function getLinkedData(dataType) {
  44062. var mainData = this[MAIN_DATA];
  44063. return (dataType == null || mainData == null)
  44064. ? mainData
  44065. : mainData[DATAS][dataType];
  44066. }
  44067. function isMainData(data) {
  44068. return data[MAIN_DATA] === data;
  44069. }
  44070. function linkAll(mainData, datas, opt) {
  44071. mainData[DATAS] = {};
  44072. each$7(datas, function (data, dataType) {
  44073. linkSingle(data, dataType, mainData, opt);
  44074. });
  44075. }
  44076. function linkSingle(data, dataType, mainData, opt) {
  44077. mainData[DATAS][dataType] = data;
  44078. data[MAIN_DATA] = mainData;
  44079. data.dataType = dataType;
  44080. if (opt.struct) {
  44081. data[opt.structAttr] = opt.struct;
  44082. opt.struct[opt.datasAttr[dataType]] = data;
  44083. }
  44084. // Supplement method.
  44085. data.getLinkedData = getLinkedData;
  44086. }
  44087. /*
  44088. * Licensed to the Apache Software Foundation (ASF) under one
  44089. * or more contributor license agreements. See the NOTICE file
  44090. * distributed with this work for additional information
  44091. * regarding copyright ownership. The ASF licenses this file
  44092. * to you under the Apache License, Version 2.0 (the
  44093. * "License"); you may not use this file except in compliance
  44094. * with the License. You may obtain a copy of the License at
  44095. *
  44096. * http://www.apache.org/licenses/LICENSE-2.0
  44097. *
  44098. * Unless required by applicable law or agreed to in writing,
  44099. * software distributed under the License is distributed on an
  44100. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44101. * KIND, either express or implied. See the License for the
  44102. * specific language governing permissions and limitations
  44103. * under the License.
  44104. */
  44105. /**
  44106. * Tree data structure
  44107. *
  44108. * @module echarts/data/Tree
  44109. */
  44110. /**
  44111. * @constructor module:echarts/data/Tree~TreeNode
  44112. * @param {string} name
  44113. * @param {module:echarts/data/Tree} hostTree
  44114. */
  44115. var TreeNode = function (name, hostTree) {
  44116. /**
  44117. * @type {string}
  44118. */
  44119. this.name = name || '';
  44120. /**
  44121. * Depth of node
  44122. *
  44123. * @type {number}
  44124. * @readOnly
  44125. */
  44126. this.depth = 0;
  44127. /**
  44128. * Height of the subtree rooted at this node.
  44129. * @type {number}
  44130. * @readOnly
  44131. */
  44132. this.height = 0;
  44133. /**
  44134. * @type {module:echarts/data/Tree~TreeNode}
  44135. * @readOnly
  44136. */
  44137. this.parentNode = null;
  44138. /**
  44139. * Reference to list item.
  44140. * Do not persistent dataIndex outside,
  44141. * besause it may be changed by list.
  44142. * If dataIndex -1,
  44143. * this node is logical deleted (filtered) in list.
  44144. *
  44145. * @type {Object}
  44146. * @readOnly
  44147. */
  44148. this.dataIndex = -1;
  44149. /**
  44150. * @type {Array.<module:echarts/data/Tree~TreeNode>}
  44151. * @readOnly
  44152. */
  44153. this.children = [];
  44154. /**
  44155. * @type {Array.<module:echarts/data/Tree~TreeNode>}
  44156. * @pubilc
  44157. */
  44158. this.viewChildren = [];
  44159. /**
  44160. * @type {moduel:echarts/data/Tree}
  44161. * @readOnly
  44162. */
  44163. this.hostTree = hostTree;
  44164. };
  44165. TreeNode.prototype = {
  44166. constructor: TreeNode,
  44167. /**
  44168. * The node is removed.
  44169. * @return {boolean} is removed.
  44170. */
  44171. isRemoved: function () {
  44172. return this.dataIndex < 0;
  44173. },
  44174. /**
  44175. * Travel this subtree (include this node).
  44176. * Usage:
  44177. * node.eachNode(function () { ... }); // preorder
  44178. * node.eachNode('preorder', function () { ... }); // preorder
  44179. * node.eachNode('postorder', function () { ... }); // postorder
  44180. * node.eachNode(
  44181. * {order: 'postorder', attr: 'viewChildren'},
  44182. * function () { ... }
  44183. * ); // postorder
  44184. *
  44185. * @param {(Object|string)} options If string, means order.
  44186. * @param {string=} options.order 'preorder' or 'postorder'
  44187. * @param {string=} options.attr 'children' or 'viewChildren'
  44188. * @param {Function} cb If in preorder and return false,
  44189. * its subtree will not be visited.
  44190. * @param {Object} [context]
  44191. */
  44192. eachNode: function (options, cb, context) {
  44193. if (typeof options === 'function') {
  44194. context = cb;
  44195. cb = options;
  44196. options = null;
  44197. }
  44198. options = options || {};
  44199. if (isString(options)) {
  44200. options = {order: options};
  44201. }
  44202. var order = options.order || 'preorder';
  44203. var children = this[options.attr || 'children'];
  44204. var suppressVisitSub;
  44205. order === 'preorder' && (suppressVisitSub = cb.call(context, this));
  44206. for (var i = 0; !suppressVisitSub && i < children.length; i++) {
  44207. children[i].eachNode(options, cb, context);
  44208. }
  44209. order === 'postorder' && cb.call(context, this);
  44210. },
  44211. /**
  44212. * Update depth and height of this subtree.
  44213. *
  44214. * @param {number} depth
  44215. */
  44216. updateDepthAndHeight: function (depth) {
  44217. var height = 0;
  44218. this.depth = depth;
  44219. for (var i = 0; i < this.children.length; i++) {
  44220. var child = this.children[i];
  44221. child.updateDepthAndHeight(depth + 1);
  44222. if (child.height > height) {
  44223. height = child.height;
  44224. }
  44225. }
  44226. this.height = height + 1;
  44227. },
  44228. /**
  44229. * @param {string} id
  44230. * @return {module:echarts/data/Tree~TreeNode}
  44231. */
  44232. getNodeById: function (id) {
  44233. if (this.getId() === id) {
  44234. return this;
  44235. }
  44236. for (var i = 0, children = this.children, len = children.length; i < len; i++) {
  44237. var res = children[i].getNodeById(id);
  44238. if (res) {
  44239. return res;
  44240. }
  44241. }
  44242. },
  44243. /**
  44244. * @param {module:echarts/data/Tree~TreeNode} node
  44245. * @return {boolean}
  44246. */
  44247. contains: function (node) {
  44248. if (node === this) {
  44249. return true;
  44250. }
  44251. for (var i = 0, children = this.children, len = children.length; i < len; i++) {
  44252. var res = children[i].contains(node);
  44253. if (res) {
  44254. return res;
  44255. }
  44256. }
  44257. },
  44258. /**
  44259. * @param {boolean} includeSelf Default false.
  44260. * @return {Array.<module:echarts/data/Tree~TreeNode>} order: [root, child, grandchild, ...]
  44261. */
  44262. getAncestors: function (includeSelf) {
  44263. var ancestors = [];
  44264. var node = includeSelf ? this : this.parentNode;
  44265. while (node) {
  44266. ancestors.push(node);
  44267. node = node.parentNode;
  44268. }
  44269. ancestors.reverse();
  44270. return ancestors;
  44271. },
  44272. /**
  44273. * @param {string|Array=} [dimension='value'] Default 'value'. can be 0, 1, 2, 3
  44274. * @return {number} Value.
  44275. */
  44276. getValue: function (dimension) {
  44277. var data = this.hostTree.data;
  44278. return data.get(data.getDimension(dimension || 'value'), this.dataIndex);
  44279. },
  44280. /**
  44281. * @param {Object} layout
  44282. * @param {boolean=} [merge=false]
  44283. */
  44284. setLayout: function (layout, merge$$1) {
  44285. this.dataIndex >= 0
  44286. && this.hostTree.data.setItemLayout(this.dataIndex, layout, merge$$1);
  44287. },
  44288. /**
  44289. * @return {Object} layout
  44290. */
  44291. getLayout: function () {
  44292. return this.hostTree.data.getItemLayout(this.dataIndex);
  44293. },
  44294. /**
  44295. * @param {string} [path]
  44296. * @return {module:echarts/model/Model}
  44297. */
  44298. getModel: function (path) {
  44299. if (this.dataIndex < 0) {
  44300. return;
  44301. }
  44302. var hostTree = this.hostTree;
  44303. var itemModel = hostTree.data.getItemModel(this.dataIndex);
  44304. var levelModel = this.getLevelModel();
  44305. // FIXME: refactor levelModel to "beforeLink", and remove levelModel here.
  44306. if (levelModel) {
  44307. return itemModel.getModel(path, levelModel.getModel(path));
  44308. }
  44309. else {
  44310. return itemModel.getModel(path);
  44311. }
  44312. },
  44313. /**
  44314. * @return {module:echarts/model/Model}
  44315. */
  44316. getLevelModel: function () {
  44317. return (this.hostTree.levelModels || [])[this.depth];
  44318. },
  44319. /**
  44320. * @example
  44321. * setItemVisual('color', color);
  44322. * setItemVisual({
  44323. * 'color': color
  44324. * });
  44325. */
  44326. setVisual: function (key, value) {
  44327. this.dataIndex >= 0
  44328. && this.hostTree.data.setItemVisual(this.dataIndex, key, value);
  44329. },
  44330. /**
  44331. * Get item visual
  44332. */
  44333. getVisual: function (key, ignoreParent) {
  44334. return this.hostTree.data.getItemVisual(this.dataIndex, key, ignoreParent);
  44335. },
  44336. /**
  44337. * @public
  44338. * @return {number}
  44339. */
  44340. getRawIndex: function () {
  44341. return this.hostTree.data.getRawIndex(this.dataIndex);
  44342. },
  44343. /**
  44344. * @public
  44345. * @return {string}
  44346. */
  44347. getId: function () {
  44348. return this.hostTree.data.getId(this.dataIndex);
  44349. },
  44350. /**
  44351. * if this is an ancestor of another node
  44352. *
  44353. * @public
  44354. * @param {TreeNode} node another node
  44355. * @return {boolean} if is ancestor
  44356. */
  44357. isAncestorOf: function (node) {
  44358. var parent = node.parentNode;
  44359. while (parent) {
  44360. if (parent === this) {
  44361. return true;
  44362. }
  44363. parent = parent.parentNode;
  44364. }
  44365. return false;
  44366. },
  44367. /**
  44368. * if this is an descendant of another node
  44369. *
  44370. * @public
  44371. * @param {TreeNode} node another node
  44372. * @return {boolean} if is descendant
  44373. */
  44374. isDescendantOf: function (node) {
  44375. return node !== this && node.isAncestorOf(this);
  44376. }
  44377. };
  44378. /**
  44379. * @constructor
  44380. * @alias module:echarts/data/Tree
  44381. * @param {module:echarts/model/Model} hostModel
  44382. * @param {Array.<Object>} levelOptions
  44383. */
  44384. function Tree(hostModel, levelOptions) {
  44385. /**
  44386. * @type {module:echarts/data/Tree~TreeNode}
  44387. * @readOnly
  44388. */
  44389. this.root;
  44390. /**
  44391. * @type {module:echarts/data/List}
  44392. * @readOnly
  44393. */
  44394. this.data;
  44395. /**
  44396. * Index of each item is the same as the raw index of coresponding list item.
  44397. * @private
  44398. * @type {Array.<module:echarts/data/Tree~TreeNode}
  44399. */
  44400. this._nodes = [];
  44401. /**
  44402. * @private
  44403. * @readOnly
  44404. * @type {module:echarts/model/Model}
  44405. */
  44406. this.hostModel = hostModel;
  44407. /**
  44408. * @private
  44409. * @readOnly
  44410. * @type {Array.<module:echarts/model/Model}
  44411. */
  44412. this.levelModels = map(levelOptions || [], function (levelDefine) {
  44413. return new Model(levelDefine, hostModel, hostModel.ecModel);
  44414. });
  44415. }
  44416. Tree.prototype = {
  44417. constructor: Tree,
  44418. type: 'tree',
  44419. /**
  44420. * Travel this subtree (include this node).
  44421. * Usage:
  44422. * node.eachNode(function () { ... }); // preorder
  44423. * node.eachNode('preorder', function () { ... }); // preorder
  44424. * node.eachNode('postorder', function () { ... }); // postorder
  44425. * node.eachNode(
  44426. * {order: 'postorder', attr: 'viewChildren'},
  44427. * function () { ... }
  44428. * ); // postorder
  44429. *
  44430. * @param {(Object|string)} options If string, means order.
  44431. * @param {string=} options.order 'preorder' or 'postorder'
  44432. * @param {string=} options.attr 'children' or 'viewChildren'
  44433. * @param {Function} cb
  44434. * @param {Object} [context]
  44435. */
  44436. eachNode: function (options, cb, context) {
  44437. this.root.eachNode(options, cb, context);
  44438. },
  44439. /**
  44440. * @param {number} dataIndex
  44441. * @return {module:echarts/data/Tree~TreeNode}
  44442. */
  44443. getNodeByDataIndex: function (dataIndex) {
  44444. var rawIndex = this.data.getRawIndex(dataIndex);
  44445. return this._nodes[rawIndex];
  44446. },
  44447. /**
  44448. * @param {string} name
  44449. * @return {module:echarts/data/Tree~TreeNode}
  44450. */
  44451. getNodeByName: function (name) {
  44452. return this.root.getNodeByName(name);
  44453. },
  44454. /**
  44455. * Update item available by list,
  44456. * when list has been performed options like 'filterSelf' or 'map'.
  44457. */
  44458. update: function () {
  44459. var data = this.data;
  44460. var nodes = this._nodes;
  44461. for (var i = 0, len = nodes.length; i < len; i++) {
  44462. nodes[i].dataIndex = -1;
  44463. }
  44464. for (var i = 0, len = data.count(); i < len; i++) {
  44465. nodes[data.getRawIndex(i)].dataIndex = i;
  44466. }
  44467. },
  44468. /**
  44469. * Clear all layouts
  44470. */
  44471. clearLayouts: function () {
  44472. this.data.clearItemLayouts();
  44473. }
  44474. };
  44475. /**
  44476. * data node format:
  44477. * {
  44478. * name: ...
  44479. * value: ...
  44480. * children: [
  44481. * {
  44482. * name: ...
  44483. * value: ...
  44484. * children: ...
  44485. * },
  44486. * ...
  44487. * ]
  44488. * }
  44489. *
  44490. * @static
  44491. * @param {Object} dataRoot Root node.
  44492. * @param {module:echarts/model/Model} hostModel
  44493. * @param {Object} treeOptions
  44494. * @param {Array.<Object>} treeOptions.levels
  44495. * @return module:echarts/data/Tree
  44496. */
  44497. Tree.createTree = function (dataRoot, hostModel, treeOptions, beforeLink) {
  44498. var tree = new Tree(hostModel, treeOptions && treeOptions.levels);
  44499. var listData = [];
  44500. var dimMax = 1;
  44501. buildHierarchy(dataRoot);
  44502. function buildHierarchy(dataNode, parentNode) {
  44503. var value = dataNode.value;
  44504. dimMax = Math.max(dimMax, isArray(value) ? value.length : 1);
  44505. listData.push(dataNode);
  44506. var node = new TreeNode(dataNode.name, tree);
  44507. parentNode
  44508. ? addChild(node, parentNode)
  44509. : (tree.root = node);
  44510. tree._nodes.push(node);
  44511. var children = dataNode.children;
  44512. if (children) {
  44513. for (var i = 0; i < children.length; i++) {
  44514. buildHierarchy(children[i], node);
  44515. }
  44516. }
  44517. }
  44518. tree.root.updateDepthAndHeight(0);
  44519. var dimensionsInfo = createDimensions(listData, {
  44520. coordDimensions: ['value'],
  44521. dimensionsCount: dimMax
  44522. });
  44523. var list = new List(dimensionsInfo, hostModel);
  44524. list.initData(listData);
  44525. beforeLink && beforeLink(list);
  44526. linkList({
  44527. mainData: list,
  44528. struct: tree,
  44529. structAttr: 'tree'
  44530. });
  44531. tree.update();
  44532. return tree;
  44533. };
  44534. /**
  44535. * It is needed to consider the mess of 'list', 'hostModel' when creating a TreeNote,
  44536. * so this function is not ready and not necessary to be public.
  44537. *
  44538. * @param {(module:echarts/data/Tree~TreeNode|Object)} child
  44539. */
  44540. function addChild(child, node) {
  44541. var children = node.children;
  44542. if (child.parentNode === node) {
  44543. return;
  44544. }
  44545. children.push(child);
  44546. child.parentNode = node;
  44547. }
  44548. /*
  44549. * Licensed to the Apache Software Foundation (ASF) under one
  44550. * or more contributor license agreements. See the NOTICE file
  44551. * distributed with this work for additional information
  44552. * regarding copyright ownership. The ASF licenses this file
  44553. * to you under the Apache License, Version 2.0 (the
  44554. * "License"); you may not use this file except in compliance
  44555. * with the License. You may obtain a copy of the License at
  44556. *
  44557. * http://www.apache.org/licenses/LICENSE-2.0
  44558. *
  44559. * Unless required by applicable law or agreed to in writing,
  44560. * software distributed under the License is distributed on an
  44561. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44562. * KIND, either express or implied. See the License for the
  44563. * specific language governing permissions and limitations
  44564. * under the License.
  44565. */
  44566. SeriesModel.extend({
  44567. type: 'series.tree',
  44568. layoutInfo: null,
  44569. // can support the position parameters 'left', 'top','right','bottom', 'width',
  44570. // 'height' in the setOption() with 'merge' mode normal.
  44571. layoutMode: 'box',
  44572. /**
  44573. * Init a tree data structure from data in option series
  44574. * @param {Object} option the object used to config echarts view
  44575. * @return {module:echarts/data/List} storage initial data
  44576. */
  44577. getInitialData: function (option) {
  44578. //create an virtual root
  44579. var root = {name: option.name, children: option.data};
  44580. var leaves = option.leaves || {};
  44581. var leavesModel = new Model(leaves, this, this.ecModel);
  44582. var tree = Tree.createTree(root, this, {}, beforeLink);
  44583. function beforeLink(nodeData) {
  44584. nodeData.wrapMethod('getItemModel', function (model, idx) {
  44585. var node = tree.getNodeByDataIndex(idx);
  44586. if (!node.children.length || !node.isExpand) {
  44587. model.parentModel = leavesModel;
  44588. }
  44589. return model;
  44590. });
  44591. }
  44592. var treeDepth = 0;
  44593. tree.eachNode('preorder', function (node) {
  44594. if (node.depth > treeDepth) {
  44595. treeDepth = node.depth;
  44596. }
  44597. });
  44598. var expandAndCollapse = option.expandAndCollapse;
  44599. var expandTreeDepth = (expandAndCollapse && option.initialTreeDepth >= 0)
  44600. ? option.initialTreeDepth : treeDepth;
  44601. tree.root.eachNode('preorder', function (node) {
  44602. var item = node.hostTree.data.getRawDataItem(node.dataIndex);
  44603. // Add item.collapsed != null, because users can collapse node original in the series.data.
  44604. node.isExpand = (item && item.collapsed != null)
  44605. ? !item.collapsed
  44606. : node.depth <= expandTreeDepth;
  44607. });
  44608. return tree.data;
  44609. },
  44610. /**
  44611. * Make the configuration 'orient' backward compatibly, with 'horizontal = LR', 'vertical = TB'.
  44612. * @returns {string} orient
  44613. */
  44614. getOrient: function () {
  44615. var orient = this.get('orient');
  44616. if (orient === 'horizontal') {
  44617. orient = 'LR';
  44618. }
  44619. else if (orient === 'vertical') {
  44620. orient = 'TB';
  44621. }
  44622. return orient;
  44623. },
  44624. setZoom: function (zoom) {
  44625. this.option.zoom = zoom;
  44626. },
  44627. setCenter: function (center) {
  44628. this.option.center = center;
  44629. },
  44630. /**
  44631. * @override
  44632. * @param {number} dataIndex
  44633. */
  44634. formatTooltip: function (dataIndex) {
  44635. var tree = this.getData().tree;
  44636. var realRoot = tree.root.children[0];
  44637. var node = tree.getNodeByDataIndex(dataIndex);
  44638. var value = node.getValue();
  44639. var name = node.name;
  44640. while (node && (node !== realRoot)) {
  44641. name = node.parentNode.name + '.' + name;
  44642. node = node.parentNode;
  44643. }
  44644. return encodeHTML(name + (
  44645. (isNaN(value) || value == null) ? '' : ' : ' + value
  44646. ));
  44647. },
  44648. defaultOption: {
  44649. zlevel: 0,
  44650. z: 2,
  44651. coordinateSystem: 'view',
  44652. // the position of the whole view
  44653. left: '12%',
  44654. top: '12%',
  44655. right: '12%',
  44656. bottom: '12%',
  44657. // the layout of the tree, two value can be selected, 'orthogonal' or 'radial'
  44658. layout: 'orthogonal',
  44659. // value can be 'polyline'
  44660. edgeShape: 'curve',
  44661. edgeForkPosition: '50%',
  44662. // true | false | 'move' | 'scale', see module:component/helper/RoamController.
  44663. roam: false,
  44664. // Symbol size scale ratio in roam
  44665. nodeScaleRatio: 0.4,
  44666. // Default on center of graph
  44667. center: null,
  44668. zoom: 1,
  44669. // The orient of orthoginal layout, can be setted to 'LR', 'TB', 'RL', 'BT'.
  44670. // and the backward compatibility configuration 'horizontal = LR', 'vertical = TB'.
  44671. orient: 'LR',
  44672. symbol: 'emptyCircle',
  44673. symbolSize: 7,
  44674. expandAndCollapse: true,
  44675. initialTreeDepth: 2,
  44676. lineStyle: {
  44677. color: '#ccc',
  44678. width: 1.5,
  44679. curveness: 0.5
  44680. },
  44681. itemStyle: {
  44682. color: 'lightsteelblue',
  44683. borderColor: '#c23531',
  44684. borderWidth: 1.5
  44685. },
  44686. label: {
  44687. show: true,
  44688. color: '#555'
  44689. },
  44690. leaves: {
  44691. label: {
  44692. show: true
  44693. }
  44694. },
  44695. animationEasing: 'linear',
  44696. animationDuration: 700,
  44697. animationDurationUpdate: 1000
  44698. }
  44699. });
  44700. /*
  44701. * Licensed to the Apache Software Foundation (ASF) under one
  44702. * or more contributor license agreements. See the NOTICE file
  44703. * distributed with this work for additional information
  44704. * regarding copyright ownership. The ASF licenses this file
  44705. * to you under the Apache License, Version 2.0 (the
  44706. * "License"); you may not use this file except in compliance
  44707. * with the License. You may obtain a copy of the License at
  44708. *
  44709. * http://www.apache.org/licenses/LICENSE-2.0
  44710. *
  44711. * Unless required by applicable law or agreed to in writing,
  44712. * software distributed under the License is distributed on an
  44713. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44714. * KIND, either express or implied. See the License for the
  44715. * specific language governing permissions and limitations
  44716. * under the License.
  44717. */
  44718. /*
  44719. * A third-party license is embeded for some of the code in this file:
  44720. * The tree layoutHelper implementation was originally copied from
  44721. * "d3.js"(https://github.com/d3/d3-hierarchy) with
  44722. * some modifications made for this project.
  44723. * (see more details in the comment of the specific method below.)
  44724. * The use of the source code of this file is also subject to the terms
  44725. * and consitions of the licence of "d3.js" (BSD-3Clause, see
  44726. * </licenses/LICENSE-d3>).
  44727. */
  44728. /**
  44729. * @file The layout algorithm of node-link tree diagrams. Here we using Reingold-Tilford algorithm to drawing
  44730. * the tree.
  44731. */
  44732. /**
  44733. * Initialize all computational message for following algorithm.
  44734. *
  44735. * @param {module:echarts/data/Tree~TreeNode} root The virtual root of the tree.
  44736. */
  44737. function init$2(root) {
  44738. root.hierNode = {
  44739. defaultAncestor: null,
  44740. ancestor: root,
  44741. prelim: 0,
  44742. modifier: 0,
  44743. change: 0,
  44744. shift: 0,
  44745. i: 0,
  44746. thread: null
  44747. };
  44748. var nodes = [root];
  44749. var node;
  44750. var children;
  44751. while (node = nodes.pop()) { // jshint ignore:line
  44752. children = node.children;
  44753. if (node.isExpand && children.length) {
  44754. var n = children.length;
  44755. for (var i = n - 1; i >= 0; i--) {
  44756. var child = children[i];
  44757. child.hierNode = {
  44758. defaultAncestor: null,
  44759. ancestor: child,
  44760. prelim: 0,
  44761. modifier: 0,
  44762. change: 0,
  44763. shift: 0,
  44764. i: i,
  44765. thread: null
  44766. };
  44767. nodes.push(child);
  44768. }
  44769. }
  44770. }
  44771. }
  44772. /**
  44773. * The implementation of this function was originally copied from "d3.js"
  44774. * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js>
  44775. * with some modifications made for this program.
  44776. * See the license statement at the head of this file.
  44777. *
  44778. * Computes a preliminary x coordinate for node. Before that, this function is
  44779. * applied recursively to the children of node, as well as the function
  44780. * apportion(). After spacing out the children by calling executeShifts(), the
  44781. * node is placed to the midpoint of its outermost children.
  44782. *
  44783. * @param {module:echarts/data/Tree~TreeNode} node
  44784. * @param {Function} separation
  44785. */
  44786. function firstWalk(node, separation) {
  44787. var children = node.isExpand ? node.children : [];
  44788. var siblings = node.parentNode.children;
  44789. var subtreeW = node.hierNode.i ? siblings[node.hierNode.i - 1] : null;
  44790. if (children.length) {
  44791. executeShifts(node);
  44792. var midPoint = (children[0].hierNode.prelim + children[children.length - 1].hierNode.prelim) / 2;
  44793. if (subtreeW) {
  44794. node.hierNode.prelim = subtreeW.hierNode.prelim + separation(node, subtreeW);
  44795. node.hierNode.modifier = node.hierNode.prelim - midPoint;
  44796. }
  44797. else {
  44798. node.hierNode.prelim = midPoint;
  44799. }
  44800. }
  44801. else if (subtreeW) {
  44802. node.hierNode.prelim = subtreeW.hierNode.prelim + separation(node, subtreeW);
  44803. }
  44804. node.parentNode.hierNode.defaultAncestor = apportion(
  44805. node,
  44806. subtreeW,
  44807. node.parentNode.hierNode.defaultAncestor || siblings[0],
  44808. separation
  44809. );
  44810. }
  44811. /**
  44812. * The implementation of this function was originally copied from "d3.js"
  44813. * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js>
  44814. * with some modifications made for this program.
  44815. * See the license statement at the head of this file.
  44816. *
  44817. * Computes all real x-coordinates by summing up the modifiers recursively.
  44818. *
  44819. * @param {module:echarts/data/Tree~TreeNode} node
  44820. */
  44821. function secondWalk(node) {
  44822. var nodeX = node.hierNode.prelim + node.parentNode.hierNode.modifier;
  44823. node.setLayout({x: nodeX}, true);
  44824. node.hierNode.modifier += node.parentNode.hierNode.modifier;
  44825. }
  44826. function separation(cb) {
  44827. return arguments.length ? cb : defaultSeparation;
  44828. }
  44829. /**
  44830. * Transform the common coordinate to radial coordinate.
  44831. *
  44832. * @param {number} x
  44833. * @param {number} y
  44834. * @return {Object}
  44835. */
  44836. function radialCoordinate(x, y) {
  44837. var radialCoor = {};
  44838. x -= Math.PI / 2;
  44839. radialCoor.x = y * Math.cos(x);
  44840. radialCoor.y = y * Math.sin(x);
  44841. return radialCoor;
  44842. }
  44843. /**
  44844. * Get the layout position of the whole view.
  44845. *
  44846. * @param {module:echarts/model/Series} seriesModel the model object of sankey series
  44847. * @param {module:echarts/ExtensionAPI} api provide the API list that the developer can call
  44848. * @return {module:zrender/core/BoundingRect} size of rect to draw the sankey view
  44849. */
  44850. function getViewRect$1(seriesModel, api) {
  44851. return getLayoutRect(
  44852. seriesModel.getBoxLayoutParams(), {
  44853. width: api.getWidth(),
  44854. height: api.getHeight()
  44855. }
  44856. );
  44857. }
  44858. /**
  44859. * All other shifts, applied to the smaller subtrees between w- and w+, are
  44860. * performed by this function.
  44861. *
  44862. * The implementation of this function was originally copied from "d3.js"
  44863. * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js>
  44864. * with some modifications made for this program.
  44865. * See the license statement at the head of this file.
  44866. *
  44867. * @param {module:echarts/data/Tree~TreeNode} node
  44868. */
  44869. function executeShifts(node) {
  44870. var children = node.children;
  44871. var n = children.length;
  44872. var shift = 0;
  44873. var change = 0;
  44874. while (--n >= 0) {
  44875. var child = children[n];
  44876. child.hierNode.prelim += shift;
  44877. child.hierNode.modifier += shift;
  44878. change += child.hierNode.change;
  44879. shift += child.hierNode.shift + change;
  44880. }
  44881. }
  44882. /**
  44883. * The implementation of this function was originally copied from "d3.js"
  44884. * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js>
  44885. * with some modifications made for this program.
  44886. * See the license statement at the head of this file.
  44887. *
  44888. * The core of the algorithm. Here, a new subtree is combined with the
  44889. * previous subtrees. Threads are used to traverse the inside and outside
  44890. * contours of the left and right subtree up to the highest common level.
  44891. * Whenever two nodes of the inside contours conflict, we compute the left
  44892. * one of the greatest uncommon ancestors using the function nextAncestor()
  44893. * and call moveSubtree() to shift the subtree and prepare the shifts of
  44894. * smaller subtrees. Finally, we add a new thread (if necessary).
  44895. *
  44896. * @param {module:echarts/data/Tree~TreeNode} subtreeV
  44897. * @param {module:echarts/data/Tree~TreeNode} subtreeW
  44898. * @param {module:echarts/data/Tree~TreeNode} ancestor
  44899. * @param {Function} separation
  44900. * @return {module:echarts/data/Tree~TreeNode}
  44901. */
  44902. function apportion(subtreeV, subtreeW, ancestor, separation) {
  44903. if (subtreeW) {
  44904. var nodeOutRight = subtreeV;
  44905. var nodeInRight = subtreeV;
  44906. var nodeOutLeft = nodeInRight.parentNode.children[0];
  44907. var nodeInLeft = subtreeW;
  44908. var sumOutRight = nodeOutRight.hierNode.modifier;
  44909. var sumInRight = nodeInRight.hierNode.modifier;
  44910. var sumOutLeft = nodeOutLeft.hierNode.modifier;
  44911. var sumInLeft = nodeInLeft.hierNode.modifier;
  44912. while (nodeInLeft = nextRight(nodeInLeft), nodeInRight = nextLeft(nodeInRight), nodeInLeft && nodeInRight) {
  44913. nodeOutRight = nextRight(nodeOutRight);
  44914. nodeOutLeft = nextLeft(nodeOutLeft);
  44915. nodeOutRight.hierNode.ancestor = subtreeV;
  44916. var shift = nodeInLeft.hierNode.prelim + sumInLeft - nodeInRight.hierNode.prelim
  44917. - sumInRight + separation(nodeInLeft, nodeInRight);
  44918. if (shift > 0) {
  44919. moveSubtree(nextAncestor(nodeInLeft, subtreeV, ancestor), subtreeV, shift);
  44920. sumInRight += shift;
  44921. sumOutRight += shift;
  44922. }
  44923. sumInLeft += nodeInLeft.hierNode.modifier;
  44924. sumInRight += nodeInRight.hierNode.modifier;
  44925. sumOutRight += nodeOutRight.hierNode.modifier;
  44926. sumOutLeft += nodeOutLeft.hierNode.modifier;
  44927. }
  44928. if (nodeInLeft && !nextRight(nodeOutRight)) {
  44929. nodeOutRight.hierNode.thread = nodeInLeft;
  44930. nodeOutRight.hierNode.modifier += sumInLeft - sumOutRight;
  44931. }
  44932. if (nodeInRight && !nextLeft(nodeOutLeft)) {
  44933. nodeOutLeft.hierNode.thread = nodeInRight;
  44934. nodeOutLeft.hierNode.modifier += sumInRight - sumOutLeft;
  44935. ancestor = subtreeV;
  44936. }
  44937. }
  44938. return ancestor;
  44939. }
  44940. /**
  44941. * This function is used to traverse the right contour of a subtree.
  44942. * It returns the rightmost child of node or the thread of node. The function
  44943. * returns null if and only if node is on the highest depth of its subtree.
  44944. *
  44945. * @param {module:echarts/data/Tree~TreeNode} node
  44946. * @return {module:echarts/data/Tree~TreeNode}
  44947. */
  44948. function nextRight(node) {
  44949. var children = node.children;
  44950. return children.length && node.isExpand ? children[children.length - 1] : node.hierNode.thread;
  44951. }
  44952. /**
  44953. * This function is used to traverse the left contour of a subtree (or a subforest).
  44954. * It returns the leftmost child of node or the thread of node. The function
  44955. * returns null if and only if node is on the highest depth of its subtree.
  44956. *
  44957. * @param {module:echarts/data/Tree~TreeNode} node
  44958. * @return {module:echarts/data/Tree~TreeNode}
  44959. */
  44960. function nextLeft(node) {
  44961. var children = node.children;
  44962. return children.length && node.isExpand ? children[0] : node.hierNode.thread;
  44963. }
  44964. /**
  44965. * If nodeInLeft’s ancestor is a sibling of node, returns nodeInLeft’s ancestor.
  44966. * Otherwise, returns the specified ancestor.
  44967. *
  44968. * @param {module:echarts/data/Tree~TreeNode} nodeInLeft
  44969. * @param {module:echarts/data/Tree~TreeNode} node
  44970. * @param {module:echarts/data/Tree~TreeNode} ancestor
  44971. * @return {module:echarts/data/Tree~TreeNode}
  44972. */
  44973. function nextAncestor(nodeInLeft, node, ancestor) {
  44974. return nodeInLeft.hierNode.ancestor.parentNode === node.parentNode
  44975. ? nodeInLeft.hierNode.ancestor : ancestor;
  44976. }
  44977. /**
  44978. * The implementation of this function was originally copied from "d3.js"
  44979. * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js>
  44980. * with some modifications made for this program.
  44981. * See the license statement at the head of this file.
  44982. *
  44983. * Shifts the current subtree rooted at wr.
  44984. * This is done by increasing prelim(w+) and modifier(w+) by shift.
  44985. *
  44986. * @param {module:echarts/data/Tree~TreeNode} wl
  44987. * @param {module:echarts/data/Tree~TreeNode} wr
  44988. * @param {number} shift [description]
  44989. */
  44990. function moveSubtree(wl, wr, shift) {
  44991. var change = shift / (wr.hierNode.i - wl.hierNode.i);
  44992. wr.hierNode.change -= change;
  44993. wr.hierNode.shift += shift;
  44994. wr.hierNode.modifier += shift;
  44995. wr.hierNode.prelim += shift;
  44996. wl.hierNode.change += change;
  44997. }
  44998. /**
  44999. * The implementation of this function was originally copied from "d3.js"
  45000. * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js>
  45001. * with some modifications made for this program.
  45002. * See the license statement at the head of this file.
  45003. */
  45004. function defaultSeparation(node1, node2) {
  45005. return node1.parentNode === node2.parentNode ? 1 : 2;
  45006. }
  45007. /*
  45008. * Licensed to the Apache Software Foundation (ASF) under one
  45009. * or more contributor license agreements. See the NOTICE file
  45010. * distributed with this work for additional information
  45011. * regarding copyright ownership. The ASF licenses this file
  45012. * to you under the Apache License, Version 2.0 (the
  45013. * "License"); you may not use this file except in compliance
  45014. * with the License. You may obtain a copy of the License at
  45015. *
  45016. * http://www.apache.org/licenses/LICENSE-2.0
  45017. *
  45018. * Unless required by applicable law or agreed to in writing,
  45019. * software distributed under the License is distributed on an
  45020. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45021. * KIND, either express or implied. See the License for the
  45022. * specific language governing permissions and limitations
  45023. * under the License.
  45024. */
  45025. var TreeShape = extendShape({
  45026. shape: {
  45027. parentPoint: [],
  45028. childPoints: [],
  45029. orient: '',
  45030. forkPosition: ''
  45031. },
  45032. style: {
  45033. stroke: '#000',
  45034. fill: null
  45035. },
  45036. buildPath: function (ctx, shape) {
  45037. var childPoints = shape.childPoints;
  45038. var childLen = childPoints.length;
  45039. var parentPoint = shape.parentPoint;
  45040. var firstChildPos = childPoints[0];
  45041. var lastChildPos = childPoints[childLen - 1];
  45042. if (childLen === 1) {
  45043. ctx.moveTo(parentPoint[0], parentPoint[1]);
  45044. ctx.lineTo(firstChildPos[0], firstChildPos[1]);
  45045. return;
  45046. }
  45047. var orient = shape.orient;
  45048. var forkDim = (orient === 'TB' || orient === 'BT') ? 0 : 1;
  45049. var otherDim = 1 - forkDim;
  45050. var forkPosition = parsePercent$1(shape.forkPosition, 1);
  45051. var tmpPoint = [];
  45052. tmpPoint[forkDim] = parentPoint[forkDim];
  45053. tmpPoint[otherDim] = parentPoint[otherDim] + (lastChildPos[otherDim] - parentPoint[otherDim]) * forkPosition;
  45054. ctx.moveTo(parentPoint[0], parentPoint[1]);
  45055. ctx.lineTo(tmpPoint[0], tmpPoint[1]);
  45056. ctx.moveTo(firstChildPos[0], firstChildPos[1]);
  45057. tmpPoint[forkDim] = firstChildPos[forkDim];
  45058. ctx.lineTo(tmpPoint[0], tmpPoint[1]);
  45059. tmpPoint[forkDim] = lastChildPos[forkDim];
  45060. ctx.lineTo(tmpPoint[0], tmpPoint[1]);
  45061. ctx.lineTo(lastChildPos[0], lastChildPos[1]);
  45062. for (var i = 1; i < childLen - 1; i++) {
  45063. var point = childPoints[i];
  45064. ctx.moveTo(point[0], point[1]);
  45065. tmpPoint[forkDim] = point[forkDim];
  45066. ctx.lineTo(tmpPoint[0], tmpPoint[1]);
  45067. }
  45068. }
  45069. });
  45070. extendChartView({
  45071. type: 'tree',
  45072. /**
  45073. * Init the chart
  45074. * @override
  45075. * @param {module:echarts/model/Global} ecModel
  45076. * @param {module:echarts/ExtensionAPI} api
  45077. */
  45078. init: function (ecModel, api) {
  45079. /**
  45080. * @private
  45081. * @type {module:echarts/data/Tree}
  45082. */
  45083. this._oldTree;
  45084. /**
  45085. * @private
  45086. * @type {module:zrender/container/Group}
  45087. */
  45088. this._mainGroup = new Group();
  45089. /**
  45090. * @private
  45091. * @type {module:echarts/componet/helper/RoamController}
  45092. */
  45093. this._controller = new RoamController(api.getZr());
  45094. this._controllerHost = {target: this.group};
  45095. this.group.add(this._mainGroup);
  45096. },
  45097. render: function (seriesModel, ecModel, api, payload) {
  45098. var data = seriesModel.getData();
  45099. var layoutInfo = seriesModel.layoutInfo;
  45100. var group = this._mainGroup;
  45101. var layout = seriesModel.get('layout');
  45102. if (layout === 'radial') {
  45103. group.attr('position', [layoutInfo.x + layoutInfo.width / 2, layoutInfo.y + layoutInfo.height / 2]);
  45104. }
  45105. else {
  45106. group.attr('position', [layoutInfo.x, layoutInfo.y]);
  45107. }
  45108. this._updateViewCoordSys(seriesModel, layoutInfo, layout);
  45109. this._updateController(seriesModel, ecModel, api);
  45110. var oldData = this._data;
  45111. var seriesScope = {
  45112. expandAndCollapse: seriesModel.get('expandAndCollapse'),
  45113. layout: layout,
  45114. edgeShape: seriesModel.get('edgeShape'),
  45115. edgeForkPosition: seriesModel.get('edgeForkPosition'),
  45116. orient: seriesModel.getOrient(),
  45117. curvature: seriesModel.get('lineStyle.curveness'),
  45118. symbolRotate: seriesModel.get('symbolRotate'),
  45119. symbolOffset: seriesModel.get('symbolOffset'),
  45120. hoverAnimation: seriesModel.get('hoverAnimation'),
  45121. useNameLabel: true,
  45122. fadeIn: true
  45123. };
  45124. data.diff(oldData)
  45125. .add(function (newIdx) {
  45126. if (symbolNeedsDraw$1(data, newIdx)) {
  45127. // Create node and edge
  45128. updateNode(data, newIdx, null, group, seriesModel, seriesScope);
  45129. }
  45130. })
  45131. .update(function (newIdx, oldIdx) {
  45132. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  45133. if (!symbolNeedsDraw$1(data, newIdx)) {
  45134. symbolEl && removeNode(oldData, oldIdx, symbolEl, group, seriesModel, seriesScope);
  45135. return;
  45136. }
  45137. // Update node and edge
  45138. updateNode(data, newIdx, symbolEl, group, seriesModel, seriesScope);
  45139. })
  45140. .remove(function (oldIdx) {
  45141. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  45142. // When remove a collapsed node of subtree, since the collapsed
  45143. // node haven't been initialized with a symbol element,
  45144. // you can't found it's symbol element through index.
  45145. // so if we want to remove the symbol element we should insure
  45146. // that the symbol element is not null.
  45147. if (symbolEl) {
  45148. removeNode(oldData, oldIdx, symbolEl, group, seriesModel, seriesScope);
  45149. }
  45150. })
  45151. .execute();
  45152. this._nodeScaleRatio = seriesModel.get('nodeScaleRatio');
  45153. this._updateNodeAndLinkScale(seriesModel);
  45154. if (seriesScope.expandAndCollapse === true) {
  45155. data.eachItemGraphicEl(function (el, dataIndex) {
  45156. el.off('click').on('click', function () {
  45157. api.dispatchAction({
  45158. type: 'treeExpandAndCollapse',
  45159. seriesId: seriesModel.id,
  45160. dataIndex: dataIndex
  45161. });
  45162. });
  45163. });
  45164. }
  45165. this._data = data;
  45166. },
  45167. _updateViewCoordSys: function (seriesModel) {
  45168. var data = seriesModel.getData();
  45169. var points = [];
  45170. data.each(function (idx) {
  45171. var layout = data.getItemLayout(idx);
  45172. if (layout && !isNaN(layout.x) && !isNaN(layout.y)) {
  45173. points.push([+layout.x, +layout.y]);
  45174. }
  45175. });
  45176. var min = [];
  45177. var max = [];
  45178. fromPoints(points, min, max);
  45179. // If don't Store min max when collapse the root node after roam,
  45180. // the root node will disappear.
  45181. var oldMin = this._min;
  45182. var oldMax = this._max;
  45183. // If width or height is 0
  45184. if (max[0] - min[0] === 0) {
  45185. min[0] = oldMin ? oldMin[0] : min[0] - 1;
  45186. max[0] = oldMax ? oldMax[0] : max[0] + 1;
  45187. }
  45188. if (max[1] - min[1] === 0) {
  45189. min[1] = oldMin ? oldMin[1] : min[1] - 1;
  45190. max[1] = oldMax ? oldMax[1] : max[1] + 1;
  45191. }
  45192. var viewCoordSys = seriesModel.coordinateSystem = new View();
  45193. viewCoordSys.zoomLimit = seriesModel.get('scaleLimit');
  45194. viewCoordSys.setBoundingRect(min[0], min[1], max[0] - min[0], max[1] - min[1]);
  45195. viewCoordSys.setCenter(seriesModel.get('center'));
  45196. viewCoordSys.setZoom(seriesModel.get('zoom'));
  45197. // Here we use viewCoordSys just for computing the 'position' and 'scale' of the group
  45198. this.group.attr({
  45199. position: viewCoordSys.position,
  45200. scale: viewCoordSys.scale
  45201. });
  45202. this._viewCoordSys = viewCoordSys;
  45203. this._min = min;
  45204. this._max = max;
  45205. },
  45206. _updateController: function (seriesModel, ecModel, api) {
  45207. var controller = this._controller;
  45208. var controllerHost = this._controllerHost;
  45209. var group = this.group;
  45210. controller.setPointerChecker(function (e, x, y) {
  45211. var rect = group.getBoundingRect();
  45212. rect.applyTransform(group.transform);
  45213. return rect.contain(x, y)
  45214. && !onIrrelevantElement(e, api, seriesModel);
  45215. });
  45216. controller.enable(seriesModel.get('roam'));
  45217. controllerHost.zoomLimit = seriesModel.get('scaleLimit');
  45218. controllerHost.zoom = seriesModel.coordinateSystem.getZoom();
  45219. controller
  45220. .off('pan')
  45221. .off('zoom')
  45222. .on('pan', function (e) {
  45223. updateViewOnPan(controllerHost, e.dx, e.dy);
  45224. api.dispatchAction({
  45225. seriesId: seriesModel.id,
  45226. type: 'treeRoam',
  45227. dx: e.dx,
  45228. dy: e.dy
  45229. });
  45230. }, this)
  45231. .on('zoom', function (e) {
  45232. updateViewOnZoom(controllerHost, e.scale, e.originX, e.originY);
  45233. api.dispatchAction({
  45234. seriesId: seriesModel.id,
  45235. type: 'treeRoam',
  45236. zoom: e.scale,
  45237. originX: e.originX,
  45238. originY: e.originY
  45239. });
  45240. this._updateNodeAndLinkScale(seriesModel);
  45241. }, this);
  45242. },
  45243. _updateNodeAndLinkScale: function (seriesModel) {
  45244. var data = seriesModel.getData();
  45245. var nodeScale = this._getNodeGlobalScale(seriesModel);
  45246. var invScale = [nodeScale, nodeScale];
  45247. data.eachItemGraphicEl(function (el, idx) {
  45248. el.attr('scale', invScale);
  45249. });
  45250. },
  45251. _getNodeGlobalScale: function (seriesModel) {
  45252. var coordSys = seriesModel.coordinateSystem;
  45253. if (coordSys.type !== 'view') {
  45254. return 1;
  45255. }
  45256. var nodeScaleRatio = this._nodeScaleRatio;
  45257. var groupScale = coordSys.scale;
  45258. var groupZoom = (groupScale && groupScale[0]) || 1;
  45259. // Scale node when zoom changes
  45260. var roamZoom = coordSys.getZoom();
  45261. var nodeScale = (roamZoom - 1) * nodeScaleRatio + 1;
  45262. return nodeScale / groupZoom;
  45263. },
  45264. dispose: function () {
  45265. this._controller && this._controller.dispose();
  45266. this._controllerHost = {};
  45267. },
  45268. remove: function () {
  45269. this._mainGroup.removeAll();
  45270. this._data = null;
  45271. }
  45272. });
  45273. function symbolNeedsDraw$1(data, dataIndex) {
  45274. var layout = data.getItemLayout(dataIndex);
  45275. return layout
  45276. && !isNaN(layout.x) && !isNaN(layout.y)
  45277. && data.getItemVisual(dataIndex, 'symbol') !== 'none';
  45278. }
  45279. function getTreeNodeStyle(node, itemModel, seriesScope) {
  45280. seriesScope.itemModel = itemModel;
  45281. seriesScope.itemStyle = itemModel.getModel('itemStyle').getItemStyle();
  45282. seriesScope.hoverItemStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  45283. seriesScope.lineStyle = itemModel.getModel('lineStyle').getLineStyle();
  45284. seriesScope.labelModel = itemModel.getModel('label');
  45285. seriesScope.hoverLabelModel = itemModel.getModel('emphasis.label');
  45286. if (node.isExpand === false && node.children.length !== 0) {
  45287. seriesScope.symbolInnerColor = seriesScope.itemStyle.fill;
  45288. }
  45289. else {
  45290. seriesScope.symbolInnerColor = '#fff';
  45291. }
  45292. return seriesScope;
  45293. }
  45294. function updateNode(data, dataIndex, symbolEl, group, seriesModel, seriesScope) {
  45295. var isInit = !symbolEl;
  45296. var node = data.tree.getNodeByDataIndex(dataIndex);
  45297. var itemModel = node.getModel();
  45298. var seriesScope = getTreeNodeStyle(node, itemModel, seriesScope);
  45299. var virtualRoot = data.tree.root;
  45300. var source = node.parentNode === virtualRoot ? node : node.parentNode || node;
  45301. var sourceSymbolEl = data.getItemGraphicEl(source.dataIndex);
  45302. var sourceLayout = source.getLayout();
  45303. var sourceOldLayout = sourceSymbolEl
  45304. ? {
  45305. x: sourceSymbolEl.position[0],
  45306. y: sourceSymbolEl.position[1],
  45307. rawX: sourceSymbolEl.__radialOldRawX,
  45308. rawY: sourceSymbolEl.__radialOldRawY
  45309. }
  45310. : sourceLayout;
  45311. var targetLayout = node.getLayout();
  45312. if (isInit) {
  45313. symbolEl = new SymbolClz$1(data, dataIndex, seriesScope);
  45314. symbolEl.attr('position', [sourceOldLayout.x, sourceOldLayout.y]);
  45315. }
  45316. else {
  45317. symbolEl.updateData(data, dataIndex, seriesScope);
  45318. }
  45319. symbolEl.__radialOldRawX = symbolEl.__radialRawX;
  45320. symbolEl.__radialOldRawY = symbolEl.__radialRawY;
  45321. symbolEl.__radialRawX = targetLayout.rawX;
  45322. symbolEl.__radialRawY = targetLayout.rawY;
  45323. group.add(symbolEl);
  45324. data.setItemGraphicEl(dataIndex, symbolEl);
  45325. updateProps(symbolEl, {
  45326. position: [targetLayout.x, targetLayout.y]
  45327. }, seriesModel);
  45328. var symbolPath = symbolEl.getSymbolPath();
  45329. if (seriesScope.layout === 'radial') {
  45330. var realRoot = virtualRoot.children[0];
  45331. var rootLayout = realRoot.getLayout();
  45332. var length = realRoot.children.length;
  45333. var rad;
  45334. var isLeft;
  45335. if (targetLayout.x === rootLayout.x && node.isExpand === true) {
  45336. var center = {};
  45337. center.x = (realRoot.children[0].getLayout().x + realRoot.children[length - 1].getLayout().x) / 2;
  45338. center.y = (realRoot.children[0].getLayout().y + realRoot.children[length - 1].getLayout().y) / 2;
  45339. rad = Math.atan2(center.y - rootLayout.y, center.x - rootLayout.x);
  45340. if (rad < 0) {
  45341. rad = Math.PI * 2 + rad;
  45342. }
  45343. isLeft = center.x < rootLayout.x;
  45344. if (isLeft) {
  45345. rad = rad - Math.PI;
  45346. }
  45347. }
  45348. else {
  45349. rad = Math.atan2(targetLayout.y - rootLayout.y, targetLayout.x - rootLayout.x);
  45350. if (rad < 0) {
  45351. rad = Math.PI * 2 + rad;
  45352. }
  45353. if (node.children.length === 0 || (node.children.length !== 0 && node.isExpand === false)) {
  45354. isLeft = targetLayout.x < rootLayout.x;
  45355. if (isLeft) {
  45356. rad = rad - Math.PI;
  45357. }
  45358. }
  45359. else {
  45360. isLeft = targetLayout.x > rootLayout.x;
  45361. if (!isLeft) {
  45362. rad = rad - Math.PI;
  45363. }
  45364. }
  45365. }
  45366. var textPosition = isLeft ? 'left' : 'right';
  45367. var rotate = seriesScope.labelModel.get('rotate');
  45368. var labelRotateRadian = rotate * (Math.PI / 180);
  45369. symbolPath.setStyle({
  45370. textPosition: seriesScope.labelModel.get('position') || textPosition,
  45371. textRotation: rotate == null ? -rad : labelRotateRadian,
  45372. textOrigin: 'center',
  45373. verticalAlign: 'middle'
  45374. });
  45375. }
  45376. drawEdge(
  45377. seriesModel, node, virtualRoot, symbolEl, sourceOldLayout,
  45378. sourceLayout, targetLayout, group, seriesScope
  45379. );
  45380. }
  45381. function drawEdge(
  45382. seriesModel, node, virtualRoot, symbolEl, sourceOldLayout,
  45383. sourceLayout, targetLayout, group, seriesScope
  45384. ) {
  45385. var edgeShape = seriesScope.edgeShape;
  45386. var edge = symbolEl.__edge;
  45387. if (edgeShape === 'curve') {
  45388. if (node.parentNode && node.parentNode !== virtualRoot) {
  45389. if (!edge) {
  45390. edge = symbolEl.__edge = new BezierCurve({
  45391. shape: getEdgeShape(seriesScope, sourceOldLayout, sourceOldLayout),
  45392. style: defaults({opacity: 0, strokeNoScale: true}, seriesScope.lineStyle)
  45393. });
  45394. }
  45395. updateProps(edge, {
  45396. shape: getEdgeShape(seriesScope, sourceLayout, targetLayout),
  45397. style: {opacity: 1}
  45398. }, seriesModel);
  45399. }
  45400. }
  45401. else if (edgeShape === 'polyline') {
  45402. if (seriesScope.layout === 'orthogonal') {
  45403. if (node !== virtualRoot && node.children && (node.children.length !== 0) && (node.isExpand === true)) {
  45404. var children = node.children;
  45405. var childPoints = [];
  45406. for (var i = 0; i < children.length; i++) {
  45407. var childLayout = children[i].getLayout();
  45408. childPoints.push([childLayout.x, childLayout.y]);
  45409. }
  45410. if (!edge) {
  45411. edge = symbolEl.__edge = new TreeShape({
  45412. shape: {
  45413. parentPoint: [targetLayout.x, targetLayout.y],
  45414. childPoints: [[targetLayout.x, targetLayout.y]],
  45415. orient: seriesScope.orient,
  45416. forkPosition: seriesScope.edgeForkPosition
  45417. },
  45418. style: defaults({opacity: 0, strokeNoScale: true}, seriesScope.lineStyle)
  45419. });
  45420. }
  45421. updateProps(edge, {
  45422. shape: {
  45423. parentPoint: [targetLayout.x, targetLayout.y],
  45424. childPoints: childPoints
  45425. },
  45426. style: {opacity: 1}
  45427. }, seriesModel);
  45428. }
  45429. }
  45430. else {
  45431. if (__DEV__) {
  45432. throw new Error('The polyline edgeShape can only be used in orthogonal layout');
  45433. }
  45434. }
  45435. }
  45436. group.add(edge);
  45437. }
  45438. function removeNode(data, dataIndex, symbolEl, group, seriesModel, seriesScope) {
  45439. var node = data.tree.getNodeByDataIndex(dataIndex);
  45440. var virtualRoot = data.tree.root;
  45441. var itemModel = node.getModel();
  45442. var seriesScope = getTreeNodeStyle(node, itemModel, seriesScope);
  45443. var source = node.parentNode === virtualRoot ? node : node.parentNode || node;
  45444. var edgeShape = seriesScope.edgeShape;
  45445. var sourceLayout;
  45446. while (sourceLayout = source.getLayout(), sourceLayout == null) {
  45447. source = source.parentNode === virtualRoot ? source : source.parentNode || source;
  45448. }
  45449. updateProps(symbolEl, {
  45450. position: [sourceLayout.x + 1, sourceLayout.y + 1]
  45451. }, seriesModel, function () {
  45452. group.remove(symbolEl);
  45453. data.setItemGraphicEl(dataIndex, null);
  45454. });
  45455. symbolEl.fadeOut(null, {keepLabel: true});
  45456. var sourceSymbolEl = data.getItemGraphicEl(source.dataIndex);
  45457. var sourceEdge = sourceSymbolEl.__edge;
  45458. // 1. when expand the sub tree, delete the children node should delete the edge of
  45459. // the source at the same time. because the polyline edge shape is only owned by the source.
  45460. // 2.when the node is the only children of the source, delete the node should delete the edge of
  45461. // the source at the same time. the same reason as above.
  45462. var edge = symbolEl.__edge
  45463. || ((source.isExpand === false || source.children.length === 1) ? sourceEdge : undefined);
  45464. var edgeShape = seriesScope.edgeShape;
  45465. if (edge) {
  45466. if (edgeShape === 'curve') {
  45467. updateProps(edge, {
  45468. shape: getEdgeShape(seriesScope, sourceLayout, sourceLayout),
  45469. style: {
  45470. opacity: 0
  45471. }
  45472. }, seriesModel, function () {
  45473. group.remove(edge);
  45474. });
  45475. }
  45476. else if (edgeShape === 'polyline' && seriesScope.layout === 'orthogonal') {
  45477. updateProps(edge, {
  45478. shape: {
  45479. parentPoint: [sourceLayout.x, sourceLayout.y],
  45480. childPoints: [[sourceLayout.x, sourceLayout.y]]
  45481. },
  45482. style: {
  45483. opacity: 0
  45484. }
  45485. }, seriesModel, function () {
  45486. group.remove(edge);
  45487. });
  45488. }
  45489. }
  45490. }
  45491. function getEdgeShape(seriesScope, sourceLayout, targetLayout) {
  45492. var cpx1;
  45493. var cpy1;
  45494. var cpx2;
  45495. var cpy2;
  45496. var orient = seriesScope.orient;
  45497. var x1;
  45498. var x2;
  45499. var y1;
  45500. var y2;
  45501. if (seriesScope.layout === 'radial') {
  45502. x1 = sourceLayout.rawX;
  45503. y1 = sourceLayout.rawY;
  45504. x2 = targetLayout.rawX;
  45505. y2 = targetLayout.rawY;
  45506. var radialCoor1 = radialCoordinate(x1, y1);
  45507. var radialCoor2 = radialCoordinate(x1, y1 + (y2 - y1) * seriesScope.curvature);
  45508. var radialCoor3 = radialCoordinate(x2, y2 + (y1 - y2) * seriesScope.curvature);
  45509. var radialCoor4 = radialCoordinate(x2, y2);
  45510. return {
  45511. x1: radialCoor1.x,
  45512. y1: radialCoor1.y,
  45513. x2: radialCoor4.x,
  45514. y2: radialCoor4.y,
  45515. cpx1: radialCoor2.x,
  45516. cpy1: radialCoor2.y,
  45517. cpx2: radialCoor3.x,
  45518. cpy2: radialCoor3.y
  45519. };
  45520. }
  45521. else {
  45522. x1 = sourceLayout.x;
  45523. y1 = sourceLayout.y;
  45524. x2 = targetLayout.x;
  45525. y2 = targetLayout.y;
  45526. if (orient === 'LR' || orient === 'RL') {
  45527. cpx1 = x1 + (x2 - x1) * seriesScope.curvature;
  45528. cpy1 = y1;
  45529. cpx2 = x2 + (x1 - x2) * seriesScope.curvature;
  45530. cpy2 = y2;
  45531. }
  45532. if (orient === 'TB' || orient === 'BT') {
  45533. cpx1 = x1;
  45534. cpy1 = y1 + (y2 - y1) * seriesScope.curvature;
  45535. cpx2 = x2;
  45536. cpy2 = y2 + (y1 - y2) * seriesScope.curvature;
  45537. }
  45538. }
  45539. return {
  45540. x1: x1,
  45541. y1: y1,
  45542. x2: x2,
  45543. y2: y2,
  45544. cpx1: cpx1,
  45545. cpy1: cpy1,
  45546. cpx2: cpx2,
  45547. cpy2: cpy2
  45548. };
  45549. }
  45550. /*
  45551. * Licensed to the Apache Software Foundation (ASF) under one
  45552. * or more contributor license agreements. See the NOTICE file
  45553. * distributed with this work for additional information
  45554. * regarding copyright ownership. The ASF licenses this file
  45555. * to you under the Apache License, Version 2.0 (the
  45556. * "License"); you may not use this file except in compliance
  45557. * with the License. You may obtain a copy of the License at
  45558. *
  45559. * http://www.apache.org/licenses/LICENSE-2.0
  45560. *
  45561. * Unless required by applicable law or agreed to in writing,
  45562. * software distributed under the License is distributed on an
  45563. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45564. * KIND, either express or implied. See the License for the
  45565. * specific language governing permissions and limitations
  45566. * under the License.
  45567. */
  45568. registerAction({
  45569. type: 'treeExpandAndCollapse',
  45570. event: 'treeExpandAndCollapse',
  45571. update: 'update'
  45572. }, function (payload, ecModel) {
  45573. ecModel.eachComponent({mainType: 'series', subType: 'tree', query: payload}, function (seriesModel) {
  45574. var dataIndex = payload.dataIndex;
  45575. var tree = seriesModel.getData().tree;
  45576. var node = tree.getNodeByDataIndex(dataIndex);
  45577. node.isExpand = !node.isExpand;
  45578. });
  45579. });
  45580. registerAction({
  45581. type: 'treeRoam',
  45582. event: 'treeRoam',
  45583. // Here we set 'none' instead of 'update', because roam action
  45584. // just need to update the transform matrix without having to recalculate
  45585. // the layout. So don't need to go through the whole update process, such
  45586. // as 'dataPrcocess', 'coordSystemUpdate', 'layout' and so on.
  45587. update: 'none'
  45588. }, function (payload, ecModel) {
  45589. ecModel.eachComponent({mainType: 'series', subType: 'tree', query: payload}, function (seriesModel) {
  45590. var coordSys = seriesModel.coordinateSystem;
  45591. var res = updateCenterAndZoom(coordSys, payload);
  45592. seriesModel.setCenter
  45593. && seriesModel.setCenter(res.center);
  45594. seriesModel.setZoom
  45595. && seriesModel.setZoom(res.zoom);
  45596. });
  45597. });
  45598. /*
  45599. * Licensed to the Apache Software Foundation (ASF) under one
  45600. * or more contributor license agreements. See the NOTICE file
  45601. * distributed with this work for additional information
  45602. * regarding copyright ownership. The ASF licenses this file
  45603. * to you under the Apache License, Version 2.0 (the
  45604. * "License"); you may not use this file except in compliance
  45605. * with the License. You may obtain a copy of the License at
  45606. *
  45607. * http://www.apache.org/licenses/LICENSE-2.0
  45608. *
  45609. * Unless required by applicable law or agreed to in writing,
  45610. * software distributed under the License is distributed on an
  45611. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45612. * KIND, either express or implied. See the License for the
  45613. * specific language governing permissions and limitations
  45614. * under the License.
  45615. */
  45616. /**
  45617. * Traverse the tree from bottom to top and do something
  45618. * @param {module:echarts/data/Tree~TreeNode} root The real root of the tree
  45619. * @param {Function} callback
  45620. */
  45621. function eachAfter(root, callback, separation) {
  45622. var nodes = [root];
  45623. var next = [];
  45624. var node;
  45625. while (node = nodes.pop()) { // jshint ignore:line
  45626. next.push(node);
  45627. if (node.isExpand) {
  45628. var children = node.children;
  45629. if (children.length) {
  45630. for (var i = 0; i < children.length; i++) {
  45631. nodes.push(children[i]);
  45632. }
  45633. }
  45634. }
  45635. }
  45636. while (node = next.pop()) { // jshint ignore:line
  45637. callback(node, separation);
  45638. }
  45639. }
  45640. /**
  45641. * Traverse the tree from top to bottom and do something
  45642. * @param {module:echarts/data/Tree~TreeNode} root The real root of the tree
  45643. * @param {Function} callback
  45644. */
  45645. function eachBefore(root, callback) {
  45646. var nodes = [root];
  45647. var node;
  45648. while (node = nodes.pop()) { // jshint ignore:line
  45649. callback(node);
  45650. if (node.isExpand) {
  45651. var children = node.children;
  45652. if (children.length) {
  45653. for (var i = children.length - 1; i >= 0; i--) {
  45654. nodes.push(children[i]);
  45655. }
  45656. }
  45657. }
  45658. }
  45659. }
  45660. /*
  45661. * Licensed to the Apache Software Foundation (ASF) under one
  45662. * or more contributor license agreements. See the NOTICE file
  45663. * distributed with this work for additional information
  45664. * regarding copyright ownership. The ASF licenses this file
  45665. * to you under the Apache License, Version 2.0 (the
  45666. * "License"); you may not use this file except in compliance
  45667. * with the License. You may obtain a copy of the License at
  45668. *
  45669. * http://www.apache.org/licenses/LICENSE-2.0
  45670. *
  45671. * Unless required by applicable law or agreed to in writing,
  45672. * software distributed under the License is distributed on an
  45673. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45674. * KIND, either express or implied. See the License for the
  45675. * specific language governing permissions and limitations
  45676. * under the License.
  45677. */
  45678. var treeLayout = function (ecModel, api) {
  45679. ecModel.eachSeriesByType('tree', function (seriesModel) {
  45680. commonLayout(seriesModel, api);
  45681. });
  45682. };
  45683. function commonLayout(seriesModel, api) {
  45684. var layoutInfo = getViewRect$1(seriesModel, api);
  45685. seriesModel.layoutInfo = layoutInfo;
  45686. var layout = seriesModel.get('layout');
  45687. var width = 0;
  45688. var height = 0;
  45689. var separation$$1 = null;
  45690. if (layout === 'radial') {
  45691. width = 2 * Math.PI;
  45692. height = Math.min(layoutInfo.height, layoutInfo.width) / 2;
  45693. separation$$1 = separation(function (node1, node2) {
  45694. return (node1.parentNode === node2.parentNode ? 1 : 2) / node1.depth;
  45695. });
  45696. }
  45697. else {
  45698. width = layoutInfo.width;
  45699. height = layoutInfo.height;
  45700. separation$$1 = separation();
  45701. }
  45702. var virtualRoot = seriesModel.getData().tree.root;
  45703. var realRoot = virtualRoot.children[0];
  45704. if (realRoot) {
  45705. init$2(virtualRoot);
  45706. eachAfter(realRoot, firstWalk, separation$$1);
  45707. virtualRoot.hierNode.modifier = -realRoot.hierNode.prelim;
  45708. eachBefore(realRoot, secondWalk);
  45709. var left = realRoot;
  45710. var right = realRoot;
  45711. var bottom = realRoot;
  45712. eachBefore(realRoot, function (node) {
  45713. var x = node.getLayout().x;
  45714. if (x < left.getLayout().x) {
  45715. left = node;
  45716. }
  45717. if (x > right.getLayout().x) {
  45718. right = node;
  45719. }
  45720. if (node.depth > bottom.depth) {
  45721. bottom = node;
  45722. }
  45723. });
  45724. var delta = left === right ? 1 : separation$$1(left, right) / 2;
  45725. var tx = delta - left.getLayout().x;
  45726. var kx = 0;
  45727. var ky = 0;
  45728. var coorX = 0;
  45729. var coorY = 0;
  45730. if (layout === 'radial') {
  45731. kx = width / (right.getLayout().x + delta + tx);
  45732. // here we use (node.depth - 1), bucause the real root's depth is 1
  45733. ky = height / ((bottom.depth - 1) || 1);
  45734. eachBefore(realRoot, function (node) {
  45735. coorX = (node.getLayout().x + tx) * kx;
  45736. coorY = (node.depth - 1) * ky;
  45737. var finalCoor = radialCoordinate(coorX, coorY);
  45738. node.setLayout({x: finalCoor.x, y: finalCoor.y, rawX: coorX, rawY: coorY}, true);
  45739. });
  45740. }
  45741. else {
  45742. var orient = seriesModel.getOrient();
  45743. if (orient === 'RL' || orient === 'LR') {
  45744. ky = height / (right.getLayout().x + delta + tx);
  45745. kx = width / ((bottom.depth - 1) || 1);
  45746. eachBefore(realRoot, function (node) {
  45747. coorY = (node.getLayout().x + tx) * ky;
  45748. coorX = orient === 'LR'
  45749. ? (node.depth - 1) * kx
  45750. : width - (node.depth - 1) * kx;
  45751. node.setLayout({x: coorX, y: coorY}, true);
  45752. });
  45753. }
  45754. else if (orient === 'TB' || orient === 'BT') {
  45755. kx = width / (right.getLayout().x + delta + tx);
  45756. ky = height / ((bottom.depth - 1) || 1);
  45757. eachBefore(realRoot, function (node) {
  45758. coorX = (node.getLayout().x + tx) * kx;
  45759. coorY = orient === 'TB'
  45760. ? (node.depth - 1) * ky
  45761. : height - (node.depth - 1) * ky;
  45762. node.setLayout({x: coorX, y: coorY}, true);
  45763. });
  45764. }
  45765. }
  45766. }
  45767. }
  45768. /*
  45769. * Licensed to the Apache Software Foundation (ASF) under one
  45770. * or more contributor license agreements. See the NOTICE file
  45771. * distributed with this work for additional information
  45772. * regarding copyright ownership. The ASF licenses this file
  45773. * to you under the Apache License, Version 2.0 (the
  45774. * "License"); you may not use this file except in compliance
  45775. * with the License. You may obtain a copy of the License at
  45776. *
  45777. * http://www.apache.org/licenses/LICENSE-2.0
  45778. *
  45779. * Unless required by applicable law or agreed to in writing,
  45780. * software distributed under the License is distributed on an
  45781. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45782. * KIND, either express or implied. See the License for the
  45783. * specific language governing permissions and limitations
  45784. * under the License.
  45785. */
  45786. registerVisual(visualSymbol('tree', 'circle'));
  45787. registerLayout(treeLayout);
  45788. /*
  45789. * Licensed to the Apache Software Foundation (ASF) under one
  45790. * or more contributor license agreements. See the NOTICE file
  45791. * distributed with this work for additional information
  45792. * regarding copyright ownership. The ASF licenses this file
  45793. * to you under the Apache License, Version 2.0 (the
  45794. * "License"); you may not use this file except in compliance
  45795. * with the License. You may obtain a copy of the License at
  45796. *
  45797. * http://www.apache.org/licenses/LICENSE-2.0
  45798. *
  45799. * Unless required by applicable law or agreed to in writing,
  45800. * software distributed under the License is distributed on an
  45801. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45802. * KIND, either express or implied. See the License for the
  45803. * specific language governing permissions and limitations
  45804. * under the License.
  45805. */
  45806. function retrieveTargetInfo(payload, validPayloadTypes, seriesModel) {
  45807. if (payload && indexOf(validPayloadTypes, payload.type) >= 0) {
  45808. var root = seriesModel.getData().tree.root;
  45809. var targetNode = payload.targetNode;
  45810. if (typeof targetNode === 'string') {
  45811. targetNode = root.getNodeById(targetNode);
  45812. }
  45813. if (targetNode && root.contains(targetNode)) {
  45814. return {node: targetNode};
  45815. }
  45816. var targetNodeId = payload.targetNodeId;
  45817. if (targetNodeId != null && (targetNode = root.getNodeById(targetNodeId))) {
  45818. return {node: targetNode};
  45819. }
  45820. }
  45821. }
  45822. // Not includes the given node at the last item.
  45823. function getPathToRoot(node) {
  45824. var path = [];
  45825. while (node) {
  45826. node = node.parentNode;
  45827. node && path.push(node);
  45828. }
  45829. return path.reverse();
  45830. }
  45831. function aboveViewRoot(viewRoot, node) {
  45832. var viewPath = getPathToRoot(viewRoot);
  45833. return indexOf(viewPath, node) >= 0;
  45834. }
  45835. // From root to the input node (the input node will be included).
  45836. function wrapTreePathInfo(node, seriesModel) {
  45837. var treePathInfo = [];
  45838. while (node) {
  45839. var nodeDataIndex = node.dataIndex;
  45840. treePathInfo.push({
  45841. name: node.name,
  45842. dataIndex: nodeDataIndex,
  45843. value: seriesModel.getRawValue(nodeDataIndex)
  45844. });
  45845. node = node.parentNode;
  45846. }
  45847. treePathInfo.reverse();
  45848. return treePathInfo;
  45849. }
  45850. /*
  45851. * Licensed to the Apache Software Foundation (ASF) under one
  45852. * or more contributor license agreements. See the NOTICE file
  45853. * distributed with this work for additional information
  45854. * regarding copyright ownership. The ASF licenses this file
  45855. * to you under the Apache License, Version 2.0 (the
  45856. * "License"); you may not use this file except in compliance
  45857. * with the License. You may obtain a copy of the License at
  45858. *
  45859. * http://www.apache.org/licenses/LICENSE-2.0
  45860. *
  45861. * Unless required by applicable law or agreed to in writing,
  45862. * software distributed under the License is distributed on an
  45863. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45864. * KIND, either express or implied. See the License for the
  45865. * specific language governing permissions and limitations
  45866. * under the License.
  45867. */
  45868. SeriesModel.extend({
  45869. type: 'series.treemap',
  45870. layoutMode: 'box',
  45871. dependencies: ['grid', 'polar'],
  45872. preventUsingHoverLayer: true,
  45873. /**
  45874. * @type {module:echarts/data/Tree~Node}
  45875. */
  45876. _viewRoot: null,
  45877. defaultOption: {
  45878. // Disable progressive rendering
  45879. progressive: 0,
  45880. // center: ['50%', '50%'], // not supported in ec3.
  45881. // size: ['80%', '80%'], // deprecated, compatible with ec2.
  45882. left: 'center',
  45883. top: 'middle',
  45884. right: null,
  45885. bottom: null,
  45886. width: '80%',
  45887. height: '80%',
  45888. sort: true, // Can be null or false or true
  45889. // (order by desc default, asc not supported yet (strange effect))
  45890. clipWindow: 'origin', // Size of clipped window when zooming. 'origin' or 'fullscreen'
  45891. squareRatio: 0.5 * (1 + Math.sqrt(5)), // golden ratio
  45892. leafDepth: null, // Nodes on depth from root are regarded as leaves.
  45893. // Count from zero (zero represents only view root).
  45894. drillDownIcon: '▶', // Use html character temporarily because it is complicated
  45895. // to align specialized icon. ▷▶❒❐▼✚
  45896. zoomToNodeRatio: 0.32 * 0.32, // Be effective when using zoomToNode. Specify the proportion of the
  45897. // target node area in the view area.
  45898. roam: true, // true, false, 'scale' or 'zoom', 'move'.
  45899. nodeClick: 'zoomToNode', // Leaf node click behaviour: 'zoomToNode', 'link', false.
  45900. // If leafDepth is set and clicking a node which has children but
  45901. // be on left depth, the behaviour would be changing root. Otherwise
  45902. // use behavious defined above.
  45903. animation: true,
  45904. animationDurationUpdate: 900,
  45905. animationEasing: 'quinticInOut',
  45906. breadcrumb: {
  45907. show: true,
  45908. height: 22,
  45909. left: 'center',
  45910. top: 'bottom',
  45911. // right
  45912. // bottom
  45913. emptyItemWidth: 25, // Width of empty node.
  45914. itemStyle: {
  45915. color: 'rgba(0,0,0,0.7)', //'#5793f3',
  45916. borderColor: 'rgba(255,255,255,0.7)',
  45917. borderWidth: 1,
  45918. shadowColor: 'rgba(150,150,150,1)',
  45919. shadowBlur: 3,
  45920. shadowOffsetX: 0,
  45921. shadowOffsetY: 0,
  45922. textStyle: {
  45923. color: '#fff'
  45924. }
  45925. },
  45926. emphasis: {
  45927. textStyle: {}
  45928. }
  45929. },
  45930. label: {
  45931. show: true,
  45932. // Do not use textDistance, for ellipsis rect just the same as treemap node rect.
  45933. distance: 0,
  45934. padding: 5,
  45935. position: 'inside', // Can be [5, '5%'] or position stirng like 'insideTopLeft', ...
  45936. // formatter: null,
  45937. color: '#fff',
  45938. ellipsis: true
  45939. // align
  45940. // verticalAlign
  45941. },
  45942. upperLabel: { // Label when node is parent.
  45943. show: false,
  45944. position: [0, '50%'],
  45945. height: 20,
  45946. // formatter: null,
  45947. color: '#fff',
  45948. ellipsis: true,
  45949. // align: null,
  45950. verticalAlign: 'middle'
  45951. },
  45952. itemStyle: {
  45953. color: null, // Can be 'none' if not necessary.
  45954. colorAlpha: null, // Can be 'none' if not necessary.
  45955. colorSaturation: null, // Can be 'none' if not necessary.
  45956. borderWidth: 0,
  45957. gapWidth: 0,
  45958. borderColor: '#fff',
  45959. borderColorSaturation: null // If specified, borderColor will be ineffective, and the
  45960. // border color is evaluated by color of current node and
  45961. // borderColorSaturation.
  45962. },
  45963. emphasis: {
  45964. upperLabel: {
  45965. show: true,
  45966. position: [0, '50%'],
  45967. color: '#fff',
  45968. ellipsis: true,
  45969. verticalAlign: 'middle'
  45970. }
  45971. },
  45972. visualDimension: 0, // Can be 0, 1, 2, 3.
  45973. visualMin: null,
  45974. visualMax: null,
  45975. color: [], // + treemapSeries.color should not be modified. Please only modified
  45976. // level[n].color (if necessary).
  45977. // + Specify color list of each level. level[0].color would be global
  45978. // color list if not specified. (see method `setDefault`).
  45979. // + But set as a empty array to forbid fetch color from global palette
  45980. // when using nodeModel.get('color'), otherwise nodes on deep level
  45981. // will always has color palette set and are not able to inherit color
  45982. // from parent node.
  45983. // + TreemapSeries.color can not be set as 'none', otherwise effect
  45984. // legend color fetching (see seriesColor.js).
  45985. colorAlpha: null, // Array. Specify color alpha range of each level, like [0.2, 0.8]
  45986. colorSaturation: null, // Array. Specify color saturation of each level, like [0.2, 0.5]
  45987. colorMappingBy: 'index', // 'value' or 'index' or 'id'.
  45988. visibleMin: 10, // If area less than this threshold (unit: pixel^2), node will not
  45989. // be rendered. Only works when sort is 'asc' or 'desc'.
  45990. childrenVisibleMin: null, // If area of a node less than this threshold (unit: pixel^2),
  45991. // grandchildren will not show.
  45992. // Why grandchildren? If not grandchildren but children,
  45993. // some siblings show children and some not,
  45994. // the appearance may be mess and not consistent,
  45995. levels: [] // Each item: {
  45996. // visibleMin, itemStyle, visualDimension, label
  45997. // }
  45998. // data: {
  45999. // value: [],
  46000. // children: [],
  46001. // link: 'http://xxx.xxx.xxx',
  46002. // target: 'blank' or 'self'
  46003. // }
  46004. },
  46005. /**
  46006. * @override
  46007. */
  46008. getInitialData: function (option, ecModel) {
  46009. // Create a virtual root.
  46010. var root = {name: option.name, children: option.data};
  46011. completeTreeValue(root);
  46012. var levels = option.levels || [];
  46013. levels = option.levels = setDefault(levels, ecModel);
  46014. var levelModels = map(levels || [], function (levelDefine) {
  46015. return new Model(levelDefine, this, ecModel);
  46016. }, this);
  46017. // Make sure always a new tree is created when setOption,
  46018. // in TreemapView, we check whether oldTree === newTree
  46019. // to choose mappings approach among old shapes and new shapes.
  46020. var tree = Tree.createTree(root, this, null, beforeLink);
  46021. function beforeLink(nodeData) {
  46022. nodeData.wrapMethod('getItemModel', function (model, idx) {
  46023. var node = tree.getNodeByDataIndex(idx);
  46024. var levelModel = levelModels[node.depth];
  46025. levelModel && (model.parentModel = levelModel);
  46026. return model;
  46027. });
  46028. }
  46029. return tree.data;
  46030. },
  46031. optionUpdated: function () {
  46032. this.resetViewRoot();
  46033. },
  46034. /**
  46035. * @override
  46036. * @param {number} dataIndex
  46037. * @param {boolean} [mutipleSeries=false]
  46038. */
  46039. formatTooltip: function (dataIndex) {
  46040. var data = this.getData();
  46041. var value = this.getRawValue(dataIndex);
  46042. var formattedValue = isArray(value)
  46043. ? addCommas(value[0]) : addCommas(value);
  46044. var name = data.getName(dataIndex);
  46045. return encodeHTML(name + ': ' + formattedValue);
  46046. },
  46047. /**
  46048. * Add tree path to tooltip param
  46049. *
  46050. * @override
  46051. * @param {number} dataIndex
  46052. * @return {Object}
  46053. */
  46054. getDataParams: function (dataIndex) {
  46055. var params = SeriesModel.prototype.getDataParams.apply(this, arguments);
  46056. var node = this.getData().tree.getNodeByDataIndex(dataIndex);
  46057. params.treePathInfo = wrapTreePathInfo(node, this);
  46058. return params;
  46059. },
  46060. /**
  46061. * @public
  46062. * @param {Object} layoutInfo {
  46063. * x: containerGroup x
  46064. * y: containerGroup y
  46065. * width: containerGroup width
  46066. * height: containerGroup height
  46067. * }
  46068. */
  46069. setLayoutInfo: function (layoutInfo) {
  46070. /**
  46071. * @readOnly
  46072. * @type {Object}
  46073. */
  46074. this.layoutInfo = this.layoutInfo || {};
  46075. extend(this.layoutInfo, layoutInfo);
  46076. },
  46077. /**
  46078. * @param {string} id
  46079. * @return {number} index
  46080. */
  46081. mapIdToIndex: function (id) {
  46082. // A feature is implemented:
  46083. // index is monotone increasing with the sequence of
  46084. // input id at the first time.
  46085. // This feature can make sure that each data item and its
  46086. // mapped color have the same index between data list and
  46087. // color list at the beginning, which is useful for user
  46088. // to adjust data-color mapping.
  46089. /**
  46090. * @private
  46091. * @type {Object}
  46092. */
  46093. var idIndexMap = this._idIndexMap;
  46094. if (!idIndexMap) {
  46095. idIndexMap = this._idIndexMap = createHashMap();
  46096. /**
  46097. * @private
  46098. * @type {number}
  46099. */
  46100. this._idIndexMapCount = 0;
  46101. }
  46102. var index = idIndexMap.get(id);
  46103. if (index == null) {
  46104. idIndexMap.set(id, index = this._idIndexMapCount++);
  46105. }
  46106. return index;
  46107. },
  46108. getViewRoot: function () {
  46109. return this._viewRoot;
  46110. },
  46111. /**
  46112. * @param {module:echarts/data/Tree~Node} [viewRoot]
  46113. */
  46114. resetViewRoot: function (viewRoot) {
  46115. viewRoot
  46116. ? (this._viewRoot = viewRoot)
  46117. : (viewRoot = this._viewRoot);
  46118. var root = this.getRawData().tree.root;
  46119. if (!viewRoot
  46120. || (viewRoot !== root && !root.contains(viewRoot))
  46121. ) {
  46122. this._viewRoot = root;
  46123. }
  46124. }
  46125. });
  46126. /**
  46127. * @param {Object} dataNode
  46128. */
  46129. function completeTreeValue(dataNode) {
  46130. // Postorder travel tree.
  46131. // If value of none-leaf node is not set,
  46132. // calculate it by suming up the value of all children.
  46133. var sum = 0;
  46134. each$1(dataNode.children, function (child) {
  46135. completeTreeValue(child);
  46136. var childValue = child.value;
  46137. isArray(childValue) && (childValue = childValue[0]);
  46138. sum += childValue;
  46139. });
  46140. var thisValue = dataNode.value;
  46141. if (isArray(thisValue)) {
  46142. thisValue = thisValue[0];
  46143. }
  46144. if (thisValue == null || isNaN(thisValue)) {
  46145. thisValue = sum;
  46146. }
  46147. // Value should not less than 0.
  46148. if (thisValue < 0) {
  46149. thisValue = 0;
  46150. }
  46151. isArray(dataNode.value)
  46152. ? (dataNode.value[0] = thisValue)
  46153. : (dataNode.value = thisValue);
  46154. }
  46155. /**
  46156. * set default to level configuration
  46157. */
  46158. function setDefault(levels, ecModel) {
  46159. var globalColorList = ecModel.get('color');
  46160. if (!globalColorList) {
  46161. return;
  46162. }
  46163. levels = levels || [];
  46164. var hasColorDefine;
  46165. each$1(levels, function (levelDefine) {
  46166. var model = new Model(levelDefine);
  46167. var modelColor = model.get('color');
  46168. if (model.get('itemStyle.color')
  46169. || (modelColor && modelColor !== 'none')
  46170. ) {
  46171. hasColorDefine = true;
  46172. }
  46173. });
  46174. if (!hasColorDefine) {
  46175. var level0 = levels[0] || (levels[0] = {});
  46176. level0.color = globalColorList.slice();
  46177. }
  46178. return levels;
  46179. }
  46180. /*
  46181. * Licensed to the Apache Software Foundation (ASF) under one
  46182. * or more contributor license agreements. See the NOTICE file
  46183. * distributed with this work for additional information
  46184. * regarding copyright ownership. The ASF licenses this file
  46185. * to you under the Apache License, Version 2.0 (the
  46186. * "License"); you may not use this file except in compliance
  46187. * with the License. You may obtain a copy of the License at
  46188. *
  46189. * http://www.apache.org/licenses/LICENSE-2.0
  46190. *
  46191. * Unless required by applicable law or agreed to in writing,
  46192. * software distributed under the License is distributed on an
  46193. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46194. * KIND, either express or implied. See the License for the
  46195. * specific language governing permissions and limitations
  46196. * under the License.
  46197. */
  46198. var TEXT_PADDING = 8;
  46199. var ITEM_GAP = 8;
  46200. var ARRAY_LENGTH = 5;
  46201. function Breadcrumb(containerGroup) {
  46202. /**
  46203. * @private
  46204. * @type {module:zrender/container/Group}
  46205. */
  46206. this.group = new Group();
  46207. containerGroup.add(this.group);
  46208. }
  46209. Breadcrumb.prototype = {
  46210. constructor: Breadcrumb,
  46211. render: function (seriesModel, api, targetNode, onSelect) {
  46212. var model = seriesModel.getModel('breadcrumb');
  46213. var thisGroup = this.group;
  46214. thisGroup.removeAll();
  46215. if (!model.get('show') || !targetNode) {
  46216. return;
  46217. }
  46218. var normalStyleModel = model.getModel('itemStyle');
  46219. // var emphasisStyleModel = model.getModel('emphasis.itemStyle');
  46220. var textStyleModel = normalStyleModel.getModel('textStyle');
  46221. var layoutParam = {
  46222. pos: {
  46223. left: model.get('left'),
  46224. right: model.get('right'),
  46225. top: model.get('top'),
  46226. bottom: model.get('bottom')
  46227. },
  46228. box: {
  46229. width: api.getWidth(),
  46230. height: api.getHeight()
  46231. },
  46232. emptyItemWidth: model.get('emptyItemWidth'),
  46233. totalWidth: 0,
  46234. renderList: []
  46235. };
  46236. this._prepare(targetNode, layoutParam, textStyleModel);
  46237. this._renderContent(seriesModel, layoutParam, normalStyleModel, textStyleModel, onSelect);
  46238. positionElement(thisGroup, layoutParam.pos, layoutParam.box);
  46239. },
  46240. /**
  46241. * Prepare render list and total width
  46242. * @private
  46243. */
  46244. _prepare: function (targetNode, layoutParam, textStyleModel) {
  46245. for (var node = targetNode; node; node = node.parentNode) {
  46246. var text = node.getModel().get('name');
  46247. var textRect = textStyleModel.getTextRect(text);
  46248. var itemWidth = Math.max(
  46249. textRect.width + TEXT_PADDING * 2,
  46250. layoutParam.emptyItemWidth
  46251. );
  46252. layoutParam.totalWidth += itemWidth + ITEM_GAP;
  46253. layoutParam.renderList.push({node: node, text: text, width: itemWidth});
  46254. }
  46255. },
  46256. /**
  46257. * @private
  46258. */
  46259. _renderContent: function (
  46260. seriesModel, layoutParam, normalStyleModel, textStyleModel, onSelect
  46261. ) {
  46262. // Start rendering.
  46263. var lastX = 0;
  46264. var emptyItemWidth = layoutParam.emptyItemWidth;
  46265. var height = seriesModel.get('breadcrumb.height');
  46266. var availableSize = getAvailableSize(layoutParam.pos, layoutParam.box);
  46267. var totalWidth = layoutParam.totalWidth;
  46268. var renderList = layoutParam.renderList;
  46269. for (var i = renderList.length - 1; i >= 0; i--) {
  46270. var item = renderList[i];
  46271. var itemNode = item.node;
  46272. var itemWidth = item.width;
  46273. var text = item.text;
  46274. // Hdie text and shorten width if necessary.
  46275. if (totalWidth > availableSize.width) {
  46276. totalWidth -= itemWidth - emptyItemWidth;
  46277. itemWidth = emptyItemWidth;
  46278. text = null;
  46279. }
  46280. var el = new Polygon({
  46281. shape: {
  46282. points: makeItemPoints(
  46283. lastX, 0, itemWidth, height,
  46284. i === renderList.length - 1, i === 0
  46285. )
  46286. },
  46287. style: defaults(
  46288. normalStyleModel.getItemStyle(),
  46289. {
  46290. lineJoin: 'bevel',
  46291. text: text,
  46292. textFill: textStyleModel.getTextColor(),
  46293. textFont: textStyleModel.getFont()
  46294. }
  46295. ),
  46296. z: 10,
  46297. onclick: curry(onSelect, itemNode)
  46298. });
  46299. this.group.add(el);
  46300. packEventData(el, seriesModel, itemNode);
  46301. lastX += itemWidth + ITEM_GAP;
  46302. }
  46303. },
  46304. /**
  46305. * @override
  46306. */
  46307. remove: function () {
  46308. this.group.removeAll();
  46309. }
  46310. };
  46311. function makeItemPoints(x, y, itemWidth, itemHeight, head, tail) {
  46312. var points = [
  46313. [head ? x : x - ARRAY_LENGTH, y],
  46314. [x + itemWidth, y],
  46315. [x + itemWidth, y + itemHeight],
  46316. [head ? x : x - ARRAY_LENGTH, y + itemHeight]
  46317. ];
  46318. !tail && points.splice(2, 0, [x + itemWidth + ARRAY_LENGTH, y + itemHeight / 2]);
  46319. !head && points.push([x, y + itemHeight / 2]);
  46320. return points;
  46321. }
  46322. // Package custom mouse event.
  46323. function packEventData(el, seriesModel, itemNode) {
  46324. el.eventData = {
  46325. componentType: 'series',
  46326. componentSubType: 'treemap',
  46327. componentIndex: seriesModel.componentIndex,
  46328. seriesIndex: seriesModel.componentIndex,
  46329. seriesName: seriesModel.name,
  46330. seriesType: 'treemap',
  46331. selfType: 'breadcrumb', // Distinguish with click event on treemap node.
  46332. nodeData: {
  46333. dataIndex: itemNode && itemNode.dataIndex,
  46334. name: itemNode && itemNode.name
  46335. },
  46336. treePathInfo: itemNode && wrapTreePathInfo(itemNode, seriesModel)
  46337. };
  46338. }
  46339. /*
  46340. * Licensed to the Apache Software Foundation (ASF) under one
  46341. * or more contributor license agreements. See the NOTICE file
  46342. * distributed with this work for additional information
  46343. * regarding copyright ownership. The ASF licenses this file
  46344. * to you under the Apache License, Version 2.0 (the
  46345. * "License"); you may not use this file except in compliance
  46346. * with the License. You may obtain a copy of the License at
  46347. *
  46348. * http://www.apache.org/licenses/LICENSE-2.0
  46349. *
  46350. * Unless required by applicable law or agreed to in writing,
  46351. * software distributed under the License is distributed on an
  46352. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46353. * KIND, either express or implied. See the License for the
  46354. * specific language governing permissions and limitations
  46355. * under the License.
  46356. */
  46357. /**
  46358. * @param {number} [time=500] Time in ms
  46359. * @param {string} [easing='linear']
  46360. * @param {number} [delay=0]
  46361. * @param {Function} [callback]
  46362. *
  46363. * @example
  46364. * // Animate position
  46365. * animation
  46366. * .createWrap()
  46367. * .add(el1, {position: [10, 10]})
  46368. * .add(el2, {shape: {width: 500}, style: {fill: 'red'}}, 400)
  46369. * .done(function () { // done })
  46370. * .start('cubicOut');
  46371. */
  46372. function createWrap() {
  46373. var storage = [];
  46374. var elExistsMap = {};
  46375. var doneCallback;
  46376. return {
  46377. /**
  46378. * Caution: a el can only be added once, otherwise 'done'
  46379. * might not be called. This method checks this (by el.id),
  46380. * suppresses adding and returns false when existing el found.
  46381. *
  46382. * @param {modele:zrender/Element} el
  46383. * @param {Object} target
  46384. * @param {number} [time=500]
  46385. * @param {number} [delay=0]
  46386. * @param {string} [easing='linear']
  46387. * @return {boolean} Whether adding succeeded.
  46388. *
  46389. * @example
  46390. * add(el, target, time, delay, easing);
  46391. * add(el, target, time, easing);
  46392. * add(el, target, time);
  46393. * add(el, target);
  46394. */
  46395. add: function (el, target, time, delay, easing) {
  46396. if (isString(delay)) {
  46397. easing = delay;
  46398. delay = 0;
  46399. }
  46400. if (elExistsMap[el.id]) {
  46401. return false;
  46402. }
  46403. elExistsMap[el.id] = 1;
  46404. storage.push(
  46405. {el: el, target: target, time: time, delay: delay, easing: easing}
  46406. );
  46407. return true;
  46408. },
  46409. /**
  46410. * Only execute when animation finished. Will not execute when any
  46411. * of 'stop' or 'stopAnimation' called.
  46412. *
  46413. * @param {Function} callback
  46414. */
  46415. done: function (callback) {
  46416. doneCallback = callback;
  46417. return this;
  46418. },
  46419. /**
  46420. * Will stop exist animation firstly.
  46421. */
  46422. start: function () {
  46423. var count = storage.length;
  46424. for (var i = 0, len = storage.length; i < len; i++) {
  46425. var item = storage[i];
  46426. item.el.animateTo(item.target, item.time, item.delay, item.easing, done);
  46427. }
  46428. return this;
  46429. function done() {
  46430. count--;
  46431. if (!count) {
  46432. storage.length = 0;
  46433. elExistsMap = {};
  46434. doneCallback && doneCallback();
  46435. }
  46436. }
  46437. }
  46438. };
  46439. }
  46440. /*
  46441. * Licensed to the Apache Software Foundation (ASF) under one
  46442. * or more contributor license agreements. See the NOTICE file
  46443. * distributed with this work for additional information
  46444. * regarding copyright ownership. The ASF licenses this file
  46445. * to you under the Apache License, Version 2.0 (the
  46446. * "License"); you may not use this file except in compliance
  46447. * with the License. You may obtain a copy of the License at
  46448. *
  46449. * http://www.apache.org/licenses/LICENSE-2.0
  46450. *
  46451. * Unless required by applicable law or agreed to in writing,
  46452. * software distributed under the License is distributed on an
  46453. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46454. * KIND, either express or implied. See the License for the
  46455. * specific language governing permissions and limitations
  46456. * under the License.
  46457. */
  46458. var bind$1 = bind;
  46459. var Group$2 = Group;
  46460. var Rect$1 = Rect;
  46461. var each$8 = each$1;
  46462. var DRAG_THRESHOLD = 3;
  46463. var PATH_LABEL_NOAMAL = ['label'];
  46464. var PATH_LABEL_EMPHASIS = ['emphasis', 'label'];
  46465. var PATH_UPPERLABEL_NORMAL = ['upperLabel'];
  46466. var PATH_UPPERLABEL_EMPHASIS = ['emphasis', 'upperLabel'];
  46467. var Z_BASE = 10; // Should bigger than every z.
  46468. var Z_BG = 1;
  46469. var Z_CONTENT = 2;
  46470. var getItemStyleEmphasis = makeStyleMapper([
  46471. ['fill', 'color'],
  46472. // `borderColor` and `borderWidth` has been occupied,
  46473. // so use `stroke` to indicate the stroke of the rect.
  46474. ['stroke', 'strokeColor'],
  46475. ['lineWidth', 'strokeWidth'],
  46476. ['shadowBlur'],
  46477. ['shadowOffsetX'],
  46478. ['shadowOffsetY'],
  46479. ['shadowColor']
  46480. ]);
  46481. var getItemStyleNormal = function (model) {
  46482. // Normal style props should include emphasis style props.
  46483. var itemStyle = getItemStyleEmphasis(model);
  46484. // Clear styles set by emphasis.
  46485. itemStyle.stroke = itemStyle.fill = itemStyle.lineWidth = null;
  46486. return itemStyle;
  46487. };
  46488. extendChartView({
  46489. type: 'treemap',
  46490. /**
  46491. * @override
  46492. */
  46493. init: function (o, api) {
  46494. /**
  46495. * @private
  46496. * @type {module:zrender/container/Group}
  46497. */
  46498. this._containerGroup;
  46499. /**
  46500. * @private
  46501. * @type {Object.<string, Array.<module:zrender/container/Group>>}
  46502. */
  46503. this._storage = createStorage();
  46504. /**
  46505. * @private
  46506. * @type {module:echarts/data/Tree}
  46507. */
  46508. this._oldTree;
  46509. /**
  46510. * @private
  46511. * @type {module:echarts/chart/treemap/Breadcrumb}
  46512. */
  46513. this._breadcrumb;
  46514. /**
  46515. * @private
  46516. * @type {module:echarts/component/helper/RoamController}
  46517. */
  46518. this._controller;
  46519. /**
  46520. * 'ready', 'animating'
  46521. * @private
  46522. */
  46523. this._state = 'ready';
  46524. },
  46525. /**
  46526. * @override
  46527. */
  46528. render: function (seriesModel, ecModel, api, payload) {
  46529. var models = ecModel.findComponents({
  46530. mainType: 'series', subType: 'treemap', query: payload
  46531. });
  46532. if (indexOf(models, seriesModel) < 0) {
  46533. return;
  46534. }
  46535. this.seriesModel = seriesModel;
  46536. this.api = api;
  46537. this.ecModel = ecModel;
  46538. var types = ['treemapZoomToNode', 'treemapRootToNode'];
  46539. var targetInfo = retrieveTargetInfo(payload, types, seriesModel);
  46540. var payloadType = payload && payload.type;
  46541. var layoutInfo = seriesModel.layoutInfo;
  46542. var isInit = !this._oldTree;
  46543. var thisStorage = this._storage;
  46544. // Mark new root when action is treemapRootToNode.
  46545. var reRoot = (payloadType === 'treemapRootToNode' && targetInfo && thisStorage)
  46546. ? {
  46547. rootNodeGroup: thisStorage.nodeGroup[targetInfo.node.getRawIndex()],
  46548. direction: payload.direction
  46549. }
  46550. : null;
  46551. var containerGroup = this._giveContainerGroup(layoutInfo);
  46552. var renderResult = this._doRender(containerGroup, seriesModel, reRoot);
  46553. (
  46554. !isInit && (
  46555. !payloadType
  46556. || payloadType === 'treemapZoomToNode'
  46557. || payloadType === 'treemapRootToNode'
  46558. )
  46559. )
  46560. ? this._doAnimation(containerGroup, renderResult, seriesModel, reRoot)
  46561. : renderResult.renderFinally();
  46562. this._resetController(api);
  46563. this._renderBreadcrumb(seriesModel, api, targetInfo);
  46564. },
  46565. /**
  46566. * @private
  46567. */
  46568. _giveContainerGroup: function (layoutInfo) {
  46569. var containerGroup = this._containerGroup;
  46570. if (!containerGroup) {
  46571. // FIXME
  46572. // 加一层containerGroup是为了clip,但是现在clip功能并没有实现。
  46573. containerGroup = this._containerGroup = new Group$2();
  46574. this._initEvents(containerGroup);
  46575. this.group.add(containerGroup);
  46576. }
  46577. containerGroup.attr('position', [layoutInfo.x, layoutInfo.y]);
  46578. return containerGroup;
  46579. },
  46580. /**
  46581. * @private
  46582. */
  46583. _doRender: function (containerGroup, seriesModel, reRoot) {
  46584. var thisTree = seriesModel.getData().tree;
  46585. var oldTree = this._oldTree;
  46586. // Clear last shape records.
  46587. var lastsForAnimation = createStorage();
  46588. var thisStorage = createStorage();
  46589. var oldStorage = this._storage;
  46590. var willInvisibleEls = [];
  46591. var doRenderNode = curry(
  46592. renderNode, seriesModel,
  46593. thisStorage, oldStorage, reRoot,
  46594. lastsForAnimation, willInvisibleEls
  46595. );
  46596. // Notice: when thisTree and oldTree are the same tree (see list.cloneShallow),
  46597. // the oldTree is actually losted, so we can not find all of the old graphic
  46598. // elements from tree. So we use this stragegy: make element storage, move
  46599. // from old storage to new storage, clear old storage.
  46600. dualTravel(
  46601. thisTree.root ? [thisTree.root] : [],
  46602. (oldTree && oldTree.root) ? [oldTree.root] : [],
  46603. containerGroup,
  46604. thisTree === oldTree || !oldTree,
  46605. 0
  46606. );
  46607. // Process all removing.
  46608. var willDeleteEls = clearStorage(oldStorage);
  46609. this._oldTree = thisTree;
  46610. this._storage = thisStorage;
  46611. return {
  46612. lastsForAnimation: lastsForAnimation,
  46613. willDeleteEls: willDeleteEls,
  46614. renderFinally: renderFinally
  46615. };
  46616. function dualTravel(thisViewChildren, oldViewChildren, parentGroup, sameTree, depth) {
  46617. // When 'render' is triggered by action,
  46618. // 'this' and 'old' may be the same tree,
  46619. // we use rawIndex in that case.
  46620. if (sameTree) {
  46621. oldViewChildren = thisViewChildren;
  46622. each$8(thisViewChildren, function (child, index) {
  46623. !child.isRemoved() && processNode(index, index);
  46624. });
  46625. }
  46626. // Diff hierarchically (diff only in each subtree, but not whole).
  46627. // because, consistency of view is important.
  46628. else {
  46629. (new DataDiffer(oldViewChildren, thisViewChildren, getKey, getKey))
  46630. .add(processNode)
  46631. .update(processNode)
  46632. .remove(curry(processNode, null))
  46633. .execute();
  46634. }
  46635. function getKey(node) {
  46636. // Identify by name or raw index.
  46637. return node.getId();
  46638. }
  46639. function processNode(newIndex, oldIndex) {
  46640. var thisNode = newIndex != null ? thisViewChildren[newIndex] : null;
  46641. var oldNode = oldIndex != null ? oldViewChildren[oldIndex] : null;
  46642. var group = doRenderNode(thisNode, oldNode, parentGroup, depth);
  46643. group && dualTravel(
  46644. thisNode && thisNode.viewChildren || [],
  46645. oldNode && oldNode.viewChildren || [],
  46646. group,
  46647. sameTree,
  46648. depth + 1
  46649. );
  46650. }
  46651. }
  46652. function clearStorage(storage) {
  46653. var willDeleteEls = createStorage();
  46654. storage && each$8(storage, function (store, storageName) {
  46655. var delEls = willDeleteEls[storageName];
  46656. each$8(store, function (el) {
  46657. el && (delEls.push(el), el.__tmWillDelete = 1);
  46658. });
  46659. });
  46660. return willDeleteEls;
  46661. }
  46662. function renderFinally() {
  46663. each$8(willDeleteEls, function (els) {
  46664. each$8(els, function (el) {
  46665. el.parent && el.parent.remove(el);
  46666. });
  46667. });
  46668. each$8(willInvisibleEls, function (el) {
  46669. el.invisible = true;
  46670. // Setting invisible is for optimizing, so no need to set dirty,
  46671. // just mark as invisible.
  46672. el.dirty();
  46673. });
  46674. }
  46675. },
  46676. /**
  46677. * @private
  46678. */
  46679. _doAnimation: function (containerGroup, renderResult, seriesModel, reRoot) {
  46680. if (!seriesModel.get('animation')) {
  46681. return;
  46682. }
  46683. var duration = seriesModel.get('animationDurationUpdate');
  46684. var easing = seriesModel.get('animationEasing');
  46685. var animationWrap = createWrap();
  46686. // Make delete animations.
  46687. each$8(renderResult.willDeleteEls, function (store, storageName) {
  46688. each$8(store, function (el, rawIndex) {
  46689. if (el.invisible) {
  46690. return;
  46691. }
  46692. var parent = el.parent; // Always has parent, and parent is nodeGroup.
  46693. var target;
  46694. if (reRoot && reRoot.direction === 'drillDown') {
  46695. target = parent === reRoot.rootNodeGroup
  46696. // This is the content element of view root.
  46697. // Only `content` will enter this branch, because
  46698. // `background` and `nodeGroup` will not be deleted.
  46699. ? {
  46700. shape: {
  46701. x: 0,
  46702. y: 0,
  46703. width: parent.__tmNodeWidth,
  46704. height: parent.__tmNodeHeight
  46705. },
  46706. style: {
  46707. opacity: 0
  46708. }
  46709. }
  46710. // Others.
  46711. : {style: {opacity: 0}};
  46712. }
  46713. else {
  46714. var targetX = 0;
  46715. var targetY = 0;
  46716. if (!parent.__tmWillDelete) {
  46717. // Let node animate to right-bottom corner, cooperating with fadeout,
  46718. // which is appropriate for user understanding.
  46719. // Divided by 2 for reRoot rolling up effect.
  46720. targetX = parent.__tmNodeWidth / 2;
  46721. targetY = parent.__tmNodeHeight / 2;
  46722. }
  46723. target = storageName === 'nodeGroup'
  46724. ? {position: [targetX, targetY], style: {opacity: 0}}
  46725. : {
  46726. shape: {x: targetX, y: targetY, width: 0, height: 0},
  46727. style: {opacity: 0}
  46728. };
  46729. }
  46730. target && animationWrap.add(el, target, duration, easing);
  46731. });
  46732. });
  46733. // Make other animations
  46734. each$8(this._storage, function (store, storageName) {
  46735. each$8(store, function (el, rawIndex) {
  46736. var last = renderResult.lastsForAnimation[storageName][rawIndex];
  46737. var target = {};
  46738. if (!last) {
  46739. return;
  46740. }
  46741. if (storageName === 'nodeGroup') {
  46742. if (last.old) {
  46743. target.position = el.position.slice();
  46744. el.attr('position', last.old);
  46745. }
  46746. }
  46747. else {
  46748. if (last.old) {
  46749. target.shape = extend({}, el.shape);
  46750. el.setShape(last.old);
  46751. }
  46752. if (last.fadein) {
  46753. el.setStyle('opacity', 0);
  46754. target.style = {opacity: 1};
  46755. }
  46756. // When animation is stopped for succedent animation starting,
  46757. // el.style.opacity might not be 1
  46758. else if (el.style.opacity !== 1) {
  46759. target.style = {opacity: 1};
  46760. }
  46761. }
  46762. animationWrap.add(el, target, duration, easing);
  46763. });
  46764. }, this);
  46765. this._state = 'animating';
  46766. animationWrap
  46767. .done(bind$1(function () {
  46768. this._state = 'ready';
  46769. renderResult.renderFinally();
  46770. }, this))
  46771. .start();
  46772. },
  46773. /**
  46774. * @private
  46775. */
  46776. _resetController: function (api) {
  46777. var controller = this._controller;
  46778. // Init controller.
  46779. if (!controller) {
  46780. controller = this._controller = new RoamController(api.getZr());
  46781. controller.enable(this.seriesModel.get('roam'));
  46782. controller.on('pan', bind$1(this._onPan, this));
  46783. controller.on('zoom', bind$1(this._onZoom, this));
  46784. }
  46785. var rect = new BoundingRect(0, 0, api.getWidth(), api.getHeight());
  46786. controller.setPointerChecker(function (e, x, y) {
  46787. return rect.contain(x, y);
  46788. });
  46789. },
  46790. /**
  46791. * @private
  46792. */
  46793. _clearController: function () {
  46794. var controller = this._controller;
  46795. if (controller) {
  46796. controller.dispose();
  46797. controller = null;
  46798. }
  46799. },
  46800. /**
  46801. * @private
  46802. */
  46803. _onPan: function (e) {
  46804. if (this._state !== 'animating'
  46805. && (Math.abs(e.dx) > DRAG_THRESHOLD || Math.abs(e.dy) > DRAG_THRESHOLD)
  46806. ) {
  46807. // These param must not be cached.
  46808. var root = this.seriesModel.getData().tree.root;
  46809. if (!root) {
  46810. return;
  46811. }
  46812. var rootLayout = root.getLayout();
  46813. if (!rootLayout) {
  46814. return;
  46815. }
  46816. this.api.dispatchAction({
  46817. type: 'treemapMove',
  46818. from: this.uid,
  46819. seriesId: this.seriesModel.id,
  46820. rootRect: {
  46821. x: rootLayout.x + e.dx, y: rootLayout.y + e.dy,
  46822. width: rootLayout.width, height: rootLayout.height
  46823. }
  46824. });
  46825. }
  46826. },
  46827. /**
  46828. * @private
  46829. */
  46830. _onZoom: function (e) {
  46831. var mouseX = e.originX;
  46832. var mouseY = e.originY;
  46833. if (this._state !== 'animating') {
  46834. // These param must not be cached.
  46835. var root = this.seriesModel.getData().tree.root;
  46836. if (!root) {
  46837. return;
  46838. }
  46839. var rootLayout = root.getLayout();
  46840. if (!rootLayout) {
  46841. return;
  46842. }
  46843. var rect = new BoundingRect(
  46844. rootLayout.x, rootLayout.y, rootLayout.width, rootLayout.height
  46845. );
  46846. var layoutInfo = this.seriesModel.layoutInfo;
  46847. // Transform mouse coord from global to containerGroup.
  46848. mouseX -= layoutInfo.x;
  46849. mouseY -= layoutInfo.y;
  46850. // Scale root bounding rect.
  46851. var m = create$1();
  46852. translate(m, m, [-mouseX, -mouseY]);
  46853. scale$1(m, m, [e.scale, e.scale]);
  46854. translate(m, m, [mouseX, mouseY]);
  46855. rect.applyTransform(m);
  46856. this.api.dispatchAction({
  46857. type: 'treemapRender',
  46858. from: this.uid,
  46859. seriesId: this.seriesModel.id,
  46860. rootRect: {
  46861. x: rect.x, y: rect.y,
  46862. width: rect.width, height: rect.height
  46863. }
  46864. });
  46865. }
  46866. },
  46867. /**
  46868. * @private
  46869. */
  46870. _initEvents: function (containerGroup) {
  46871. containerGroup.on('click', function (e) {
  46872. if (this._state !== 'ready') {
  46873. return;
  46874. }
  46875. var nodeClick = this.seriesModel.get('nodeClick', true);
  46876. if (!nodeClick) {
  46877. return;
  46878. }
  46879. var targetInfo = this.findTarget(e.offsetX, e.offsetY);
  46880. if (!targetInfo) {
  46881. return;
  46882. }
  46883. var node = targetInfo.node;
  46884. if (node.getLayout().isLeafRoot) {
  46885. this._rootToNode(targetInfo);
  46886. }
  46887. else {
  46888. if (nodeClick === 'zoomToNode') {
  46889. this._zoomToNode(targetInfo);
  46890. }
  46891. else if (nodeClick === 'link') {
  46892. var itemModel = node.hostTree.data.getItemModel(node.dataIndex);
  46893. var link = itemModel.get('link', true);
  46894. var linkTarget = itemModel.get('target', true) || 'blank';
  46895. link && windowOpen(link, linkTarget);
  46896. }
  46897. }
  46898. }, this);
  46899. },
  46900. /**
  46901. * @private
  46902. */
  46903. _renderBreadcrumb: function (seriesModel, api, targetInfo) {
  46904. if (!targetInfo) {
  46905. targetInfo = seriesModel.get('leafDepth', true) != null
  46906. ? {node: seriesModel.getViewRoot()}
  46907. // FIXME
  46908. // better way?
  46909. // Find breadcrumb tail on center of containerGroup.
  46910. : this.findTarget(api.getWidth() / 2, api.getHeight() / 2);
  46911. if (!targetInfo) {
  46912. targetInfo = {node: seriesModel.getData().tree.root};
  46913. }
  46914. }
  46915. (this._breadcrumb || (this._breadcrumb = new Breadcrumb(this.group)))
  46916. .render(seriesModel, api, targetInfo.node, bind$1(onSelect, this));
  46917. function onSelect(node) {
  46918. if (this._state !== 'animating') {
  46919. aboveViewRoot(seriesModel.getViewRoot(), node)
  46920. ? this._rootToNode({node: node})
  46921. : this._zoomToNode({node: node});
  46922. }
  46923. }
  46924. },
  46925. /**
  46926. * @override
  46927. */
  46928. remove: function () {
  46929. this._clearController();
  46930. this._containerGroup && this._containerGroup.removeAll();
  46931. this._storage = createStorage();
  46932. this._state = 'ready';
  46933. this._breadcrumb && this._breadcrumb.remove();
  46934. },
  46935. dispose: function () {
  46936. this._clearController();
  46937. },
  46938. /**
  46939. * @private
  46940. */
  46941. _zoomToNode: function (targetInfo) {
  46942. this.api.dispatchAction({
  46943. type: 'treemapZoomToNode',
  46944. from: this.uid,
  46945. seriesId: this.seriesModel.id,
  46946. targetNode: targetInfo.node
  46947. });
  46948. },
  46949. /**
  46950. * @private
  46951. */
  46952. _rootToNode: function (targetInfo) {
  46953. this.api.dispatchAction({
  46954. type: 'treemapRootToNode',
  46955. from: this.uid,
  46956. seriesId: this.seriesModel.id,
  46957. targetNode: targetInfo.node
  46958. });
  46959. },
  46960. /**
  46961. * @public
  46962. * @param {number} x Global coord x.
  46963. * @param {number} y Global coord y.
  46964. * @return {Object} info If not found, return undefined;
  46965. * @return {number} info.node Target node.
  46966. * @return {number} info.offsetX x refer to target node.
  46967. * @return {number} info.offsetY y refer to target node.
  46968. */
  46969. findTarget: function (x, y) {
  46970. var targetInfo;
  46971. var viewRoot = this.seriesModel.getViewRoot();
  46972. viewRoot.eachNode({attr: 'viewChildren', order: 'preorder'}, function (node) {
  46973. var bgEl = this._storage.background[node.getRawIndex()];
  46974. // If invisible, there might be no element.
  46975. if (bgEl) {
  46976. var point = bgEl.transformCoordToLocal(x, y);
  46977. var shape = bgEl.shape;
  46978. // For performance consideration, dont use 'getBoundingRect'.
  46979. if (shape.x <= point[0]
  46980. && point[0] <= shape.x + shape.width
  46981. && shape.y <= point[1]
  46982. && point[1] <= shape.y + shape.height
  46983. ) {
  46984. targetInfo = {node: node, offsetX: point[0], offsetY: point[1]};
  46985. }
  46986. else {
  46987. return false; // Suppress visit subtree.
  46988. }
  46989. }
  46990. }, this);
  46991. return targetInfo;
  46992. }
  46993. });
  46994. /**
  46995. * @inner
  46996. */
  46997. function createStorage() {
  46998. return {nodeGroup: [], background: [], content: []};
  46999. }
  47000. /**
  47001. * @inner
  47002. * @return Return undefined means do not travel further.
  47003. */
  47004. function renderNode(
  47005. seriesModel, thisStorage, oldStorage, reRoot,
  47006. lastsForAnimation, willInvisibleEls,
  47007. thisNode, oldNode, parentGroup, depth
  47008. ) {
  47009. // Whether under viewRoot.
  47010. if (!thisNode) {
  47011. // Deleting nodes will be performed finally. This method just find
  47012. // element from old storage, or create new element, set them to new
  47013. // storage, and set styles.
  47014. return;
  47015. }
  47016. // -------------------------------------------------------------------
  47017. // Start of closure variables available in "Procedures in renderNode".
  47018. var thisLayout = thisNode.getLayout();
  47019. var data = seriesModel.getData();
  47020. // Only for enabling highlight/downplay. Clear firstly.
  47021. // Because some node will not be rendered.
  47022. data.setItemGraphicEl(thisNode.dataIndex, null);
  47023. if (!thisLayout || !thisLayout.isInView) {
  47024. return;
  47025. }
  47026. var thisWidth = thisLayout.width;
  47027. var thisHeight = thisLayout.height;
  47028. var borderWidth = thisLayout.borderWidth;
  47029. var thisInvisible = thisLayout.invisible;
  47030. var thisRawIndex = thisNode.getRawIndex();
  47031. var oldRawIndex = oldNode && oldNode.getRawIndex();
  47032. var thisViewChildren = thisNode.viewChildren;
  47033. var upperHeight = thisLayout.upperHeight;
  47034. var isParent = thisViewChildren && thisViewChildren.length;
  47035. var itemStyleNormalModel = thisNode.getModel('itemStyle');
  47036. var itemStyleEmphasisModel = thisNode.getModel('emphasis.itemStyle');
  47037. // End of closure ariables available in "Procedures in renderNode".
  47038. // -----------------------------------------------------------------
  47039. // Node group
  47040. var group = giveGraphic('nodeGroup', Group$2);
  47041. if (!group) {
  47042. return;
  47043. }
  47044. parentGroup.add(group);
  47045. // x,y are not set when el is above view root.
  47046. group.attr('position', [thisLayout.x || 0, thisLayout.y || 0]);
  47047. group.__tmNodeWidth = thisWidth;
  47048. group.__tmNodeHeight = thisHeight;
  47049. if (thisLayout.isAboveViewRoot) {
  47050. return group;
  47051. }
  47052. var nodeModel = thisNode.getModel();
  47053. // Background
  47054. var bg = giveGraphic('background', Rect$1, depth, Z_BG);
  47055. bg && renderBackground(group, bg, isParent && thisLayout.upperLabelHeight);
  47056. // No children, render content.
  47057. if (isParent) {
  47058. // Because of the implementation about "traverse" in graphic hover style, we
  47059. // can not set hover listener on the "group" of non-leaf node. Otherwise the
  47060. // hover event from the descendents will be listenered.
  47061. if (isHighDownDispatcher(group)) {
  47062. setAsHighDownDispatcher(group, false);
  47063. }
  47064. if (bg) {
  47065. setAsHighDownDispatcher(bg, true);
  47066. // Only for enabling highlight/downplay.
  47067. data.setItemGraphicEl(thisNode.dataIndex, bg);
  47068. }
  47069. }
  47070. else {
  47071. var content = giveGraphic('content', Rect$1, depth, Z_CONTENT);
  47072. content && renderContent(group, content);
  47073. if (bg && isHighDownDispatcher(bg)) {
  47074. setAsHighDownDispatcher(bg, false);
  47075. }
  47076. setAsHighDownDispatcher(group, true);
  47077. // Only for enabling highlight/downplay.
  47078. data.setItemGraphicEl(thisNode.dataIndex, group);
  47079. }
  47080. return group;
  47081. // ----------------------------
  47082. // | Procedures in renderNode |
  47083. // ----------------------------
  47084. function renderBackground(group, bg, useUpperLabel) {
  47085. // For tooltip.
  47086. bg.dataIndex = thisNode.dataIndex;
  47087. bg.seriesIndex = seriesModel.seriesIndex;
  47088. bg.setShape({x: 0, y: 0, width: thisWidth, height: thisHeight});
  47089. if (thisInvisible) {
  47090. // If invisible, do not set visual, otherwise the element will
  47091. // change immediately before animation. We think it is OK to
  47092. // remain its origin color when moving out of the view window.
  47093. processInvisible(bg);
  47094. }
  47095. else {
  47096. bg.invisible = false;
  47097. var visualBorderColor = thisNode.getVisual('borderColor', true);
  47098. var emphasisBorderColor = itemStyleEmphasisModel.get('borderColor');
  47099. var normalStyle = getItemStyleNormal(itemStyleNormalModel);
  47100. normalStyle.fill = visualBorderColor;
  47101. var emphasisStyle = getItemStyleEmphasis(itemStyleEmphasisModel);
  47102. emphasisStyle.fill = emphasisBorderColor;
  47103. if (useUpperLabel) {
  47104. var upperLabelWidth = thisWidth - 2 * borderWidth;
  47105. prepareText(
  47106. normalStyle, emphasisStyle, visualBorderColor, upperLabelWidth, upperHeight,
  47107. {x: borderWidth, y: 0, width: upperLabelWidth, height: upperHeight}
  47108. );
  47109. }
  47110. // For old bg.
  47111. else {
  47112. normalStyle.text = emphasisStyle.text = null;
  47113. }
  47114. bg.setStyle(normalStyle);
  47115. setElementHoverStyle(bg, emphasisStyle);
  47116. }
  47117. group.add(bg);
  47118. }
  47119. function renderContent(group, content) {
  47120. // For tooltip.
  47121. content.dataIndex = thisNode.dataIndex;
  47122. content.seriesIndex = seriesModel.seriesIndex;
  47123. var contentWidth = Math.max(thisWidth - 2 * borderWidth, 0);
  47124. var contentHeight = Math.max(thisHeight - 2 * borderWidth, 0);
  47125. content.culling = true;
  47126. content.setShape({
  47127. x: borderWidth,
  47128. y: borderWidth,
  47129. width: contentWidth,
  47130. height: contentHeight
  47131. });
  47132. if (thisInvisible) {
  47133. // If invisible, do not set visual, otherwise the element will
  47134. // change immediately before animation. We think it is OK to
  47135. // remain its origin color when moving out of the view window.
  47136. processInvisible(content);
  47137. }
  47138. else {
  47139. content.invisible = false;
  47140. var visualColor = thisNode.getVisual('color', true);
  47141. var normalStyle = getItemStyleNormal(itemStyleNormalModel);
  47142. normalStyle.fill = visualColor;
  47143. var emphasisStyle = getItemStyleEmphasis(itemStyleEmphasisModel);
  47144. prepareText(normalStyle, emphasisStyle, visualColor, contentWidth, contentHeight);
  47145. content.setStyle(normalStyle);
  47146. setElementHoverStyle(content, emphasisStyle);
  47147. }
  47148. group.add(content);
  47149. }
  47150. function processInvisible(element) {
  47151. // Delay invisible setting utill animation finished,
  47152. // avoid element vanish suddenly before animation.
  47153. !element.invisible && willInvisibleEls.push(element);
  47154. }
  47155. function prepareText(normalStyle, emphasisStyle, visualColor, width, height, upperLabelRect) {
  47156. var defaultText = nodeModel.get('name');
  47157. var normalLabelModel = nodeModel.getModel(
  47158. upperLabelRect ? PATH_UPPERLABEL_NORMAL : PATH_LABEL_NOAMAL
  47159. );
  47160. var emphasisLabelModel = nodeModel.getModel(
  47161. upperLabelRect ? PATH_UPPERLABEL_EMPHASIS : PATH_LABEL_EMPHASIS
  47162. );
  47163. var isShow = normalLabelModel.getShallow('show');
  47164. setLabelStyle(
  47165. normalStyle, emphasisStyle, normalLabelModel, emphasisLabelModel,
  47166. {
  47167. defaultText: isShow ? defaultText : null,
  47168. autoColor: visualColor,
  47169. isRectText: true,
  47170. labelFetcher: seriesModel,
  47171. labelDataIndex: thisNode.dataIndex,
  47172. labelProp: upperLabelRect ? 'upperLabel' : 'label'
  47173. }
  47174. );
  47175. addDrillDownIcon(normalStyle, upperLabelRect, thisLayout);
  47176. addDrillDownIcon(emphasisStyle, upperLabelRect, thisLayout);
  47177. upperLabelRect && (normalStyle.textRect = clone(upperLabelRect));
  47178. normalStyle.truncate = (isShow && normalLabelModel.get('ellipsis'))
  47179. ? {
  47180. outerWidth: width,
  47181. outerHeight: height,
  47182. minChar: 2
  47183. }
  47184. : null;
  47185. }
  47186. function addDrillDownIcon(style, upperLabelRect, thisLayout) {
  47187. var text = style.text;
  47188. if (!upperLabelRect && thisLayout.isLeafRoot && text != null) {
  47189. var iconChar = seriesModel.get('drillDownIcon', true);
  47190. style.text = iconChar ? iconChar + ' ' + text : text;
  47191. }
  47192. }
  47193. function giveGraphic(storageName, Ctor, depth, z) {
  47194. var element = oldRawIndex != null && oldStorage[storageName][oldRawIndex];
  47195. var lasts = lastsForAnimation[storageName];
  47196. if (element) {
  47197. // Remove from oldStorage
  47198. oldStorage[storageName][oldRawIndex] = null;
  47199. prepareAnimationWhenHasOld(lasts, element, storageName);
  47200. }
  47201. // If invisible and no old element, do not create new element (for optimizing).
  47202. else if (!thisInvisible) {
  47203. element = new Ctor({z: calculateZ(depth, z)});
  47204. element.__tmDepth = depth;
  47205. element.__tmStorageName = storageName;
  47206. prepareAnimationWhenNoOld(lasts, element, storageName);
  47207. }
  47208. // Set to thisStorage
  47209. return (thisStorage[storageName][thisRawIndex] = element);
  47210. }
  47211. function prepareAnimationWhenHasOld(lasts, element, storageName) {
  47212. var lastCfg = lasts[thisRawIndex] = {};
  47213. lastCfg.old = storageName === 'nodeGroup'
  47214. ? element.position.slice()
  47215. : extend({}, element.shape);
  47216. }
  47217. // If a element is new, we need to find the animation start point carefully,
  47218. // otherwise it will looks strange when 'zoomToNode'.
  47219. function prepareAnimationWhenNoOld(lasts, element, storageName) {
  47220. var lastCfg = lasts[thisRawIndex] = {};
  47221. var parentNode = thisNode.parentNode;
  47222. if (parentNode && (!reRoot || reRoot.direction === 'drillDown')) {
  47223. var parentOldX = 0;
  47224. var parentOldY = 0;
  47225. // New nodes appear from right-bottom corner in 'zoomToNode' animation.
  47226. // For convenience, get old bounding rect from background.
  47227. var parentOldBg = lastsForAnimation.background[parentNode.getRawIndex()];
  47228. if (!reRoot && parentOldBg && parentOldBg.old) {
  47229. parentOldX = parentOldBg.old.width;
  47230. parentOldY = parentOldBg.old.height;
  47231. }
  47232. // When no parent old shape found, its parent is new too,
  47233. // so we can just use {x:0, y:0}.
  47234. lastCfg.old = storageName === 'nodeGroup'
  47235. ? [0, parentOldY]
  47236. : {x: parentOldX, y: parentOldY, width: 0, height: 0};
  47237. }
  47238. // Fade in, user can be aware that these nodes are new.
  47239. lastCfg.fadein = storageName !== 'nodeGroup';
  47240. }
  47241. }
  47242. // We can not set all backgroud with the same z, Because the behaviour of
  47243. // drill down and roll up differ background creation sequence from tree
  47244. // hierarchy sequence, which cause that lowser background element overlap
  47245. // upper ones. So we calculate z based on depth.
  47246. // Moreover, we try to shrink down z interval to [0, 1] to avoid that
  47247. // treemap with large z overlaps other components.
  47248. function calculateZ(depth, zInLevel) {
  47249. var zb = depth * Z_BASE + zInLevel;
  47250. return (zb - 1) / zb;
  47251. }
  47252. /*
  47253. * Licensed to the Apache Software Foundation (ASF) under one
  47254. * or more contributor license agreements. See the NOTICE file
  47255. * distributed with this work for additional information
  47256. * regarding copyright ownership. The ASF licenses this file
  47257. * to you under the Apache License, Version 2.0 (the
  47258. * "License"); you may not use this file except in compliance
  47259. * with the License. You may obtain a copy of the License at
  47260. *
  47261. * http://www.apache.org/licenses/LICENSE-2.0
  47262. *
  47263. * Unless required by applicable law or agreed to in writing,
  47264. * software distributed under the License is distributed on an
  47265. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47266. * KIND, either express or implied. See the License for the
  47267. * specific language governing permissions and limitations
  47268. * under the License.
  47269. */
  47270. /**
  47271. * @file Treemap action
  47272. */
  47273. var noop$1 = function () {};
  47274. var actionTypes = [
  47275. 'treemapZoomToNode',
  47276. 'treemapRender',
  47277. 'treemapMove'
  47278. ];
  47279. for (var i$2 = 0; i$2 < actionTypes.length; i$2++) {
  47280. registerAction({type: actionTypes[i$2], update: 'updateView'}, noop$1);
  47281. }
  47282. registerAction(
  47283. {type: 'treemapRootToNode', update: 'updateView'},
  47284. function (payload, ecModel) {
  47285. ecModel.eachComponent(
  47286. {mainType: 'series', subType: 'treemap', query: payload},
  47287. handleRootToNode
  47288. );
  47289. function handleRootToNode(model, index) {
  47290. var types = ['treemapZoomToNode', 'treemapRootToNode'];
  47291. var targetInfo = retrieveTargetInfo(payload, types, model);
  47292. if (targetInfo) {
  47293. var originViewRoot = model.getViewRoot();
  47294. if (originViewRoot) {
  47295. payload.direction = aboveViewRoot(originViewRoot, targetInfo.node)
  47296. ? 'rollUp' : 'drillDown';
  47297. }
  47298. model.resetViewRoot(targetInfo.node);
  47299. }
  47300. }
  47301. }
  47302. );
  47303. /*
  47304. * Licensed to the Apache Software Foundation (ASF) under one
  47305. * or more contributor license agreements. See the NOTICE file
  47306. * distributed with this work for additional information
  47307. * regarding copyright ownership. The ASF licenses this file
  47308. * to you under the Apache License, Version 2.0 (the
  47309. * "License"); you may not use this file except in compliance
  47310. * with the License. You may obtain a copy of the License at
  47311. *
  47312. * http://www.apache.org/licenses/LICENSE-2.0
  47313. *
  47314. * Unless required by applicable law or agreed to in writing,
  47315. * software distributed under the License is distributed on an
  47316. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47317. * KIND, either express or implied. See the License for the
  47318. * specific language governing permissions and limitations
  47319. * under the License.
  47320. */
  47321. var each$9 = each$1;
  47322. var isObject$5 = isObject$1;
  47323. var CATEGORY_DEFAULT_VISUAL_INDEX = -1;
  47324. /**
  47325. * @param {Object} option
  47326. * @param {string} [option.type] See visualHandlers.
  47327. * @param {string} [option.mappingMethod] 'linear' or 'piecewise' or 'category' or 'fixed'
  47328. * @param {Array.<number>=} [option.dataExtent] [minExtent, maxExtent],
  47329. * required when mappingMethod is 'linear'
  47330. * @param {Array.<Object>=} [option.pieceList] [
  47331. * {value: someValue},
  47332. * {interval: [min1, max1], visual: {...}},
  47333. * {interval: [min2, max2]}
  47334. * ],
  47335. * required when mappingMethod is 'piecewise'.
  47336. * Visual for only each piece can be specified.
  47337. * @param {Array.<string|Object>=} [option.categories] ['cate1', 'cate2']
  47338. * required when mappingMethod is 'category'.
  47339. * If no option.categories, categories is set
  47340. * as [0, 1, 2, ...].
  47341. * @param {boolean} [option.loop=false] Whether loop mapping when mappingMethod is 'category'.
  47342. * @param {(Array|Object|*)} [option.visual] Visual data.
  47343. * when mappingMethod is 'category',
  47344. * visual data can be array or object
  47345. * (like: {cate1: '#222', none: '#fff'})
  47346. * or primary types (which represents
  47347. * defualt category visual), otherwise visual
  47348. * can be array or primary (which will be
  47349. * normalized to array).
  47350. *
  47351. */
  47352. var VisualMapping = function (option) {
  47353. var mappingMethod = option.mappingMethod;
  47354. var visualType = option.type;
  47355. /**
  47356. * @readOnly
  47357. * @type {Object}
  47358. */
  47359. var thisOption = this.option = clone(option);
  47360. /**
  47361. * @readOnly
  47362. * @type {string}
  47363. */
  47364. this.type = visualType;
  47365. /**
  47366. * @readOnly
  47367. * @type {string}
  47368. */
  47369. this.mappingMethod = mappingMethod;
  47370. /**
  47371. * @private
  47372. * @type {Function}
  47373. */
  47374. this._normalizeData = normalizers[mappingMethod];
  47375. var visualHandler = visualHandlers[visualType];
  47376. /**
  47377. * @public
  47378. * @type {Function}
  47379. */
  47380. this.applyVisual = visualHandler.applyVisual;
  47381. /**
  47382. * @public
  47383. * @type {Function}
  47384. */
  47385. this.getColorMapper = visualHandler.getColorMapper;
  47386. /**
  47387. * @private
  47388. * @type {Function}
  47389. */
  47390. this._doMap = visualHandler._doMap[mappingMethod];
  47391. if (mappingMethod === 'piecewise') {
  47392. normalizeVisualRange(thisOption);
  47393. preprocessForPiecewise(thisOption);
  47394. }
  47395. else if (mappingMethod === 'category') {
  47396. thisOption.categories
  47397. ? preprocessForSpecifiedCategory(thisOption)
  47398. // categories is ordinal when thisOption.categories not specified,
  47399. // which need no more preprocess except normalize visual.
  47400. : normalizeVisualRange(thisOption, true);
  47401. }
  47402. else { // mappingMethod === 'linear' or 'fixed'
  47403. assert$1(mappingMethod !== 'linear' || thisOption.dataExtent);
  47404. normalizeVisualRange(thisOption);
  47405. }
  47406. };
  47407. VisualMapping.prototype = {
  47408. constructor: VisualMapping,
  47409. mapValueToVisual: function (value) {
  47410. var normalized = this._normalizeData(value);
  47411. return this._doMap(normalized, value);
  47412. },
  47413. getNormalizer: function () {
  47414. return bind(this._normalizeData, this);
  47415. }
  47416. };
  47417. var visualHandlers = VisualMapping.visualHandlers = {
  47418. color: {
  47419. applyVisual: makeApplyVisual('color'),
  47420. /**
  47421. * Create a mapper function
  47422. * @return {Function}
  47423. */
  47424. getColorMapper: function () {
  47425. var thisOption = this.option;
  47426. return bind(
  47427. thisOption.mappingMethod === 'category'
  47428. ? function (value, isNormalized) {
  47429. !isNormalized && (value = this._normalizeData(value));
  47430. return doMapCategory.call(this, value);
  47431. }
  47432. : function (value, isNormalized, out) {
  47433. // If output rgb array
  47434. // which will be much faster and useful in pixel manipulation
  47435. var returnRGBArray = !!out;
  47436. !isNormalized && (value = this._normalizeData(value));
  47437. out = fastLerp(value, thisOption.parsedVisual, out);
  47438. return returnRGBArray ? out : stringify(out, 'rgba');
  47439. },
  47440. this
  47441. );
  47442. },
  47443. _doMap: {
  47444. linear: function (normalized) {
  47445. return stringify(
  47446. fastLerp(normalized, this.option.parsedVisual),
  47447. 'rgba'
  47448. );
  47449. },
  47450. category: doMapCategory,
  47451. piecewise: function (normalized, value) {
  47452. var result = getSpecifiedVisual.call(this, value);
  47453. if (result == null) {
  47454. result = stringify(
  47455. fastLerp(normalized, this.option.parsedVisual),
  47456. 'rgba'
  47457. );
  47458. }
  47459. return result;
  47460. },
  47461. fixed: doMapFixed
  47462. }
  47463. },
  47464. colorHue: makePartialColorVisualHandler(function (color, value) {
  47465. return modifyHSL(color, value);
  47466. }),
  47467. colorSaturation: makePartialColorVisualHandler(function (color, value) {
  47468. return modifyHSL(color, null, value);
  47469. }),
  47470. colorLightness: makePartialColorVisualHandler(function (color, value) {
  47471. return modifyHSL(color, null, null, value);
  47472. }),
  47473. colorAlpha: makePartialColorVisualHandler(function (color, value) {
  47474. return modifyAlpha(color, value);
  47475. }),
  47476. opacity: {
  47477. applyVisual: makeApplyVisual('opacity'),
  47478. _doMap: makeDoMap([0, 1])
  47479. },
  47480. liftZ: {
  47481. applyVisual: makeApplyVisual('liftZ'),
  47482. _doMap: {
  47483. linear: doMapFixed,
  47484. category: doMapFixed,
  47485. piecewise: doMapFixed,
  47486. fixed: doMapFixed
  47487. }
  47488. },
  47489. symbol: {
  47490. applyVisual: function (value, getter, setter) {
  47491. var symbolCfg = this.mapValueToVisual(value);
  47492. if (isString(symbolCfg)) {
  47493. setter('symbol', symbolCfg);
  47494. }
  47495. else if (isObject$5(symbolCfg)) {
  47496. for (var name in symbolCfg) {
  47497. if (symbolCfg.hasOwnProperty(name)) {
  47498. setter(name, symbolCfg[name]);
  47499. }
  47500. }
  47501. }
  47502. },
  47503. _doMap: {
  47504. linear: doMapToArray,
  47505. category: doMapCategory,
  47506. piecewise: function (normalized, value) {
  47507. var result = getSpecifiedVisual.call(this, value);
  47508. if (result == null) {
  47509. result = doMapToArray.call(this, normalized);
  47510. }
  47511. return result;
  47512. },
  47513. fixed: doMapFixed
  47514. }
  47515. },
  47516. symbolSize: {
  47517. applyVisual: makeApplyVisual('symbolSize'),
  47518. _doMap: makeDoMap([0, 1])
  47519. }
  47520. };
  47521. function preprocessForPiecewise(thisOption) {
  47522. var pieceList = thisOption.pieceList;
  47523. thisOption.hasSpecialVisual = false;
  47524. each$1(pieceList, function (piece, index) {
  47525. piece.originIndex = index;
  47526. // piece.visual is "result visual value" but not
  47527. // a visual range, so it does not need to be normalized.
  47528. if (piece.visual != null) {
  47529. thisOption.hasSpecialVisual = true;
  47530. }
  47531. });
  47532. }
  47533. function preprocessForSpecifiedCategory(thisOption) {
  47534. // Hash categories.
  47535. var categories = thisOption.categories;
  47536. var visual = thisOption.visual;
  47537. var categoryMap = thisOption.categoryMap = {};
  47538. each$9(categories, function (cate, index) {
  47539. categoryMap[cate] = index;
  47540. });
  47541. // Process visual map input.
  47542. if (!isArray(visual)) {
  47543. var visualArr = [];
  47544. if (isObject$1(visual)) {
  47545. each$9(visual, function (v, cate) {
  47546. var index = categoryMap[cate];
  47547. visualArr[index != null ? index : CATEGORY_DEFAULT_VISUAL_INDEX] = v;
  47548. });
  47549. }
  47550. else { // Is primary type, represents default visual.
  47551. visualArr[CATEGORY_DEFAULT_VISUAL_INDEX] = visual;
  47552. }
  47553. visual = setVisualToOption(thisOption, visualArr);
  47554. }
  47555. // Remove categories that has no visual,
  47556. // then we can mapping them to CATEGORY_DEFAULT_VISUAL_INDEX.
  47557. for (var i = categories.length - 1; i >= 0; i--) {
  47558. if (visual[i] == null) {
  47559. delete categoryMap[categories[i]];
  47560. categories.pop();
  47561. }
  47562. }
  47563. }
  47564. function normalizeVisualRange(thisOption, isCategory) {
  47565. var visual = thisOption.visual;
  47566. var visualArr = [];
  47567. if (isObject$1(visual)) {
  47568. each$9(visual, function (v) {
  47569. visualArr.push(v);
  47570. });
  47571. }
  47572. else if (visual != null) {
  47573. visualArr.push(visual);
  47574. }
  47575. var doNotNeedPair = {color: 1, symbol: 1};
  47576. if (!isCategory
  47577. && visualArr.length === 1
  47578. && !doNotNeedPair.hasOwnProperty(thisOption.type)
  47579. ) {
  47580. // Do not care visualArr.length === 0, which is illegal.
  47581. visualArr[1] = visualArr[0];
  47582. }
  47583. setVisualToOption(thisOption, visualArr);
  47584. }
  47585. function makePartialColorVisualHandler(applyValue) {
  47586. return {
  47587. applyVisual: function (value, getter, setter) {
  47588. value = this.mapValueToVisual(value);
  47589. // Must not be array value
  47590. setter('color', applyValue(getter('color'), value));
  47591. },
  47592. _doMap: makeDoMap([0, 1])
  47593. };
  47594. }
  47595. function doMapToArray(normalized) {
  47596. var visual = this.option.visual;
  47597. return visual[
  47598. Math.round(linearMap(normalized, [0, 1], [0, visual.length - 1], true))
  47599. ] || {};
  47600. }
  47601. function makeApplyVisual(visualType) {
  47602. return function (value, getter, setter) {
  47603. setter(visualType, this.mapValueToVisual(value));
  47604. };
  47605. }
  47606. function doMapCategory(normalized) {
  47607. var visual = this.option.visual;
  47608. return visual[
  47609. (this.option.loop && normalized !== CATEGORY_DEFAULT_VISUAL_INDEX)
  47610. ? normalized % visual.length
  47611. : normalized
  47612. ];
  47613. }
  47614. function doMapFixed() {
  47615. return this.option.visual[0];
  47616. }
  47617. function makeDoMap(sourceExtent) {
  47618. return {
  47619. linear: function (normalized) {
  47620. return linearMap(normalized, sourceExtent, this.option.visual, true);
  47621. },
  47622. category: doMapCategory,
  47623. piecewise: function (normalized, value) {
  47624. var result = getSpecifiedVisual.call(this, value);
  47625. if (result == null) {
  47626. result = linearMap(normalized, sourceExtent, this.option.visual, true);
  47627. }
  47628. return result;
  47629. },
  47630. fixed: doMapFixed
  47631. };
  47632. }
  47633. function getSpecifiedVisual(value) {
  47634. var thisOption = this.option;
  47635. var pieceList = thisOption.pieceList;
  47636. if (thisOption.hasSpecialVisual) {
  47637. var pieceIndex = VisualMapping.findPieceIndex(value, pieceList);
  47638. var piece = pieceList[pieceIndex];
  47639. if (piece && piece.visual) {
  47640. return piece.visual[this.type];
  47641. }
  47642. }
  47643. }
  47644. function setVisualToOption(thisOption, visualArr) {
  47645. thisOption.visual = visualArr;
  47646. if (thisOption.type === 'color') {
  47647. thisOption.parsedVisual = map(visualArr, function (item) {
  47648. return parse(item);
  47649. });
  47650. }
  47651. return visualArr;
  47652. }
  47653. /**
  47654. * Normalizers by mapping methods.
  47655. */
  47656. var normalizers = {
  47657. linear: function (value) {
  47658. return linearMap(value, this.option.dataExtent, [0, 1], true);
  47659. },
  47660. piecewise: function (value) {
  47661. var pieceList = this.option.pieceList;
  47662. var pieceIndex = VisualMapping.findPieceIndex(value, pieceList, true);
  47663. if (pieceIndex != null) {
  47664. return linearMap(pieceIndex, [0, pieceList.length - 1], [0, 1], true);
  47665. }
  47666. },
  47667. category: function (value) {
  47668. var index = this.option.categories
  47669. ? this.option.categoryMap[value]
  47670. : value; // ordinal
  47671. return index == null ? CATEGORY_DEFAULT_VISUAL_INDEX : index;
  47672. },
  47673. fixed: noop
  47674. };
  47675. /**
  47676. * List available visual types.
  47677. *
  47678. * @public
  47679. * @return {Array.<string>}
  47680. */
  47681. VisualMapping.listVisualTypes = function () {
  47682. var visualTypes = [];
  47683. each$1(visualHandlers, function (handler, key) {
  47684. visualTypes.push(key);
  47685. });
  47686. return visualTypes;
  47687. };
  47688. /**
  47689. * @public
  47690. */
  47691. VisualMapping.addVisualHandler = function (name, handler) {
  47692. visualHandlers[name] = handler;
  47693. };
  47694. /**
  47695. * @public
  47696. */
  47697. VisualMapping.isValidType = function (visualType) {
  47698. return visualHandlers.hasOwnProperty(visualType);
  47699. };
  47700. /**
  47701. * Convinent method.
  47702. * Visual can be Object or Array or primary type.
  47703. *
  47704. * @public
  47705. */
  47706. VisualMapping.eachVisual = function (visual, callback, context) {
  47707. if (isObject$1(visual)) {
  47708. each$1(visual, callback, context);
  47709. }
  47710. else {
  47711. callback.call(context, visual);
  47712. }
  47713. };
  47714. VisualMapping.mapVisual = function (visual, callback, context) {
  47715. var isPrimary;
  47716. var newVisual = isArray(visual)
  47717. ? []
  47718. : isObject$1(visual)
  47719. ? {}
  47720. : (isPrimary = true, null);
  47721. VisualMapping.eachVisual(visual, function (v, key) {
  47722. var newVal = callback.call(context, v, key);
  47723. isPrimary ? (newVisual = newVal) : (newVisual[key] = newVal);
  47724. });
  47725. return newVisual;
  47726. };
  47727. /**
  47728. * @public
  47729. * @param {Object} obj
  47730. * @return {Object} new object containers visual values.
  47731. * If no visuals, return null.
  47732. */
  47733. VisualMapping.retrieveVisuals = function (obj) {
  47734. var ret = {};
  47735. var hasVisual;
  47736. obj && each$9(visualHandlers, function (h, visualType) {
  47737. if (obj.hasOwnProperty(visualType)) {
  47738. ret[visualType] = obj[visualType];
  47739. hasVisual = true;
  47740. }
  47741. });
  47742. return hasVisual ? ret : null;
  47743. };
  47744. /**
  47745. * Give order to visual types, considering colorSaturation, colorAlpha depends on color.
  47746. *
  47747. * @public
  47748. * @param {(Object|Array)} visualTypes If Object, like: {color: ..., colorSaturation: ...}
  47749. * IF Array, like: ['color', 'symbol', 'colorSaturation']
  47750. * @return {Array.<string>} Sorted visual types.
  47751. */
  47752. VisualMapping.prepareVisualTypes = function (visualTypes) {
  47753. if (isObject$5(visualTypes)) {
  47754. var types = [];
  47755. each$9(visualTypes, function (item, type) {
  47756. types.push(type);
  47757. });
  47758. visualTypes = types;
  47759. }
  47760. else if (isArray(visualTypes)) {
  47761. visualTypes = visualTypes.slice();
  47762. }
  47763. else {
  47764. return [];
  47765. }
  47766. visualTypes.sort(function (type1, type2) {
  47767. // color should be front of colorSaturation, colorAlpha, ...
  47768. // symbol and symbolSize do not matter.
  47769. return (type2 === 'color' && type1 !== 'color' && type1.indexOf('color') === 0)
  47770. ? 1 : -1;
  47771. });
  47772. return visualTypes;
  47773. };
  47774. /**
  47775. * 'color', 'colorSaturation', 'colorAlpha', ... are depends on 'color'.
  47776. * Other visuals are only depends on themself.
  47777. *
  47778. * @public
  47779. * @param {string} visualType1
  47780. * @param {string} visualType2
  47781. * @return {boolean}
  47782. */
  47783. VisualMapping.dependsOn = function (visualType1, visualType2) {
  47784. return visualType2 === 'color'
  47785. ? !!(visualType1 && visualType1.indexOf(visualType2) === 0)
  47786. : visualType1 === visualType2;
  47787. };
  47788. /**
  47789. * @param {number} value
  47790. * @param {Array.<Object>} pieceList [{value: ..., interval: [min, max]}, ...]
  47791. * Always from small to big.
  47792. * @param {boolean} [findClosestWhenOutside=false]
  47793. * @return {number} index
  47794. */
  47795. VisualMapping.findPieceIndex = function (value, pieceList, findClosestWhenOutside) {
  47796. var possibleI;
  47797. var abs = Infinity;
  47798. // value has the higher priority.
  47799. for (var i = 0, len = pieceList.length; i < len; i++) {
  47800. var pieceValue = pieceList[i].value;
  47801. if (pieceValue != null) {
  47802. if (pieceValue === value
  47803. // FIXME
  47804. // It is supposed to compare value according to value type of dimension,
  47805. // but currently value type can exactly be string or number.
  47806. // Compromise for numeric-like string (like '12'), especially
  47807. // in the case that visualMap.categories is ['22', '33'].
  47808. || (typeof pieceValue === 'string' && pieceValue === value + '')
  47809. ) {
  47810. return i;
  47811. }
  47812. findClosestWhenOutside && updatePossible(pieceValue, i);
  47813. }
  47814. }
  47815. for (var i = 0, len = pieceList.length; i < len; i++) {
  47816. var piece = pieceList[i];
  47817. var interval = piece.interval;
  47818. var close = piece.close;
  47819. if (interval) {
  47820. if (interval[0] === -Infinity) {
  47821. if (littleThan(close[1], value, interval[1])) {
  47822. return i;
  47823. }
  47824. }
  47825. else if (interval[1] === Infinity) {
  47826. if (littleThan(close[0], interval[0], value)) {
  47827. return i;
  47828. }
  47829. }
  47830. else if (
  47831. littleThan(close[0], interval[0], value)
  47832. && littleThan(close[1], value, interval[1])
  47833. ) {
  47834. return i;
  47835. }
  47836. findClosestWhenOutside && updatePossible(interval[0], i);
  47837. findClosestWhenOutside && updatePossible(interval[1], i);
  47838. }
  47839. }
  47840. if (findClosestWhenOutside) {
  47841. return value === Infinity
  47842. ? pieceList.length - 1
  47843. : value === -Infinity
  47844. ? 0
  47845. : possibleI;
  47846. }
  47847. function updatePossible(val, index) {
  47848. var newAbs = Math.abs(val - value);
  47849. if (newAbs < abs) {
  47850. abs = newAbs;
  47851. possibleI = index;
  47852. }
  47853. }
  47854. };
  47855. function littleThan(close, a, b) {
  47856. return close ? a <= b : a < b;
  47857. }
  47858. /*
  47859. * Licensed to the Apache Software Foundation (ASF) under one
  47860. * or more contributor license agreements. See the NOTICE file
  47861. * distributed with this work for additional information
  47862. * regarding copyright ownership. The ASF licenses this file
  47863. * to you under the Apache License, Version 2.0 (the
  47864. * "License"); you may not use this file except in compliance
  47865. * with the License. You may obtain a copy of the License at
  47866. *
  47867. * http://www.apache.org/licenses/LICENSE-2.0
  47868. *
  47869. * Unless required by applicable law or agreed to in writing,
  47870. * software distributed under the License is distributed on an
  47871. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47872. * KIND, either express or implied. See the License for the
  47873. * specific language governing permissions and limitations
  47874. * under the License.
  47875. */
  47876. var isArray$2 = isArray;
  47877. var ITEM_STYLE_NORMAL = 'itemStyle';
  47878. var treemapVisual = {
  47879. seriesType: 'treemap',
  47880. reset: function (seriesModel, ecModel, api, payload) {
  47881. var tree = seriesModel.getData().tree;
  47882. var root = tree.root;
  47883. var seriesItemStyleModel = seriesModel.getModel(ITEM_STYLE_NORMAL);
  47884. if (root.isRemoved()) {
  47885. return;
  47886. }
  47887. var levelItemStyles = map(tree.levelModels, function (levelModel) {
  47888. return levelModel ? levelModel.get(ITEM_STYLE_NORMAL) : null;
  47889. });
  47890. travelTree(
  47891. root, // Visual should calculate from tree root but not view root.
  47892. {},
  47893. levelItemStyles,
  47894. seriesItemStyleModel,
  47895. seriesModel.getViewRoot().getAncestors(),
  47896. seriesModel
  47897. );
  47898. }
  47899. };
  47900. function travelTree(
  47901. node, designatedVisual, levelItemStyles, seriesItemStyleModel,
  47902. viewRootAncestors, seriesModel
  47903. ) {
  47904. var nodeModel = node.getModel();
  47905. var nodeLayout = node.getLayout();
  47906. // Optimize
  47907. if (!nodeLayout || nodeLayout.invisible || !nodeLayout.isInView) {
  47908. return;
  47909. }
  47910. var nodeItemStyleModel = node.getModel(ITEM_STYLE_NORMAL);
  47911. var levelItemStyle = levelItemStyles[node.depth];
  47912. var visuals = buildVisuals(
  47913. nodeItemStyleModel, designatedVisual, levelItemStyle, seriesItemStyleModel
  47914. );
  47915. // calculate border color
  47916. var borderColor = nodeItemStyleModel.get('borderColor');
  47917. var borderColorSaturation = nodeItemStyleModel.get('borderColorSaturation');
  47918. var thisNodeColor;
  47919. if (borderColorSaturation != null) {
  47920. // For performance, do not always execute 'calculateColor'.
  47921. thisNodeColor = calculateColor(visuals, node);
  47922. borderColor = calculateBorderColor(borderColorSaturation, thisNodeColor);
  47923. }
  47924. node.setVisual('borderColor', borderColor);
  47925. var viewChildren = node.viewChildren;
  47926. if (!viewChildren || !viewChildren.length) {
  47927. thisNodeColor = calculateColor(visuals, node);
  47928. // Apply visual to this node.
  47929. node.setVisual('color', thisNodeColor);
  47930. }
  47931. else {
  47932. var mapping = buildVisualMapping(
  47933. node, nodeModel, nodeLayout, nodeItemStyleModel, visuals, viewChildren
  47934. );
  47935. // Designate visual to children.
  47936. each$1(viewChildren, function (child, index) {
  47937. // If higher than viewRoot, only ancestors of viewRoot is needed to visit.
  47938. if (child.depth >= viewRootAncestors.length
  47939. || child === viewRootAncestors[child.depth]
  47940. ) {
  47941. var childVisual = mapVisual$1(
  47942. nodeModel, visuals, child, index, mapping, seriesModel
  47943. );
  47944. travelTree(
  47945. child, childVisual, levelItemStyles, seriesItemStyleModel,
  47946. viewRootAncestors, seriesModel
  47947. );
  47948. }
  47949. });
  47950. }
  47951. }
  47952. function buildVisuals(
  47953. nodeItemStyleModel, designatedVisual, levelItemStyle, seriesItemStyleModel
  47954. ) {
  47955. var visuals = extend({}, designatedVisual);
  47956. each$1(['color', 'colorAlpha', 'colorSaturation'], function (visualName) {
  47957. // Priority: thisNode > thisLevel > parentNodeDesignated > seriesModel
  47958. var val = nodeItemStyleModel.get(visualName, true); // Ignore parent
  47959. val == null && levelItemStyle && (val = levelItemStyle[visualName]);
  47960. val == null && (val = designatedVisual[visualName]);
  47961. val == null && (val = seriesItemStyleModel.get(visualName));
  47962. val != null && (visuals[visualName] = val);
  47963. });
  47964. return visuals;
  47965. }
  47966. function calculateColor(visuals) {
  47967. var color = getValueVisualDefine(visuals, 'color');
  47968. if (color) {
  47969. var colorAlpha = getValueVisualDefine(visuals, 'colorAlpha');
  47970. var colorSaturation = getValueVisualDefine(visuals, 'colorSaturation');
  47971. if (colorSaturation) {
  47972. color = modifyHSL(color, null, null, colorSaturation);
  47973. }
  47974. if (colorAlpha) {
  47975. color = modifyAlpha(color, colorAlpha);
  47976. }
  47977. return color;
  47978. }
  47979. }
  47980. function calculateBorderColor(borderColorSaturation, thisNodeColor) {
  47981. return thisNodeColor != null
  47982. ? modifyHSL(thisNodeColor, null, null, borderColorSaturation)
  47983. : null;
  47984. }
  47985. function getValueVisualDefine(visuals, name) {
  47986. var value = visuals[name];
  47987. if (value != null && value !== 'none') {
  47988. return value;
  47989. }
  47990. }
  47991. function buildVisualMapping(
  47992. node, nodeModel, nodeLayout, nodeItemStyleModel, visuals, viewChildren
  47993. ) {
  47994. if (!viewChildren || !viewChildren.length) {
  47995. return;
  47996. }
  47997. var rangeVisual = getRangeVisual(nodeModel, 'color')
  47998. || (
  47999. visuals.color != null
  48000. && visuals.color !== 'none'
  48001. && (
  48002. getRangeVisual(nodeModel, 'colorAlpha')
  48003. || getRangeVisual(nodeModel, 'colorSaturation')
  48004. )
  48005. );
  48006. if (!rangeVisual) {
  48007. return;
  48008. }
  48009. var visualMin = nodeModel.get('visualMin');
  48010. var visualMax = nodeModel.get('visualMax');
  48011. var dataExtent = nodeLayout.dataExtent.slice();
  48012. visualMin != null && visualMin < dataExtent[0] && (dataExtent[0] = visualMin);
  48013. visualMax != null && visualMax > dataExtent[1] && (dataExtent[1] = visualMax);
  48014. var colorMappingBy = nodeModel.get('colorMappingBy');
  48015. var opt = {
  48016. type: rangeVisual.name,
  48017. dataExtent: dataExtent,
  48018. visual: rangeVisual.range
  48019. };
  48020. if (opt.type === 'color'
  48021. && (colorMappingBy === 'index' || colorMappingBy === 'id')
  48022. ) {
  48023. opt.mappingMethod = 'category';
  48024. opt.loop = true;
  48025. // categories is ordinal, so do not set opt.categories.
  48026. }
  48027. else {
  48028. opt.mappingMethod = 'linear';
  48029. }
  48030. var mapping = new VisualMapping(opt);
  48031. mapping.__drColorMappingBy = colorMappingBy;
  48032. return mapping;
  48033. }
  48034. // Notice: If we dont have the attribute 'colorRange', but only use
  48035. // attribute 'color' to represent both concepts of 'colorRange' and 'color',
  48036. // (It means 'colorRange' when 'color' is Array, means 'color' when not array),
  48037. // this problem will be encountered:
  48038. // If a level-1 node dont have children, and its siblings has children,
  48039. // and colorRange is set on level-1, then the node can not be colored.
  48040. // So we separate 'colorRange' and 'color' to different attributes.
  48041. function getRangeVisual(nodeModel, name) {
  48042. // 'colorRange', 'colorARange', 'colorSRange'.
  48043. // If not exsits on this node, fetch from levels and series.
  48044. var range = nodeModel.get(name);
  48045. return (isArray$2(range) && range.length) ? {name: name, range: range} : null;
  48046. }
  48047. function mapVisual$1(nodeModel, visuals, child, index, mapping, seriesModel) {
  48048. var childVisuals = extend({}, visuals);
  48049. if (mapping) {
  48050. var mappingType = mapping.type;
  48051. var colorMappingBy = mappingType === 'color' && mapping.__drColorMappingBy;
  48052. var value = colorMappingBy === 'index'
  48053. ? index
  48054. : colorMappingBy === 'id'
  48055. ? seriesModel.mapIdToIndex(child.getId())
  48056. : child.getValue(nodeModel.get('visualDimension'));
  48057. childVisuals[mappingType] = mapping.mapValueToVisual(value);
  48058. }
  48059. return childVisuals;
  48060. }
  48061. /*
  48062. * Licensed to the Apache Software Foundation (ASF) under one
  48063. * or more contributor license agreements. See the NOTICE file
  48064. * distributed with this work for additional information
  48065. * regarding copyright ownership. The ASF licenses this file
  48066. * to you under the Apache License, Version 2.0 (the
  48067. * "License"); you may not use this file except in compliance
  48068. * with the License. You may obtain a copy of the License at
  48069. *
  48070. * http://www.apache.org/licenses/LICENSE-2.0
  48071. *
  48072. * Unless required by applicable law or agreed to in writing,
  48073. * software distributed under the License is distributed on an
  48074. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48075. * KIND, either express or implied. See the License for the
  48076. * specific language governing permissions and limitations
  48077. * under the License.
  48078. */
  48079. /*
  48080. * A third-party license is embeded for some of the code in this file:
  48081. * The treemap layout implementation was originally copied from
  48082. * "d3.js" with some modifications made for this project.
  48083. * (See more details in the comment of the method "squarify" below.)
  48084. * The use of the source code of this file is also subject to the terms
  48085. * and consitions of the license of "d3.js" (BSD-3Clause, see
  48086. * </licenses/LICENSE-d3>).
  48087. */
  48088. var mathMax$5 = Math.max;
  48089. var mathMin$5 = Math.min;
  48090. var retrieveValue = retrieve;
  48091. var each$10 = each$1;
  48092. var PATH_BORDER_WIDTH = ['itemStyle', 'borderWidth'];
  48093. var PATH_GAP_WIDTH = ['itemStyle', 'gapWidth'];
  48094. var PATH_UPPER_LABEL_SHOW = ['upperLabel', 'show'];
  48095. var PATH_UPPER_LABEL_HEIGHT = ['upperLabel', 'height'];
  48096. /**
  48097. * @public
  48098. */
  48099. var treemapLayout = {
  48100. seriesType: 'treemap',
  48101. reset: function (seriesModel, ecModel, api, payload) {
  48102. // Layout result in each node:
  48103. // {x, y, width, height, area, borderWidth}
  48104. var ecWidth = api.getWidth();
  48105. var ecHeight = api.getHeight();
  48106. var seriesOption = seriesModel.option;
  48107. var layoutInfo = getLayoutRect(
  48108. seriesModel.getBoxLayoutParams(),
  48109. {
  48110. width: api.getWidth(),
  48111. height: api.getHeight()
  48112. }
  48113. );
  48114. var size = seriesOption.size || []; // Compatible with ec2.
  48115. var containerWidth = parsePercent$1(
  48116. retrieveValue(layoutInfo.width, size[0]),
  48117. ecWidth
  48118. );
  48119. var containerHeight = parsePercent$1(
  48120. retrieveValue(layoutInfo.height, size[1]),
  48121. ecHeight
  48122. );
  48123. // Fetch payload info.
  48124. var payloadType = payload && payload.type;
  48125. var types = ['treemapZoomToNode', 'treemapRootToNode'];
  48126. var targetInfo = retrieveTargetInfo(payload, types, seriesModel);
  48127. var rootRect = (payloadType === 'treemapRender' || payloadType === 'treemapMove')
  48128. ? payload.rootRect : null;
  48129. var viewRoot = seriesModel.getViewRoot();
  48130. var viewAbovePath = getPathToRoot(viewRoot);
  48131. if (payloadType !== 'treemapMove') {
  48132. var rootSize = payloadType === 'treemapZoomToNode'
  48133. ? estimateRootSize(
  48134. seriesModel, targetInfo, viewRoot, containerWidth, containerHeight
  48135. )
  48136. : rootRect
  48137. ? [rootRect.width, rootRect.height]
  48138. : [containerWidth, containerHeight];
  48139. var sort = seriesOption.sort;
  48140. if (sort && sort !== 'asc' && sort !== 'desc') {
  48141. sort = 'desc';
  48142. }
  48143. var options = {
  48144. squareRatio: seriesOption.squareRatio,
  48145. sort: sort,
  48146. leafDepth: seriesOption.leafDepth
  48147. };
  48148. // layout should be cleared because using updateView but not update.
  48149. viewRoot.hostTree.clearLayouts();
  48150. // TODO
  48151. // optimize: if out of view clip, do not layout.
  48152. // But take care that if do not render node out of view clip,
  48153. // how to calculate start po
  48154. var viewRootLayout = {
  48155. x: 0, y: 0,
  48156. width: rootSize[0], height: rootSize[1],
  48157. area: rootSize[0] * rootSize[1]
  48158. };
  48159. viewRoot.setLayout(viewRootLayout);
  48160. squarify(viewRoot, options, false, 0);
  48161. // Supplement layout.
  48162. var viewRootLayout = viewRoot.getLayout();
  48163. each$10(viewAbovePath, function (node, index) {
  48164. var childValue = (viewAbovePath[index + 1] || viewRoot).getValue();
  48165. node.setLayout(extend(
  48166. {dataExtent: [childValue, childValue], borderWidth: 0, upperHeight: 0},
  48167. viewRootLayout
  48168. ));
  48169. });
  48170. }
  48171. var treeRoot = seriesModel.getData().tree.root;
  48172. treeRoot.setLayout(
  48173. calculateRootPosition(layoutInfo, rootRect, targetInfo),
  48174. true
  48175. );
  48176. seriesModel.setLayoutInfo(layoutInfo);
  48177. // FIXME
  48178. // 现在没有clip功能,暂时取ec高宽。
  48179. prunning(
  48180. treeRoot,
  48181. // Transform to base element coordinate system.
  48182. new BoundingRect(-layoutInfo.x, -layoutInfo.y, ecWidth, ecHeight),
  48183. viewAbovePath,
  48184. viewRoot,
  48185. 0
  48186. );
  48187. }
  48188. };
  48189. /**
  48190. * Layout treemap with squarify algorithm.
  48191. * The original presentation of this algorithm
  48192. * was made by Mark Bruls, Kees Huizing, and Jarke J. van Wijk
  48193. * <https://graphics.ethz.ch/teaching/scivis_common/Literature/squarifiedTreeMaps.pdf>.
  48194. * The implementation of this algorithm was originally copied from "d3.js"
  48195. * <https://github.com/d3/d3/blob/9cc9a875e636a1dcf36cc1e07bdf77e1ad6e2c74/src/layout/treemap.js>
  48196. * with some modifications made for this program.
  48197. * See the license statement at the head of this file.
  48198. *
  48199. * @protected
  48200. * @param {module:echarts/data/Tree~TreeNode} node
  48201. * @param {Object} options
  48202. * @param {string} options.sort 'asc' or 'desc'
  48203. * @param {number} options.squareRatio
  48204. * @param {boolean} hideChildren
  48205. * @param {number} depth
  48206. */
  48207. function squarify(node, options, hideChildren, depth) {
  48208. var width;
  48209. var height;
  48210. if (node.isRemoved()) {
  48211. return;
  48212. }
  48213. var thisLayout = node.getLayout();
  48214. width = thisLayout.width;
  48215. height = thisLayout.height;
  48216. // Considering border and gap
  48217. var nodeModel = node.getModel();
  48218. var borderWidth = nodeModel.get(PATH_BORDER_WIDTH);
  48219. var halfGapWidth = nodeModel.get(PATH_GAP_WIDTH) / 2;
  48220. var upperLabelHeight = getUpperLabelHeight(nodeModel);
  48221. var upperHeight = Math.max(borderWidth, upperLabelHeight);
  48222. var layoutOffset = borderWidth - halfGapWidth;
  48223. var layoutOffsetUpper = upperHeight - halfGapWidth;
  48224. var nodeModel = node.getModel();
  48225. node.setLayout({
  48226. borderWidth: borderWidth,
  48227. upperHeight: upperHeight,
  48228. upperLabelHeight: upperLabelHeight
  48229. }, true);
  48230. width = mathMax$5(width - 2 * layoutOffset, 0);
  48231. height = mathMax$5(height - layoutOffset - layoutOffsetUpper, 0);
  48232. var totalArea = width * height;
  48233. var viewChildren = initChildren(
  48234. node, nodeModel, totalArea, options, hideChildren, depth
  48235. );
  48236. if (!viewChildren.length) {
  48237. return;
  48238. }
  48239. var rect = {x: layoutOffset, y: layoutOffsetUpper, width: width, height: height};
  48240. var rowFixedLength = mathMin$5(width, height);
  48241. var best = Infinity; // the best row score so far
  48242. var row = [];
  48243. row.area = 0;
  48244. for (var i = 0, len = viewChildren.length; i < len;) {
  48245. var child = viewChildren[i];
  48246. row.push(child);
  48247. row.area += child.getLayout().area;
  48248. var score = worst(row, rowFixedLength, options.squareRatio);
  48249. // continue with this orientation
  48250. if (score <= best) {
  48251. i++;
  48252. best = score;
  48253. }
  48254. // abort, and try a different orientation
  48255. else {
  48256. row.area -= row.pop().getLayout().area;
  48257. position(row, rowFixedLength, rect, halfGapWidth, false);
  48258. rowFixedLength = mathMin$5(rect.width, rect.height);
  48259. row.length = row.area = 0;
  48260. best = Infinity;
  48261. }
  48262. }
  48263. if (row.length) {
  48264. position(row, rowFixedLength, rect, halfGapWidth, true);
  48265. }
  48266. if (!hideChildren) {
  48267. var childrenVisibleMin = nodeModel.get('childrenVisibleMin');
  48268. if (childrenVisibleMin != null && totalArea < childrenVisibleMin) {
  48269. hideChildren = true;
  48270. }
  48271. }
  48272. for (var i = 0, len = viewChildren.length; i < len; i++) {
  48273. squarify(viewChildren[i], options, hideChildren, depth + 1);
  48274. }
  48275. }
  48276. /**
  48277. * Set area to each child, and calculate data extent for visual coding.
  48278. */
  48279. function initChildren(node, nodeModel, totalArea, options, hideChildren, depth) {
  48280. var viewChildren = node.children || [];
  48281. var orderBy = options.sort;
  48282. orderBy !== 'asc' && orderBy !== 'desc' && (orderBy = null);
  48283. var overLeafDepth = options.leafDepth != null && options.leafDepth <= depth;
  48284. // leafDepth has higher priority.
  48285. if (hideChildren && !overLeafDepth) {
  48286. return (node.viewChildren = []);
  48287. }
  48288. // Sort children, order by desc.
  48289. viewChildren = filter(viewChildren, function (child) {
  48290. return !child.isRemoved();
  48291. });
  48292. sort$1(viewChildren, orderBy);
  48293. var info = statistic(nodeModel, viewChildren, orderBy);
  48294. if (info.sum === 0) {
  48295. return (node.viewChildren = []);
  48296. }
  48297. info.sum = filterByThreshold(nodeModel, totalArea, info.sum, orderBy, viewChildren);
  48298. if (info.sum === 0) {
  48299. return (node.viewChildren = []);
  48300. }
  48301. // Set area to each child.
  48302. for (var i = 0, len = viewChildren.length; i < len; i++) {
  48303. var area = viewChildren[i].getValue() / info.sum * totalArea;
  48304. // Do not use setLayout({...}, true), because it is needed to clear last layout.
  48305. viewChildren[i].setLayout({area: area});
  48306. }
  48307. if (overLeafDepth) {
  48308. viewChildren.length && node.setLayout({isLeafRoot: true}, true);
  48309. viewChildren.length = 0;
  48310. }
  48311. node.viewChildren = viewChildren;
  48312. node.setLayout({dataExtent: info.dataExtent}, true);
  48313. return viewChildren;
  48314. }
  48315. /**
  48316. * Consider 'visibleMin'. Modify viewChildren and get new sum.
  48317. */
  48318. function filterByThreshold(nodeModel, totalArea, sum, orderBy, orderedChildren) {
  48319. // visibleMin is not supported yet when no option.sort.
  48320. if (!orderBy) {
  48321. return sum;
  48322. }
  48323. var visibleMin = nodeModel.get('visibleMin');
  48324. var len = orderedChildren.length;
  48325. var deletePoint = len;
  48326. // Always travel from little value to big value.
  48327. for (var i = len - 1; i >= 0; i--) {
  48328. var value = orderedChildren[
  48329. orderBy === 'asc' ? len - i - 1 : i
  48330. ].getValue();
  48331. if (value / sum * totalArea < visibleMin) {
  48332. deletePoint = i;
  48333. sum -= value;
  48334. }
  48335. }
  48336. orderBy === 'asc'
  48337. ? orderedChildren.splice(0, len - deletePoint)
  48338. : orderedChildren.splice(deletePoint, len - deletePoint);
  48339. return sum;
  48340. }
  48341. /**
  48342. * Sort
  48343. */
  48344. function sort$1(viewChildren, orderBy) {
  48345. if (orderBy) {
  48346. viewChildren.sort(function (a, b) {
  48347. var diff = orderBy === 'asc'
  48348. ? a.getValue() - b.getValue() : b.getValue() - a.getValue();
  48349. return diff === 0
  48350. ? (orderBy === 'asc'
  48351. ? a.dataIndex - b.dataIndex : b.dataIndex - a.dataIndex
  48352. )
  48353. : diff;
  48354. });
  48355. }
  48356. return viewChildren;
  48357. }
  48358. /**
  48359. * Statistic
  48360. */
  48361. function statistic(nodeModel, children, orderBy) {
  48362. // Calculate sum.
  48363. var sum = 0;
  48364. for (var i = 0, len = children.length; i < len; i++) {
  48365. sum += children[i].getValue();
  48366. }
  48367. // Statistic data extent for latter visual coding.
  48368. // Notice: data extent should be calculate based on raw children
  48369. // but not filtered view children, otherwise visual mapping will not
  48370. // be stable when zoom (where children is filtered by visibleMin).
  48371. var dimension = nodeModel.get('visualDimension');
  48372. var dataExtent;
  48373. // The same as area dimension.
  48374. if (!children || !children.length) {
  48375. dataExtent = [NaN, NaN];
  48376. }
  48377. else if (dimension === 'value' && orderBy) {
  48378. dataExtent = [
  48379. children[children.length - 1].getValue(),
  48380. children[0].getValue()
  48381. ];
  48382. orderBy === 'asc' && dataExtent.reverse();
  48383. }
  48384. // Other dimension.
  48385. else {
  48386. var dataExtent = [Infinity, -Infinity];
  48387. each$10(children, function (child) {
  48388. var value = child.getValue(dimension);
  48389. value < dataExtent[0] && (dataExtent[0] = value);
  48390. value > dataExtent[1] && (dataExtent[1] = value);
  48391. });
  48392. }
  48393. return {sum: sum, dataExtent: dataExtent};
  48394. }
  48395. /**
  48396. * Computes the score for the specified row,
  48397. * as the worst aspect ratio.
  48398. */
  48399. function worst(row, rowFixedLength, ratio) {
  48400. var areaMax = 0;
  48401. var areaMin = Infinity;
  48402. for (var i = 0, area, len = row.length; i < len; i++) {
  48403. area = row[i].getLayout().area;
  48404. if (area) {
  48405. area < areaMin && (areaMin = area);
  48406. area > areaMax && (areaMax = area);
  48407. }
  48408. }
  48409. var squareArea = row.area * row.area;
  48410. var f = rowFixedLength * rowFixedLength * ratio;
  48411. return squareArea
  48412. ? mathMax$5(
  48413. (f * areaMax) / squareArea,
  48414. squareArea / (f * areaMin)
  48415. )
  48416. : Infinity;
  48417. }
  48418. /**
  48419. * Positions the specified row of nodes. Modifies `rect`.
  48420. */
  48421. function position(row, rowFixedLength, rect, halfGapWidth, flush) {
  48422. // When rowFixedLength === rect.width,
  48423. // it is horizontal subdivision,
  48424. // rowFixedLength is the width of the subdivision,
  48425. // rowOtherLength is the height of the subdivision,
  48426. // and nodes will be positioned from left to right.
  48427. // wh[idx0WhenH] means: when horizontal,
  48428. // wh[idx0WhenH] => wh[0] => 'width'.
  48429. // xy[idx1WhenH] => xy[1] => 'y'.
  48430. var idx0WhenH = rowFixedLength === rect.width ? 0 : 1;
  48431. var idx1WhenH = 1 - idx0WhenH;
  48432. var xy = ['x', 'y'];
  48433. var wh = ['width', 'height'];
  48434. var last = rect[xy[idx0WhenH]];
  48435. var rowOtherLength = rowFixedLength
  48436. ? row.area / rowFixedLength : 0;
  48437. if (flush || rowOtherLength > rect[wh[idx1WhenH]]) {
  48438. rowOtherLength = rect[wh[idx1WhenH]]; // over+underflow
  48439. }
  48440. for (var i = 0, rowLen = row.length; i < rowLen; i++) {
  48441. var node = row[i];
  48442. var nodeLayout = {};
  48443. var step = rowOtherLength
  48444. ? node.getLayout().area / rowOtherLength : 0;
  48445. var wh1 = nodeLayout[wh[idx1WhenH]] = mathMax$5(rowOtherLength - 2 * halfGapWidth, 0);
  48446. // We use Math.max/min to avoid negative width/height when considering gap width.
  48447. var remain = rect[xy[idx0WhenH]] + rect[wh[idx0WhenH]] - last;
  48448. var modWH = (i === rowLen - 1 || remain < step) ? remain : step;
  48449. var wh0 = nodeLayout[wh[idx0WhenH]] = mathMax$5(modWH - 2 * halfGapWidth, 0);
  48450. nodeLayout[xy[idx1WhenH]] = rect[xy[idx1WhenH]] + mathMin$5(halfGapWidth, wh1 / 2);
  48451. nodeLayout[xy[idx0WhenH]] = last + mathMin$5(halfGapWidth, wh0 / 2);
  48452. last += modWH;
  48453. node.setLayout(nodeLayout, true);
  48454. }
  48455. rect[xy[idx1WhenH]] += rowOtherLength;
  48456. rect[wh[idx1WhenH]] -= rowOtherLength;
  48457. }
  48458. // Return [containerWidth, containerHeight] as defualt.
  48459. function estimateRootSize(seriesModel, targetInfo, viewRoot, containerWidth, containerHeight) {
  48460. // If targetInfo.node exists, we zoom to the node,
  48461. // so estimate whold width and heigth by target node.
  48462. var currNode = (targetInfo || {}).node;
  48463. var defaultSize = [containerWidth, containerHeight];
  48464. if (!currNode || currNode === viewRoot) {
  48465. return defaultSize;
  48466. }
  48467. var parent;
  48468. var viewArea = containerWidth * containerHeight;
  48469. var area = viewArea * seriesModel.option.zoomToNodeRatio;
  48470. while (parent = currNode.parentNode) { // jshint ignore:line
  48471. var sum = 0;
  48472. var siblings = parent.children;
  48473. for (var i = 0, len = siblings.length; i < len; i++) {
  48474. sum += siblings[i].getValue();
  48475. }
  48476. var currNodeValue = currNode.getValue();
  48477. if (currNodeValue === 0) {
  48478. return defaultSize;
  48479. }
  48480. area *= sum / currNodeValue;
  48481. // Considering border, suppose aspect ratio is 1.
  48482. var parentModel = parent.getModel();
  48483. var borderWidth = parentModel.get(PATH_BORDER_WIDTH);
  48484. var upperHeight = Math.max(borderWidth, getUpperLabelHeight(parentModel, borderWidth));
  48485. area += 4 * borderWidth * borderWidth
  48486. + (3 * borderWidth + upperHeight) * Math.pow(area, 0.5);
  48487. area > MAX_SAFE_INTEGER && (area = MAX_SAFE_INTEGER);
  48488. currNode = parent;
  48489. }
  48490. area < viewArea && (area = viewArea);
  48491. var scale = Math.pow(area / viewArea, 0.5);
  48492. return [containerWidth * scale, containerHeight * scale];
  48493. }
  48494. // Root postion base on coord of containerGroup
  48495. function calculateRootPosition(layoutInfo, rootRect, targetInfo) {
  48496. if (rootRect) {
  48497. return {x: rootRect.x, y: rootRect.y};
  48498. }
  48499. var defaultPosition = {x: 0, y: 0};
  48500. if (!targetInfo) {
  48501. return defaultPosition;
  48502. }
  48503. // If targetInfo is fetched by 'retrieveTargetInfo',
  48504. // old tree and new tree are the same tree,
  48505. // so the node still exists and we can visit it.
  48506. var targetNode = targetInfo.node;
  48507. var layout = targetNode.getLayout();
  48508. if (!layout) {
  48509. return defaultPosition;
  48510. }
  48511. // Transform coord from local to container.
  48512. var targetCenter = [layout.width / 2, layout.height / 2];
  48513. var node = targetNode;
  48514. while (node) {
  48515. var nodeLayout = node.getLayout();
  48516. targetCenter[0] += nodeLayout.x;
  48517. targetCenter[1] += nodeLayout.y;
  48518. node = node.parentNode;
  48519. }
  48520. return {
  48521. x: layoutInfo.width / 2 - targetCenter[0],
  48522. y: layoutInfo.height / 2 - targetCenter[1]
  48523. };
  48524. }
  48525. // Mark nodes visible for prunning when visual coding and rendering.
  48526. // Prunning depends on layout and root position, so we have to do it after layout.
  48527. function prunning(node, clipRect, viewAbovePath, viewRoot, depth) {
  48528. var nodeLayout = node.getLayout();
  48529. var nodeInViewAbovePath = viewAbovePath[depth];
  48530. var isAboveViewRoot = nodeInViewAbovePath && nodeInViewAbovePath === node;
  48531. if (
  48532. (nodeInViewAbovePath && !isAboveViewRoot)
  48533. || (depth === viewAbovePath.length && node !== viewRoot)
  48534. ) {
  48535. return;
  48536. }
  48537. node.setLayout({
  48538. // isInView means: viewRoot sub tree + viewAbovePath
  48539. isInView: true,
  48540. // invisible only means: outside view clip so that the node can not
  48541. // see but still layout for animation preparation but not render.
  48542. invisible: !isAboveViewRoot && !clipRect.intersect(nodeLayout),
  48543. isAboveViewRoot: isAboveViewRoot
  48544. }, true);
  48545. // Transform to child coordinate.
  48546. var childClipRect = new BoundingRect(
  48547. clipRect.x - nodeLayout.x,
  48548. clipRect.y - nodeLayout.y,
  48549. clipRect.width,
  48550. clipRect.height
  48551. );
  48552. each$10(node.viewChildren || [], function (child) {
  48553. prunning(child, childClipRect, viewAbovePath, viewRoot, depth + 1);
  48554. });
  48555. }
  48556. function getUpperLabelHeight(model) {
  48557. return model.get(PATH_UPPER_LABEL_SHOW) ? model.get(PATH_UPPER_LABEL_HEIGHT) : 0;
  48558. }
  48559. /*
  48560. * Licensed to the Apache Software Foundation (ASF) under one
  48561. * or more contributor license agreements. See the NOTICE file
  48562. * distributed with this work for additional information
  48563. * regarding copyright ownership. The ASF licenses this file
  48564. * to you under the Apache License, Version 2.0 (the
  48565. * "License"); you may not use this file except in compliance
  48566. * with the License. You may obtain a copy of the License at
  48567. *
  48568. * http://www.apache.org/licenses/LICENSE-2.0
  48569. *
  48570. * Unless required by applicable law or agreed to in writing,
  48571. * software distributed under the License is distributed on an
  48572. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48573. * KIND, either express or implied. See the License for the
  48574. * specific language governing permissions and limitations
  48575. * under the License.
  48576. */
  48577. registerVisual(treemapVisual);
  48578. registerLayout(treemapLayout);
  48579. /*
  48580. * Licensed to the Apache Software Foundation (ASF) under one
  48581. * or more contributor license agreements. See the NOTICE file
  48582. * distributed with this work for additional information
  48583. * regarding copyright ownership. The ASF licenses this file
  48584. * to you under the Apache License, Version 2.0 (the
  48585. * "License"); you may not use this file except in compliance
  48586. * with the License. You may obtain a copy of the License at
  48587. *
  48588. * http://www.apache.org/licenses/LICENSE-2.0
  48589. *
  48590. * Unless required by applicable law or agreed to in writing,
  48591. * software distributed under the License is distributed on an
  48592. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48593. * KIND, either express or implied. See the License for the
  48594. * specific language governing permissions and limitations
  48595. * under the License.
  48596. */
  48597. // id may be function name of Object, add a prefix to avoid this problem.
  48598. function generateNodeKey(id) {
  48599. return '_EC_' + id;
  48600. }
  48601. /**
  48602. * @alias module:echarts/data/Graph
  48603. * @constructor
  48604. * @param {boolean} directed
  48605. */
  48606. var Graph = function (directed) {
  48607. /**
  48608. * 是否是有向图
  48609. * @type {boolean}
  48610. * @private
  48611. */
  48612. this._directed = directed || false;
  48613. /**
  48614. * @type {Array.<module:echarts/data/Graph.Node>}
  48615. * @readOnly
  48616. */
  48617. this.nodes = [];
  48618. /**
  48619. * @type {Array.<module:echarts/data/Graph.Edge>}
  48620. * @readOnly
  48621. */
  48622. this.edges = [];
  48623. /**
  48624. * @type {Object.<string, module:echarts/data/Graph.Node>}
  48625. * @private
  48626. */
  48627. this._nodesMap = {};
  48628. /**
  48629. * @type {Object.<string, module:echarts/data/Graph.Edge>}
  48630. * @private
  48631. */
  48632. this._edgesMap = {};
  48633. /**
  48634. * @type {module:echarts/data/List}
  48635. * @readOnly
  48636. */
  48637. this.data;
  48638. /**
  48639. * @type {module:echarts/data/List}
  48640. * @readOnly
  48641. */
  48642. this.edgeData;
  48643. };
  48644. var graphProto = Graph.prototype;
  48645. /**
  48646. * @type {string}
  48647. */
  48648. graphProto.type = 'graph';
  48649. /**
  48650. * If is directed graph
  48651. * @return {boolean}
  48652. */
  48653. graphProto.isDirected = function () {
  48654. return this._directed;
  48655. };
  48656. /**
  48657. * Add a new node
  48658. * @param {string} id
  48659. * @param {number} [dataIndex]
  48660. */
  48661. graphProto.addNode = function (id, dataIndex) {
  48662. id = id == null ? ('' + dataIndex) : ('' + id);
  48663. var nodesMap = this._nodesMap;
  48664. if (nodesMap[generateNodeKey(id)]) {
  48665. if (__DEV__) {
  48666. console.error('Graph nodes have duplicate name or id');
  48667. }
  48668. return;
  48669. }
  48670. var node = new Node(id, dataIndex);
  48671. node.hostGraph = this;
  48672. this.nodes.push(node);
  48673. nodesMap[generateNodeKey(id)] = node;
  48674. return node;
  48675. };
  48676. /**
  48677. * Get node by data index
  48678. * @param {number} dataIndex
  48679. * @return {module:echarts/data/Graph~Node}
  48680. */
  48681. graphProto.getNodeByIndex = function (dataIndex) {
  48682. var rawIdx = this.data.getRawIndex(dataIndex);
  48683. return this.nodes[rawIdx];
  48684. };
  48685. /**
  48686. * Get node by id
  48687. * @param {string} id
  48688. * @return {module:echarts/data/Graph.Node}
  48689. */
  48690. graphProto.getNodeById = function (id) {
  48691. return this._nodesMap[generateNodeKey(id)];
  48692. };
  48693. /**
  48694. * Add a new edge
  48695. * @param {number|string|module:echarts/data/Graph.Node} n1
  48696. * @param {number|string|module:echarts/data/Graph.Node} n2
  48697. * @param {number} [dataIndex=-1]
  48698. * @return {module:echarts/data/Graph.Edge}
  48699. */
  48700. graphProto.addEdge = function (n1, n2, dataIndex) {
  48701. var nodesMap = this._nodesMap;
  48702. var edgesMap = this._edgesMap;
  48703. // PNEDING
  48704. if (typeof n1 === 'number') {
  48705. n1 = this.nodes[n1];
  48706. }
  48707. if (typeof n2 === 'number') {
  48708. n2 = this.nodes[n2];
  48709. }
  48710. if (!Node.isInstance(n1)) {
  48711. n1 = nodesMap[generateNodeKey(n1)];
  48712. }
  48713. if (!Node.isInstance(n2)) {
  48714. n2 = nodesMap[generateNodeKey(n2)];
  48715. }
  48716. if (!n1 || !n2) {
  48717. return;
  48718. }
  48719. var key = n1.id + '-' + n2.id;
  48720. // PENDING
  48721. if (edgesMap[key]) {
  48722. return;
  48723. }
  48724. var edge = new Edge(n1, n2, dataIndex);
  48725. edge.hostGraph = this;
  48726. if (this._directed) {
  48727. n1.outEdges.push(edge);
  48728. n2.inEdges.push(edge);
  48729. }
  48730. n1.edges.push(edge);
  48731. if (n1 !== n2) {
  48732. n2.edges.push(edge);
  48733. }
  48734. this.edges.push(edge);
  48735. edgesMap[key] = edge;
  48736. return edge;
  48737. };
  48738. /**
  48739. * Get edge by data index
  48740. * @param {number} dataIndex
  48741. * @return {module:echarts/data/Graph~Node}
  48742. */
  48743. graphProto.getEdgeByIndex = function (dataIndex) {
  48744. var rawIdx = this.edgeData.getRawIndex(dataIndex);
  48745. return this.edges[rawIdx];
  48746. };
  48747. /**
  48748. * Get edge by two linked nodes
  48749. * @param {module:echarts/data/Graph.Node|string} n1
  48750. * @param {module:echarts/data/Graph.Node|string} n2
  48751. * @return {module:echarts/data/Graph.Edge}
  48752. */
  48753. graphProto.getEdge = function (n1, n2) {
  48754. if (Node.isInstance(n1)) {
  48755. n1 = n1.id;
  48756. }
  48757. if (Node.isInstance(n2)) {
  48758. n2 = n2.id;
  48759. }
  48760. var edgesMap = this._edgesMap;
  48761. if (this._directed) {
  48762. return edgesMap[n1 + '-' + n2];
  48763. }
  48764. else {
  48765. return edgesMap[n1 + '-' + n2]
  48766. || edgesMap[n2 + '-' + n1];
  48767. }
  48768. };
  48769. /**
  48770. * Iterate all nodes
  48771. * @param {Function} cb
  48772. * @param {*} [context]
  48773. */
  48774. graphProto.eachNode = function (cb, context) {
  48775. var nodes = this.nodes;
  48776. var len = nodes.length;
  48777. for (var i = 0; i < len; i++) {
  48778. if (nodes[i].dataIndex >= 0) {
  48779. cb.call(context, nodes[i], i);
  48780. }
  48781. }
  48782. };
  48783. /**
  48784. * Iterate all edges
  48785. * @param {Function} cb
  48786. * @param {*} [context]
  48787. */
  48788. graphProto.eachEdge = function (cb, context) {
  48789. var edges = this.edges;
  48790. var len = edges.length;
  48791. for (var i = 0; i < len; i++) {
  48792. if (edges[i].dataIndex >= 0
  48793. && edges[i].node1.dataIndex >= 0
  48794. && edges[i].node2.dataIndex >= 0
  48795. ) {
  48796. cb.call(context, edges[i], i);
  48797. }
  48798. }
  48799. };
  48800. /**
  48801. * Breadth first traverse
  48802. * @param {Function} cb
  48803. * @param {module:echarts/data/Graph.Node} startNode
  48804. * @param {string} [direction='none'] 'none'|'in'|'out'
  48805. * @param {*} [context]
  48806. */
  48807. graphProto.breadthFirstTraverse = function (
  48808. cb, startNode, direction, context
  48809. ) {
  48810. if (!Node.isInstance(startNode)) {
  48811. startNode = this._nodesMap[generateNodeKey(startNode)];
  48812. }
  48813. if (!startNode) {
  48814. return;
  48815. }
  48816. var edgeType = direction === 'out'
  48817. ? 'outEdges' : (direction === 'in' ? 'inEdges' : 'edges');
  48818. for (var i = 0; i < this.nodes.length; i++) {
  48819. this.nodes[i].__visited = false;
  48820. }
  48821. if (cb.call(context, startNode, null)) {
  48822. return;
  48823. }
  48824. var queue = [startNode];
  48825. while (queue.length) {
  48826. var currentNode = queue.shift();
  48827. var edges = currentNode[edgeType];
  48828. for (var i = 0; i < edges.length; i++) {
  48829. var e = edges[i];
  48830. var otherNode = e.node1 === currentNode
  48831. ? e.node2 : e.node1;
  48832. if (!otherNode.__visited) {
  48833. if (cb.call(context, otherNode, currentNode)) {
  48834. // Stop traversing
  48835. return;
  48836. }
  48837. queue.push(otherNode);
  48838. otherNode.__visited = true;
  48839. }
  48840. }
  48841. }
  48842. };
  48843. // TODO
  48844. // graphProto.depthFirstTraverse = function (
  48845. // cb, startNode, direction, context
  48846. // ) {
  48847. // };
  48848. // Filter update
  48849. graphProto.update = function () {
  48850. var data = this.data;
  48851. var edgeData = this.edgeData;
  48852. var nodes = this.nodes;
  48853. var edges = this.edges;
  48854. for (var i = 0, len = nodes.length; i < len; i++) {
  48855. nodes[i].dataIndex = -1;
  48856. }
  48857. for (var i = 0, len = data.count(); i < len; i++) {
  48858. nodes[data.getRawIndex(i)].dataIndex = i;
  48859. }
  48860. edgeData.filterSelf(function (idx) {
  48861. var edge = edges[edgeData.getRawIndex(idx)];
  48862. return edge.node1.dataIndex >= 0 && edge.node2.dataIndex >= 0;
  48863. });
  48864. // Update edge
  48865. for (var i = 0, len = edges.length; i < len; i++) {
  48866. edges[i].dataIndex = -1;
  48867. }
  48868. for (var i = 0, len = edgeData.count(); i < len; i++) {
  48869. edges[edgeData.getRawIndex(i)].dataIndex = i;
  48870. }
  48871. };
  48872. /**
  48873. * @return {module:echarts/data/Graph}
  48874. */
  48875. graphProto.clone = function () {
  48876. var graph = new Graph(this._directed);
  48877. var nodes = this.nodes;
  48878. var edges = this.edges;
  48879. for (var i = 0; i < nodes.length; i++) {
  48880. graph.addNode(nodes[i].id, nodes[i].dataIndex);
  48881. }
  48882. for (var i = 0; i < edges.length; i++) {
  48883. var e = edges[i];
  48884. graph.addEdge(e.node1.id, e.node2.id, e.dataIndex);
  48885. }
  48886. return graph;
  48887. };
  48888. /**
  48889. * @alias module:echarts/data/Graph.Node
  48890. */
  48891. function Node(id, dataIndex) {
  48892. /**
  48893. * @type {string}
  48894. */
  48895. this.id = id == null ? '' : id;
  48896. /**
  48897. * @type {Array.<module:echarts/data/Graph.Edge>}
  48898. */
  48899. this.inEdges = [];
  48900. /**
  48901. * @type {Array.<module:echarts/data/Graph.Edge>}
  48902. */
  48903. this.outEdges = [];
  48904. /**
  48905. * @type {Array.<module:echarts/data/Graph.Edge>}
  48906. */
  48907. this.edges = [];
  48908. /**
  48909. * @type {module:echarts/data/Graph}
  48910. */
  48911. this.hostGraph;
  48912. /**
  48913. * @type {number}
  48914. */
  48915. this.dataIndex = dataIndex == null ? -1 : dataIndex;
  48916. }
  48917. Node.prototype = {
  48918. constructor: Node,
  48919. /**
  48920. * @return {number}
  48921. */
  48922. degree: function () {
  48923. return this.edges.length;
  48924. },
  48925. /**
  48926. * @return {number}
  48927. */
  48928. inDegree: function () {
  48929. return this.inEdges.length;
  48930. },
  48931. /**
  48932. * @return {number}
  48933. */
  48934. outDegree: function () {
  48935. return this.outEdges.length;
  48936. },
  48937. /**
  48938. * @param {string} [path]
  48939. * @return {module:echarts/model/Model}
  48940. */
  48941. getModel: function (path) {
  48942. if (this.dataIndex < 0) {
  48943. return;
  48944. }
  48945. var graph = this.hostGraph;
  48946. var itemModel = graph.data.getItemModel(this.dataIndex);
  48947. return itemModel.getModel(path);
  48948. }
  48949. };
  48950. /**
  48951. * 图边
  48952. * @alias module:echarts/data/Graph.Edge
  48953. * @param {module:echarts/data/Graph.Node} n1
  48954. * @param {module:echarts/data/Graph.Node} n2
  48955. * @param {number} [dataIndex=-1]
  48956. */
  48957. function Edge(n1, n2, dataIndex) {
  48958. /**
  48959. * 节点1,如果是有向图则为源节点
  48960. * @type {module:echarts/data/Graph.Node}
  48961. */
  48962. this.node1 = n1;
  48963. /**
  48964. * 节点2,如果是有向图则为目标节点
  48965. * @type {module:echarts/data/Graph.Node}
  48966. */
  48967. this.node2 = n2;
  48968. this.dataIndex = dataIndex == null ? -1 : dataIndex;
  48969. }
  48970. /**
  48971. * @param {string} [path]
  48972. * @return {module:echarts/model/Model}
  48973. */
  48974. Edge.prototype.getModel = function (path) {
  48975. if (this.dataIndex < 0) {
  48976. return;
  48977. }
  48978. var graph = this.hostGraph;
  48979. var itemModel = graph.edgeData.getItemModel(this.dataIndex);
  48980. return itemModel.getModel(path);
  48981. };
  48982. var createGraphDataProxyMixin = function (hostName, dataName) {
  48983. return {
  48984. /**
  48985. * @param {string=} [dimension='value'] Default 'value'. can be 'a', 'b', 'c', 'd', 'e'.
  48986. * @return {number}
  48987. */
  48988. getValue: function (dimension) {
  48989. var data = this[hostName][dataName];
  48990. return data.get(data.getDimension(dimension || 'value'), this.dataIndex);
  48991. },
  48992. /**
  48993. * @param {Object|string} key
  48994. * @param {*} [value]
  48995. */
  48996. setVisual: function (key, value) {
  48997. this.dataIndex >= 0
  48998. && this[hostName][dataName].setItemVisual(this.dataIndex, key, value);
  48999. },
  49000. /**
  49001. * @param {string} key
  49002. * @return {boolean}
  49003. */
  49004. getVisual: function (key, ignoreParent) {
  49005. return this[hostName][dataName].getItemVisual(this.dataIndex, key, ignoreParent);
  49006. },
  49007. /**
  49008. * @param {Object} layout
  49009. * @return {boolean} [merge=false]
  49010. */
  49011. setLayout: function (layout, merge$$1) {
  49012. this.dataIndex >= 0
  49013. && this[hostName][dataName].setItemLayout(this.dataIndex, layout, merge$$1);
  49014. },
  49015. /**
  49016. * @return {Object}
  49017. */
  49018. getLayout: function () {
  49019. return this[hostName][dataName].getItemLayout(this.dataIndex);
  49020. },
  49021. /**
  49022. * @return {module:zrender/Element}
  49023. */
  49024. getGraphicEl: function () {
  49025. return this[hostName][dataName].getItemGraphicEl(this.dataIndex);
  49026. },
  49027. /**
  49028. * @return {number}
  49029. */
  49030. getRawIndex: function () {
  49031. return this[hostName][dataName].getRawIndex(this.dataIndex);
  49032. }
  49033. };
  49034. };
  49035. mixin(Node, createGraphDataProxyMixin('hostGraph', 'data'));
  49036. mixin(Edge, createGraphDataProxyMixin('hostGraph', 'edgeData'));
  49037. Graph.Node = Node;
  49038. Graph.Edge = Edge;
  49039. enableClassCheck(Node);
  49040. enableClassCheck(Edge);
  49041. /*
  49042. * Licensed to the Apache Software Foundation (ASF) under one
  49043. * or more contributor license agreements. See the NOTICE file
  49044. * distributed with this work for additional information
  49045. * regarding copyright ownership. The ASF licenses this file
  49046. * to you under the Apache License, Version 2.0 (the
  49047. * "License"); you may not use this file except in compliance
  49048. * with the License. You may obtain a copy of the License at
  49049. *
  49050. * http://www.apache.org/licenses/LICENSE-2.0
  49051. *
  49052. * Unless required by applicable law or agreed to in writing,
  49053. * software distributed under the License is distributed on an
  49054. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49055. * KIND, either express or implied. See the License for the
  49056. * specific language governing permissions and limitations
  49057. * under the License.
  49058. */
  49059. var createGraphFromNodeEdge = function (nodes, edges, seriesModel, directed, beforeLink) {
  49060. // ??? TODO
  49061. // support dataset?
  49062. var graph = new Graph(directed);
  49063. for (var i = 0; i < nodes.length; i++) {
  49064. graph.addNode(retrieve(
  49065. // Id, name, dataIndex
  49066. nodes[i].id, nodes[i].name, i
  49067. ), i);
  49068. }
  49069. var linkNameList = [];
  49070. var validEdges = [];
  49071. var linkCount = 0;
  49072. for (var i = 0; i < edges.length; i++) {
  49073. var link = edges[i];
  49074. var source = link.source;
  49075. var target = link.target;
  49076. // addEdge may fail when source or target not exists
  49077. if (graph.addEdge(source, target, linkCount)) {
  49078. validEdges.push(link);
  49079. linkNameList.push(retrieve(link.id, source + ' > ' + target));
  49080. linkCount++;
  49081. }
  49082. }
  49083. var coordSys = seriesModel.get('coordinateSystem');
  49084. var nodeData;
  49085. if (coordSys === 'cartesian2d' || coordSys === 'polar') {
  49086. nodeData = createListFromArray(nodes, seriesModel);
  49087. }
  49088. else {
  49089. var coordSysCtor = CoordinateSystemManager.get(coordSys);
  49090. var coordDimensions = (coordSysCtor && coordSysCtor.type !== 'view')
  49091. ? (coordSysCtor.dimensions || []) : [];
  49092. // FIXME: Some geo do not need `value` dimenson, whereas `calendar` needs
  49093. // `value` dimension, but graph need `value` dimension. It's better to
  49094. // uniform this behavior.
  49095. if (indexOf(coordDimensions, 'value') < 0) {
  49096. coordDimensions.concat(['value']);
  49097. }
  49098. var dimensionNames = createDimensions(nodes, {
  49099. coordDimensions: coordDimensions
  49100. });
  49101. nodeData = new List(dimensionNames, seriesModel);
  49102. nodeData.initData(nodes);
  49103. }
  49104. var edgeData = new List(['value'], seriesModel);
  49105. edgeData.initData(validEdges, linkNameList);
  49106. beforeLink && beforeLink(nodeData, edgeData);
  49107. linkList({
  49108. mainData: nodeData,
  49109. struct: graph,
  49110. structAttr: 'graph',
  49111. datas: {node: nodeData, edge: edgeData},
  49112. datasAttr: {node: 'data', edge: 'edgeData'}
  49113. });
  49114. // Update dataIndex of nodes and edges because invalid edge may be removed
  49115. graph.update();
  49116. return graph;
  49117. };
  49118. /*
  49119. * Licensed to the Apache Software Foundation (ASF) under one
  49120. * or more contributor license agreements. See the NOTICE file
  49121. * distributed with this work for additional information
  49122. * regarding copyright ownership. The ASF licenses this file
  49123. * to you under the Apache License, Version 2.0 (the
  49124. * "License"); you may not use this file except in compliance
  49125. * with the License. You may obtain a copy of the License at
  49126. *
  49127. * http://www.apache.org/licenses/LICENSE-2.0
  49128. *
  49129. * Unless required by applicable law or agreed to in writing,
  49130. * software distributed under the License is distributed on an
  49131. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49132. * KIND, either express or implied. See the License for the
  49133. * specific language governing permissions and limitations
  49134. * under the License.
  49135. */
  49136. var GraphSeries = extendSeriesModel({
  49137. type: 'series.graph',
  49138. init: function (option) {
  49139. GraphSeries.superApply(this, 'init', arguments);
  49140. var self = this;
  49141. function getCategoriesData() {
  49142. return self._categoriesData;
  49143. }
  49144. // Provide data for legend select
  49145. this.legendVisualProvider = new LegendVisualProvider(
  49146. getCategoriesData, getCategoriesData
  49147. );
  49148. this.fillDataTextStyle(option.edges || option.links);
  49149. this._updateCategoriesData();
  49150. },
  49151. mergeOption: function (option) {
  49152. GraphSeries.superApply(this, 'mergeOption', arguments);
  49153. this.fillDataTextStyle(option.edges || option.links);
  49154. this._updateCategoriesData();
  49155. },
  49156. mergeDefaultAndTheme: function (option) {
  49157. GraphSeries.superApply(this, 'mergeDefaultAndTheme', arguments);
  49158. defaultEmphasis(option, ['edgeLabel'], ['show']);
  49159. },
  49160. getInitialData: function (option, ecModel) {
  49161. var edges = option.edges || option.links || [];
  49162. var nodes = option.data || option.nodes || [];
  49163. var self = this;
  49164. if (nodes && edges) {
  49165. return createGraphFromNodeEdge(nodes, edges, this, true, beforeLink).data;
  49166. }
  49167. function beforeLink(nodeData, edgeData) {
  49168. // Overwrite nodeData.getItemModel to
  49169. nodeData.wrapMethod('getItemModel', function (model) {
  49170. var categoriesModels = self._categoriesModels;
  49171. var categoryIdx = model.getShallow('category');
  49172. var categoryModel = categoriesModels[categoryIdx];
  49173. if (categoryModel) {
  49174. categoryModel.parentModel = model.parentModel;
  49175. model.parentModel = categoryModel;
  49176. }
  49177. return model;
  49178. });
  49179. var edgeLabelModel = self.getModel('edgeLabel');
  49180. // For option `edgeLabel` can be found by label.xxx.xxx on item mode.
  49181. var fakeSeriesModel = new Model(
  49182. {label: edgeLabelModel.option},
  49183. edgeLabelModel.parentModel,
  49184. ecModel
  49185. );
  49186. var emphasisEdgeLabelModel = self.getModel('emphasis.edgeLabel');
  49187. var emphasisFakeSeriesModel = new Model(
  49188. {emphasis: {label: emphasisEdgeLabelModel.option}},
  49189. emphasisEdgeLabelModel.parentModel,
  49190. ecModel
  49191. );
  49192. edgeData.wrapMethod('getItemModel', function (model) {
  49193. model.customizeGetParent(edgeGetParent);
  49194. return model;
  49195. });
  49196. function edgeGetParent(path) {
  49197. path = this.parsePath(path);
  49198. return (path && path[0] === 'label')
  49199. ? fakeSeriesModel
  49200. : (path && path[0] === 'emphasis' && path[1] === 'label')
  49201. ? emphasisFakeSeriesModel
  49202. : this.parentModel;
  49203. }
  49204. }
  49205. },
  49206. /**
  49207. * @return {module:echarts/data/Graph}
  49208. */
  49209. getGraph: function () {
  49210. return this.getData().graph;
  49211. },
  49212. /**
  49213. * @return {module:echarts/data/List}
  49214. */
  49215. getEdgeData: function () {
  49216. return this.getGraph().edgeData;
  49217. },
  49218. /**
  49219. * @return {module:echarts/data/List}
  49220. */
  49221. getCategoriesData: function () {
  49222. return this._categoriesData;
  49223. },
  49224. /**
  49225. * @override
  49226. */
  49227. formatTooltip: function (dataIndex, multipleSeries, dataType) {
  49228. if (dataType === 'edge') {
  49229. var nodeData = this.getData();
  49230. var params = this.getDataParams(dataIndex, dataType);
  49231. var edge = nodeData.graph.getEdgeByIndex(dataIndex);
  49232. var sourceName = nodeData.getName(edge.node1.dataIndex);
  49233. var targetName = nodeData.getName(edge.node2.dataIndex);
  49234. var html = [];
  49235. sourceName != null && html.push(sourceName);
  49236. targetName != null && html.push(targetName);
  49237. html = encodeHTML(html.join(' > '));
  49238. if (params.value) {
  49239. html += ' : ' + encodeHTML(params.value);
  49240. }
  49241. return html;
  49242. }
  49243. else { // dataType === 'node' or empty
  49244. return GraphSeries.superApply(this, 'formatTooltip', arguments);
  49245. }
  49246. },
  49247. _updateCategoriesData: function () {
  49248. var categories = map(this.option.categories || [], function (category) {
  49249. // Data must has value
  49250. return category.value != null ? category : extend({
  49251. value: 0
  49252. }, category);
  49253. });
  49254. var categoriesData = new List(['value'], this);
  49255. categoriesData.initData(categories);
  49256. this._categoriesData = categoriesData;
  49257. this._categoriesModels = categoriesData.mapArray(function (idx) {
  49258. return categoriesData.getItemModel(idx, true);
  49259. });
  49260. },
  49261. setZoom: function (zoom) {
  49262. this.option.zoom = zoom;
  49263. },
  49264. setCenter: function (center) {
  49265. this.option.center = center;
  49266. },
  49267. isAnimationEnabled: function () {
  49268. return GraphSeries.superCall(this, 'isAnimationEnabled')
  49269. // Not enable animation when do force layout
  49270. && !(this.get('layout') === 'force' && this.get('force.layoutAnimation'));
  49271. },
  49272. defaultOption: {
  49273. zlevel: 0,
  49274. z: 2,
  49275. coordinateSystem: 'view',
  49276. // Default option for all coordinate systems
  49277. // xAxisIndex: 0,
  49278. // yAxisIndex: 0,
  49279. // polarIndex: 0,
  49280. // geoIndex: 0,
  49281. legendHoverLink: true,
  49282. hoverAnimation: true,
  49283. layout: null,
  49284. focusNodeAdjacency: false,
  49285. // Configuration of circular layout
  49286. circular: {
  49287. rotateLabel: false
  49288. },
  49289. // Configuration of force directed layout
  49290. force: {
  49291. initLayout: null,
  49292. // Node repulsion. Can be an array to represent range.
  49293. repulsion: [0, 50],
  49294. gravity: 0.1,
  49295. // Initial friction
  49296. friction: 0.6,
  49297. // Edge length. Can be an array to represent range.
  49298. edgeLength: 30,
  49299. layoutAnimation: true
  49300. },
  49301. left: 'center',
  49302. top: 'center',
  49303. // right: null,
  49304. // bottom: null,
  49305. // width: '80%',
  49306. // height: '80%',
  49307. symbol: 'circle',
  49308. symbolSize: 10,
  49309. edgeSymbol: ['none', 'none'],
  49310. edgeSymbolSize: 10,
  49311. edgeLabel: {
  49312. position: 'middle',
  49313. distance: 5
  49314. },
  49315. draggable: false,
  49316. roam: false,
  49317. // Default on center of graph
  49318. center: null,
  49319. zoom: 1,
  49320. // Symbol size scale ratio in roam
  49321. nodeScaleRatio: 0.6,
  49322. // cursor: null,
  49323. // categories: [],
  49324. // data: []
  49325. // Or
  49326. // nodes: []
  49327. //
  49328. // links: []
  49329. // Or
  49330. // edges: []
  49331. label: {
  49332. show: false,
  49333. formatter: '{b}'
  49334. },
  49335. itemStyle: {},
  49336. lineStyle: {
  49337. color: '#aaa',
  49338. width: 1,
  49339. curveness: 0,
  49340. opacity: 0.5
  49341. },
  49342. emphasis: {
  49343. label: {
  49344. show: true
  49345. }
  49346. }
  49347. }
  49348. });
  49349. /*
  49350. * Licensed to the Apache Software Foundation (ASF) under one
  49351. * or more contributor license agreements. See the NOTICE file
  49352. * distributed with this work for additional information
  49353. * regarding copyright ownership. The ASF licenses this file
  49354. * to you under the Apache License, Version 2.0 (the
  49355. * "License"); you may not use this file except in compliance
  49356. * with the License. You may obtain a copy of the License at
  49357. *
  49358. * http://www.apache.org/licenses/LICENSE-2.0
  49359. *
  49360. * Unless required by applicable law or agreed to in writing,
  49361. * software distributed under the License is distributed on an
  49362. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49363. * KIND, either express or implied. See the License for the
  49364. * specific language governing permissions and limitations
  49365. * under the License.
  49366. */
  49367. /**
  49368. * Line path for bezier and straight line draw
  49369. */
  49370. var straightLineProto = Line.prototype;
  49371. var bezierCurveProto = BezierCurve.prototype;
  49372. function isLine(shape) {
  49373. return isNaN(+shape.cpx1) || isNaN(+shape.cpy1);
  49374. }
  49375. var LinePath = extendShape({
  49376. type: 'ec-line',
  49377. style: {
  49378. stroke: '#000',
  49379. fill: null
  49380. },
  49381. shape: {
  49382. x1: 0,
  49383. y1: 0,
  49384. x2: 0,
  49385. y2: 0,
  49386. percent: 1,
  49387. cpx1: null,
  49388. cpy1: null
  49389. },
  49390. buildPath: function (ctx, shape) {
  49391. this[isLine(shape) ? '_buildPathLine' : '_buildPathCurve'](ctx, shape);
  49392. },
  49393. _buildPathLine: straightLineProto.buildPath,
  49394. _buildPathCurve: bezierCurveProto.buildPath,
  49395. pointAt: function (t) {
  49396. return this[isLine(this.shape) ? '_pointAtLine' : '_pointAtCurve'](t);
  49397. },
  49398. _pointAtLine: straightLineProto.pointAt,
  49399. _pointAtCurve: bezierCurveProto.pointAt,
  49400. tangentAt: function (t) {
  49401. var shape = this.shape;
  49402. var p = isLine(shape)
  49403. ? [shape.x2 - shape.x1, shape.y2 - shape.y1]
  49404. : this._tangentAtCurve(t);
  49405. return normalize(p, p);
  49406. },
  49407. _tangentAtCurve: bezierCurveProto.tangentAt
  49408. });
  49409. /*
  49410. * Licensed to the Apache Software Foundation (ASF) under one
  49411. * or more contributor license agreements. See the NOTICE file
  49412. * distributed with this work for additional information
  49413. * regarding copyright ownership. The ASF licenses this file
  49414. * to you under the Apache License, Version 2.0 (the
  49415. * "License"); you may not use this file except in compliance
  49416. * with the License. You may obtain a copy of the License at
  49417. *
  49418. * http://www.apache.org/licenses/LICENSE-2.0
  49419. *
  49420. * Unless required by applicable law or agreed to in writing,
  49421. * software distributed under the License is distributed on an
  49422. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49423. * KIND, either express or implied. See the License for the
  49424. * specific language governing permissions and limitations
  49425. * under the License.
  49426. */
  49427. /**
  49428. * @module echarts/chart/helper/Line
  49429. */
  49430. var SYMBOL_CATEGORIES = ['fromSymbol', 'toSymbol'];
  49431. function makeSymbolTypeKey(symbolCategory) {
  49432. return '_' + symbolCategory + 'Type';
  49433. }
  49434. /**
  49435. * @inner
  49436. */
  49437. function createSymbol$1(name, lineData, idx) {
  49438. var color = lineData.getItemVisual(idx, 'color');
  49439. var symbolType = lineData.getItemVisual(idx, name);
  49440. var symbolSize = lineData.getItemVisual(idx, name + 'Size');
  49441. if (!symbolType || symbolType === 'none') {
  49442. return;
  49443. }
  49444. if (!isArray(symbolSize)) {
  49445. symbolSize = [symbolSize, symbolSize];
  49446. }
  49447. var symbolPath = createSymbol(
  49448. symbolType, -symbolSize[0] / 2, -symbolSize[1] / 2,
  49449. symbolSize[0], symbolSize[1], color
  49450. );
  49451. symbolPath.name = name;
  49452. return symbolPath;
  49453. }
  49454. function createLine(points) {
  49455. var line = new LinePath({
  49456. name: 'line',
  49457. subPixelOptimize: true
  49458. });
  49459. setLinePoints(line.shape, points);
  49460. return line;
  49461. }
  49462. function setLinePoints(targetShape, points) {
  49463. targetShape.x1 = points[0][0];
  49464. targetShape.y1 = points[0][1];
  49465. targetShape.x2 = points[1][0];
  49466. targetShape.y2 = points[1][1];
  49467. targetShape.percent = 1;
  49468. var cp1 = points[2];
  49469. if (cp1) {
  49470. targetShape.cpx1 = cp1[0];
  49471. targetShape.cpy1 = cp1[1];
  49472. }
  49473. else {
  49474. targetShape.cpx1 = NaN;
  49475. targetShape.cpy1 = NaN;
  49476. }
  49477. }
  49478. function updateSymbolAndLabelBeforeLineUpdate() {
  49479. var lineGroup = this;
  49480. var symbolFrom = lineGroup.childOfName('fromSymbol');
  49481. var symbolTo = lineGroup.childOfName('toSymbol');
  49482. var label = lineGroup.childOfName('label');
  49483. // Quick reject
  49484. if (!symbolFrom && !symbolTo && label.ignore) {
  49485. return;
  49486. }
  49487. var invScale = 1;
  49488. var parentNode = this.parent;
  49489. while (parentNode) {
  49490. if (parentNode.scale) {
  49491. invScale /= parentNode.scale[0];
  49492. }
  49493. parentNode = parentNode.parent;
  49494. }
  49495. var line = lineGroup.childOfName('line');
  49496. // If line not changed
  49497. // FIXME Parent scale changed
  49498. if (!this.__dirty && !line.__dirty) {
  49499. return;
  49500. }
  49501. var percent = line.shape.percent;
  49502. var fromPos = line.pointAt(0);
  49503. var toPos = line.pointAt(percent);
  49504. var d = sub([], toPos, fromPos);
  49505. normalize(d, d);
  49506. if (symbolFrom) {
  49507. symbolFrom.attr('position', fromPos);
  49508. var tangent = line.tangentAt(0);
  49509. symbolFrom.attr('rotation', Math.PI / 2 - Math.atan2(
  49510. tangent[1], tangent[0]
  49511. ));
  49512. symbolFrom.attr('scale', [invScale * percent, invScale * percent]);
  49513. }
  49514. if (symbolTo) {
  49515. symbolTo.attr('position', toPos);
  49516. var tangent = line.tangentAt(1);
  49517. symbolTo.attr('rotation', -Math.PI / 2 - Math.atan2(
  49518. tangent[1], tangent[0]
  49519. ));
  49520. symbolTo.attr('scale', [invScale * percent, invScale * percent]);
  49521. }
  49522. if (!label.ignore) {
  49523. label.attr('position', toPos);
  49524. var textPosition;
  49525. var textAlign;
  49526. var textVerticalAlign;
  49527. var textOrigin;
  49528. var distance$$1 = label.__labelDistance;
  49529. var distanceX = distance$$1[0] * invScale;
  49530. var distanceY = distance$$1[1] * invScale;
  49531. var halfPercent = percent / 2;
  49532. var tangent = line.tangentAt(halfPercent);
  49533. var n = [tangent[1], -tangent[0]];
  49534. var cp = line.pointAt(halfPercent);
  49535. if (n[1] > 0) {
  49536. n[0] = -n[0];
  49537. n[1] = -n[1];
  49538. }
  49539. var dir = tangent[0] < 0 ? -1 : 1;
  49540. if (label.__position !== 'start' && label.__position !== 'end') {
  49541. var rotation = -Math.atan2(tangent[1], tangent[0]);
  49542. if (toPos[0] < fromPos[0]) {
  49543. rotation = Math.PI + rotation;
  49544. }
  49545. label.attr('rotation', rotation);
  49546. }
  49547. var dy;
  49548. switch (label.__position) {
  49549. case 'insideStartTop':
  49550. case 'insideMiddleTop':
  49551. case 'insideEndTop':
  49552. case 'middle':
  49553. dy = -distanceY;
  49554. textVerticalAlign = 'bottom';
  49555. break;
  49556. case 'insideStartBottom':
  49557. case 'insideMiddleBottom':
  49558. case 'insideEndBottom':
  49559. dy = distanceY;
  49560. textVerticalAlign = 'top';
  49561. break;
  49562. default:
  49563. dy = 0;
  49564. textVerticalAlign = 'middle';
  49565. }
  49566. switch (label.__position) {
  49567. case 'end':
  49568. textPosition = [d[0] * distanceX + toPos[0], d[1] * distanceY + toPos[1]];
  49569. textAlign = d[0] > 0.8 ? 'left' : (d[0] < -0.8 ? 'right' : 'center');
  49570. textVerticalAlign = d[1] > 0.8 ? 'top' : (d[1] < -0.8 ? 'bottom' : 'middle');
  49571. break;
  49572. case 'start':
  49573. textPosition = [-d[0] * distanceX + fromPos[0], -d[1] * distanceY + fromPos[1]];
  49574. textAlign = d[0] > 0.8 ? 'right' : (d[0] < -0.8 ? 'left' : 'center');
  49575. textVerticalAlign = d[1] > 0.8 ? 'bottom' : (d[1] < -0.8 ? 'top' : 'middle');
  49576. break;
  49577. case 'insideStartTop':
  49578. case 'insideStart':
  49579. case 'insideStartBottom':
  49580. textPosition = [distanceX * dir + fromPos[0], fromPos[1] + dy];
  49581. textAlign = tangent[0] < 0 ? 'right' : 'left';
  49582. textOrigin = [-distanceX * dir, -dy];
  49583. break;
  49584. case 'insideMiddleTop':
  49585. case 'insideMiddle':
  49586. case 'insideMiddleBottom':
  49587. case 'middle':
  49588. textPosition = [cp[0], cp[1] + dy];
  49589. textAlign = 'center';
  49590. textOrigin = [0, -dy];
  49591. break;
  49592. case 'insideEndTop':
  49593. case 'insideEnd':
  49594. case 'insideEndBottom':
  49595. textPosition = [-distanceX * dir + toPos[0], toPos[1] + dy];
  49596. textAlign = tangent[0] >= 0 ? 'right' : 'left';
  49597. textOrigin = [distanceX * dir, -dy];
  49598. break;
  49599. }
  49600. label.attr({
  49601. style: {
  49602. // Use the user specified text align and baseline first
  49603. textVerticalAlign: label.__verticalAlign || textVerticalAlign,
  49604. textAlign: label.__textAlign || textAlign
  49605. },
  49606. position: textPosition,
  49607. scale: [invScale, invScale],
  49608. origin: textOrigin
  49609. });
  49610. }
  49611. }
  49612. /**
  49613. * @constructor
  49614. * @extends {module:zrender/graphic/Group}
  49615. * @alias {module:echarts/chart/helper/Line}
  49616. */
  49617. function Line$1(lineData, idx, seriesScope) {
  49618. Group.call(this);
  49619. this._createLine(lineData, idx, seriesScope);
  49620. }
  49621. var lineProto = Line$1.prototype;
  49622. // Update symbol position and rotation
  49623. lineProto.beforeUpdate = updateSymbolAndLabelBeforeLineUpdate;
  49624. lineProto._createLine = function (lineData, idx, seriesScope) {
  49625. var seriesModel = lineData.hostModel;
  49626. var linePoints = lineData.getItemLayout(idx);
  49627. var line = createLine(linePoints);
  49628. line.shape.percent = 0;
  49629. initProps(line, {
  49630. shape: {
  49631. percent: 1
  49632. }
  49633. }, seriesModel, idx);
  49634. this.add(line);
  49635. var label = new Text({
  49636. name: 'label',
  49637. // FIXME
  49638. // Temporary solution for `focusNodeAdjacency`.
  49639. // line label do not use the opacity of lineStyle.
  49640. lineLabelOriginalOpacity: 1
  49641. });
  49642. this.add(label);
  49643. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  49644. var symbol = createSymbol$1(symbolCategory, lineData, idx);
  49645. // symbols must added after line to make sure
  49646. // it will be updated after line#update.
  49647. // Or symbol position and rotation update in line#beforeUpdate will be one frame slow
  49648. this.add(symbol);
  49649. this[makeSymbolTypeKey(symbolCategory)] = lineData.getItemVisual(idx, symbolCategory);
  49650. }, this);
  49651. this._updateCommonStl(lineData, idx, seriesScope);
  49652. };
  49653. lineProto.updateData = function (lineData, idx, seriesScope) {
  49654. var seriesModel = lineData.hostModel;
  49655. var line = this.childOfName('line');
  49656. var linePoints = lineData.getItemLayout(idx);
  49657. var target = {
  49658. shape: {}
  49659. };
  49660. setLinePoints(target.shape, linePoints);
  49661. updateProps(line, target, seriesModel, idx);
  49662. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  49663. var symbolType = lineData.getItemVisual(idx, symbolCategory);
  49664. var key = makeSymbolTypeKey(symbolCategory);
  49665. // Symbol changed
  49666. if (this[key] !== symbolType) {
  49667. this.remove(this.childOfName(symbolCategory));
  49668. var symbol = createSymbol$1(symbolCategory, lineData, idx);
  49669. this.add(symbol);
  49670. }
  49671. this[key] = symbolType;
  49672. }, this);
  49673. this._updateCommonStl(lineData, idx, seriesScope);
  49674. };
  49675. lineProto._updateCommonStl = function (lineData, idx, seriesScope) {
  49676. var seriesModel = lineData.hostModel;
  49677. var line = this.childOfName('line');
  49678. var lineStyle = seriesScope && seriesScope.lineStyle;
  49679. var hoverLineStyle = seriesScope && seriesScope.hoverLineStyle;
  49680. var labelModel = seriesScope && seriesScope.labelModel;
  49681. var hoverLabelModel = seriesScope && seriesScope.hoverLabelModel;
  49682. // Optimization for large dataset
  49683. if (!seriesScope || lineData.hasItemOption) {
  49684. var itemModel = lineData.getItemModel(idx);
  49685. lineStyle = itemModel.getModel('lineStyle').getLineStyle();
  49686. hoverLineStyle = itemModel.getModel('emphasis.lineStyle').getLineStyle();
  49687. labelModel = itemModel.getModel('label');
  49688. hoverLabelModel = itemModel.getModel('emphasis.label');
  49689. }
  49690. var visualColor = lineData.getItemVisual(idx, 'color');
  49691. var visualOpacity = retrieve3(
  49692. lineData.getItemVisual(idx, 'opacity'),
  49693. lineStyle.opacity,
  49694. 1
  49695. );
  49696. line.useStyle(defaults(
  49697. {
  49698. strokeNoScale: true,
  49699. fill: 'none',
  49700. stroke: visualColor,
  49701. opacity: visualOpacity
  49702. },
  49703. lineStyle
  49704. ));
  49705. line.hoverStyle = hoverLineStyle;
  49706. // Update symbol
  49707. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  49708. var symbol = this.childOfName(symbolCategory);
  49709. if (symbol) {
  49710. symbol.setColor(visualColor);
  49711. symbol.setStyle({
  49712. opacity: visualOpacity
  49713. });
  49714. }
  49715. }, this);
  49716. var showLabel = labelModel.getShallow('show');
  49717. var hoverShowLabel = hoverLabelModel.getShallow('show');
  49718. var label = this.childOfName('label');
  49719. var defaultLabelColor;
  49720. var baseText;
  49721. // FIXME: the logic below probably should be merged to `graphic.setLabelStyle`.
  49722. if (showLabel || hoverShowLabel) {
  49723. defaultLabelColor = visualColor || '#000';
  49724. baseText = seriesModel.getFormattedLabel(idx, 'normal', lineData.dataType);
  49725. if (baseText == null) {
  49726. var rawVal = seriesModel.getRawValue(idx);
  49727. baseText = rawVal == null
  49728. ? lineData.getName(idx)
  49729. : isFinite(rawVal)
  49730. ? round$1(rawVal)
  49731. : rawVal;
  49732. }
  49733. }
  49734. var normalText = showLabel ? baseText : null;
  49735. var emphasisText = hoverShowLabel
  49736. ? retrieve2(
  49737. seriesModel.getFormattedLabel(idx, 'emphasis', lineData.dataType),
  49738. baseText
  49739. )
  49740. : null;
  49741. var labelStyle = label.style;
  49742. // Always set `textStyle` even if `normalStyle.text` is null, because default
  49743. // values have to be set on `normalStyle`.
  49744. if (normalText != null || emphasisText != null) {
  49745. setTextStyle(label.style, labelModel, {
  49746. text: normalText
  49747. }, {
  49748. autoColor: defaultLabelColor
  49749. });
  49750. label.__textAlign = labelStyle.textAlign;
  49751. label.__verticalAlign = labelStyle.textVerticalAlign;
  49752. // 'start', 'middle', 'end'
  49753. label.__position = labelModel.get('position') || 'middle';
  49754. var distance$$1 = labelModel.get('distance');
  49755. if (!isArray(distance$$1)) {
  49756. distance$$1 = [distance$$1, distance$$1];
  49757. }
  49758. label.__labelDistance = distance$$1;
  49759. }
  49760. if (emphasisText != null) {
  49761. // Only these properties supported in this emphasis style here.
  49762. label.hoverStyle = {
  49763. text: emphasisText,
  49764. textFill: hoverLabelModel.getTextColor(true),
  49765. // For merging hover style to normal style, do not use
  49766. // `hoverLabelModel.getFont()` here.
  49767. fontStyle: hoverLabelModel.getShallow('fontStyle'),
  49768. fontWeight: hoverLabelModel.getShallow('fontWeight'),
  49769. fontSize: hoverLabelModel.getShallow('fontSize'),
  49770. fontFamily: hoverLabelModel.getShallow('fontFamily')
  49771. };
  49772. }
  49773. else {
  49774. label.hoverStyle = {
  49775. text: null
  49776. };
  49777. }
  49778. label.ignore = !showLabel && !hoverShowLabel;
  49779. setHoverStyle(this);
  49780. };
  49781. lineProto.highlight = function () {
  49782. this.trigger('emphasis');
  49783. };
  49784. lineProto.downplay = function () {
  49785. this.trigger('normal');
  49786. };
  49787. lineProto.updateLayout = function (lineData, idx) {
  49788. this.setLinePoints(lineData.getItemLayout(idx));
  49789. };
  49790. lineProto.setLinePoints = function (points) {
  49791. var linePath = this.childOfName('line');
  49792. setLinePoints(linePath.shape, points);
  49793. linePath.dirty();
  49794. };
  49795. inherits(Line$1, Group);
  49796. /*
  49797. * Licensed to the Apache Software Foundation (ASF) under one
  49798. * or more contributor license agreements. See the NOTICE file
  49799. * distributed with this work for additional information
  49800. * regarding copyright ownership. The ASF licenses this file
  49801. * to you under the Apache License, Version 2.0 (the
  49802. * "License"); you may not use this file except in compliance
  49803. * with the License. You may obtain a copy of the License at
  49804. *
  49805. * http://www.apache.org/licenses/LICENSE-2.0
  49806. *
  49807. * Unless required by applicable law or agreed to in writing,
  49808. * software distributed under the License is distributed on an
  49809. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49810. * KIND, either express or implied. See the License for the
  49811. * specific language governing permissions and limitations
  49812. * under the License.
  49813. */
  49814. /**
  49815. * @module echarts/chart/helper/LineDraw
  49816. */
  49817. // import IncrementalDisplayable from 'zrender/src/graphic/IncrementalDisplayable';
  49818. /**
  49819. * @alias module:echarts/component/marker/LineDraw
  49820. * @constructor
  49821. */
  49822. function LineDraw(ctor) {
  49823. this._ctor = ctor || Line$1;
  49824. this.group = new Group();
  49825. }
  49826. var lineDrawProto = LineDraw.prototype;
  49827. lineDrawProto.isPersistent = function () {
  49828. return true;
  49829. };
  49830. /**
  49831. * @param {module:echarts/data/List} lineData
  49832. */
  49833. lineDrawProto.updateData = function (lineData) {
  49834. var lineDraw = this;
  49835. var group = lineDraw.group;
  49836. var oldLineData = lineDraw._lineData;
  49837. lineDraw._lineData = lineData;
  49838. // There is no oldLineData only when first rendering or switching from
  49839. // stream mode to normal mode, where previous elements should be removed.
  49840. if (!oldLineData) {
  49841. group.removeAll();
  49842. }
  49843. var seriesScope = makeSeriesScope$1(lineData);
  49844. lineData.diff(oldLineData)
  49845. .add(function (idx) {
  49846. doAdd(lineDraw, lineData, idx, seriesScope);
  49847. })
  49848. .update(function (newIdx, oldIdx) {
  49849. doUpdate(lineDraw, oldLineData, lineData, oldIdx, newIdx, seriesScope);
  49850. })
  49851. .remove(function (idx) {
  49852. group.remove(oldLineData.getItemGraphicEl(idx));
  49853. })
  49854. .execute();
  49855. };
  49856. function doAdd(lineDraw, lineData, idx, seriesScope) {
  49857. var itemLayout = lineData.getItemLayout(idx);
  49858. if (!lineNeedsDraw(itemLayout)) {
  49859. return;
  49860. }
  49861. var el = new lineDraw._ctor(lineData, idx, seriesScope);
  49862. lineData.setItemGraphicEl(idx, el);
  49863. lineDraw.group.add(el);
  49864. }
  49865. function doUpdate(lineDraw, oldLineData, newLineData, oldIdx, newIdx, seriesScope) {
  49866. var itemEl = oldLineData.getItemGraphicEl(oldIdx);
  49867. if (!lineNeedsDraw(newLineData.getItemLayout(newIdx))) {
  49868. lineDraw.group.remove(itemEl);
  49869. return;
  49870. }
  49871. if (!itemEl) {
  49872. itemEl = new lineDraw._ctor(newLineData, newIdx, seriesScope);
  49873. }
  49874. else {
  49875. itemEl.updateData(newLineData, newIdx, seriesScope);
  49876. }
  49877. newLineData.setItemGraphicEl(newIdx, itemEl);
  49878. lineDraw.group.add(itemEl);
  49879. }
  49880. lineDrawProto.updateLayout = function () {
  49881. var lineData = this._lineData;
  49882. // Do not support update layout in incremental mode.
  49883. if (!lineData) {
  49884. return;
  49885. }
  49886. lineData.eachItemGraphicEl(function (el, idx) {
  49887. el.updateLayout(lineData, idx);
  49888. }, this);
  49889. };
  49890. lineDrawProto.incrementalPrepareUpdate = function (lineData) {
  49891. this._seriesScope = makeSeriesScope$1(lineData);
  49892. this._lineData = null;
  49893. this.group.removeAll();
  49894. };
  49895. function isEffectObject(el) {
  49896. return el.animators && el.animators.length > 0;
  49897. }
  49898. lineDrawProto.incrementalUpdate = function (taskParams, lineData) {
  49899. function updateIncrementalAndHover(el) {
  49900. if (!el.isGroup && !isEffectObject(el)) {
  49901. el.incremental = el.useHoverLayer = true;
  49902. }
  49903. }
  49904. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  49905. var itemLayout = lineData.getItemLayout(idx);
  49906. if (lineNeedsDraw(itemLayout)) {
  49907. var el = new this._ctor(lineData, idx, this._seriesScope);
  49908. el.traverse(updateIncrementalAndHover);
  49909. this.group.add(el);
  49910. lineData.setItemGraphicEl(idx, el);
  49911. }
  49912. }
  49913. };
  49914. function makeSeriesScope$1(lineData) {
  49915. var hostModel = lineData.hostModel;
  49916. return {
  49917. lineStyle: hostModel.getModel('lineStyle').getLineStyle(),
  49918. hoverLineStyle: hostModel.getModel('emphasis.lineStyle').getLineStyle(),
  49919. labelModel: hostModel.getModel('label'),
  49920. hoverLabelModel: hostModel.getModel('emphasis.label')
  49921. };
  49922. }
  49923. lineDrawProto.remove = function () {
  49924. this._clearIncremental();
  49925. this._incremental = null;
  49926. this.group.removeAll();
  49927. };
  49928. lineDrawProto._clearIncremental = function () {
  49929. var incremental = this._incremental;
  49930. if (incremental) {
  49931. incremental.clearDisplaybles();
  49932. }
  49933. };
  49934. function isPointNaN(pt) {
  49935. return isNaN(pt[0]) || isNaN(pt[1]);
  49936. }
  49937. function lineNeedsDraw(pts) {
  49938. return !isPointNaN(pts[0]) && !isPointNaN(pts[1]);
  49939. }
  49940. /*
  49941. * Licensed to the Apache Software Foundation (ASF) under one
  49942. * or more contributor license agreements. See the NOTICE file
  49943. * distributed with this work for additional information
  49944. * regarding copyright ownership. The ASF licenses this file
  49945. * to you under the Apache License, Version 2.0 (the
  49946. * "License"); you may not use this file except in compliance
  49947. * with the License. You may obtain a copy of the License at
  49948. *
  49949. * http://www.apache.org/licenses/LICENSE-2.0
  49950. *
  49951. * Unless required by applicable law or agreed to in writing,
  49952. * software distributed under the License is distributed on an
  49953. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49954. * KIND, either express or implied. See the License for the
  49955. * specific language governing permissions and limitations
  49956. * under the License.
  49957. */
  49958. function getNodeGlobalScale(seriesModel) {
  49959. var coordSys = seriesModel.coordinateSystem;
  49960. if (coordSys.type !== 'view') {
  49961. return 1;
  49962. }
  49963. var nodeScaleRatio = seriesModel.option.nodeScaleRatio;
  49964. var groupScale = coordSys.scale;
  49965. var groupZoom = (groupScale && groupScale[0]) || 1;
  49966. // Scale node when zoom changes
  49967. var roamZoom = coordSys.getZoom();
  49968. var nodeScale = (roamZoom - 1) * nodeScaleRatio + 1;
  49969. return nodeScale / groupZoom;
  49970. }
  49971. function getSymbolSize$1(node) {
  49972. var symbolSize = node.getVisual('symbolSize');
  49973. if (symbolSize instanceof Array) {
  49974. symbolSize = (symbolSize[0] + symbolSize[1]) / 2;
  49975. }
  49976. return +symbolSize;
  49977. }
  49978. /*
  49979. * Licensed to the Apache Software Foundation (ASF) under one
  49980. * or more contributor license agreements. See the NOTICE file
  49981. * distributed with this work for additional information
  49982. * regarding copyright ownership. The ASF licenses this file
  49983. * to you under the Apache License, Version 2.0 (the
  49984. * "License"); you may not use this file except in compliance
  49985. * with the License. You may obtain a copy of the License at
  49986. *
  49987. * http://www.apache.org/licenses/LICENSE-2.0
  49988. *
  49989. * Unless required by applicable law or agreed to in writing,
  49990. * software distributed under the License is distributed on an
  49991. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49992. * KIND, either express or implied. See the License for the
  49993. * specific language governing permissions and limitations
  49994. * under the License.
  49995. */
  49996. var v1 = [];
  49997. var v2 = [];
  49998. var v3 = [];
  49999. var quadraticAt$1 = quadraticAt;
  50000. var v2DistSquare = distSquare;
  50001. var mathAbs$1 = Math.abs;
  50002. function intersectCurveCircle(curvePoints, center, radius) {
  50003. var p0 = curvePoints[0];
  50004. var p1 = curvePoints[1];
  50005. var p2 = curvePoints[2];
  50006. var d = Infinity;
  50007. var t;
  50008. var radiusSquare = radius * radius;
  50009. var interval = 0.1;
  50010. for (var _t = 0.1; _t <= 0.9; _t += 0.1) {
  50011. v1[0] = quadraticAt$1(p0[0], p1[0], p2[0], _t);
  50012. v1[1] = quadraticAt$1(p0[1], p1[1], p2[1], _t);
  50013. var diff = mathAbs$1(v2DistSquare(v1, center) - radiusSquare);
  50014. if (diff < d) {
  50015. d = diff;
  50016. t = _t;
  50017. }
  50018. }
  50019. // Assume the segment is monotone,Find root through Bisection method
  50020. // At most 32 iteration
  50021. for (var i = 0; i < 32; i++) {
  50022. // var prev = t - interval;
  50023. var next = t + interval;
  50024. // v1[0] = quadraticAt(p0[0], p1[0], p2[0], prev);
  50025. // v1[1] = quadraticAt(p0[1], p1[1], p2[1], prev);
  50026. v2[0] = quadraticAt$1(p0[0], p1[0], p2[0], t);
  50027. v2[1] = quadraticAt$1(p0[1], p1[1], p2[1], t);
  50028. v3[0] = quadraticAt$1(p0[0], p1[0], p2[0], next);
  50029. v3[1] = quadraticAt$1(p0[1], p1[1], p2[1], next);
  50030. var diff = v2DistSquare(v2, center) - radiusSquare;
  50031. if (mathAbs$1(diff) < 1e-2) {
  50032. break;
  50033. }
  50034. // var prevDiff = v2DistSquare(v1, center) - radiusSquare;
  50035. var nextDiff = v2DistSquare(v3, center) - radiusSquare;
  50036. interval /= 2;
  50037. if (diff < 0) {
  50038. if (nextDiff >= 0) {
  50039. t = t + interval;
  50040. }
  50041. else {
  50042. t = t - interval;
  50043. }
  50044. }
  50045. else {
  50046. if (nextDiff >= 0) {
  50047. t = t - interval;
  50048. }
  50049. else {
  50050. t = t + interval;
  50051. }
  50052. }
  50053. }
  50054. return t;
  50055. }
  50056. // Adjust edge to avoid
  50057. var adjustEdge = function (graph, scale$$1) {
  50058. var tmp0 = [];
  50059. var quadraticSubdivide$$1 = quadraticSubdivide;
  50060. var pts = [[], [], []];
  50061. var pts2 = [[], []];
  50062. var v = [];
  50063. scale$$1 /= 2;
  50064. graph.eachEdge(function (edge, idx) {
  50065. var linePoints = edge.getLayout();
  50066. var fromSymbol = edge.getVisual('fromSymbol');
  50067. var toSymbol = edge.getVisual('toSymbol');
  50068. if (!linePoints.__original) {
  50069. linePoints.__original = [
  50070. clone$1(linePoints[0]),
  50071. clone$1(linePoints[1])
  50072. ];
  50073. if (linePoints[2]) {
  50074. linePoints.__original.push(clone$1(linePoints[2]));
  50075. }
  50076. }
  50077. var originalPoints = linePoints.__original;
  50078. // Quadratic curve
  50079. if (linePoints[2] != null) {
  50080. copy(pts[0], originalPoints[0]);
  50081. copy(pts[1], originalPoints[2]);
  50082. copy(pts[2], originalPoints[1]);
  50083. if (fromSymbol && fromSymbol !== 'none') {
  50084. var symbolSize = getSymbolSize$1(edge.node1);
  50085. var t = intersectCurveCircle(pts, originalPoints[0], symbolSize * scale$$1);
  50086. // Subdivide and get the second
  50087. quadraticSubdivide$$1(pts[0][0], pts[1][0], pts[2][0], t, tmp0);
  50088. pts[0][0] = tmp0[3];
  50089. pts[1][0] = tmp0[4];
  50090. quadraticSubdivide$$1(pts[0][1], pts[1][1], pts[2][1], t, tmp0);
  50091. pts[0][1] = tmp0[3];
  50092. pts[1][1] = tmp0[4];
  50093. }
  50094. if (toSymbol && toSymbol !== 'none') {
  50095. var symbolSize = getSymbolSize$1(edge.node2);
  50096. var t = intersectCurveCircle(pts, originalPoints[1], symbolSize * scale$$1);
  50097. // Subdivide and get the first
  50098. quadraticSubdivide$$1(pts[0][0], pts[1][0], pts[2][0], t, tmp0);
  50099. pts[1][0] = tmp0[1];
  50100. pts[2][0] = tmp0[2];
  50101. quadraticSubdivide$$1(pts[0][1], pts[1][1], pts[2][1], t, tmp0);
  50102. pts[1][1] = tmp0[1];
  50103. pts[2][1] = tmp0[2];
  50104. }
  50105. // Copy back to layout
  50106. copy(linePoints[0], pts[0]);
  50107. copy(linePoints[1], pts[2]);
  50108. copy(linePoints[2], pts[1]);
  50109. }
  50110. // Line
  50111. else {
  50112. copy(pts2[0], originalPoints[0]);
  50113. copy(pts2[1], originalPoints[1]);
  50114. sub(v, pts2[1], pts2[0]);
  50115. normalize(v, v);
  50116. if (fromSymbol && fromSymbol !== 'none') {
  50117. var symbolSize = getSymbolSize$1(edge.node1);
  50118. scaleAndAdd(pts2[0], pts2[0], v, symbolSize * scale$$1);
  50119. }
  50120. if (toSymbol && toSymbol !== 'none') {
  50121. var symbolSize = getSymbolSize$1(edge.node2);
  50122. scaleAndAdd(pts2[1], pts2[1], v, -symbolSize * scale$$1);
  50123. }
  50124. copy(linePoints[0], pts2[0]);
  50125. copy(linePoints[1], pts2[1]);
  50126. }
  50127. });
  50128. };
  50129. /*
  50130. * Licensed to the Apache Software Foundation (ASF) under one
  50131. * or more contributor license agreements. See the NOTICE file
  50132. * distributed with this work for additional information
  50133. * regarding copyright ownership. The ASF licenses this file
  50134. * to you under the Apache License, Version 2.0 (the
  50135. * "License"); you may not use this file except in compliance
  50136. * with the License. You may obtain a copy of the License at
  50137. *
  50138. * http://www.apache.org/licenses/LICENSE-2.0
  50139. *
  50140. * Unless required by applicable law or agreed to in writing,
  50141. * software distributed under the License is distributed on an
  50142. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50143. * KIND, either express or implied. See the License for the
  50144. * specific language governing permissions and limitations
  50145. * under the License.
  50146. */
  50147. var FOCUS_ADJACENCY = '__focusNodeAdjacency';
  50148. var UNFOCUS_ADJACENCY = '__unfocusNodeAdjacency';
  50149. var nodeOpacityPath = ['itemStyle', 'opacity'];
  50150. var lineOpacityPath = ['lineStyle', 'opacity'];
  50151. function getItemOpacity(item, opacityPath) {
  50152. var opacity = item.getVisual('opacity');
  50153. return opacity != null ? opacity : item.getModel().get(opacityPath);
  50154. }
  50155. function fadeOutItem(item, opacityPath, opacityRatio) {
  50156. var el = item.getGraphicEl();
  50157. var opacity = getItemOpacity(item, opacityPath);
  50158. if (opacityRatio != null) {
  50159. opacity == null && (opacity = 1);
  50160. opacity *= opacityRatio;
  50161. }
  50162. el.downplay && el.downplay();
  50163. el.traverse(function (child) {
  50164. if (!child.isGroup) {
  50165. var opct = child.lineLabelOriginalOpacity;
  50166. if (opct == null || opacityRatio != null) {
  50167. opct = opacity;
  50168. }
  50169. child.setStyle('opacity', opct);
  50170. }
  50171. });
  50172. }
  50173. function fadeInItem(item, opacityPath) {
  50174. var opacity = getItemOpacity(item, opacityPath);
  50175. var el = item.getGraphicEl();
  50176. // Should go back to normal opacity first, consider hoverLayer,
  50177. // where current state is copied to elMirror, and support
  50178. // emphasis opacity here.
  50179. el.traverse(function (child) {
  50180. !child.isGroup && child.setStyle('opacity', opacity);
  50181. });
  50182. el.highlight && el.highlight();
  50183. }
  50184. extendChartView({
  50185. type: 'graph',
  50186. init: function (ecModel, api) {
  50187. var symbolDraw = new SymbolDraw();
  50188. var lineDraw = new LineDraw();
  50189. var group = this.group;
  50190. this._controller = new RoamController(api.getZr());
  50191. this._controllerHost = {target: group};
  50192. group.add(symbolDraw.group);
  50193. group.add(lineDraw.group);
  50194. this._symbolDraw = symbolDraw;
  50195. this._lineDraw = lineDraw;
  50196. this._firstRender = true;
  50197. },
  50198. render: function (seriesModel, ecModel, api) {
  50199. var graphView = this;
  50200. var coordSys = seriesModel.coordinateSystem;
  50201. this._model = seriesModel;
  50202. var symbolDraw = this._symbolDraw;
  50203. var lineDraw = this._lineDraw;
  50204. var group = this.group;
  50205. if (coordSys.type === 'view') {
  50206. var groupNewProp = {
  50207. position: coordSys.position,
  50208. scale: coordSys.scale
  50209. };
  50210. if (this._firstRender) {
  50211. group.attr(groupNewProp);
  50212. }
  50213. else {
  50214. updateProps(group, groupNewProp, seriesModel);
  50215. }
  50216. }
  50217. // Fix edge contact point with node
  50218. adjustEdge(seriesModel.getGraph(), getNodeGlobalScale(seriesModel));
  50219. var data = seriesModel.getData();
  50220. symbolDraw.updateData(data);
  50221. var edgeData = seriesModel.getEdgeData();
  50222. lineDraw.updateData(edgeData);
  50223. this._updateNodeAndLinkScale();
  50224. this._updateController(seriesModel, ecModel, api);
  50225. clearTimeout(this._layoutTimeout);
  50226. var forceLayout = seriesModel.forceLayout;
  50227. var layoutAnimation = seriesModel.get('force.layoutAnimation');
  50228. if (forceLayout) {
  50229. this._startForceLayoutIteration(forceLayout, layoutAnimation);
  50230. }
  50231. data.eachItemGraphicEl(function (el, idx) {
  50232. var itemModel = data.getItemModel(idx);
  50233. // Update draggable
  50234. el.off('drag').off('dragend');
  50235. var draggable = itemModel.get('draggable');
  50236. if (draggable) {
  50237. el.on('drag', function () {
  50238. if (forceLayout) {
  50239. forceLayout.warmUp();
  50240. !this._layouting
  50241. && this._startForceLayoutIteration(forceLayout, layoutAnimation);
  50242. forceLayout.setFixed(idx);
  50243. // Write position back to layout
  50244. data.setItemLayout(idx, el.position);
  50245. }
  50246. }, this).on('dragend', function () {
  50247. if (forceLayout) {
  50248. forceLayout.setUnfixed(idx);
  50249. }
  50250. }, this);
  50251. }
  50252. el.setDraggable(draggable && forceLayout);
  50253. el[FOCUS_ADJACENCY] && el.off('mouseover', el[FOCUS_ADJACENCY]);
  50254. el[UNFOCUS_ADJACENCY] && el.off('mouseout', el[UNFOCUS_ADJACENCY]);
  50255. if (itemModel.get('focusNodeAdjacency')) {
  50256. el.on('mouseover', el[FOCUS_ADJACENCY] = function () {
  50257. graphView._clearTimer();
  50258. api.dispatchAction({
  50259. type: 'focusNodeAdjacency',
  50260. seriesId: seriesModel.id,
  50261. dataIndex: el.dataIndex
  50262. });
  50263. });
  50264. el.on('mouseout', el[UNFOCUS_ADJACENCY] = function () {
  50265. graphView._dispatchUnfocus(api);
  50266. });
  50267. }
  50268. }, this);
  50269. data.graph.eachEdge(function (edge) {
  50270. var el = edge.getGraphicEl();
  50271. el[FOCUS_ADJACENCY] && el.off('mouseover', el[FOCUS_ADJACENCY]);
  50272. el[UNFOCUS_ADJACENCY] && el.off('mouseout', el[UNFOCUS_ADJACENCY]);
  50273. if (edge.getModel().get('focusNodeAdjacency')) {
  50274. el.on('mouseover', el[FOCUS_ADJACENCY] = function () {
  50275. graphView._clearTimer();
  50276. api.dispatchAction({
  50277. type: 'focusNodeAdjacency',
  50278. seriesId: seriesModel.id,
  50279. edgeDataIndex: edge.dataIndex
  50280. });
  50281. });
  50282. el.on('mouseout', el[UNFOCUS_ADJACENCY] = function () {
  50283. graphView._dispatchUnfocus(api);
  50284. });
  50285. }
  50286. });
  50287. var circularRotateLabel = seriesModel.get('layout') === 'circular'
  50288. && seriesModel.get('circular.rotateLabel');
  50289. var cx = data.getLayout('cx');
  50290. var cy = data.getLayout('cy');
  50291. data.eachItemGraphicEl(function (el, idx) {
  50292. var itemModel = data.getItemModel(idx);
  50293. var labelRotate = itemModel.get('label.rotate') || 0;
  50294. var symbolPath = el.getSymbolPath();
  50295. if (circularRotateLabel) {
  50296. var pos = data.getItemLayout(idx);
  50297. var rad = Math.atan2(pos[1] - cy, pos[0] - cx);
  50298. if (rad < 0) {
  50299. rad = Math.PI * 2 + rad;
  50300. }
  50301. var isLeft = pos[0] < cx;
  50302. if (isLeft) {
  50303. rad = rad - Math.PI;
  50304. }
  50305. var textPosition = isLeft ? 'left' : 'right';
  50306. modifyLabelStyle(
  50307. symbolPath,
  50308. {
  50309. textRotation: -rad,
  50310. textPosition: textPosition,
  50311. textOrigin: 'center'
  50312. },
  50313. {
  50314. textPosition: textPosition
  50315. }
  50316. );
  50317. }
  50318. else {
  50319. modifyLabelStyle(
  50320. symbolPath,
  50321. {
  50322. textRotation: labelRotate *= Math.PI / 180
  50323. }
  50324. );
  50325. }
  50326. });
  50327. this._firstRender = false;
  50328. },
  50329. dispose: function () {
  50330. this._controller && this._controller.dispose();
  50331. this._controllerHost = {};
  50332. this._clearTimer();
  50333. },
  50334. _dispatchUnfocus: function (api, opt) {
  50335. var self = this;
  50336. this._clearTimer();
  50337. this._unfocusDelayTimer = setTimeout(function () {
  50338. self._unfocusDelayTimer = null;
  50339. api.dispatchAction({
  50340. type: 'unfocusNodeAdjacency',
  50341. seriesId: self._model.id
  50342. });
  50343. }, 500);
  50344. },
  50345. _clearTimer: function () {
  50346. if (this._unfocusDelayTimer) {
  50347. clearTimeout(this._unfocusDelayTimer);
  50348. this._unfocusDelayTimer = null;
  50349. }
  50350. },
  50351. focusNodeAdjacency: function (seriesModel, ecModel, api, payload) {
  50352. var data = seriesModel.getData();
  50353. var graph = data.graph;
  50354. var dataIndex = payload.dataIndex;
  50355. var edgeDataIndex = payload.edgeDataIndex;
  50356. var node = graph.getNodeByIndex(dataIndex);
  50357. var edge = graph.getEdgeByIndex(edgeDataIndex);
  50358. if (!node && !edge) {
  50359. return;
  50360. }
  50361. graph.eachNode(function (node) {
  50362. fadeOutItem(node, nodeOpacityPath, 0.1);
  50363. });
  50364. graph.eachEdge(function (edge) {
  50365. fadeOutItem(edge, lineOpacityPath, 0.1);
  50366. });
  50367. if (node) {
  50368. fadeInItem(node, nodeOpacityPath);
  50369. each$1(node.edges, function (adjacentEdge) {
  50370. if (adjacentEdge.dataIndex < 0) {
  50371. return;
  50372. }
  50373. fadeInItem(adjacentEdge, lineOpacityPath);
  50374. fadeInItem(adjacentEdge.node1, nodeOpacityPath);
  50375. fadeInItem(adjacentEdge.node2, nodeOpacityPath);
  50376. });
  50377. }
  50378. if (edge) {
  50379. fadeInItem(edge, lineOpacityPath);
  50380. fadeInItem(edge.node1, nodeOpacityPath);
  50381. fadeInItem(edge.node2, nodeOpacityPath);
  50382. }
  50383. },
  50384. unfocusNodeAdjacency: function (seriesModel, ecModel, api, payload) {
  50385. var graph = seriesModel.getData().graph;
  50386. graph.eachNode(function (node) {
  50387. fadeOutItem(node, nodeOpacityPath);
  50388. });
  50389. graph.eachEdge(function (edge) {
  50390. fadeOutItem(edge, lineOpacityPath);
  50391. });
  50392. },
  50393. _startForceLayoutIteration: function (forceLayout, layoutAnimation) {
  50394. var self = this;
  50395. (function step() {
  50396. forceLayout.step(function (stopped) {
  50397. self.updateLayout(self._model);
  50398. (self._layouting = !stopped) && (
  50399. layoutAnimation
  50400. ? (self._layoutTimeout = setTimeout(step, 16))
  50401. : step()
  50402. );
  50403. });
  50404. })();
  50405. },
  50406. _updateController: function (seriesModel, ecModel, api) {
  50407. var controller = this._controller;
  50408. var controllerHost = this._controllerHost;
  50409. var group = this.group;
  50410. controller.setPointerChecker(function (e, x, y) {
  50411. var rect = group.getBoundingRect();
  50412. rect.applyTransform(group.transform);
  50413. return rect.contain(x, y)
  50414. && !onIrrelevantElement(e, api, seriesModel);
  50415. });
  50416. if (seriesModel.coordinateSystem.type !== 'view') {
  50417. controller.disable();
  50418. return;
  50419. }
  50420. controller.enable(seriesModel.get('roam'));
  50421. controllerHost.zoomLimit = seriesModel.get('scaleLimit');
  50422. controllerHost.zoom = seriesModel.coordinateSystem.getZoom();
  50423. controller
  50424. .off('pan')
  50425. .off('zoom')
  50426. .on('pan', function (e) {
  50427. updateViewOnPan(controllerHost, e.dx, e.dy);
  50428. api.dispatchAction({
  50429. seriesId: seriesModel.id,
  50430. type: 'graphRoam',
  50431. dx: e.dx,
  50432. dy: e.dy
  50433. });
  50434. })
  50435. .on('zoom', function (e) {
  50436. updateViewOnZoom(controllerHost, e.scale, e.originX, e.originY);
  50437. api.dispatchAction({
  50438. seriesId: seriesModel.id,
  50439. type: 'graphRoam',
  50440. zoom: e.scale,
  50441. originX: e.originX,
  50442. originY: e.originY
  50443. });
  50444. this._updateNodeAndLinkScale();
  50445. adjustEdge(seriesModel.getGraph(), getNodeGlobalScale(seriesModel));
  50446. this._lineDraw.updateLayout();
  50447. }, this);
  50448. },
  50449. _updateNodeAndLinkScale: function () {
  50450. var seriesModel = this._model;
  50451. var data = seriesModel.getData();
  50452. var nodeScale = getNodeGlobalScale(seriesModel);
  50453. var invScale = [nodeScale, nodeScale];
  50454. data.eachItemGraphicEl(function (el, idx) {
  50455. el.attr('scale', invScale);
  50456. });
  50457. },
  50458. updateLayout: function (seriesModel) {
  50459. adjustEdge(seriesModel.getGraph(), getNodeGlobalScale(seriesModel));
  50460. this._symbolDraw.updateLayout();
  50461. this._lineDraw.updateLayout();
  50462. },
  50463. remove: function (ecModel, api) {
  50464. this._symbolDraw && this._symbolDraw.remove();
  50465. this._lineDraw && this._lineDraw.remove();
  50466. }
  50467. });
  50468. /*
  50469. * Licensed to the Apache Software Foundation (ASF) under one
  50470. * or more contributor license agreements. See the NOTICE file
  50471. * distributed with this work for additional information
  50472. * regarding copyright ownership. The ASF licenses this file
  50473. * to you under the Apache License, Version 2.0 (the
  50474. * "License"); you may not use this file except in compliance
  50475. * with the License. You may obtain a copy of the License at
  50476. *
  50477. * http://www.apache.org/licenses/LICENSE-2.0
  50478. *
  50479. * Unless required by applicable law or agreed to in writing,
  50480. * software distributed under the License is distributed on an
  50481. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50482. * KIND, either express or implied. See the License for the
  50483. * specific language governing permissions and limitations
  50484. * under the License.
  50485. */
  50486. /**
  50487. * @payload
  50488. * @property {number} [seriesIndex]
  50489. * @property {string} [seriesId]
  50490. * @property {string} [seriesName]
  50491. * @property {number} [dataIndex]
  50492. */
  50493. registerAction({
  50494. type: 'focusNodeAdjacency',
  50495. event: 'focusNodeAdjacency',
  50496. update: 'series:focusNodeAdjacency'
  50497. }, function () {});
  50498. /**
  50499. * @payload
  50500. * @property {number} [seriesIndex]
  50501. * @property {string} [seriesId]
  50502. * @property {string} [seriesName]
  50503. */
  50504. registerAction({
  50505. type: 'unfocusNodeAdjacency',
  50506. event: 'unfocusNodeAdjacency',
  50507. update: 'series:unfocusNodeAdjacency'
  50508. }, function () {});
  50509. /*
  50510. * Licensed to the Apache Software Foundation (ASF) under one
  50511. * or more contributor license agreements. See the NOTICE file
  50512. * distributed with this work for additional information
  50513. * regarding copyright ownership. The ASF licenses this file
  50514. * to you under the Apache License, Version 2.0 (the
  50515. * "License"); you may not use this file except in compliance
  50516. * with the License. You may obtain a copy of the License at
  50517. *
  50518. * http://www.apache.org/licenses/LICENSE-2.0
  50519. *
  50520. * Unless required by applicable law or agreed to in writing,
  50521. * software distributed under the License is distributed on an
  50522. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50523. * KIND, either express or implied. See the License for the
  50524. * specific language governing permissions and limitations
  50525. * under the License.
  50526. */
  50527. var actionInfo = {
  50528. type: 'graphRoam',
  50529. event: 'graphRoam',
  50530. update: 'none'
  50531. };
  50532. /**
  50533. * @payload
  50534. * @property {string} name Series name
  50535. * @property {number} [dx]
  50536. * @property {number} [dy]
  50537. * @property {number} [zoom]
  50538. * @property {number} [originX]
  50539. * @property {number} [originY]
  50540. */
  50541. registerAction(actionInfo, function (payload, ecModel) {
  50542. ecModel.eachComponent({mainType: 'series', query: payload}, function (seriesModel) {
  50543. var coordSys = seriesModel.coordinateSystem;
  50544. var res = updateCenterAndZoom(coordSys, payload);
  50545. seriesModel.setCenter
  50546. && seriesModel.setCenter(res.center);
  50547. seriesModel.setZoom
  50548. && seriesModel.setZoom(res.zoom);
  50549. });
  50550. });
  50551. /*
  50552. * Licensed to the Apache Software Foundation (ASF) under one
  50553. * or more contributor license agreements. See the NOTICE file
  50554. * distributed with this work for additional information
  50555. * regarding copyright ownership. The ASF licenses this file
  50556. * to you under the Apache License, Version 2.0 (the
  50557. * "License"); you may not use this file except in compliance
  50558. * with the License. You may obtain a copy of the License at
  50559. *
  50560. * http://www.apache.org/licenses/LICENSE-2.0
  50561. *
  50562. * Unless required by applicable law or agreed to in writing,
  50563. * software distributed under the License is distributed on an
  50564. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50565. * KIND, either express or implied. See the License for the
  50566. * specific language governing permissions and limitations
  50567. * under the License.
  50568. */
  50569. var categoryFilter = function (ecModel) {
  50570. var legendModels = ecModel.findComponents({
  50571. mainType: 'legend'
  50572. });
  50573. if (!legendModels || !legendModels.length) {
  50574. return;
  50575. }
  50576. ecModel.eachSeriesByType('graph', function (graphSeries) {
  50577. var categoriesData = graphSeries.getCategoriesData();
  50578. var graph = graphSeries.getGraph();
  50579. var data = graph.data;
  50580. var categoryNames = categoriesData.mapArray(categoriesData.getName);
  50581. data.filterSelf(function (idx) {
  50582. var model = data.getItemModel(idx);
  50583. var category = model.getShallow('category');
  50584. if (category != null) {
  50585. if (typeof category === 'number') {
  50586. category = categoryNames[category];
  50587. }
  50588. // If in any legend component the status is not selected.
  50589. for (var i = 0; i < legendModels.length; i++) {
  50590. if (!legendModels[i].isSelected(category)) {
  50591. return false;
  50592. }
  50593. }
  50594. }
  50595. return true;
  50596. });
  50597. }, this);
  50598. };
  50599. /*
  50600. * Licensed to the Apache Software Foundation (ASF) under one
  50601. * or more contributor license agreements. See the NOTICE file
  50602. * distributed with this work for additional information
  50603. * regarding copyright ownership. The ASF licenses this file
  50604. * to you under the Apache License, Version 2.0 (the
  50605. * "License"); you may not use this file except in compliance
  50606. * with the License. You may obtain a copy of the License at
  50607. *
  50608. * http://www.apache.org/licenses/LICENSE-2.0
  50609. *
  50610. * Unless required by applicable law or agreed to in writing,
  50611. * software distributed under the License is distributed on an
  50612. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50613. * KIND, either express or implied. See the License for the
  50614. * specific language governing permissions and limitations
  50615. * under the License.
  50616. */
  50617. var categoryVisual = function (ecModel) {
  50618. var paletteScope = {};
  50619. ecModel.eachSeriesByType('graph', function (seriesModel) {
  50620. var categoriesData = seriesModel.getCategoriesData();
  50621. var data = seriesModel.getData();
  50622. var categoryNameIdxMap = {};
  50623. categoriesData.each(function (idx) {
  50624. var name = categoriesData.getName(idx);
  50625. // Add prefix to avoid conflict with Object.prototype.
  50626. categoryNameIdxMap['ec-' + name] = idx;
  50627. var itemModel = categoriesData.getItemModel(idx);
  50628. var color = itemModel.get('itemStyle.color')
  50629. || seriesModel.getColorFromPalette(name, paletteScope);
  50630. categoriesData.setItemVisual(idx, 'color', color);
  50631. var itemStyleList = ['opacity', 'symbol', 'symbolSize', 'symbolKeepAspect'];
  50632. for (var i = 0; i < itemStyleList.length; i++) {
  50633. var itemStyle = itemModel.getShallow(itemStyleList[i], true);
  50634. if (itemStyle != null) {
  50635. categoriesData.setItemVisual(idx, itemStyleList[i], itemStyle);
  50636. }
  50637. }
  50638. });
  50639. // Assign category color to visual
  50640. if (categoriesData.count()) {
  50641. data.each(function (idx) {
  50642. var model = data.getItemModel(idx);
  50643. var category = model.getShallow('category');
  50644. if (category != null) {
  50645. if (typeof category === 'string') {
  50646. category = categoryNameIdxMap['ec-' + category];
  50647. }
  50648. var itemStyleList = ['color', 'opacity', 'symbol', 'symbolSize', 'symbolKeepAspect'];
  50649. for (var i = 0; i < itemStyleList.length; i++) {
  50650. if (data.getItemVisual(idx, itemStyleList[i], true) == null) {
  50651. data.setItemVisual(
  50652. idx, itemStyleList[i],
  50653. categoriesData.getItemVisual(category, itemStyleList[i])
  50654. );
  50655. }
  50656. }
  50657. }
  50658. });
  50659. }
  50660. });
  50661. };
  50662. /*
  50663. * Licensed to the Apache Software Foundation (ASF) under one
  50664. * or more contributor license agreements. See the NOTICE file
  50665. * distributed with this work for additional information
  50666. * regarding copyright ownership. The ASF licenses this file
  50667. * to you under the Apache License, Version 2.0 (the
  50668. * "License"); you may not use this file except in compliance
  50669. * with the License. You may obtain a copy of the License at
  50670. *
  50671. * http://www.apache.org/licenses/LICENSE-2.0
  50672. *
  50673. * Unless required by applicable law or agreed to in writing,
  50674. * software distributed under the License is distributed on an
  50675. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50676. * KIND, either express or implied. See the License for the
  50677. * specific language governing permissions and limitations
  50678. * under the License.
  50679. */
  50680. function normalize$1(a) {
  50681. if (!(a instanceof Array)) {
  50682. a = [a, a];
  50683. }
  50684. return a;
  50685. }
  50686. var edgeVisual = function (ecModel) {
  50687. ecModel.eachSeriesByType('graph', function (seriesModel) {
  50688. var graph = seriesModel.getGraph();
  50689. var edgeData = seriesModel.getEdgeData();
  50690. var symbolType = normalize$1(seriesModel.get('edgeSymbol'));
  50691. var symbolSize = normalize$1(seriesModel.get('edgeSymbolSize'));
  50692. var colorQuery = 'lineStyle.color'.split('.');
  50693. var opacityQuery = 'lineStyle.opacity'.split('.');
  50694. edgeData.setVisual('fromSymbol', symbolType && symbolType[0]);
  50695. edgeData.setVisual('toSymbol', symbolType && symbolType[1]);
  50696. edgeData.setVisual('fromSymbolSize', symbolSize && symbolSize[0]);
  50697. edgeData.setVisual('toSymbolSize', symbolSize && symbolSize[1]);
  50698. edgeData.setVisual('color', seriesModel.get(colorQuery));
  50699. edgeData.setVisual('opacity', seriesModel.get(opacityQuery));
  50700. edgeData.each(function (idx) {
  50701. var itemModel = edgeData.getItemModel(idx);
  50702. var edge = graph.getEdgeByIndex(idx);
  50703. var symbolType = normalize$1(itemModel.getShallow('symbol', true));
  50704. var symbolSize = normalize$1(itemModel.getShallow('symbolSize', true));
  50705. // Edge visual must after node visual
  50706. var color = itemModel.get(colorQuery);
  50707. var opacity = itemModel.get(opacityQuery);
  50708. switch (color) {
  50709. case 'source':
  50710. color = edge.node1.getVisual('color');
  50711. break;
  50712. case 'target':
  50713. color = edge.node2.getVisual('color');
  50714. break;
  50715. }
  50716. symbolType[0] && edge.setVisual('fromSymbol', symbolType[0]);
  50717. symbolType[1] && edge.setVisual('toSymbol', symbolType[1]);
  50718. symbolSize[0] && edge.setVisual('fromSymbolSize', symbolSize[0]);
  50719. symbolSize[1] && edge.setVisual('toSymbolSize', symbolSize[1]);
  50720. edge.setVisual('color', color);
  50721. edge.setVisual('opacity', opacity);
  50722. });
  50723. });
  50724. };
  50725. /*
  50726. * Licensed to the Apache Software Foundation (ASF) under one
  50727. * or more contributor license agreements. See the NOTICE file
  50728. * distributed with this work for additional information
  50729. * regarding copyright ownership. The ASF licenses this file
  50730. * to you under the Apache License, Version 2.0 (the
  50731. * "License"); you may not use this file except in compliance
  50732. * with the License. You may obtain a copy of the License at
  50733. *
  50734. * http://www.apache.org/licenses/LICENSE-2.0
  50735. *
  50736. * Unless required by applicable law or agreed to in writing,
  50737. * software distributed under the License is distributed on an
  50738. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50739. * KIND, either express or implied. See the License for the
  50740. * specific language governing permissions and limitations
  50741. * under the License.
  50742. */
  50743. function simpleLayout$1(seriesModel) {
  50744. var coordSys = seriesModel.coordinateSystem;
  50745. if (coordSys && coordSys.type !== 'view') {
  50746. return;
  50747. }
  50748. var graph = seriesModel.getGraph();
  50749. graph.eachNode(function (node) {
  50750. var model = node.getModel();
  50751. node.setLayout([+model.get('x'), +model.get('y')]);
  50752. });
  50753. simpleLayoutEdge(graph);
  50754. }
  50755. function simpleLayoutEdge(graph) {
  50756. graph.eachEdge(function (edge) {
  50757. var curveness = edge.getModel().get('lineStyle.curveness') || 0;
  50758. var p1 = clone$1(edge.node1.getLayout());
  50759. var p2 = clone$1(edge.node2.getLayout());
  50760. var points = [p1, p2];
  50761. if (+curveness) {
  50762. points.push([
  50763. (p1[0] + p2[0]) / 2 - (p1[1] - p2[1]) * curveness,
  50764. (p1[1] + p2[1]) / 2 - (p2[0] - p1[0]) * curveness
  50765. ]);
  50766. }
  50767. edge.setLayout(points);
  50768. });
  50769. }
  50770. /*
  50771. * Licensed to the Apache Software Foundation (ASF) under one
  50772. * or more contributor license agreements. See the NOTICE file
  50773. * distributed with this work for additional information
  50774. * regarding copyright ownership. The ASF licenses this file
  50775. * to you under the Apache License, Version 2.0 (the
  50776. * "License"); you may not use this file except in compliance
  50777. * with the License. You may obtain a copy of the License at
  50778. *
  50779. * http://www.apache.org/licenses/LICENSE-2.0
  50780. *
  50781. * Unless required by applicable law or agreed to in writing,
  50782. * software distributed under the License is distributed on an
  50783. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50784. * KIND, either express or implied. See the License for the
  50785. * specific language governing permissions and limitations
  50786. * under the License.
  50787. */
  50788. var simpleLayout = function (ecModel, api) {
  50789. ecModel.eachSeriesByType('graph', function (seriesModel) {
  50790. var layout = seriesModel.get('layout');
  50791. var coordSys = seriesModel.coordinateSystem;
  50792. if (coordSys && coordSys.type !== 'view') {
  50793. var data = seriesModel.getData();
  50794. var dimensions = [];
  50795. each$1(coordSys.dimensions, function (coordDim) {
  50796. dimensions = dimensions.concat(data.mapDimension(coordDim, true));
  50797. });
  50798. for (var dataIndex = 0; dataIndex < data.count(); dataIndex++) {
  50799. var value = [];
  50800. var hasValue = false;
  50801. for (var i = 0; i < dimensions.length; i++) {
  50802. var val = data.get(dimensions[i], dataIndex);
  50803. if (!isNaN(val)) {
  50804. hasValue = true;
  50805. }
  50806. value.push(val);
  50807. }
  50808. if (hasValue) {
  50809. data.setItemLayout(dataIndex, coordSys.dataToPoint(value));
  50810. }
  50811. else {
  50812. // Also {Array.<number>}, not undefined to avoid if...else... statement
  50813. data.setItemLayout(dataIndex, [NaN, NaN]);
  50814. }
  50815. }
  50816. simpleLayoutEdge(data.graph);
  50817. }
  50818. else if (!layout || layout === 'none') {
  50819. simpleLayout$1(seriesModel);
  50820. }
  50821. });
  50822. };
  50823. /*
  50824. * Licensed to the Apache Software Foundation (ASF) under one
  50825. * or more contributor license agreements. See the NOTICE file
  50826. * distributed with this work for additional information
  50827. * regarding copyright ownership. The ASF licenses this file
  50828. * to you under the Apache License, Version 2.0 (the
  50829. * "License"); you may not use this file except in compliance
  50830. * with the License. You may obtain a copy of the License at
  50831. *
  50832. * http://www.apache.org/licenses/LICENSE-2.0
  50833. *
  50834. * Unless required by applicable law or agreed to in writing,
  50835. * software distributed under the License is distributed on an
  50836. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50837. * KIND, either express or implied. See the License for the
  50838. * specific language governing permissions and limitations
  50839. * under the License.
  50840. */
  50841. var PI$3 = Math.PI;
  50842. var _symbolRadiansHalf = [];
  50843. /**
  50844. * `basedOn` can be:
  50845. * 'value':
  50846. * This layout is not accurate and have same bad case. For example,
  50847. * if the min value is very smaller than the max value, the nodes
  50848. * with the min value probably overlap even though there is enough
  50849. * space to layout them. So we only use this approach in the as the
  50850. * init layout of the force layout.
  50851. * FIXME
  50852. * Probably we do not need this method any more but use
  50853. * `basedOn: 'symbolSize'` in force layout if
  50854. * delay its init operations to GraphView.
  50855. * 'symbolSize':
  50856. * This approach work only if all of the symbol size calculated.
  50857. * That is, the progressive rendering is not applied to graph.
  50858. * FIXME
  50859. * If progressive rendering is applied to graph some day,
  50860. * probably we have to use `basedOn: 'value'`.
  50861. *
  50862. * @param {module:echarts/src/model/Series} seriesModel
  50863. * @param {string} basedOn 'value' or 'symbolSize'
  50864. */
  50865. function circularLayout$1(seriesModel, basedOn) {
  50866. var coordSys = seriesModel.coordinateSystem;
  50867. if (coordSys && coordSys.type !== 'view') {
  50868. return;
  50869. }
  50870. var rect = coordSys.getBoundingRect();
  50871. var nodeData = seriesModel.getData();
  50872. var graph = nodeData.graph;
  50873. var cx = rect.width / 2 + rect.x;
  50874. var cy = rect.height / 2 + rect.y;
  50875. var r = Math.min(rect.width, rect.height) / 2;
  50876. var count = nodeData.count();
  50877. nodeData.setLayout({
  50878. cx: cx,
  50879. cy: cy
  50880. });
  50881. if (!count) {
  50882. return;
  50883. }
  50884. _layoutNodesBasedOn[basedOn](seriesModel, coordSys, graph, nodeData, r, cx, cy, count);
  50885. graph.eachEdge(function (edge) {
  50886. var curveness = edge.getModel().get('lineStyle.curveness') || 0;
  50887. var p1 = clone$1(edge.node1.getLayout());
  50888. var p2 = clone$1(edge.node2.getLayout());
  50889. var cp1;
  50890. var x12 = (p1[0] + p2[0]) / 2;
  50891. var y12 = (p1[1] + p2[1]) / 2;
  50892. if (+curveness) {
  50893. curveness *= 3;
  50894. cp1 = [
  50895. cx * curveness + x12 * (1 - curveness),
  50896. cy * curveness + y12 * (1 - curveness)
  50897. ];
  50898. }
  50899. edge.setLayout([p1, p2, cp1]);
  50900. });
  50901. }
  50902. var _layoutNodesBasedOn = {
  50903. value: function (seriesModel, coordSys, graph, nodeData, r, cx, cy, count) {
  50904. var angle = 0;
  50905. var sum = nodeData.getSum('value');
  50906. var unitAngle = Math.PI * 2 / (sum || count);
  50907. graph.eachNode(function (node) {
  50908. var value = node.getValue('value');
  50909. var radianHalf = unitAngle * (sum ? value : 1) / 2;
  50910. angle += radianHalf;
  50911. node.setLayout([
  50912. r * Math.cos(angle) + cx,
  50913. r * Math.sin(angle) + cy
  50914. ]);
  50915. angle += radianHalf;
  50916. });
  50917. },
  50918. symbolSize: function (seriesModel, coordSys, graph, nodeData, r, cx, cy, count) {
  50919. var sumRadian = 0;
  50920. _symbolRadiansHalf.length = count;
  50921. var nodeScale = getNodeGlobalScale(seriesModel);
  50922. graph.eachNode(function (node) {
  50923. var symbolSize = getSymbolSize$1(node);
  50924. // Normally this case will not happen, but we still add
  50925. // some the defensive code (2px is an arbitrary value).
  50926. isNaN(symbolSize) && (symbolSize = 2);
  50927. symbolSize < 0 && (symbolSize = 0);
  50928. symbolSize *= nodeScale;
  50929. var symbolRadianHalf = Math.asin(symbolSize / 2 / r);
  50930. // when `symbolSize / 2` is bigger than `r`.
  50931. isNaN(symbolRadianHalf) && (symbolRadianHalf = PI$3 / 2);
  50932. _symbolRadiansHalf[node.dataIndex] = symbolRadianHalf;
  50933. sumRadian += symbolRadianHalf * 2;
  50934. });
  50935. var halfRemainRadian = (2 * PI$3 - sumRadian) / count / 2;
  50936. var angle = 0;
  50937. graph.eachNode(function (node) {
  50938. var radianHalf = halfRemainRadian + _symbolRadiansHalf[node.dataIndex];
  50939. angle += radianHalf;
  50940. node.setLayout([
  50941. r * Math.cos(angle) + cx,
  50942. r * Math.sin(angle) + cy
  50943. ]);
  50944. angle += radianHalf;
  50945. });
  50946. }
  50947. };
  50948. /*
  50949. * Licensed to the Apache Software Foundation (ASF) under one
  50950. * or more contributor license agreements. See the NOTICE file
  50951. * distributed with this work for additional information
  50952. * regarding copyright ownership. The ASF licenses this file
  50953. * to you under the Apache License, Version 2.0 (the
  50954. * "License"); you may not use this file except in compliance
  50955. * with the License. You may obtain a copy of the License at
  50956. *
  50957. * http://www.apache.org/licenses/LICENSE-2.0
  50958. *
  50959. * Unless required by applicable law or agreed to in writing,
  50960. * software distributed under the License is distributed on an
  50961. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50962. * KIND, either express or implied. See the License for the
  50963. * specific language governing permissions and limitations
  50964. * under the License.
  50965. */
  50966. var circularLayout = function (ecModel) {
  50967. ecModel.eachSeriesByType('graph', function (seriesModel) {
  50968. if (seriesModel.get('layout') === 'circular') {
  50969. circularLayout$1(seriesModel, 'symbolSize');
  50970. }
  50971. });
  50972. };
  50973. /*
  50974. * Licensed to the Apache Software Foundation (ASF) under one
  50975. * or more contributor license agreements. See the NOTICE file
  50976. * distributed with this work for additional information
  50977. * regarding copyright ownership. The ASF licenses this file
  50978. * to you under the Apache License, Version 2.0 (the
  50979. * "License"); you may not use this file except in compliance
  50980. * with the License. You may obtain a copy of the License at
  50981. *
  50982. * http://www.apache.org/licenses/LICENSE-2.0
  50983. *
  50984. * Unless required by applicable law or agreed to in writing,
  50985. * software distributed under the License is distributed on an
  50986. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50987. * KIND, either express or implied. See the License for the
  50988. * specific language governing permissions and limitations
  50989. * under the License.
  50990. */
  50991. /*
  50992. * A third-party license is embeded for some of the code in this file:
  50993. * Some formulas were originally copied from "d3.js" with some
  50994. * modifications made for this project.
  50995. * (See more details in the comment of the method "step" below.)
  50996. * The use of the source code of this file is also subject to the terms
  50997. * and consitions of the license of "d3.js" (BSD-3Clause, see
  50998. * </licenses/LICENSE-d3>).
  50999. */
  51000. var scaleAndAdd$2 = scaleAndAdd;
  51001. // function adjacentNode(n, e) {
  51002. // return e.n1 === n ? e.n2 : e.n1;
  51003. // }
  51004. function forceLayout$1(nodes, edges, opts) {
  51005. var rect = opts.rect;
  51006. var width = rect.width;
  51007. var height = rect.height;
  51008. var center = [rect.x + width / 2, rect.y + height / 2];
  51009. // var scale = opts.scale || 1;
  51010. var gravity = opts.gravity == null ? 0.1 : opts.gravity;
  51011. // for (var i = 0; i < edges.length; i++) {
  51012. // var e = edges[i];
  51013. // var n1 = e.n1;
  51014. // var n2 = e.n2;
  51015. // n1.edges = n1.edges || [];
  51016. // n2.edges = n2.edges || [];
  51017. // n1.edges.push(e);
  51018. // n2.edges.push(e);
  51019. // }
  51020. // Init position
  51021. for (var i = 0; i < nodes.length; i++) {
  51022. var n = nodes[i];
  51023. if (!n.p) {
  51024. n.p = create(
  51025. width * (Math.random() - 0.5) + center[0],
  51026. height * (Math.random() - 0.5) + center[1]
  51027. );
  51028. }
  51029. n.pp = clone$1(n.p);
  51030. n.edges = null;
  51031. }
  51032. // Formula in 'Graph Drawing by Force-directed Placement'
  51033. // var k = scale * Math.sqrt(width * height / nodes.length);
  51034. // var k2 = k * k;
  51035. var initialFriction = opts.friction == null ? 0.6 : opts.friction;
  51036. var friction = initialFriction;
  51037. return {
  51038. warmUp: function () {
  51039. friction = initialFriction * 0.8;
  51040. },
  51041. setFixed: function (idx) {
  51042. nodes[idx].fixed = true;
  51043. },
  51044. setUnfixed: function (idx) {
  51045. nodes[idx].fixed = false;
  51046. },
  51047. /**
  51048. * Some formulas were originally copied from "d3.js"
  51049. * https://github.com/d3/d3/blob/b516d77fb8566b576088e73410437494717ada26/src/layout/force.js
  51050. * with some modifications made for this project.
  51051. * See the license statement at the head of this file.
  51052. */
  51053. step: function (cb) {
  51054. var v12 = [];
  51055. var nLen = nodes.length;
  51056. for (var i = 0; i < edges.length; i++) {
  51057. var e = edges[i];
  51058. if (e.ignoreForceLayout) {
  51059. continue;
  51060. }
  51061. var n1 = e.n1;
  51062. var n2 = e.n2;
  51063. sub(v12, n2.p, n1.p);
  51064. var d = len(v12) - e.d;
  51065. var w = n2.w / (n1.w + n2.w);
  51066. if (isNaN(w)) {
  51067. w = 0;
  51068. }
  51069. normalize(v12, v12);
  51070. !n1.fixed && scaleAndAdd$2(n1.p, n1.p, v12, w * d * friction);
  51071. !n2.fixed && scaleAndAdd$2(n2.p, n2.p, v12, -(1 - w) * d * friction);
  51072. }
  51073. // Gravity
  51074. for (var i = 0; i < nLen; i++) {
  51075. var n = nodes[i];
  51076. if (!n.fixed) {
  51077. sub(v12, center, n.p);
  51078. // var d = vec2.len(v12);
  51079. // vec2.scale(v12, v12, 1 / d);
  51080. // var gravityFactor = gravity;
  51081. scaleAndAdd$2(n.p, n.p, v12, gravity * friction);
  51082. }
  51083. }
  51084. // Repulsive
  51085. // PENDING
  51086. for (var i = 0; i < nLen; i++) {
  51087. var n1 = nodes[i];
  51088. for (var j = i + 1; j < nLen; j++) {
  51089. var n2 = nodes[j];
  51090. sub(v12, n2.p, n1.p);
  51091. var d = len(v12);
  51092. if (d === 0) {
  51093. // Random repulse
  51094. set(v12, Math.random() - 0.5, Math.random() - 0.5);
  51095. d = 1;
  51096. }
  51097. var repFact = (n1.rep + n2.rep) / d / d;
  51098. !n1.fixed && scaleAndAdd$2(n1.pp, n1.pp, v12, repFact);
  51099. !n2.fixed && scaleAndAdd$2(n2.pp, n2.pp, v12, -repFact);
  51100. }
  51101. }
  51102. var v = [];
  51103. for (var i = 0; i < nLen; i++) {
  51104. var n = nodes[i];
  51105. if (!n.fixed) {
  51106. sub(v, n.p, n.pp);
  51107. scaleAndAdd$2(n.p, n.p, v, friction);
  51108. copy(n.pp, n.p);
  51109. }
  51110. }
  51111. friction = friction * 0.992;
  51112. cb && cb(nodes, edges, friction < 0.01);
  51113. }
  51114. };
  51115. }
  51116. /*
  51117. * Licensed to the Apache Software Foundation (ASF) under one
  51118. * or more contributor license agreements. See the NOTICE file
  51119. * distributed with this work for additional information
  51120. * regarding copyright ownership. The ASF licenses this file
  51121. * to you under the Apache License, Version 2.0 (the
  51122. * "License"); you may not use this file except in compliance
  51123. * with the License. You may obtain a copy of the License at
  51124. *
  51125. * http://www.apache.org/licenses/LICENSE-2.0
  51126. *
  51127. * Unless required by applicable law or agreed to in writing,
  51128. * software distributed under the License is distributed on an
  51129. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51130. * KIND, either express or implied. See the License for the
  51131. * specific language governing permissions and limitations
  51132. * under the License.
  51133. */
  51134. var forceLayout = function (ecModel) {
  51135. ecModel.eachSeriesByType('graph', function (graphSeries) {
  51136. var coordSys = graphSeries.coordinateSystem;
  51137. if (coordSys && coordSys.type !== 'view') {
  51138. return;
  51139. }
  51140. if (graphSeries.get('layout') === 'force') {
  51141. var preservedPoints = graphSeries.preservedPoints || {};
  51142. var graph = graphSeries.getGraph();
  51143. var nodeData = graph.data;
  51144. var edgeData = graph.edgeData;
  51145. var forceModel = graphSeries.getModel('force');
  51146. var initLayout = forceModel.get('initLayout');
  51147. if (graphSeries.preservedPoints) {
  51148. nodeData.each(function (idx) {
  51149. var id = nodeData.getId(idx);
  51150. nodeData.setItemLayout(idx, preservedPoints[id] || [NaN, NaN]);
  51151. });
  51152. }
  51153. else if (!initLayout || initLayout === 'none') {
  51154. simpleLayout$1(graphSeries);
  51155. }
  51156. else if (initLayout === 'circular') {
  51157. circularLayout$1(graphSeries, 'value');
  51158. }
  51159. var nodeDataExtent = nodeData.getDataExtent('value');
  51160. var edgeDataExtent = edgeData.getDataExtent('value');
  51161. // var edgeDataExtent = edgeData.getDataExtent('value');
  51162. var repulsion = forceModel.get('repulsion');
  51163. var edgeLength = forceModel.get('edgeLength');
  51164. if (!isArray(repulsion)) {
  51165. repulsion = [repulsion, repulsion];
  51166. }
  51167. if (!isArray(edgeLength)) {
  51168. edgeLength = [edgeLength, edgeLength];
  51169. }
  51170. // Larger value has smaller length
  51171. edgeLength = [edgeLength[1], edgeLength[0]];
  51172. var nodes = nodeData.mapArray('value', function (value, idx) {
  51173. var point = nodeData.getItemLayout(idx);
  51174. var rep = linearMap(value, nodeDataExtent, repulsion);
  51175. if (isNaN(rep)) {
  51176. rep = (repulsion[0] + repulsion[1]) / 2;
  51177. }
  51178. return {
  51179. w: rep,
  51180. rep: rep,
  51181. fixed: nodeData.getItemModel(idx).get('fixed'),
  51182. p: (!point || isNaN(point[0]) || isNaN(point[1])) ? null : point
  51183. };
  51184. });
  51185. var edges = edgeData.mapArray('value', function (value, idx) {
  51186. var edge = graph.getEdgeByIndex(idx);
  51187. var d = linearMap(value, edgeDataExtent, edgeLength);
  51188. if (isNaN(d)) {
  51189. d = (edgeLength[0] + edgeLength[1]) / 2;
  51190. }
  51191. var edgeModel = edge.getModel();
  51192. return {
  51193. n1: nodes[edge.node1.dataIndex],
  51194. n2: nodes[edge.node2.dataIndex],
  51195. d: d,
  51196. curveness: edgeModel.get('lineStyle.curveness') || 0,
  51197. ignoreForceLayout: edgeModel.get('ignoreForceLayout')
  51198. };
  51199. });
  51200. var coordSys = graphSeries.coordinateSystem;
  51201. var rect = coordSys.getBoundingRect();
  51202. var forceInstance = forceLayout$1(nodes, edges, {
  51203. rect: rect,
  51204. gravity: forceModel.get('gravity'),
  51205. friction: forceModel.get('friction')
  51206. });
  51207. var oldStep = forceInstance.step;
  51208. forceInstance.step = function (cb) {
  51209. for (var i = 0, l = nodes.length; i < l; i++) {
  51210. if (nodes[i].fixed) {
  51211. // Write back to layout instance
  51212. copy(nodes[i].p, graph.getNodeByIndex(i).getLayout());
  51213. }
  51214. }
  51215. oldStep(function (nodes, edges, stopped) {
  51216. for (var i = 0, l = nodes.length; i < l; i++) {
  51217. if (!nodes[i].fixed) {
  51218. graph.getNodeByIndex(i).setLayout(nodes[i].p);
  51219. }
  51220. preservedPoints[nodeData.getId(i)] = nodes[i].p;
  51221. }
  51222. for (var i = 0, l = edges.length; i < l; i++) {
  51223. var e = edges[i];
  51224. var edge = graph.getEdgeByIndex(i);
  51225. var p1 = e.n1.p;
  51226. var p2 = e.n2.p;
  51227. var points = edge.getLayout();
  51228. points = points ? points.slice() : [];
  51229. points[0] = points[0] || [];
  51230. points[1] = points[1] || [];
  51231. copy(points[0], p1);
  51232. copy(points[1], p2);
  51233. if (+e.curveness) {
  51234. points[2] = [
  51235. (p1[0] + p2[0]) / 2 - (p1[1] - p2[1]) * e.curveness,
  51236. (p1[1] + p2[1]) / 2 - (p2[0] - p1[0]) * e.curveness
  51237. ];
  51238. }
  51239. edge.setLayout(points);
  51240. }
  51241. // Update layout
  51242. cb && cb(stopped);
  51243. });
  51244. };
  51245. graphSeries.forceLayout = forceInstance;
  51246. graphSeries.preservedPoints = preservedPoints;
  51247. // Step to get the layout
  51248. forceInstance.step();
  51249. }
  51250. else {
  51251. // Remove prev injected forceLayout instance
  51252. graphSeries.forceLayout = null;
  51253. }
  51254. });
  51255. };
  51256. /*
  51257. * Licensed to the Apache Software Foundation (ASF) under one
  51258. * or more contributor license agreements. See the NOTICE file
  51259. * distributed with this work for additional information
  51260. * regarding copyright ownership. The ASF licenses this file
  51261. * to you under the Apache License, Version 2.0 (the
  51262. * "License"); you may not use this file except in compliance
  51263. * with the License. You may obtain a copy of the License at
  51264. *
  51265. * http://www.apache.org/licenses/LICENSE-2.0
  51266. *
  51267. * Unless required by applicable law or agreed to in writing,
  51268. * software distributed under the License is distributed on an
  51269. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51270. * KIND, either express or implied. See the License for the
  51271. * specific language governing permissions and limitations
  51272. * under the License.
  51273. */
  51274. // FIXME Where to create the simple view coordinate system
  51275. function getViewRect$2(seriesModel, api, aspect) {
  51276. var option = seriesModel.getBoxLayoutParams();
  51277. option.aspect = aspect;
  51278. return getLayoutRect(option, {
  51279. width: api.getWidth(),
  51280. height: api.getHeight()
  51281. });
  51282. }
  51283. var createView = function (ecModel, api) {
  51284. var viewList = [];
  51285. ecModel.eachSeriesByType('graph', function (seriesModel) {
  51286. var coordSysType = seriesModel.get('coordinateSystem');
  51287. if (!coordSysType || coordSysType === 'view') {
  51288. var data = seriesModel.getData();
  51289. var positions = data.mapArray(function (idx) {
  51290. var itemModel = data.getItemModel(idx);
  51291. return [+itemModel.get('x'), +itemModel.get('y')];
  51292. });
  51293. var min = [];
  51294. var max = [];
  51295. fromPoints(positions, min, max);
  51296. // If width or height is 0
  51297. if (max[0] - min[0] === 0) {
  51298. max[0] += 1;
  51299. min[0] -= 1;
  51300. }
  51301. if (max[1] - min[1] === 0) {
  51302. max[1] += 1;
  51303. min[1] -= 1;
  51304. }
  51305. var aspect = (max[0] - min[0]) / (max[1] - min[1]);
  51306. // FIXME If get view rect after data processed?
  51307. var viewRect = getViewRect$2(seriesModel, api, aspect);
  51308. // Position may be NaN, use view rect instead
  51309. if (isNaN(aspect)) {
  51310. min = [viewRect.x, viewRect.y];
  51311. max = [viewRect.x + viewRect.width, viewRect.y + viewRect.height];
  51312. }
  51313. var bbWidth = max[0] - min[0];
  51314. var bbHeight = max[1] - min[1];
  51315. var viewWidth = viewRect.width;
  51316. var viewHeight = viewRect.height;
  51317. var viewCoordSys = seriesModel.coordinateSystem = new View();
  51318. viewCoordSys.zoomLimit = seriesModel.get('scaleLimit');
  51319. viewCoordSys.setBoundingRect(
  51320. min[0], min[1], bbWidth, bbHeight
  51321. );
  51322. viewCoordSys.setViewRect(
  51323. viewRect.x, viewRect.y, viewWidth, viewHeight
  51324. );
  51325. // Update roam info
  51326. viewCoordSys.setCenter(seriesModel.get('center'));
  51327. viewCoordSys.setZoom(seriesModel.get('zoom'));
  51328. viewList.push(viewCoordSys);
  51329. }
  51330. });
  51331. return viewList;
  51332. };
  51333. /*
  51334. * Licensed to the Apache Software Foundation (ASF) under one
  51335. * or more contributor license agreements. See the NOTICE file
  51336. * distributed with this work for additional information
  51337. * regarding copyright ownership. The ASF licenses this file
  51338. * to you under the Apache License, Version 2.0 (the
  51339. * "License"); you may not use this file except in compliance
  51340. * with the License. You may obtain a copy of the License at
  51341. *
  51342. * http://www.apache.org/licenses/LICENSE-2.0
  51343. *
  51344. * Unless required by applicable law or agreed to in writing,
  51345. * software distributed under the License is distributed on an
  51346. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51347. * KIND, either express or implied. See the License for the
  51348. * specific language governing permissions and limitations
  51349. * under the License.
  51350. */
  51351. registerProcessor(categoryFilter);
  51352. registerVisual(visualSymbol('graph', 'circle', null));
  51353. registerVisual(categoryVisual);
  51354. registerVisual(edgeVisual);
  51355. registerLayout(simpleLayout);
  51356. registerLayout(PRIORITY.VISUAL.POST_CHART_LAYOUT, circularLayout);
  51357. registerLayout(forceLayout);
  51358. // Graph view coordinate system
  51359. registerCoordinateSystem('graphView', {
  51360. create: createView
  51361. });
  51362. /*
  51363. * Licensed to the Apache Software Foundation (ASF) under one
  51364. * or more contributor license agreements. See the NOTICE file
  51365. * distributed with this work for additional information
  51366. * regarding copyright ownership. The ASF licenses this file
  51367. * to you under the Apache License, Version 2.0 (the
  51368. * "License"); you may not use this file except in compliance
  51369. * with the License. You may obtain a copy of the License at
  51370. *
  51371. * http://www.apache.org/licenses/LICENSE-2.0
  51372. *
  51373. * Unless required by applicable law or agreed to in writing,
  51374. * software distributed under the License is distributed on an
  51375. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51376. * KIND, either express or implied. See the License for the
  51377. * specific language governing permissions and limitations
  51378. * under the License.
  51379. */
  51380. var GaugeSeries = SeriesModel.extend({
  51381. type: 'series.gauge',
  51382. getInitialData: function (option, ecModel) {
  51383. return createListSimply(this, ['value']);
  51384. },
  51385. defaultOption: {
  51386. zlevel: 0,
  51387. z: 2,
  51388. // 默认全局居中
  51389. center: ['50%', '50%'],
  51390. legendHoverLink: true,
  51391. radius: '75%',
  51392. startAngle: 225,
  51393. endAngle: -45,
  51394. clockwise: true,
  51395. // 最小值
  51396. min: 0,
  51397. // 最大值
  51398. max: 100,
  51399. // 分割段数,默认为10
  51400. splitNumber: 10,
  51401. // 坐标轴线
  51402. axisLine: {
  51403. // 默认显示,属性show控制显示与否
  51404. show: true,
  51405. lineStyle: { // 属性lineStyle控制线条样式
  51406. color: [[0.2, '#91c7ae'], [0.8, '#63869e'], [1, '#c23531']],
  51407. width: 30
  51408. }
  51409. },
  51410. // 分隔线
  51411. splitLine: {
  51412. // 默认显示,属性show控制显示与否
  51413. show: true,
  51414. // 属性length控制线长
  51415. length: 30,
  51416. // 属性lineStyle(详见lineStyle)控制线条样式
  51417. lineStyle: {
  51418. color: '#eee',
  51419. width: 2,
  51420. type: 'solid'
  51421. }
  51422. },
  51423. // 坐标轴小标记
  51424. axisTick: {
  51425. // 属性show控制显示与否,默认不显示
  51426. show: true,
  51427. // 每份split细分多少段
  51428. splitNumber: 5,
  51429. // 属性length控制线长
  51430. length: 8,
  51431. // 属性lineStyle控制线条样式
  51432. lineStyle: {
  51433. color: '#eee',
  51434. width: 1,
  51435. type: 'solid'
  51436. }
  51437. },
  51438. axisLabel: {
  51439. show: true,
  51440. distance: 5,
  51441. // formatter: null,
  51442. color: 'auto'
  51443. },
  51444. pointer: {
  51445. show: true,
  51446. length: '80%',
  51447. width: 8
  51448. },
  51449. itemStyle: {
  51450. color: 'auto'
  51451. },
  51452. title: {
  51453. show: true,
  51454. // x, y,单位px
  51455. offsetCenter: [0, '-40%'],
  51456. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  51457. color: '#333',
  51458. fontSize: 15
  51459. },
  51460. detail: {
  51461. show: true,
  51462. backgroundColor: 'rgba(0,0,0,0)',
  51463. borderWidth: 0,
  51464. borderColor: '#ccc',
  51465. width: 100,
  51466. height: null, // self-adaption
  51467. padding: [5, 10],
  51468. // x, y,单位px
  51469. offsetCenter: [0, '40%'],
  51470. // formatter: null,
  51471. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  51472. color: 'auto',
  51473. fontSize: 30
  51474. }
  51475. }
  51476. });
  51477. /*
  51478. * Licensed to the Apache Software Foundation (ASF) under one
  51479. * or more contributor license agreements. See the NOTICE file
  51480. * distributed with this work for additional information
  51481. * regarding copyright ownership. The ASF licenses this file
  51482. * to you under the Apache License, Version 2.0 (the
  51483. * "License"); you may not use this file except in compliance
  51484. * with the License. You may obtain a copy of the License at
  51485. *
  51486. * http://www.apache.org/licenses/LICENSE-2.0
  51487. *
  51488. * Unless required by applicable law or agreed to in writing,
  51489. * software distributed under the License is distributed on an
  51490. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51491. * KIND, either express or implied. See the License for the
  51492. * specific language governing permissions and limitations
  51493. * under the License.
  51494. */
  51495. var PointerPath = Path.extend({
  51496. type: 'echartsGaugePointer',
  51497. shape: {
  51498. angle: 0,
  51499. width: 10,
  51500. r: 10,
  51501. x: 0,
  51502. y: 0
  51503. },
  51504. buildPath: function (ctx, shape) {
  51505. var mathCos = Math.cos;
  51506. var mathSin = Math.sin;
  51507. var r = shape.r;
  51508. var width = shape.width;
  51509. var angle = shape.angle;
  51510. var x = shape.x - mathCos(angle) * width * (width >= r / 3 ? 1 : 2);
  51511. var y = shape.y - mathSin(angle) * width * (width >= r / 3 ? 1 : 2);
  51512. angle = shape.angle - Math.PI / 2;
  51513. ctx.moveTo(x, y);
  51514. ctx.lineTo(
  51515. shape.x + mathCos(angle) * width,
  51516. shape.y + mathSin(angle) * width
  51517. );
  51518. ctx.lineTo(
  51519. shape.x + mathCos(shape.angle) * r,
  51520. shape.y + mathSin(shape.angle) * r
  51521. );
  51522. ctx.lineTo(
  51523. shape.x - mathCos(angle) * width,
  51524. shape.y - mathSin(angle) * width
  51525. );
  51526. ctx.lineTo(x, y);
  51527. return;
  51528. }
  51529. });
  51530. /*
  51531. * Licensed to the Apache Software Foundation (ASF) under one
  51532. * or more contributor license agreements. See the NOTICE file
  51533. * distributed with this work for additional information
  51534. * regarding copyright ownership. The ASF licenses this file
  51535. * to you under the Apache License, Version 2.0 (the
  51536. * "License"); you may not use this file except in compliance
  51537. * with the License. You may obtain a copy of the License at
  51538. *
  51539. * http://www.apache.org/licenses/LICENSE-2.0
  51540. *
  51541. * Unless required by applicable law or agreed to in writing,
  51542. * software distributed under the License is distributed on an
  51543. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51544. * KIND, either express or implied. See the License for the
  51545. * specific language governing permissions and limitations
  51546. * under the License.
  51547. */
  51548. function parsePosition(seriesModel, api) {
  51549. var center = seriesModel.get('center');
  51550. var width = api.getWidth();
  51551. var height = api.getHeight();
  51552. var size = Math.min(width, height);
  51553. var cx = parsePercent$1(center[0], api.getWidth());
  51554. var cy = parsePercent$1(center[1], api.getHeight());
  51555. var r = parsePercent$1(seriesModel.get('radius'), size / 2);
  51556. return {
  51557. cx: cx,
  51558. cy: cy,
  51559. r: r
  51560. };
  51561. }
  51562. function formatLabel(label, labelFormatter) {
  51563. if (labelFormatter) {
  51564. if (typeof labelFormatter === 'string') {
  51565. label = labelFormatter.replace('{value}', label != null ? label : '');
  51566. }
  51567. else if (typeof labelFormatter === 'function') {
  51568. label = labelFormatter(label);
  51569. }
  51570. }
  51571. return label;
  51572. }
  51573. var PI2$5 = Math.PI * 2;
  51574. var GaugeView = Chart.extend({
  51575. type: 'gauge',
  51576. render: function (seriesModel, ecModel, api) {
  51577. this.group.removeAll();
  51578. var colorList = seriesModel.get('axisLine.lineStyle.color');
  51579. var posInfo = parsePosition(seriesModel, api);
  51580. this._renderMain(
  51581. seriesModel, ecModel, api, colorList, posInfo
  51582. );
  51583. },
  51584. dispose: function () {},
  51585. _renderMain: function (seriesModel, ecModel, api, colorList, posInfo) {
  51586. var group = this.group;
  51587. var axisLineModel = seriesModel.getModel('axisLine');
  51588. var lineStyleModel = axisLineModel.getModel('lineStyle');
  51589. var clockwise = seriesModel.get('clockwise');
  51590. var startAngle = -seriesModel.get('startAngle') / 180 * Math.PI;
  51591. var endAngle = -seriesModel.get('endAngle') / 180 * Math.PI;
  51592. var angleRangeSpan = (endAngle - startAngle) % PI2$5;
  51593. var prevEndAngle = startAngle;
  51594. var axisLineWidth = lineStyleModel.get('width');
  51595. var showAxis = axisLineModel.get('show');
  51596. for (var i = 0; showAxis && i < colorList.length; i++) {
  51597. // Clamp
  51598. var percent = Math.min(Math.max(colorList[i][0], 0), 1);
  51599. var endAngle = startAngle + angleRangeSpan * percent;
  51600. var sector = new Sector({
  51601. shape: {
  51602. startAngle: prevEndAngle,
  51603. endAngle: endAngle,
  51604. cx: posInfo.cx,
  51605. cy: posInfo.cy,
  51606. clockwise: clockwise,
  51607. r0: posInfo.r - axisLineWidth,
  51608. r: posInfo.r
  51609. },
  51610. silent: true
  51611. });
  51612. sector.setStyle({
  51613. fill: colorList[i][1]
  51614. });
  51615. sector.setStyle(lineStyleModel.getLineStyle(
  51616. // Because we use sector to simulate arc
  51617. // so the properties for stroking are useless
  51618. ['color', 'borderWidth', 'borderColor']
  51619. ));
  51620. group.add(sector);
  51621. prevEndAngle = endAngle;
  51622. }
  51623. var getColor = function (percent) {
  51624. // Less than 0
  51625. if (percent <= 0) {
  51626. return colorList[0][1];
  51627. }
  51628. for (var i = 0; i < colorList.length; i++) {
  51629. if (colorList[i][0] >= percent
  51630. && (i === 0 ? 0 : colorList[i - 1][0]) < percent
  51631. ) {
  51632. return colorList[i][1];
  51633. }
  51634. }
  51635. // More than 1
  51636. return colorList[i - 1][1];
  51637. };
  51638. if (!clockwise) {
  51639. var tmp = startAngle;
  51640. startAngle = endAngle;
  51641. endAngle = tmp;
  51642. }
  51643. this._renderTicks(
  51644. seriesModel, ecModel, api, getColor, posInfo,
  51645. startAngle, endAngle, clockwise
  51646. );
  51647. this._renderPointer(
  51648. seriesModel, ecModel, api, getColor, posInfo,
  51649. startAngle, endAngle, clockwise
  51650. );
  51651. this._renderTitle(
  51652. seriesModel, ecModel, api, getColor, posInfo
  51653. );
  51654. this._renderDetail(
  51655. seriesModel, ecModel, api, getColor, posInfo
  51656. );
  51657. },
  51658. _renderTicks: function (
  51659. seriesModel, ecModel, api, getColor, posInfo,
  51660. startAngle, endAngle, clockwise
  51661. ) {
  51662. var group = this.group;
  51663. var cx = posInfo.cx;
  51664. var cy = posInfo.cy;
  51665. var r = posInfo.r;
  51666. var minVal = +seriesModel.get('min');
  51667. var maxVal = +seriesModel.get('max');
  51668. var splitLineModel = seriesModel.getModel('splitLine');
  51669. var tickModel = seriesModel.getModel('axisTick');
  51670. var labelModel = seriesModel.getModel('axisLabel');
  51671. var splitNumber = seriesModel.get('splitNumber');
  51672. var subSplitNumber = tickModel.get('splitNumber');
  51673. var splitLineLen = parsePercent$1(
  51674. splitLineModel.get('length'), r
  51675. );
  51676. var tickLen = parsePercent$1(
  51677. tickModel.get('length'), r
  51678. );
  51679. var angle = startAngle;
  51680. var step = (endAngle - startAngle) / splitNumber;
  51681. var subStep = step / subSplitNumber;
  51682. var splitLineStyle = splitLineModel.getModel('lineStyle').getLineStyle();
  51683. var tickLineStyle = tickModel.getModel('lineStyle').getLineStyle();
  51684. for (var i = 0; i <= splitNumber; i++) {
  51685. var unitX = Math.cos(angle);
  51686. var unitY = Math.sin(angle);
  51687. // Split line
  51688. if (splitLineModel.get('show')) {
  51689. var splitLine = new Line({
  51690. shape: {
  51691. x1: unitX * r + cx,
  51692. y1: unitY * r + cy,
  51693. x2: unitX * (r - splitLineLen) + cx,
  51694. y2: unitY * (r - splitLineLen) + cy
  51695. },
  51696. style: splitLineStyle,
  51697. silent: true
  51698. });
  51699. if (splitLineStyle.stroke === 'auto') {
  51700. splitLine.setStyle({
  51701. stroke: getColor(i / splitNumber)
  51702. });
  51703. }
  51704. group.add(splitLine);
  51705. }
  51706. // Label
  51707. if (labelModel.get('show')) {
  51708. var label = formatLabel(
  51709. round$1(i / splitNumber * (maxVal - minVal) + minVal),
  51710. labelModel.get('formatter')
  51711. );
  51712. var distance = labelModel.get('distance');
  51713. var autoColor = getColor(i / splitNumber);
  51714. group.add(new Text({
  51715. style: setTextStyle({}, labelModel, {
  51716. text: label,
  51717. x: unitX * (r - splitLineLen - distance) + cx,
  51718. y: unitY * (r - splitLineLen - distance) + cy,
  51719. textVerticalAlign: unitY < -0.4 ? 'top' : (unitY > 0.4 ? 'bottom' : 'middle'),
  51720. textAlign: unitX < -0.4 ? 'left' : (unitX > 0.4 ? 'right' : 'center')
  51721. }, {autoColor: autoColor}),
  51722. silent: true
  51723. }));
  51724. }
  51725. // Axis tick
  51726. if (tickModel.get('show') && i !== splitNumber) {
  51727. for (var j = 0; j <= subSplitNumber; j++) {
  51728. var unitX = Math.cos(angle);
  51729. var unitY = Math.sin(angle);
  51730. var tickLine = new Line({
  51731. shape: {
  51732. x1: unitX * r + cx,
  51733. y1: unitY * r + cy,
  51734. x2: unitX * (r - tickLen) + cx,
  51735. y2: unitY * (r - tickLen) + cy
  51736. },
  51737. silent: true,
  51738. style: tickLineStyle
  51739. });
  51740. if (tickLineStyle.stroke === 'auto') {
  51741. tickLine.setStyle({
  51742. stroke: getColor((i + j / subSplitNumber) / splitNumber)
  51743. });
  51744. }
  51745. group.add(tickLine);
  51746. angle += subStep;
  51747. }
  51748. angle -= subStep;
  51749. }
  51750. else {
  51751. angle += step;
  51752. }
  51753. }
  51754. },
  51755. _renderPointer: function (
  51756. seriesModel, ecModel, api, getColor, posInfo,
  51757. startAngle, endAngle, clockwise
  51758. ) {
  51759. var group = this.group;
  51760. var oldData = this._data;
  51761. if (!seriesModel.get('pointer.show')) {
  51762. // Remove old element
  51763. oldData && oldData.eachItemGraphicEl(function (el) {
  51764. group.remove(el);
  51765. });
  51766. return;
  51767. }
  51768. var valueExtent = [+seriesModel.get('min'), +seriesModel.get('max')];
  51769. var angleExtent = [startAngle, endAngle];
  51770. var data = seriesModel.getData();
  51771. var valueDim = data.mapDimension('value');
  51772. data.diff(oldData)
  51773. .add(function (idx) {
  51774. var pointer = new PointerPath({
  51775. shape: {
  51776. angle: startAngle
  51777. }
  51778. });
  51779. initProps(pointer, {
  51780. shape: {
  51781. angle: linearMap(data.get(valueDim, idx), valueExtent, angleExtent, true)
  51782. }
  51783. }, seriesModel);
  51784. group.add(pointer);
  51785. data.setItemGraphicEl(idx, pointer);
  51786. })
  51787. .update(function (newIdx, oldIdx) {
  51788. var pointer = oldData.getItemGraphicEl(oldIdx);
  51789. updateProps(pointer, {
  51790. shape: {
  51791. angle: linearMap(data.get(valueDim, newIdx), valueExtent, angleExtent, true)
  51792. }
  51793. }, seriesModel);
  51794. group.add(pointer);
  51795. data.setItemGraphicEl(newIdx, pointer);
  51796. })
  51797. .remove(function (idx) {
  51798. var pointer = oldData.getItemGraphicEl(idx);
  51799. group.remove(pointer);
  51800. })
  51801. .execute();
  51802. data.eachItemGraphicEl(function (pointer, idx) {
  51803. var itemModel = data.getItemModel(idx);
  51804. var pointerModel = itemModel.getModel('pointer');
  51805. pointer.setShape({
  51806. x: posInfo.cx,
  51807. y: posInfo.cy,
  51808. width: parsePercent$1(
  51809. pointerModel.get('width'), posInfo.r
  51810. ),
  51811. r: parsePercent$1(pointerModel.get('length'), posInfo.r)
  51812. });
  51813. pointer.useStyle(itemModel.getModel('itemStyle').getItemStyle());
  51814. if (pointer.style.fill === 'auto') {
  51815. pointer.setStyle('fill', getColor(
  51816. linearMap(data.get(valueDim, idx), valueExtent, [0, 1], true)
  51817. ));
  51818. }
  51819. setHoverStyle(
  51820. pointer, itemModel.getModel('emphasis.itemStyle').getItemStyle()
  51821. );
  51822. });
  51823. this._data = data;
  51824. },
  51825. _renderTitle: function (
  51826. seriesModel, ecModel, api, getColor, posInfo
  51827. ) {
  51828. var data = seriesModel.getData();
  51829. var valueDim = data.mapDimension('value');
  51830. var titleModel = seriesModel.getModel('title');
  51831. if (titleModel.get('show')) {
  51832. var offsetCenter = titleModel.get('offsetCenter');
  51833. var x = posInfo.cx + parsePercent$1(offsetCenter[0], posInfo.r);
  51834. var y = posInfo.cy + parsePercent$1(offsetCenter[1], posInfo.r);
  51835. var minVal = +seriesModel.get('min');
  51836. var maxVal = +seriesModel.get('max');
  51837. var value = seriesModel.getData().get(valueDim, 0);
  51838. var autoColor = getColor(
  51839. linearMap(value, [minVal, maxVal], [0, 1], true)
  51840. );
  51841. this.group.add(new Text({
  51842. silent: true,
  51843. style: setTextStyle({}, titleModel, {
  51844. x: x,
  51845. y: y,
  51846. // FIXME First data name ?
  51847. text: data.getName(0),
  51848. textAlign: 'center',
  51849. textVerticalAlign: 'middle'
  51850. }, {autoColor: autoColor, forceRich: true})
  51851. }));
  51852. }
  51853. },
  51854. _renderDetail: function (
  51855. seriesModel, ecModel, api, getColor, posInfo
  51856. ) {
  51857. var detailModel = seriesModel.getModel('detail');
  51858. var minVal = +seriesModel.get('min');
  51859. var maxVal = +seriesModel.get('max');
  51860. if (detailModel.get('show')) {
  51861. var offsetCenter = detailModel.get('offsetCenter');
  51862. var x = posInfo.cx + parsePercent$1(offsetCenter[0], posInfo.r);
  51863. var y = posInfo.cy + parsePercent$1(offsetCenter[1], posInfo.r);
  51864. var width = parsePercent$1(detailModel.get('width'), posInfo.r);
  51865. var height = parsePercent$1(detailModel.get('height'), posInfo.r);
  51866. var data = seriesModel.getData();
  51867. var value = data.get(data.mapDimension('value'), 0);
  51868. var autoColor = getColor(
  51869. linearMap(value, [minVal, maxVal], [0, 1], true)
  51870. );
  51871. this.group.add(new Text({
  51872. silent: true,
  51873. style: setTextStyle({}, detailModel, {
  51874. x: x,
  51875. y: y,
  51876. text: formatLabel(
  51877. // FIXME First data name ?
  51878. value, detailModel.get('formatter')
  51879. ),
  51880. textWidth: isNaN(width) ? null : width,
  51881. textHeight: isNaN(height) ? null : height,
  51882. textAlign: 'center',
  51883. textVerticalAlign: 'middle'
  51884. }, {autoColor: autoColor, forceRich: true})
  51885. }));
  51886. }
  51887. }
  51888. });
  51889. /*
  51890. * Licensed to the Apache Software Foundation (ASF) under one
  51891. * or more contributor license agreements. See the NOTICE file
  51892. * distributed with this work for additional information
  51893. * regarding copyright ownership. The ASF licenses this file
  51894. * to you under the Apache License, Version 2.0 (the
  51895. * "License"); you may not use this file except in compliance
  51896. * with the License. You may obtain a copy of the License at
  51897. *
  51898. * http://www.apache.org/licenses/LICENSE-2.0
  51899. *
  51900. * Unless required by applicable law or agreed to in writing,
  51901. * software distributed under the License is distributed on an
  51902. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51903. * KIND, either express or implied. See the License for the
  51904. * specific language governing permissions and limitations
  51905. * under the License.
  51906. */
  51907. /*
  51908. * Licensed to the Apache Software Foundation (ASF) under one
  51909. * or more contributor license agreements. See the NOTICE file
  51910. * distributed with this work for additional information
  51911. * regarding copyright ownership. The ASF licenses this file
  51912. * to you under the Apache License, Version 2.0 (the
  51913. * "License"); you may not use this file except in compliance
  51914. * with the License. You may obtain a copy of the License at
  51915. *
  51916. * http://www.apache.org/licenses/LICENSE-2.0
  51917. *
  51918. * Unless required by applicable law or agreed to in writing,
  51919. * software distributed under the License is distributed on an
  51920. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51921. * KIND, either express or implied. See the License for the
  51922. * specific language governing permissions and limitations
  51923. * under the License.
  51924. */
  51925. var FunnelSeries = extendSeriesModel({
  51926. type: 'series.funnel',
  51927. init: function (option) {
  51928. FunnelSeries.superApply(this, 'init', arguments);
  51929. // Enable legend selection for each data item
  51930. // Use a function instead of direct access because data reference may changed
  51931. this.legendVisualProvider = new LegendVisualProvider(
  51932. bind(this.getData, this), bind(this.getRawData, this)
  51933. );
  51934. // Extend labelLine emphasis
  51935. this._defaultLabelLine(option);
  51936. },
  51937. getInitialData: function (option, ecModel) {
  51938. return createListSimply(this, {
  51939. coordDimensions: ['value'],
  51940. encodeDefaulter: curry(makeSeriesEncodeForNameBased, this)
  51941. });
  51942. },
  51943. _defaultLabelLine: function (option) {
  51944. // Extend labelLine emphasis
  51945. defaultEmphasis(option, 'labelLine', ['show']);
  51946. var labelLineNormalOpt = option.labelLine;
  51947. var labelLineEmphasisOpt = option.emphasis.labelLine;
  51948. // Not show label line if `label.normal.show = false`
  51949. labelLineNormalOpt.show = labelLineNormalOpt.show
  51950. && option.label.show;
  51951. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show
  51952. && option.emphasis.label.show;
  51953. },
  51954. // Overwrite
  51955. getDataParams: function (dataIndex) {
  51956. var data = this.getData();
  51957. var params = FunnelSeries.superCall(this, 'getDataParams', dataIndex);
  51958. var valueDim = data.mapDimension('value');
  51959. var sum = data.getSum(valueDim);
  51960. // Percent is 0 if sum is 0
  51961. params.percent = !sum ? 0 : +(data.get(valueDim, dataIndex) / sum * 100).toFixed(2);
  51962. params.$vars.push('percent');
  51963. return params;
  51964. },
  51965. defaultOption: {
  51966. zlevel: 0, // 一级层叠
  51967. z: 2, // 二级层叠
  51968. legendHoverLink: true,
  51969. left: 80,
  51970. top: 60,
  51971. right: 80,
  51972. bottom: 60,
  51973. // width: {totalWidth} - left - right,
  51974. // height: {totalHeight} - top - bottom,
  51975. // 默认取数据最小最大值
  51976. // min: 0,
  51977. // max: 100,
  51978. minSize: '0%',
  51979. maxSize: '100%',
  51980. sort: 'descending', // 'ascending', 'descending'
  51981. gap: 0,
  51982. funnelAlign: 'center',
  51983. label: {
  51984. show: true,
  51985. position: 'outer'
  51986. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  51987. },
  51988. labelLine: {
  51989. show: true,
  51990. length: 20,
  51991. lineStyle: {
  51992. // color: 各异,
  51993. width: 1,
  51994. type: 'solid'
  51995. }
  51996. },
  51997. itemStyle: {
  51998. // color: 各异,
  51999. borderColor: '#fff',
  52000. borderWidth: 1
  52001. },
  52002. emphasis: {
  52003. label: {
  52004. show: true
  52005. }
  52006. }
  52007. }
  52008. });
  52009. /*
  52010. * Licensed to the Apache Software Foundation (ASF) under one
  52011. * or more contributor license agreements. See the NOTICE file
  52012. * distributed with this work for additional information
  52013. * regarding copyright ownership. The ASF licenses this file
  52014. * to you under the Apache License, Version 2.0 (the
  52015. * "License"); you may not use this file except in compliance
  52016. * with the License. You may obtain a copy of the License at
  52017. *
  52018. * http://www.apache.org/licenses/LICENSE-2.0
  52019. *
  52020. * Unless required by applicable law or agreed to in writing,
  52021. * software distributed under the License is distributed on an
  52022. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52023. * KIND, either express or implied. See the License for the
  52024. * specific language governing permissions and limitations
  52025. * under the License.
  52026. */
  52027. /**
  52028. * Piece of pie including Sector, Label, LabelLine
  52029. * @constructor
  52030. * @extends {module:zrender/graphic/Group}
  52031. */
  52032. function FunnelPiece(data, idx) {
  52033. Group.call(this);
  52034. var polygon = new Polygon();
  52035. var labelLine = new Polyline();
  52036. var text = new Text();
  52037. this.add(polygon);
  52038. this.add(labelLine);
  52039. this.add(text);
  52040. this.highDownOnUpdate = function (fromState, toState) {
  52041. if (toState === 'emphasis') {
  52042. labelLine.ignore = labelLine.hoverIgnore;
  52043. text.ignore = text.hoverIgnore;
  52044. }
  52045. else {
  52046. labelLine.ignore = labelLine.normalIgnore;
  52047. text.ignore = text.normalIgnore;
  52048. }
  52049. };
  52050. this.updateData(data, idx, true);
  52051. }
  52052. var funnelPieceProto = FunnelPiece.prototype;
  52053. var opacityAccessPath = ['itemStyle', 'opacity'];
  52054. funnelPieceProto.updateData = function (data, idx, firstCreate) {
  52055. var polygon = this.childAt(0);
  52056. var seriesModel = data.hostModel;
  52057. var itemModel = data.getItemModel(idx);
  52058. var layout = data.getItemLayout(idx);
  52059. var opacity = data.getItemModel(idx).get(opacityAccessPath);
  52060. opacity = opacity == null ? 1 : opacity;
  52061. // Reset style
  52062. polygon.useStyle({});
  52063. if (firstCreate) {
  52064. polygon.setShape({
  52065. points: layout.points
  52066. });
  52067. polygon.setStyle({opacity: 0});
  52068. initProps(polygon, {
  52069. style: {
  52070. opacity: opacity
  52071. }
  52072. }, seriesModel, idx);
  52073. }
  52074. else {
  52075. updateProps(polygon, {
  52076. style: {
  52077. opacity: opacity
  52078. },
  52079. shape: {
  52080. points: layout.points
  52081. }
  52082. }, seriesModel, idx);
  52083. }
  52084. // Update common style
  52085. var itemStyleModel = itemModel.getModel('itemStyle');
  52086. var visualColor = data.getItemVisual(idx, 'color');
  52087. polygon.setStyle(
  52088. defaults(
  52089. {
  52090. lineJoin: 'round',
  52091. fill: visualColor
  52092. },
  52093. itemStyleModel.getItemStyle(['opacity'])
  52094. )
  52095. );
  52096. polygon.hoverStyle = itemStyleModel.getModel('emphasis').getItemStyle();
  52097. this._updateLabel(data, idx);
  52098. setHoverStyle(this);
  52099. };
  52100. funnelPieceProto._updateLabel = function (data, idx) {
  52101. var labelLine = this.childAt(1);
  52102. var labelText = this.childAt(2);
  52103. var seriesModel = data.hostModel;
  52104. var itemModel = data.getItemModel(idx);
  52105. var layout = data.getItemLayout(idx);
  52106. var labelLayout = layout.label;
  52107. var visualColor = data.getItemVisual(idx, 'color');
  52108. updateProps(labelLine, {
  52109. shape: {
  52110. points: labelLayout.linePoints || labelLayout.linePoints
  52111. }
  52112. }, seriesModel, idx);
  52113. updateProps(labelText, {
  52114. style: {
  52115. x: labelLayout.x,
  52116. y: labelLayout.y
  52117. }
  52118. }, seriesModel, idx);
  52119. labelText.attr({
  52120. rotation: labelLayout.rotation,
  52121. origin: [labelLayout.x, labelLayout.y],
  52122. z2: 10
  52123. });
  52124. var labelModel = itemModel.getModel('label');
  52125. var labelHoverModel = itemModel.getModel('emphasis.label');
  52126. var labelLineModel = itemModel.getModel('labelLine');
  52127. var labelLineHoverModel = itemModel.getModel('emphasis.labelLine');
  52128. var visualColor = data.getItemVisual(idx, 'color');
  52129. setLabelStyle(
  52130. labelText.style, labelText.hoverStyle = {}, labelModel, labelHoverModel,
  52131. {
  52132. labelFetcher: data.hostModel,
  52133. labelDataIndex: idx,
  52134. defaultText: data.getName(idx),
  52135. autoColor: visualColor,
  52136. useInsideStyle: !!labelLayout.inside
  52137. },
  52138. {
  52139. textAlign: labelLayout.textAlign,
  52140. textVerticalAlign: labelLayout.verticalAlign
  52141. }
  52142. );
  52143. labelText.ignore = labelText.normalIgnore = !labelModel.get('show');
  52144. labelText.hoverIgnore = !labelHoverModel.get('show');
  52145. labelLine.ignore = labelLine.normalIgnore = !labelLineModel.get('show');
  52146. labelLine.hoverIgnore = !labelLineHoverModel.get('show');
  52147. // Default use item visual color
  52148. labelLine.setStyle({
  52149. stroke: visualColor
  52150. });
  52151. labelLine.setStyle(labelLineModel.getModel('lineStyle').getLineStyle());
  52152. labelLine.hoverStyle = labelLineHoverModel.getModel('lineStyle').getLineStyle();
  52153. };
  52154. inherits(FunnelPiece, Group);
  52155. var FunnelView = Chart.extend({
  52156. type: 'funnel',
  52157. render: function (seriesModel, ecModel, api) {
  52158. var data = seriesModel.getData();
  52159. var oldData = this._data;
  52160. var group = this.group;
  52161. data.diff(oldData)
  52162. .add(function (idx) {
  52163. var funnelPiece = new FunnelPiece(data, idx);
  52164. data.setItemGraphicEl(idx, funnelPiece);
  52165. group.add(funnelPiece);
  52166. })
  52167. .update(function (newIdx, oldIdx) {
  52168. var piePiece = oldData.getItemGraphicEl(oldIdx);
  52169. piePiece.updateData(data, newIdx);
  52170. group.add(piePiece);
  52171. data.setItemGraphicEl(newIdx, piePiece);
  52172. })
  52173. .remove(function (idx) {
  52174. var piePiece = oldData.getItemGraphicEl(idx);
  52175. group.remove(piePiece);
  52176. })
  52177. .execute();
  52178. this._data = data;
  52179. },
  52180. remove: function () {
  52181. this.group.removeAll();
  52182. this._data = null;
  52183. },
  52184. dispose: function () {}
  52185. });
  52186. /*
  52187. * Licensed to the Apache Software Foundation (ASF) under one
  52188. * or more contributor license agreements. See the NOTICE file
  52189. * distributed with this work for additional information
  52190. * regarding copyright ownership. The ASF licenses this file
  52191. * to you under the Apache License, Version 2.0 (the
  52192. * "License"); you may not use this file except in compliance
  52193. * with the License. You may obtain a copy of the License at
  52194. *
  52195. * http://www.apache.org/licenses/LICENSE-2.0
  52196. *
  52197. * Unless required by applicable law or agreed to in writing,
  52198. * software distributed under the License is distributed on an
  52199. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52200. * KIND, either express or implied. See the License for the
  52201. * specific language governing permissions and limitations
  52202. * under the License.
  52203. */
  52204. function getViewRect$3(seriesModel, api) {
  52205. return getLayoutRect(
  52206. seriesModel.getBoxLayoutParams(), {
  52207. width: api.getWidth(),
  52208. height: api.getHeight()
  52209. }
  52210. );
  52211. }
  52212. function getSortedIndices(data, sort) {
  52213. var valueDim = data.mapDimension('value');
  52214. var valueArr = data.mapArray(valueDim, function (val) {
  52215. return val;
  52216. });
  52217. var indices = [];
  52218. var isAscending = sort === 'ascending';
  52219. for (var i = 0, len = data.count(); i < len; i++) {
  52220. indices[i] = i;
  52221. }
  52222. // Add custom sortable function & none sortable opetion by "options.sort"
  52223. if (typeof sort === 'function') {
  52224. indices.sort(sort);
  52225. }
  52226. else if (sort !== 'none') {
  52227. indices.sort(function (a, b) {
  52228. return isAscending ? valueArr[a] - valueArr[b] : valueArr[b] - valueArr[a];
  52229. });
  52230. }
  52231. return indices;
  52232. }
  52233. function labelLayout$1(data) {
  52234. data.each(function (idx) {
  52235. var itemModel = data.getItemModel(idx);
  52236. var labelModel = itemModel.getModel('label');
  52237. var labelPosition = labelModel.get('position');
  52238. var labelLineModel = itemModel.getModel('labelLine');
  52239. var layout = data.getItemLayout(idx);
  52240. var points = layout.points;
  52241. var isLabelInside = labelPosition === 'inner'
  52242. || labelPosition === 'inside' || labelPosition === 'center'
  52243. || labelPosition === 'insideLeft' || labelPosition === 'insideRight';
  52244. var textAlign;
  52245. var textX;
  52246. var textY;
  52247. var linePoints;
  52248. if (isLabelInside) {
  52249. if (labelPosition === 'insideLeft') {
  52250. textX = (points[0][0] + points[3][0]) / 2 + 5;
  52251. textY = (points[0][1] + points[3][1]) / 2;
  52252. textAlign = 'left';
  52253. }
  52254. else if (labelPosition === 'insideRight') {
  52255. textX = (points[1][0] + points[2][0]) / 2 - 5;
  52256. textY = (points[1][1] + points[2][1]) / 2;
  52257. textAlign = 'right';
  52258. }
  52259. else {
  52260. textX = (points[0][0] + points[1][0] + points[2][0] + points[3][0]) / 4;
  52261. textY = (points[0][1] + points[1][1] + points[2][1] + points[3][1]) / 4;
  52262. textAlign = 'center';
  52263. }
  52264. linePoints = [
  52265. [textX, textY], [textX, textY]
  52266. ];
  52267. }
  52268. else {
  52269. var x1;
  52270. var y1;
  52271. var x2;
  52272. var labelLineLen = labelLineModel.get('length');
  52273. if (labelPosition === 'left') {
  52274. // Left side
  52275. x1 = (points[3][0] + points[0][0]) / 2;
  52276. y1 = (points[3][1] + points[0][1]) / 2;
  52277. x2 = x1 - labelLineLen;
  52278. textX = x2 - 5;
  52279. textAlign = 'right';
  52280. }
  52281. else if (labelPosition === 'right') {
  52282. // Right side
  52283. x1 = (points[1][0] + points[2][0]) / 2;
  52284. y1 = (points[1][1] + points[2][1]) / 2;
  52285. x2 = x1 + labelLineLen;
  52286. textX = x2 + 5;
  52287. textAlign = 'left';
  52288. }
  52289. else if (labelPosition === 'rightTop') {
  52290. // RightTop side
  52291. x1 = points[1][0];
  52292. y1 = points[1][1];
  52293. x2 = x1 + labelLineLen;
  52294. textX = x2 + 5;
  52295. textAlign = 'top';
  52296. }
  52297. else if (labelPosition === 'rightBottom') {
  52298. // RightBottom side
  52299. x1 = points[2][0];
  52300. y1 = points[2][1];
  52301. x2 = x1 + labelLineLen;
  52302. textX = x2 + 5;
  52303. textAlign = 'bottom';
  52304. }
  52305. else if (labelPosition === 'leftTop') {
  52306. // LeftTop side
  52307. x1 = points[0][0];
  52308. y1 = points[1][1];
  52309. x2 = x1 - labelLineLen;
  52310. textX = x2 - 5;
  52311. textAlign = 'right';
  52312. }
  52313. else if (labelPosition === 'leftBottom') {
  52314. // LeftBottom side
  52315. x1 = points[3][0];
  52316. y1 = points[2][1];
  52317. x2 = x1 - labelLineLen;
  52318. textX = x2 - 5;
  52319. textAlign = 'right';
  52320. }
  52321. else {
  52322. // Right side
  52323. x1 = (points[1][0] + points[2][0]) / 2;
  52324. y1 = (points[1][1] + points[2][1]) / 2;
  52325. x2 = x1 + labelLineLen;
  52326. textX = x2 + 5;
  52327. textAlign = 'left';
  52328. }
  52329. var y2 = y1;
  52330. linePoints = [[x1, y1], [x2, y2]];
  52331. textY = y2;
  52332. }
  52333. layout.label = {
  52334. linePoints: linePoints,
  52335. x: textX,
  52336. y: textY,
  52337. verticalAlign: 'middle',
  52338. textAlign: textAlign,
  52339. inside: isLabelInside
  52340. };
  52341. });
  52342. }
  52343. var funnelLayout = function (ecModel, api, payload) {
  52344. ecModel.eachSeriesByType('funnel', function (seriesModel) {
  52345. var data = seriesModel.getData();
  52346. var valueDim = data.mapDimension('value');
  52347. var sort = seriesModel.get('sort');
  52348. var viewRect = getViewRect$3(seriesModel, api);
  52349. var indices = getSortedIndices(data, sort);
  52350. var sizeExtent = [
  52351. parsePercent$1(seriesModel.get('minSize'), viewRect.width),
  52352. parsePercent$1(seriesModel.get('maxSize'), viewRect.width)
  52353. ];
  52354. var dataExtent = data.getDataExtent(valueDim);
  52355. var min = seriesModel.get('min');
  52356. var max = seriesModel.get('max');
  52357. if (min == null) {
  52358. min = Math.min(dataExtent[0], 0);
  52359. }
  52360. if (max == null) {
  52361. max = dataExtent[1];
  52362. }
  52363. var funnelAlign = seriesModel.get('funnelAlign');
  52364. var gap = seriesModel.get('gap');
  52365. var itemHeight = (viewRect.height - gap * (data.count() - 1)) / data.count();
  52366. var y = viewRect.y;
  52367. var getLinePoints = function (idx, offY) {
  52368. // End point index is data.count() and we assign it 0
  52369. var val = data.get(valueDim, idx) || 0;
  52370. var itemWidth = linearMap(val, [min, max], sizeExtent, true);
  52371. var x0;
  52372. switch (funnelAlign) {
  52373. case 'left':
  52374. x0 = viewRect.x;
  52375. break;
  52376. case 'center':
  52377. x0 = viewRect.x + (viewRect.width - itemWidth) / 2;
  52378. break;
  52379. case 'right':
  52380. x0 = viewRect.x + viewRect.width - itemWidth;
  52381. break;
  52382. }
  52383. return [
  52384. [x0, offY],
  52385. [x0 + itemWidth, offY]
  52386. ];
  52387. };
  52388. if (sort === 'ascending') {
  52389. // From bottom to top
  52390. itemHeight = -itemHeight;
  52391. gap = -gap;
  52392. y += viewRect.height;
  52393. indices = indices.reverse();
  52394. }
  52395. for (var i = 0; i < indices.length; i++) {
  52396. var idx = indices[i];
  52397. var nextIdx = indices[i + 1];
  52398. var itemModel = data.getItemModel(idx);
  52399. var height = itemModel.get('itemStyle.height');
  52400. if (height == null) {
  52401. height = itemHeight;
  52402. }
  52403. else {
  52404. height = parsePercent$1(height, viewRect.height);
  52405. if (sort === 'ascending') {
  52406. height = -height;
  52407. }
  52408. }
  52409. var start = getLinePoints(idx, y);
  52410. var end = getLinePoints(nextIdx, y + height);
  52411. y += height + gap;
  52412. data.setItemLayout(idx, {
  52413. points: start.concat(end.slice().reverse())
  52414. });
  52415. }
  52416. labelLayout$1(data);
  52417. });
  52418. };
  52419. /*
  52420. * Licensed to the Apache Software Foundation (ASF) under one
  52421. * or more contributor license agreements. See the NOTICE file
  52422. * distributed with this work for additional information
  52423. * regarding copyright ownership. The ASF licenses this file
  52424. * to you under the Apache License, Version 2.0 (the
  52425. * "License"); you may not use this file except in compliance
  52426. * with the License. You may obtain a copy of the License at
  52427. *
  52428. * http://www.apache.org/licenses/LICENSE-2.0
  52429. *
  52430. * Unless required by applicable law or agreed to in writing,
  52431. * software distributed under the License is distributed on an
  52432. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52433. * KIND, either express or implied. See the License for the
  52434. * specific language governing permissions and limitations
  52435. * under the License.
  52436. */
  52437. registerVisual(dataColor('funnel'));
  52438. registerLayout(funnelLayout);
  52439. registerProcessor(dataFilter('funnel'));
  52440. /*
  52441. * Licensed to the Apache Software Foundation (ASF) under one
  52442. * or more contributor license agreements. See the NOTICE file
  52443. * distributed with this work for additional information
  52444. * regarding copyright ownership. The ASF licenses this file
  52445. * to you under the Apache License, Version 2.0 (the
  52446. * "License"); you may not use this file except in compliance
  52447. * with the License. You may obtain a copy of the License at
  52448. *
  52449. * http://www.apache.org/licenses/LICENSE-2.0
  52450. *
  52451. * Unless required by applicable law or agreed to in writing,
  52452. * software distributed under the License is distributed on an
  52453. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52454. * KIND, either express or implied. See the License for the
  52455. * specific language governing permissions and limitations
  52456. * under the License.
  52457. */
  52458. var parallelPreprocessor = function (option) {
  52459. createParallelIfNeeded(option);
  52460. mergeAxisOptionFromParallel(option);
  52461. };
  52462. /**
  52463. * Create a parallel coordinate if not exists.
  52464. * @inner
  52465. */
  52466. function createParallelIfNeeded(option) {
  52467. if (option.parallel) {
  52468. return;
  52469. }
  52470. var hasParallelSeries = false;
  52471. each$1(option.series, function (seriesOpt) {
  52472. if (seriesOpt && seriesOpt.type === 'parallel') {
  52473. hasParallelSeries = true;
  52474. }
  52475. });
  52476. if (hasParallelSeries) {
  52477. option.parallel = [{}];
  52478. }
  52479. }
  52480. /**
  52481. * Merge aixs definition from parallel option (if exists) to axis option.
  52482. * @inner
  52483. */
  52484. function mergeAxisOptionFromParallel(option) {
  52485. var axes = normalizeToArray(option.parallelAxis);
  52486. each$1(axes, function (axisOption) {
  52487. if (!isObject$1(axisOption)) {
  52488. return;
  52489. }
  52490. var parallelIndex = axisOption.parallelIndex || 0;
  52491. var parallelOption = normalizeToArray(option.parallel)[parallelIndex];
  52492. if (parallelOption && parallelOption.parallelAxisDefault) {
  52493. merge(axisOption, parallelOption.parallelAxisDefault, false);
  52494. }
  52495. });
  52496. }
  52497. /*
  52498. * Licensed to the Apache Software Foundation (ASF) under one
  52499. * or more contributor license agreements. See the NOTICE file
  52500. * distributed with this work for additional information
  52501. * regarding copyright ownership. The ASF licenses this file
  52502. * to you under the Apache License, Version 2.0 (the
  52503. * "License"); you may not use this file except in compliance
  52504. * with the License. You may obtain a copy of the License at
  52505. *
  52506. * http://www.apache.org/licenses/LICENSE-2.0
  52507. *
  52508. * Unless required by applicable law or agreed to in writing,
  52509. * software distributed under the License is distributed on an
  52510. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52511. * KIND, either express or implied. See the License for the
  52512. * specific language governing permissions and limitations
  52513. * under the License.
  52514. */
  52515. /**
  52516. * @constructor module:echarts/coord/parallel/ParallelAxis
  52517. * @extends {module:echarts/coord/Axis}
  52518. * @param {string} dim
  52519. * @param {*} scale
  52520. * @param {Array.<number>} coordExtent
  52521. * @param {string} axisType
  52522. */
  52523. var ParallelAxis = function (dim, scale, coordExtent, axisType, axisIndex) {
  52524. Axis.call(this, dim, scale, coordExtent);
  52525. /**
  52526. * Axis type
  52527. * - 'category'
  52528. * - 'value'
  52529. * - 'time'
  52530. * - 'log'
  52531. * @type {string}
  52532. */
  52533. this.type = axisType || 'value';
  52534. /**
  52535. * @type {number}
  52536. * @readOnly
  52537. */
  52538. this.axisIndex = axisIndex;
  52539. };
  52540. ParallelAxis.prototype = {
  52541. constructor: ParallelAxis,
  52542. /**
  52543. * Axis model
  52544. * @param {module:echarts/coord/parallel/AxisModel}
  52545. */
  52546. model: null,
  52547. /**
  52548. * @override
  52549. */
  52550. isHorizontal: function () {
  52551. return this.coordinateSystem.getModel().get('layout') !== 'horizontal';
  52552. }
  52553. };
  52554. inherits(ParallelAxis, Axis);
  52555. /*
  52556. * Licensed to the Apache Software Foundation (ASF) under one
  52557. * or more contributor license agreements. See the NOTICE file
  52558. * distributed with this work for additional information
  52559. * regarding copyright ownership. The ASF licenses this file
  52560. * to you under the Apache License, Version 2.0 (the
  52561. * "License"); you may not use this file except in compliance
  52562. * with the License. You may obtain a copy of the License at
  52563. *
  52564. * http://www.apache.org/licenses/LICENSE-2.0
  52565. *
  52566. * Unless required by applicable law or agreed to in writing,
  52567. * software distributed under the License is distributed on an
  52568. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52569. * KIND, either express or implied. See the License for the
  52570. * specific language governing permissions and limitations
  52571. * under the License.
  52572. */
  52573. /**
  52574. * Calculate slider move result.
  52575. * Usage:
  52576. * (1) If both handle0 and handle1 are needed to be moved, set minSpan the same as
  52577. * maxSpan and the same as `Math.abs(handleEnd[1] - handleEnds[0])`.
  52578. * (2) If handle0 is forbidden to cross handle1, set minSpan as `0`.
  52579. *
  52580. * @param {number} delta Move length.
  52581. * @param {Array.<number>} handleEnds handleEnds[0] can be bigger then handleEnds[1].
  52582. * handleEnds will be modified in this method.
  52583. * @param {Array.<number>} extent handleEnds is restricted by extent.
  52584. * extent[0] should less or equals than extent[1].
  52585. * @param {number|string} handleIndex Can be 'all', means that both move the two handleEnds.
  52586. * @param {number} [minSpan] The range of dataZoom can not be smaller than that.
  52587. * If not set, handle0 and cross handle1. If set as a non-negative
  52588. * number (including `0`), handles will push each other when reaching
  52589. * the minSpan.
  52590. * @param {number} [maxSpan] The range of dataZoom can not be larger than that.
  52591. * @return {Array.<number>} The input handleEnds.
  52592. */
  52593. var sliderMove = function (delta, handleEnds, extent, handleIndex, minSpan, maxSpan) {
  52594. delta = delta || 0;
  52595. var extentSpan = extent[1] - extent[0];
  52596. // Notice maxSpan and minSpan can be null/undefined.
  52597. if (minSpan != null) {
  52598. minSpan = restrict$1(minSpan, [0, extentSpan]);
  52599. }
  52600. if (maxSpan != null) {
  52601. maxSpan = Math.max(maxSpan, minSpan != null ? minSpan : 0);
  52602. }
  52603. if (handleIndex === 'all') {
  52604. var handleSpan = Math.abs(handleEnds[1] - handleEnds[0]);
  52605. handleSpan = restrict$1(handleSpan, [0, extentSpan]);
  52606. minSpan = maxSpan = restrict$1(handleSpan, [minSpan, maxSpan]);
  52607. handleIndex = 0;
  52608. }
  52609. handleEnds[0] = restrict$1(handleEnds[0], extent);
  52610. handleEnds[1] = restrict$1(handleEnds[1], extent);
  52611. var originalDistSign = getSpanSign(handleEnds, handleIndex);
  52612. handleEnds[handleIndex] += delta;
  52613. // Restrict in extent.
  52614. var extentMinSpan = minSpan || 0;
  52615. var realExtent = extent.slice();
  52616. originalDistSign.sign < 0 ? (realExtent[0] += extentMinSpan) : (realExtent[1] -= extentMinSpan);
  52617. handleEnds[handleIndex] = restrict$1(handleEnds[handleIndex], realExtent);
  52618. // Expand span.
  52619. var currDistSign = getSpanSign(handleEnds, handleIndex);
  52620. if (minSpan != null && (
  52621. currDistSign.sign !== originalDistSign.sign || currDistSign.span < minSpan
  52622. )) {
  52623. // If minSpan exists, 'cross' is forbidden.
  52624. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + originalDistSign.sign * minSpan;
  52625. }
  52626. // Shrink span.
  52627. var currDistSign = getSpanSign(handleEnds, handleIndex);
  52628. if (maxSpan != null && currDistSign.span > maxSpan) {
  52629. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + currDistSign.sign * maxSpan;
  52630. }
  52631. return handleEnds;
  52632. };
  52633. function getSpanSign(handleEnds, handleIndex) {
  52634. var dist = handleEnds[handleIndex] - handleEnds[1 - handleIndex];
  52635. // If `handleEnds[0] === handleEnds[1]`, always believe that handleEnd[0]
  52636. // is at left of handleEnds[1] for non-cross case.
  52637. return {span: Math.abs(dist), sign: dist > 0 ? -1 : dist < 0 ? 1 : handleIndex ? -1 : 1};
  52638. }
  52639. function restrict$1(value, extend) {
  52640. return Math.min(
  52641. extend[1] != null ? extend[1] : Infinity,
  52642. Math.max(extend[0] != null ? extend[0] : -Infinity, value)
  52643. );
  52644. }
  52645. /*
  52646. * Licensed to the Apache Software Foundation (ASF) under one
  52647. * or more contributor license agreements. See the NOTICE file
  52648. * distributed with this work for additional information
  52649. * regarding copyright ownership. The ASF licenses this file
  52650. * to you under the Apache License, Version 2.0 (the
  52651. * "License"); you may not use this file except in compliance
  52652. * with the License. You may obtain a copy of the License at
  52653. *
  52654. * http://www.apache.org/licenses/LICENSE-2.0
  52655. *
  52656. * Unless required by applicable law or agreed to in writing,
  52657. * software distributed under the License is distributed on an
  52658. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52659. * KIND, either express or implied. See the License for the
  52660. * specific language governing permissions and limitations
  52661. * under the License.
  52662. */
  52663. /**
  52664. * Parallel Coordinates
  52665. * <https://en.wikipedia.org/wiki/Parallel_coordinates>
  52666. */
  52667. var each$11 = each$1;
  52668. var mathMin$6 = Math.min;
  52669. var mathMax$6 = Math.max;
  52670. var mathFloor$2 = Math.floor;
  52671. var mathCeil$2 = Math.ceil;
  52672. var round$2 = round$1;
  52673. var PI$4 = Math.PI;
  52674. function Parallel(parallelModel, ecModel, api) {
  52675. /**
  52676. * key: dimension
  52677. * @type {Object.<string, module:echarts/coord/parallel/Axis>}
  52678. * @private
  52679. */
  52680. this._axesMap = createHashMap();
  52681. /**
  52682. * key: dimension
  52683. * value: {position: [], rotation, }
  52684. * @type {Object.<string, Object>}
  52685. * @private
  52686. */
  52687. this._axesLayout = {};
  52688. /**
  52689. * Always follow axis order.
  52690. * @type {Array.<string>}
  52691. * @readOnly
  52692. */
  52693. this.dimensions = parallelModel.dimensions;
  52694. /**
  52695. * @type {module:zrender/core/BoundingRect}
  52696. */
  52697. this._rect;
  52698. /**
  52699. * @type {module:echarts/coord/parallel/ParallelModel}
  52700. */
  52701. this._model = parallelModel;
  52702. this._init(parallelModel, ecModel, api);
  52703. }
  52704. Parallel.prototype = {
  52705. type: 'parallel',
  52706. constructor: Parallel,
  52707. /**
  52708. * Initialize cartesian coordinate systems
  52709. * @private
  52710. */
  52711. _init: function (parallelModel, ecModel, api) {
  52712. var dimensions = parallelModel.dimensions;
  52713. var parallelAxisIndex = parallelModel.parallelAxisIndex;
  52714. each$11(dimensions, function (dim, idx) {
  52715. var axisIndex = parallelAxisIndex[idx];
  52716. var axisModel = ecModel.getComponent('parallelAxis', axisIndex);
  52717. var axis = this._axesMap.set(dim, new ParallelAxis(
  52718. dim,
  52719. createScaleByModel(axisModel),
  52720. [0, 0],
  52721. axisModel.get('type'),
  52722. axisIndex
  52723. ));
  52724. var isCategory = axis.type === 'category';
  52725. axis.onBand = isCategory && axisModel.get('boundaryGap');
  52726. axis.inverse = axisModel.get('inverse');
  52727. // Injection
  52728. axisModel.axis = axis;
  52729. axis.model = axisModel;
  52730. axis.coordinateSystem = axisModel.coordinateSystem = this;
  52731. }, this);
  52732. },
  52733. /**
  52734. * Update axis scale after data processed
  52735. * @param {module:echarts/model/Global} ecModel
  52736. * @param {module:echarts/ExtensionAPI} api
  52737. */
  52738. update: function (ecModel, api) {
  52739. this._updateAxesFromSeries(this._model, ecModel);
  52740. },
  52741. /**
  52742. * @override
  52743. */
  52744. containPoint: function (point) {
  52745. var layoutInfo = this._makeLayoutInfo();
  52746. var axisBase = layoutInfo.axisBase;
  52747. var layoutBase = layoutInfo.layoutBase;
  52748. var pixelDimIndex = layoutInfo.pixelDimIndex;
  52749. var pAxis = point[1 - pixelDimIndex];
  52750. var pLayout = point[pixelDimIndex];
  52751. return pAxis >= axisBase
  52752. && pAxis <= axisBase + layoutInfo.axisLength
  52753. && pLayout >= layoutBase
  52754. && pLayout <= layoutBase + layoutInfo.layoutLength;
  52755. },
  52756. getModel: function () {
  52757. return this._model;
  52758. },
  52759. /**
  52760. * Update properties from series
  52761. * @private
  52762. */
  52763. _updateAxesFromSeries: function (parallelModel, ecModel) {
  52764. ecModel.eachSeries(function (seriesModel) {
  52765. if (!parallelModel.contains(seriesModel, ecModel)) {
  52766. return;
  52767. }
  52768. var data = seriesModel.getData();
  52769. each$11(this.dimensions, function (dim) {
  52770. var axis = this._axesMap.get(dim);
  52771. axis.scale.unionExtentFromData(data, data.mapDimension(dim));
  52772. niceScaleExtent(axis.scale, axis.model);
  52773. }, this);
  52774. }, this);
  52775. },
  52776. /**
  52777. * Resize the parallel coordinate system.
  52778. * @param {module:echarts/coord/parallel/ParallelModel} parallelModel
  52779. * @param {module:echarts/ExtensionAPI} api
  52780. */
  52781. resize: function (parallelModel, api) {
  52782. this._rect = getLayoutRect(
  52783. parallelModel.getBoxLayoutParams(),
  52784. {
  52785. width: api.getWidth(),
  52786. height: api.getHeight()
  52787. }
  52788. );
  52789. this._layoutAxes();
  52790. },
  52791. /**
  52792. * @return {module:zrender/core/BoundingRect}
  52793. */
  52794. getRect: function () {
  52795. return this._rect;
  52796. },
  52797. /**
  52798. * @private
  52799. */
  52800. _makeLayoutInfo: function () {
  52801. var parallelModel = this._model;
  52802. var rect = this._rect;
  52803. var xy = ['x', 'y'];
  52804. var wh = ['width', 'height'];
  52805. var layout = parallelModel.get('layout');
  52806. var pixelDimIndex = layout === 'horizontal' ? 0 : 1;
  52807. var layoutLength = rect[wh[pixelDimIndex]];
  52808. var layoutExtent = [0, layoutLength];
  52809. var axisCount = this.dimensions.length;
  52810. var axisExpandWidth = restrict(parallelModel.get('axisExpandWidth'), layoutExtent);
  52811. var axisExpandCount = restrict(parallelModel.get('axisExpandCount') || 0, [0, axisCount]);
  52812. var axisExpandable = parallelModel.get('axisExpandable')
  52813. && axisCount > 3
  52814. && axisCount > axisExpandCount
  52815. && axisExpandCount > 1
  52816. && axisExpandWidth > 0
  52817. && layoutLength > 0;
  52818. // `axisExpandWindow` is According to the coordinates of [0, axisExpandLength],
  52819. // for sake of consider the case that axisCollapseWidth is 0 (when screen is narrow),
  52820. // where collapsed axes should be overlapped.
  52821. var axisExpandWindow = parallelModel.get('axisExpandWindow');
  52822. var winSize;
  52823. if (!axisExpandWindow) {
  52824. winSize = restrict(axisExpandWidth * (axisExpandCount - 1), layoutExtent);
  52825. var axisExpandCenter = parallelModel.get('axisExpandCenter') || mathFloor$2(axisCount / 2);
  52826. axisExpandWindow = [axisExpandWidth * axisExpandCenter - winSize / 2];
  52827. axisExpandWindow[1] = axisExpandWindow[0] + winSize;
  52828. }
  52829. else {
  52830. winSize = restrict(axisExpandWindow[1] - axisExpandWindow[0], layoutExtent);
  52831. axisExpandWindow[1] = axisExpandWindow[0] + winSize;
  52832. }
  52833. var axisCollapseWidth = (layoutLength - winSize) / (axisCount - axisExpandCount);
  52834. // Avoid axisCollapseWidth is too small.
  52835. axisCollapseWidth < 3 && (axisCollapseWidth = 0);
  52836. // Find the first and last indices > ewin[0] and < ewin[1].
  52837. var winInnerIndices = [
  52838. mathFloor$2(round$2(axisExpandWindow[0] / axisExpandWidth, 1)) + 1,
  52839. mathCeil$2(round$2(axisExpandWindow[1] / axisExpandWidth, 1)) - 1
  52840. ];
  52841. // Pos in ec coordinates.
  52842. var axisExpandWindow0Pos = axisCollapseWidth / axisExpandWidth * axisExpandWindow[0];
  52843. return {
  52844. layout: layout,
  52845. pixelDimIndex: pixelDimIndex,
  52846. layoutBase: rect[xy[pixelDimIndex]],
  52847. layoutLength: layoutLength,
  52848. axisBase: rect[xy[1 - pixelDimIndex]],
  52849. axisLength: rect[wh[1 - pixelDimIndex]],
  52850. axisExpandable: axisExpandable,
  52851. axisExpandWidth: axisExpandWidth,
  52852. axisCollapseWidth: axisCollapseWidth,
  52853. axisExpandWindow: axisExpandWindow,
  52854. axisCount: axisCount,
  52855. winInnerIndices: winInnerIndices,
  52856. axisExpandWindow0Pos: axisExpandWindow0Pos
  52857. };
  52858. },
  52859. /**
  52860. * @private
  52861. */
  52862. _layoutAxes: function () {
  52863. var rect = this._rect;
  52864. var axes = this._axesMap;
  52865. var dimensions = this.dimensions;
  52866. var layoutInfo = this._makeLayoutInfo();
  52867. var layout = layoutInfo.layout;
  52868. axes.each(function (axis) {
  52869. var axisExtent = [0, layoutInfo.axisLength];
  52870. var idx = axis.inverse ? 1 : 0;
  52871. axis.setExtent(axisExtent[idx], axisExtent[1 - idx]);
  52872. });
  52873. each$11(dimensions, function (dim, idx) {
  52874. var posInfo = (layoutInfo.axisExpandable
  52875. ? layoutAxisWithExpand : layoutAxisWithoutExpand
  52876. )(idx, layoutInfo);
  52877. var positionTable = {
  52878. horizontal: {
  52879. x: posInfo.position,
  52880. y: layoutInfo.axisLength
  52881. },
  52882. vertical: {
  52883. x: 0,
  52884. y: posInfo.position
  52885. }
  52886. };
  52887. var rotationTable = {
  52888. horizontal: PI$4 / 2,
  52889. vertical: 0
  52890. };
  52891. var position = [
  52892. positionTable[layout].x + rect.x,
  52893. positionTable[layout].y + rect.y
  52894. ];
  52895. var rotation = rotationTable[layout];
  52896. var transform = create$1();
  52897. rotate(transform, transform, rotation);
  52898. translate(transform, transform, position);
  52899. // TODO
  52900. // tick等排布信息。
  52901. // TODO
  52902. // 根据axis order 更新 dimensions顺序。
  52903. this._axesLayout[dim] = {
  52904. position: position,
  52905. rotation: rotation,
  52906. transform: transform,
  52907. axisNameAvailableWidth: posInfo.axisNameAvailableWidth,
  52908. axisLabelShow: posInfo.axisLabelShow,
  52909. nameTruncateMaxWidth: posInfo.nameTruncateMaxWidth,
  52910. tickDirection: 1,
  52911. labelDirection: 1
  52912. };
  52913. }, this);
  52914. },
  52915. /**
  52916. * Get axis by dim.
  52917. * @param {string} dim
  52918. * @return {module:echarts/coord/parallel/ParallelAxis} [description]
  52919. */
  52920. getAxis: function (dim) {
  52921. return this._axesMap.get(dim);
  52922. },
  52923. /**
  52924. * Convert a dim value of a single item of series data to Point.
  52925. * @param {*} value
  52926. * @param {string} dim
  52927. * @return {Array}
  52928. */
  52929. dataToPoint: function (value, dim) {
  52930. return this.axisCoordToPoint(
  52931. this._axesMap.get(dim).dataToCoord(value),
  52932. dim
  52933. );
  52934. },
  52935. /**
  52936. * Travel data for one time, get activeState of each data item.
  52937. * @param {module:echarts/data/List} data
  52938. * @param {Functio} cb param: {string} activeState 'active' or 'inactive' or 'normal'
  52939. * {number} dataIndex
  52940. * @param {number} [start=0] the start dataIndex that travel from.
  52941. * @param {number} [end=data.count()] the next dataIndex of the last dataIndex will be travel.
  52942. */
  52943. eachActiveState: function (data, callback, start, end) {
  52944. start == null && (start = 0);
  52945. end == null && (end = data.count());
  52946. var axesMap = this._axesMap;
  52947. var dimensions = this.dimensions;
  52948. var dataDimensions = [];
  52949. var axisModels = [];
  52950. each$1(dimensions, function (axisDim) {
  52951. dataDimensions.push(data.mapDimension(axisDim));
  52952. axisModels.push(axesMap.get(axisDim).model);
  52953. });
  52954. var hasActiveSet = this.hasAxisBrushed();
  52955. for (var dataIndex = start; dataIndex < end; dataIndex++) {
  52956. var activeState;
  52957. if (!hasActiveSet) {
  52958. activeState = 'normal';
  52959. }
  52960. else {
  52961. activeState = 'active';
  52962. var values = data.getValues(dataDimensions, dataIndex);
  52963. for (var j = 0, lenj = dimensions.length; j < lenj; j++) {
  52964. var state = axisModels[j].getActiveState(values[j]);
  52965. if (state === 'inactive') {
  52966. activeState = 'inactive';
  52967. break;
  52968. }
  52969. }
  52970. }
  52971. callback(activeState, dataIndex);
  52972. }
  52973. },
  52974. /**
  52975. * Whether has any activeSet.
  52976. * @return {boolean}
  52977. */
  52978. hasAxisBrushed: function () {
  52979. var dimensions = this.dimensions;
  52980. var axesMap = this._axesMap;
  52981. var hasActiveSet = false;
  52982. for (var j = 0, lenj = dimensions.length; j < lenj; j++) {
  52983. if (axesMap.get(dimensions[j]).model.getActiveState() !== 'normal') {
  52984. hasActiveSet = true;
  52985. }
  52986. }
  52987. return hasActiveSet;
  52988. },
  52989. /**
  52990. * Convert coords of each axis to Point.
  52991. * Return point. For example: [10, 20]
  52992. * @param {Array.<number>} coords
  52993. * @param {string} dim
  52994. * @return {Array.<number>}
  52995. */
  52996. axisCoordToPoint: function (coord, dim) {
  52997. var axisLayout = this._axesLayout[dim];
  52998. return applyTransform$1([coord, 0], axisLayout.transform);
  52999. },
  53000. /**
  53001. * Get axis layout.
  53002. */
  53003. getAxisLayout: function (dim) {
  53004. return clone(this._axesLayout[dim]);
  53005. },
  53006. /**
  53007. * @param {Array.<number>} point
  53008. * @return {Object} {axisExpandWindow, delta, behavior: 'jump' | 'slide' | 'none'}.
  53009. */
  53010. getSlidedAxisExpandWindow: function (point) {
  53011. var layoutInfo = this._makeLayoutInfo();
  53012. var pixelDimIndex = layoutInfo.pixelDimIndex;
  53013. var axisExpandWindow = layoutInfo.axisExpandWindow.slice();
  53014. var winSize = axisExpandWindow[1] - axisExpandWindow[0];
  53015. var extent = [0, layoutInfo.axisExpandWidth * (layoutInfo.axisCount - 1)];
  53016. // Out of the area of coordinate system.
  53017. if (!this.containPoint(point)) {
  53018. return {behavior: 'none', axisExpandWindow: axisExpandWindow};
  53019. }
  53020. // Conver the point from global to expand coordinates.
  53021. var pointCoord = point[pixelDimIndex] - layoutInfo.layoutBase - layoutInfo.axisExpandWindow0Pos;
  53022. // For dragging operation convenience, the window should not be
  53023. // slided when mouse is the center area of the window.
  53024. var delta;
  53025. var behavior = 'slide';
  53026. var axisCollapseWidth = layoutInfo.axisCollapseWidth;
  53027. var triggerArea = this._model.get('axisExpandSlideTriggerArea');
  53028. // But consider touch device, jump is necessary.
  53029. var useJump = triggerArea[0] != null;
  53030. if (axisCollapseWidth) {
  53031. if (useJump && axisCollapseWidth && pointCoord < winSize * triggerArea[0]) {
  53032. behavior = 'jump';
  53033. delta = pointCoord - winSize * triggerArea[2];
  53034. }
  53035. else if (useJump && axisCollapseWidth && pointCoord > winSize * (1 - triggerArea[0])) {
  53036. behavior = 'jump';
  53037. delta = pointCoord - winSize * (1 - triggerArea[2]);
  53038. }
  53039. else {
  53040. (delta = pointCoord - winSize * triggerArea[1]) >= 0
  53041. && (delta = pointCoord - winSize * (1 - triggerArea[1])) <= 0
  53042. && (delta = 0);
  53043. }
  53044. delta *= layoutInfo.axisExpandWidth / axisCollapseWidth;
  53045. delta
  53046. ? sliderMove(delta, axisExpandWindow, extent, 'all')
  53047. // Avoid nonsense triger on mousemove.
  53048. : (behavior = 'none');
  53049. }
  53050. // When screen is too narrow, make it visible and slidable, although it is hard to interact.
  53051. else {
  53052. var winSize = axisExpandWindow[1] - axisExpandWindow[0];
  53053. var pos = extent[1] * pointCoord / winSize;
  53054. axisExpandWindow = [mathMax$6(0, pos - winSize / 2)];
  53055. axisExpandWindow[1] = mathMin$6(extent[1], axisExpandWindow[0] + winSize);
  53056. axisExpandWindow[0] = axisExpandWindow[1] - winSize;
  53057. }
  53058. return {
  53059. axisExpandWindow: axisExpandWindow,
  53060. behavior: behavior
  53061. };
  53062. }
  53063. };
  53064. function restrict(len, extent) {
  53065. return mathMin$6(mathMax$6(len, extent[0]), extent[1]);
  53066. }
  53067. function layoutAxisWithoutExpand(axisIndex, layoutInfo) {
  53068. var step = layoutInfo.layoutLength / (layoutInfo.axisCount - 1);
  53069. return {
  53070. position: step * axisIndex,
  53071. axisNameAvailableWidth: step,
  53072. axisLabelShow: true
  53073. };
  53074. }
  53075. function layoutAxisWithExpand(axisIndex, layoutInfo) {
  53076. var layoutLength = layoutInfo.layoutLength;
  53077. var axisExpandWidth = layoutInfo.axisExpandWidth;
  53078. var axisCount = layoutInfo.axisCount;
  53079. var axisCollapseWidth = layoutInfo.axisCollapseWidth;
  53080. var winInnerIndices = layoutInfo.winInnerIndices;
  53081. var position;
  53082. var axisNameAvailableWidth = axisCollapseWidth;
  53083. var axisLabelShow = false;
  53084. var nameTruncateMaxWidth;
  53085. if (axisIndex < winInnerIndices[0]) {
  53086. position = axisIndex * axisCollapseWidth;
  53087. nameTruncateMaxWidth = axisCollapseWidth;
  53088. }
  53089. else if (axisIndex <= winInnerIndices[1]) {
  53090. position = layoutInfo.axisExpandWindow0Pos
  53091. + axisIndex * axisExpandWidth - layoutInfo.axisExpandWindow[0];
  53092. axisNameAvailableWidth = axisExpandWidth;
  53093. axisLabelShow = true;
  53094. }
  53095. else {
  53096. position = layoutLength - (axisCount - 1 - axisIndex) * axisCollapseWidth;
  53097. nameTruncateMaxWidth = axisCollapseWidth;
  53098. }
  53099. return {
  53100. position: position,
  53101. axisNameAvailableWidth: axisNameAvailableWidth,
  53102. axisLabelShow: axisLabelShow,
  53103. nameTruncateMaxWidth: nameTruncateMaxWidth
  53104. };
  53105. }
  53106. /*
  53107. * Licensed to the Apache Software Foundation (ASF) under one
  53108. * or more contributor license agreements. See the NOTICE file
  53109. * distributed with this work for additional information
  53110. * regarding copyright ownership. The ASF licenses this file
  53111. * to you under the Apache License, Version 2.0 (the
  53112. * "License"); you may not use this file except in compliance
  53113. * with the License. You may obtain a copy of the License at
  53114. *
  53115. * http://www.apache.org/licenses/LICENSE-2.0
  53116. *
  53117. * Unless required by applicable law or agreed to in writing,
  53118. * software distributed under the License is distributed on an
  53119. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53120. * KIND, either express or implied. See the License for the
  53121. * specific language governing permissions and limitations
  53122. * under the License.
  53123. */
  53124. /**
  53125. * Parallel coordinate system creater.
  53126. */
  53127. function create$2(ecModel, api) {
  53128. var coordSysList = [];
  53129. ecModel.eachComponent('parallel', function (parallelModel, idx) {
  53130. var coordSys = new Parallel(parallelModel, ecModel, api);
  53131. coordSys.name = 'parallel_' + idx;
  53132. coordSys.resize(parallelModel, api);
  53133. parallelModel.coordinateSystem = coordSys;
  53134. coordSys.model = parallelModel;
  53135. coordSysList.push(coordSys);
  53136. });
  53137. // Inject the coordinateSystems into seriesModel
  53138. ecModel.eachSeries(function (seriesModel) {
  53139. if (seriesModel.get('coordinateSystem') === 'parallel') {
  53140. var parallelModel = ecModel.queryComponents({
  53141. mainType: 'parallel',
  53142. index: seriesModel.get('parallelIndex'),
  53143. id: seriesModel.get('parallelId')
  53144. })[0];
  53145. seriesModel.coordinateSystem = parallelModel.coordinateSystem;
  53146. }
  53147. });
  53148. return coordSysList;
  53149. }
  53150. CoordinateSystemManager.register('parallel', {create: create$2});
  53151. /*
  53152. * Licensed to the Apache Software Foundation (ASF) under one
  53153. * or more contributor license agreements. See the NOTICE file
  53154. * distributed with this work for additional information
  53155. * regarding copyright ownership. The ASF licenses this file
  53156. * to you under the Apache License, Version 2.0 (the
  53157. * "License"); you may not use this file except in compliance
  53158. * with the License. You may obtain a copy of the License at
  53159. *
  53160. * http://www.apache.org/licenses/LICENSE-2.0
  53161. *
  53162. * Unless required by applicable law or agreed to in writing,
  53163. * software distributed under the License is distributed on an
  53164. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53165. * KIND, either express or implied. See the License for the
  53166. * specific language governing permissions and limitations
  53167. * under the License.
  53168. */
  53169. var AxisModel$2 = ComponentModel.extend({
  53170. type: 'baseParallelAxis',
  53171. /**
  53172. * @type {module:echarts/coord/parallel/Axis}
  53173. */
  53174. axis: null,
  53175. /**
  53176. * @type {Array.<Array.<number>}
  53177. * @readOnly
  53178. */
  53179. activeIntervals: [],
  53180. /**
  53181. * @return {Object}
  53182. */
  53183. getAreaSelectStyle: function () {
  53184. return makeStyleMapper(
  53185. [
  53186. ['fill', 'color'],
  53187. ['lineWidth', 'borderWidth'],
  53188. ['stroke', 'borderColor'],
  53189. ['width', 'width'],
  53190. ['opacity', 'opacity']
  53191. ]
  53192. )(this.getModel('areaSelectStyle'));
  53193. },
  53194. /**
  53195. * The code of this feature is put on AxisModel but not ParallelAxis,
  53196. * because axisModel can be alive after echarts updating but instance of
  53197. * ParallelAxis having been disposed. this._activeInterval should be kept
  53198. * when action dispatched (i.e. legend click).
  53199. *
  53200. * @param {Array.<Array<number>>} intervals interval.length === 0
  53201. * means set all active.
  53202. * @public
  53203. */
  53204. setActiveIntervals: function (intervals) {
  53205. var activeIntervals = this.activeIntervals = clone(intervals);
  53206. // Normalize
  53207. if (activeIntervals) {
  53208. for (var i = activeIntervals.length - 1; i >= 0; i--) {
  53209. asc(activeIntervals[i]);
  53210. }
  53211. }
  53212. },
  53213. /**
  53214. * @param {number|string} [value] When attempting to detect 'no activeIntervals set',
  53215. * value can not be input.
  53216. * @return {string} 'normal': no activeIntervals set,
  53217. * 'active',
  53218. * 'inactive'.
  53219. * @public
  53220. */
  53221. getActiveState: function (value) {
  53222. var activeIntervals = this.activeIntervals;
  53223. if (!activeIntervals.length) {
  53224. return 'normal';
  53225. }
  53226. if (value == null || isNaN(value)) {
  53227. return 'inactive';
  53228. }
  53229. // Simple optimization
  53230. if (activeIntervals.length === 1) {
  53231. var interval = activeIntervals[0];
  53232. if (interval[0] <= value && value <= interval[1]) {
  53233. return 'active';
  53234. }
  53235. }
  53236. else {
  53237. for (var i = 0, len = activeIntervals.length; i < len; i++) {
  53238. if (activeIntervals[i][0] <= value && value <= activeIntervals[i][1]) {
  53239. return 'active';
  53240. }
  53241. }
  53242. }
  53243. return 'inactive';
  53244. }
  53245. });
  53246. var defaultOption$1 = {
  53247. type: 'value',
  53248. /**
  53249. * @type {Array.<number>}
  53250. */
  53251. dim: null, // 0, 1, 2, ...
  53252. // parallelIndex: null,
  53253. areaSelectStyle: {
  53254. width: 20,
  53255. borderWidth: 1,
  53256. borderColor: 'rgba(160,197,232)',
  53257. color: 'rgba(160,197,232)',
  53258. opacity: 0.3
  53259. },
  53260. realtime: true, // Whether realtime update view when select.
  53261. z: 10
  53262. };
  53263. merge(AxisModel$2.prototype, axisModelCommonMixin);
  53264. function getAxisType$1(axisName, option) {
  53265. return option.type || (option.data ? 'category' : 'value');
  53266. }
  53267. axisModelCreator('parallel', AxisModel$2, getAxisType$1, defaultOption$1);
  53268. /*
  53269. * Licensed to the Apache Software Foundation (ASF) under one
  53270. * or more contributor license agreements. See the NOTICE file
  53271. * distributed with this work for additional information
  53272. * regarding copyright ownership. The ASF licenses this file
  53273. * to you under the Apache License, Version 2.0 (the
  53274. * "License"); you may not use this file except in compliance
  53275. * with the License. You may obtain a copy of the License at
  53276. *
  53277. * http://www.apache.org/licenses/LICENSE-2.0
  53278. *
  53279. * Unless required by applicable law or agreed to in writing,
  53280. * software distributed under the License is distributed on an
  53281. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53282. * KIND, either express or implied. See the License for the
  53283. * specific language governing permissions and limitations
  53284. * under the License.
  53285. */
  53286. ComponentModel.extend({
  53287. type: 'parallel',
  53288. dependencies: ['parallelAxis'],
  53289. /**
  53290. * @type {module:echarts/coord/parallel/Parallel}
  53291. */
  53292. coordinateSystem: null,
  53293. /**
  53294. * Each item like: 'dim0', 'dim1', 'dim2', ...
  53295. * @type {Array.<string>}
  53296. * @readOnly
  53297. */
  53298. dimensions: null,
  53299. /**
  53300. * Coresponding to dimensions.
  53301. * @type {Array.<number>}
  53302. * @readOnly
  53303. */
  53304. parallelAxisIndex: null,
  53305. layoutMode: 'box',
  53306. defaultOption: {
  53307. zlevel: 0,
  53308. z: 0,
  53309. left: 80,
  53310. top: 60,
  53311. right: 80,
  53312. bottom: 60,
  53313. // width: {totalWidth} - left - right,
  53314. // height: {totalHeight} - top - bottom,
  53315. layout: 'horizontal', // 'horizontal' or 'vertical'
  53316. // FIXME
  53317. // naming?
  53318. axisExpandable: false,
  53319. axisExpandCenter: null,
  53320. axisExpandCount: 0,
  53321. axisExpandWidth: 50, // FIXME '10%' ?
  53322. axisExpandRate: 17,
  53323. axisExpandDebounce: 50,
  53324. // [out, in, jumpTarget]. In percentage. If use [null, 0.05], null means full.
  53325. // Do not doc to user until necessary.
  53326. axisExpandSlideTriggerArea: [-0.15, 0.05, 0.4],
  53327. axisExpandTriggerOn: 'click', // 'mousemove' or 'click'
  53328. parallelAxisDefault: null
  53329. },
  53330. /**
  53331. * @override
  53332. */
  53333. init: function () {
  53334. ComponentModel.prototype.init.apply(this, arguments);
  53335. this.mergeOption({});
  53336. },
  53337. /**
  53338. * @override
  53339. */
  53340. mergeOption: function (newOption) {
  53341. var thisOption = this.option;
  53342. newOption && merge(thisOption, newOption, true);
  53343. this._initDimensions();
  53344. },
  53345. /**
  53346. * Whether series or axis is in this coordinate system.
  53347. * @param {module:echarts/model/Series|module:echarts/coord/parallel/AxisModel} model
  53348. * @param {module:echarts/model/Global} ecModel
  53349. */
  53350. contains: function (model, ecModel) {
  53351. var parallelIndex = model.get('parallelIndex');
  53352. return parallelIndex != null
  53353. && ecModel.getComponent('parallel', parallelIndex) === this;
  53354. },
  53355. setAxisExpand: function (opt) {
  53356. each$1(
  53357. ['axisExpandable', 'axisExpandCenter', 'axisExpandCount', 'axisExpandWidth', 'axisExpandWindow'],
  53358. function (name) {
  53359. if (opt.hasOwnProperty(name)) {
  53360. this.option[name] = opt[name];
  53361. }
  53362. },
  53363. this
  53364. );
  53365. },
  53366. /**
  53367. * @private
  53368. */
  53369. _initDimensions: function () {
  53370. var dimensions = this.dimensions = [];
  53371. var parallelAxisIndex = this.parallelAxisIndex = [];
  53372. var axisModels = filter(this.dependentModels.parallelAxis, function (axisModel) {
  53373. // Can not use this.contains here, because
  53374. // initialization has not been completed yet.
  53375. return (axisModel.get('parallelIndex') || 0) === this.componentIndex;
  53376. }, this);
  53377. each$1(axisModels, function (axisModel) {
  53378. dimensions.push('dim' + axisModel.get('dim'));
  53379. parallelAxisIndex.push(axisModel.componentIndex);
  53380. });
  53381. }
  53382. });
  53383. /*
  53384. * Licensed to the Apache Software Foundation (ASF) under one
  53385. * or more contributor license agreements. See the NOTICE file
  53386. * distributed with this work for additional information
  53387. * regarding copyright ownership. The ASF licenses this file
  53388. * to you under the Apache License, Version 2.0 (the
  53389. * "License"); you may not use this file except in compliance
  53390. * with the License. You may obtain a copy of the License at
  53391. *
  53392. * http://www.apache.org/licenses/LICENSE-2.0
  53393. *
  53394. * Unless required by applicable law or agreed to in writing,
  53395. * software distributed under the License is distributed on an
  53396. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53397. * KIND, either express or implied. See the License for the
  53398. * specific language governing permissions and limitations
  53399. * under the License.
  53400. */
  53401. /**
  53402. * @payload
  53403. * @property {string} parallelAxisId
  53404. * @property {Array.<Array.<number>>} intervals
  53405. */
  53406. var actionInfo$1 = {
  53407. type: 'axisAreaSelect',
  53408. event: 'axisAreaSelected'
  53409. // update: 'updateVisual'
  53410. };
  53411. registerAction(actionInfo$1, function (payload, ecModel) {
  53412. ecModel.eachComponent(
  53413. {mainType: 'parallelAxis', query: payload},
  53414. function (parallelAxisModel) {
  53415. parallelAxisModel.axis.model.setActiveIntervals(payload.intervals);
  53416. }
  53417. );
  53418. });
  53419. /**
  53420. * @payload
  53421. */
  53422. registerAction('parallelAxisExpand', function (payload, ecModel) {
  53423. ecModel.eachComponent(
  53424. {mainType: 'parallel', query: payload},
  53425. function (parallelModel) {
  53426. parallelModel.setAxisExpand(payload);
  53427. }
  53428. );
  53429. });
  53430. /*
  53431. * Licensed to the Apache Software Foundation (ASF) under one
  53432. * or more contributor license agreements. See the NOTICE file
  53433. * distributed with this work for additional information
  53434. * regarding copyright ownership. The ASF licenses this file
  53435. * to you under the Apache License, Version 2.0 (the
  53436. * "License"); you may not use this file except in compliance
  53437. * with the License. You may obtain a copy of the License at
  53438. *
  53439. * http://www.apache.org/licenses/LICENSE-2.0
  53440. *
  53441. * Unless required by applicable law or agreed to in writing,
  53442. * software distributed under the License is distributed on an
  53443. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53444. * KIND, either express or implied. See the License for the
  53445. * specific language governing permissions and limitations
  53446. * under the License.
  53447. */
  53448. var curry$2 = curry;
  53449. var each$12 = each$1;
  53450. var map$2 = map;
  53451. var mathMin$7 = Math.min;
  53452. var mathMax$7 = Math.max;
  53453. var mathPow$2 = Math.pow;
  53454. var COVER_Z = 10000;
  53455. var UNSELECT_THRESHOLD = 6;
  53456. var MIN_RESIZE_LINE_WIDTH = 6;
  53457. var MUTEX_RESOURCE_KEY = 'globalPan';
  53458. var DIRECTION_MAP = {
  53459. w: [0, 0],
  53460. e: [0, 1],
  53461. n: [1, 0],
  53462. s: [1, 1]
  53463. };
  53464. var CURSOR_MAP = {
  53465. w: 'ew',
  53466. e: 'ew',
  53467. n: 'ns',
  53468. s: 'ns',
  53469. ne: 'nesw',
  53470. sw: 'nesw',
  53471. nw: 'nwse',
  53472. se: 'nwse'
  53473. };
  53474. var DEFAULT_BRUSH_OPT = {
  53475. brushStyle: {
  53476. lineWidth: 2,
  53477. stroke: 'rgba(0,0,0,0.3)',
  53478. fill: 'rgba(0,0,0,0.1)'
  53479. },
  53480. transformable: true,
  53481. brushMode: 'single',
  53482. removeOnClick: false
  53483. };
  53484. var baseUID = 0;
  53485. /**
  53486. * @alias module:echarts/component/helper/BrushController
  53487. * @constructor
  53488. * @mixin {module:zrender/mixin/Eventful}
  53489. * @event module:echarts/component/helper/BrushController#brush
  53490. * params:
  53491. * areas: Array.<Array>, coord relates to container group,
  53492. * If no container specified, to global.
  53493. * opt {
  53494. * isEnd: boolean,
  53495. * removeOnClick: boolean
  53496. * }
  53497. *
  53498. * @param {module:zrender/zrender~ZRender} zr
  53499. */
  53500. function BrushController(zr) {
  53501. if (__DEV__) {
  53502. assert$1(zr);
  53503. }
  53504. Eventful.call(this);
  53505. /**
  53506. * @type {module:zrender/zrender~ZRender}
  53507. * @private
  53508. */
  53509. this._zr = zr;
  53510. /**
  53511. * @type {module:zrender/container/Group}
  53512. * @readOnly
  53513. */
  53514. this.group = new Group();
  53515. /**
  53516. * Only for drawing (after enabledBrush).
  53517. * 'line', 'rect', 'polygon' or false
  53518. * If passing false/null/undefined, disable brush.
  53519. * If passing 'auto', determined by panel.defaultBrushType
  53520. * @private
  53521. * @type {string}
  53522. */
  53523. this._brushType;
  53524. /**
  53525. * Only for drawing (after enabledBrush).
  53526. *
  53527. * @private
  53528. * @type {Object}
  53529. */
  53530. this._brushOption;
  53531. /**
  53532. * @private
  53533. * @type {Object}
  53534. */
  53535. this._panels;
  53536. /**
  53537. * @private
  53538. * @type {Array.<nubmer>}
  53539. */
  53540. this._track = [];
  53541. /**
  53542. * @private
  53543. * @type {boolean}
  53544. */
  53545. this._dragging;
  53546. /**
  53547. * @private
  53548. * @type {Array}
  53549. */
  53550. this._covers = [];
  53551. /**
  53552. * @private
  53553. * @type {moudule:zrender/container/Group}
  53554. */
  53555. this._creatingCover;
  53556. /**
  53557. * `true` means global panel
  53558. * @private
  53559. * @type {module:zrender/container/Group|boolean}
  53560. */
  53561. this._creatingPanel;
  53562. /**
  53563. * @private
  53564. * @type {boolean}
  53565. */
  53566. this._enableGlobalPan;
  53567. /**
  53568. * @private
  53569. * @type {boolean}
  53570. */
  53571. if (__DEV__) {
  53572. this._mounted;
  53573. }
  53574. /**
  53575. * @private
  53576. * @type {string}
  53577. */
  53578. this._uid = 'brushController_' + baseUID++;
  53579. /**
  53580. * @private
  53581. * @type {Object}
  53582. */
  53583. this._handlers = {};
  53584. each$12(pointerHandlers, function (handler, eventName) {
  53585. this._handlers[eventName] = bind(handler, this);
  53586. }, this);
  53587. }
  53588. BrushController.prototype = {
  53589. constructor: BrushController,
  53590. /**
  53591. * If set to null/undefined/false, select disabled.
  53592. * @param {Object} brushOption
  53593. * @param {string|boolean} brushOption.brushType 'line', 'rect', 'polygon' or false
  53594. * If passing false/null/undefined, disable brush.
  53595. * If passing 'auto', determined by panel.defaultBrushType.
  53596. * ('auto' can not be used in global panel)
  53597. * @param {number} [brushOption.brushMode='single'] 'single' or 'multiple'
  53598. * @param {boolean} [brushOption.transformable=true]
  53599. * @param {boolean} [brushOption.removeOnClick=false]
  53600. * @param {Object} [brushOption.brushStyle]
  53601. * @param {number} [brushOption.brushStyle.width]
  53602. * @param {number} [brushOption.brushStyle.lineWidth]
  53603. * @param {string} [brushOption.brushStyle.stroke]
  53604. * @param {string} [brushOption.brushStyle.fill]
  53605. * @param {number} [brushOption.z]
  53606. */
  53607. enableBrush: function (brushOption) {
  53608. if (__DEV__) {
  53609. assert$1(this._mounted);
  53610. }
  53611. this._brushType && doDisableBrush(this);
  53612. brushOption.brushType && doEnableBrush(this, brushOption);
  53613. return this;
  53614. },
  53615. /**
  53616. * @param {Array.<Object>} panelOpts If not pass, it is global brush.
  53617. * Each items: {
  53618. * panelId, // mandatory.
  53619. * clipPath, // mandatory. function.
  53620. * isTargetByCursor, // mandatory. function.
  53621. * defaultBrushType, // optional, only used when brushType is 'auto'.
  53622. * getLinearBrushOtherExtent, // optional. function.
  53623. * }
  53624. */
  53625. setPanels: function (panelOpts) {
  53626. if (panelOpts && panelOpts.length) {
  53627. var panels = this._panels = {};
  53628. each$1(panelOpts, function (panelOpts) {
  53629. panels[panelOpts.panelId] = clone(panelOpts);
  53630. });
  53631. }
  53632. else {
  53633. this._panels = null;
  53634. }
  53635. return this;
  53636. },
  53637. /**
  53638. * @param {Object} [opt]
  53639. * @return {boolean} [opt.enableGlobalPan=false]
  53640. */
  53641. mount: function (opt) {
  53642. opt = opt || {};
  53643. if (__DEV__) {
  53644. this._mounted = true; // should be at first.
  53645. }
  53646. this._enableGlobalPan = opt.enableGlobalPan;
  53647. var thisGroup = this.group;
  53648. this._zr.add(thisGroup);
  53649. thisGroup.attr({
  53650. position: opt.position || [0, 0],
  53651. rotation: opt.rotation || 0,
  53652. scale: opt.scale || [1, 1]
  53653. });
  53654. this._transform = thisGroup.getLocalTransform();
  53655. return this;
  53656. },
  53657. eachCover: function (cb, context) {
  53658. each$12(this._covers, cb, context);
  53659. },
  53660. /**
  53661. * Update covers.
  53662. * @param {Array.<Object>} brushOptionList Like:
  53663. * [
  53664. * {id: 'xx', brushType: 'line', range: [23, 44], brushStyle, transformable},
  53665. * {id: 'yy', brushType: 'rect', range: [[23, 44], [23, 54]]},
  53666. * ...
  53667. * ]
  53668. * `brushType` is required in each cover info. (can not be 'auto')
  53669. * `id` is not mandatory.
  53670. * `brushStyle`, `transformable` is not mandatory, use DEFAULT_BRUSH_OPT by default.
  53671. * If brushOptionList is null/undefined, all covers removed.
  53672. */
  53673. updateCovers: function (brushOptionList) {
  53674. if (__DEV__) {
  53675. assert$1(this._mounted);
  53676. }
  53677. brushOptionList = map(brushOptionList, function (brushOption) {
  53678. return merge(clone(DEFAULT_BRUSH_OPT), brushOption, true);
  53679. });
  53680. var tmpIdPrefix = '\0-brush-index-';
  53681. var oldCovers = this._covers;
  53682. var newCovers = this._covers = [];
  53683. var controller = this;
  53684. var creatingCover = this._creatingCover;
  53685. (new DataDiffer(oldCovers, brushOptionList, oldGetKey, getKey))
  53686. .add(addOrUpdate)
  53687. .update(addOrUpdate)
  53688. .remove(remove)
  53689. .execute();
  53690. return this;
  53691. function getKey(brushOption, index) {
  53692. return (brushOption.id != null ? brushOption.id : tmpIdPrefix + index)
  53693. + '-' + brushOption.brushType;
  53694. }
  53695. function oldGetKey(cover, index) {
  53696. return getKey(cover.__brushOption, index);
  53697. }
  53698. function addOrUpdate(newIndex, oldIndex) {
  53699. var newBrushOption = brushOptionList[newIndex];
  53700. // Consider setOption in event listener of brushSelect,
  53701. // where updating cover when creating should be forbiden.
  53702. if (oldIndex != null && oldCovers[oldIndex] === creatingCover) {
  53703. newCovers[newIndex] = oldCovers[oldIndex];
  53704. }
  53705. else {
  53706. var cover = newCovers[newIndex] = oldIndex != null
  53707. ? (
  53708. oldCovers[oldIndex].__brushOption = newBrushOption,
  53709. oldCovers[oldIndex]
  53710. )
  53711. : endCreating(controller, createCover(controller, newBrushOption));
  53712. updateCoverAfterCreation(controller, cover);
  53713. }
  53714. }
  53715. function remove(oldIndex) {
  53716. if (oldCovers[oldIndex] !== creatingCover) {
  53717. controller.group.remove(oldCovers[oldIndex]);
  53718. }
  53719. }
  53720. },
  53721. unmount: function () {
  53722. if (__DEV__) {
  53723. if (!this._mounted) {
  53724. return;
  53725. }
  53726. }
  53727. this.enableBrush(false);
  53728. // container may 'removeAll' outside.
  53729. clearCovers(this);
  53730. this._zr.remove(this.group);
  53731. if (__DEV__) {
  53732. this._mounted = false; // should be at last.
  53733. }
  53734. return this;
  53735. },
  53736. dispose: function () {
  53737. this.unmount();
  53738. this.off();
  53739. }
  53740. };
  53741. mixin(BrushController, Eventful);
  53742. function doEnableBrush(controller, brushOption) {
  53743. var zr = controller._zr;
  53744. // Consider roam, which takes globalPan too.
  53745. if (!controller._enableGlobalPan) {
  53746. take(zr, MUTEX_RESOURCE_KEY, controller._uid);
  53747. }
  53748. mountHandlers(zr, controller._handlers);
  53749. controller._brushType = brushOption.brushType;
  53750. controller._brushOption = merge(clone(DEFAULT_BRUSH_OPT), brushOption, true);
  53751. }
  53752. function doDisableBrush(controller) {
  53753. var zr = controller._zr;
  53754. release(zr, MUTEX_RESOURCE_KEY, controller._uid);
  53755. unmountHandlers(zr, controller._handlers);
  53756. controller._brushType = controller._brushOption = null;
  53757. }
  53758. function mountHandlers(zr, handlers) {
  53759. each$12(handlers, function (handler, eventName) {
  53760. zr.on(eventName, handler);
  53761. });
  53762. }
  53763. function unmountHandlers(zr, handlers) {
  53764. each$12(handlers, function (handler, eventName) {
  53765. zr.off(eventName, handler);
  53766. });
  53767. }
  53768. function createCover(controller, brushOption) {
  53769. var cover = coverRenderers[brushOption.brushType].createCover(controller, brushOption);
  53770. cover.__brushOption = brushOption;
  53771. updateZ$1(cover, brushOption);
  53772. controller.group.add(cover);
  53773. return cover;
  53774. }
  53775. function endCreating(controller, creatingCover) {
  53776. var coverRenderer = getCoverRenderer(creatingCover);
  53777. if (coverRenderer.endCreating) {
  53778. coverRenderer.endCreating(controller, creatingCover);
  53779. updateZ$1(creatingCover, creatingCover.__brushOption);
  53780. }
  53781. return creatingCover;
  53782. }
  53783. function updateCoverShape(controller, cover) {
  53784. var brushOption = cover.__brushOption;
  53785. getCoverRenderer(cover).updateCoverShape(
  53786. controller, cover, brushOption.range, brushOption
  53787. );
  53788. }
  53789. function updateZ$1(cover, brushOption) {
  53790. var z = brushOption.z;
  53791. z == null && (z = COVER_Z);
  53792. cover.traverse(function (el) {
  53793. el.z = z;
  53794. el.z2 = z; // Consider in given container.
  53795. });
  53796. }
  53797. function updateCoverAfterCreation(controller, cover) {
  53798. getCoverRenderer(cover).updateCommon(controller, cover);
  53799. updateCoverShape(controller, cover);
  53800. }
  53801. function getCoverRenderer(cover) {
  53802. return coverRenderers[cover.__brushOption.brushType];
  53803. }
  53804. // return target panel or `true` (means global panel)
  53805. function getPanelByPoint(controller, e, localCursorPoint) {
  53806. var panels = controller._panels;
  53807. if (!panels) {
  53808. return true; // Global panel
  53809. }
  53810. var panel;
  53811. var transform = controller._transform;
  53812. each$12(panels, function (pn) {
  53813. pn.isTargetByCursor(e, localCursorPoint, transform) && (panel = pn);
  53814. });
  53815. return panel;
  53816. }
  53817. // Return a panel or true
  53818. function getPanelByCover(controller, cover) {
  53819. var panels = controller._panels;
  53820. if (!panels) {
  53821. return true; // Global panel
  53822. }
  53823. var panelId = cover.__brushOption.panelId;
  53824. // User may give cover without coord sys info,
  53825. // which is then treated as global panel.
  53826. return panelId != null ? panels[panelId] : true;
  53827. }
  53828. function clearCovers(controller) {
  53829. var covers = controller._covers;
  53830. var originalLength = covers.length;
  53831. each$12(covers, function (cover) {
  53832. controller.group.remove(cover);
  53833. }, controller);
  53834. covers.length = 0;
  53835. return !!originalLength;
  53836. }
  53837. function trigger$1(controller, opt) {
  53838. var areas = map$2(controller._covers, function (cover) {
  53839. var brushOption = cover.__brushOption;
  53840. var range = clone(brushOption.range);
  53841. return {
  53842. brushType: brushOption.brushType,
  53843. panelId: brushOption.panelId,
  53844. range: range
  53845. };
  53846. });
  53847. controller.trigger('brush', areas, {
  53848. isEnd: !!opt.isEnd,
  53849. removeOnClick: !!opt.removeOnClick
  53850. });
  53851. }
  53852. function shouldShowCover(controller) {
  53853. var track = controller._track;
  53854. if (!track.length) {
  53855. return false;
  53856. }
  53857. var p2 = track[track.length - 1];
  53858. var p1 = track[0];
  53859. var dx = p2[0] - p1[0];
  53860. var dy = p2[1] - p1[1];
  53861. var dist = mathPow$2(dx * dx + dy * dy, 0.5);
  53862. return dist > UNSELECT_THRESHOLD;
  53863. }
  53864. function getTrackEnds(track) {
  53865. var tail = track.length - 1;
  53866. tail < 0 && (tail = 0);
  53867. return [track[0], track[tail]];
  53868. }
  53869. function createBaseRectCover(doDrift, controller, brushOption, edgeNames) {
  53870. var cover = new Group();
  53871. cover.add(new Rect({
  53872. name: 'main',
  53873. style: makeStyle(brushOption),
  53874. silent: true,
  53875. draggable: true,
  53876. cursor: 'move',
  53877. drift: curry$2(doDrift, controller, cover, 'nswe'),
  53878. ondragend: curry$2(trigger$1, controller, {isEnd: true})
  53879. }));
  53880. each$12(
  53881. edgeNames,
  53882. function (name) {
  53883. cover.add(new Rect({
  53884. name: name,
  53885. style: {opacity: 0},
  53886. draggable: true,
  53887. silent: true,
  53888. invisible: true,
  53889. drift: curry$2(doDrift, controller, cover, name),
  53890. ondragend: curry$2(trigger$1, controller, {isEnd: true})
  53891. }));
  53892. }
  53893. );
  53894. return cover;
  53895. }
  53896. function updateBaseRect(controller, cover, localRange, brushOption) {
  53897. var lineWidth = brushOption.brushStyle.lineWidth || 0;
  53898. var handleSize = mathMax$7(lineWidth, MIN_RESIZE_LINE_WIDTH);
  53899. var x = localRange[0][0];
  53900. var y = localRange[1][0];
  53901. var xa = x - lineWidth / 2;
  53902. var ya = y - lineWidth / 2;
  53903. var x2 = localRange[0][1];
  53904. var y2 = localRange[1][1];
  53905. var x2a = x2 - handleSize + lineWidth / 2;
  53906. var y2a = y2 - handleSize + lineWidth / 2;
  53907. var width = x2 - x;
  53908. var height = y2 - y;
  53909. var widtha = width + lineWidth;
  53910. var heighta = height + lineWidth;
  53911. updateRectShape(controller, cover, 'main', x, y, width, height);
  53912. if (brushOption.transformable) {
  53913. updateRectShape(controller, cover, 'w', xa, ya, handleSize, heighta);
  53914. updateRectShape(controller, cover, 'e', x2a, ya, handleSize, heighta);
  53915. updateRectShape(controller, cover, 'n', xa, ya, widtha, handleSize);
  53916. updateRectShape(controller, cover, 's', xa, y2a, widtha, handleSize);
  53917. updateRectShape(controller, cover, 'nw', xa, ya, handleSize, handleSize);
  53918. updateRectShape(controller, cover, 'ne', x2a, ya, handleSize, handleSize);
  53919. updateRectShape(controller, cover, 'sw', xa, y2a, handleSize, handleSize);
  53920. updateRectShape(controller, cover, 'se', x2a, y2a, handleSize, handleSize);
  53921. }
  53922. }
  53923. function updateCommon(controller, cover) {
  53924. var brushOption = cover.__brushOption;
  53925. var transformable = brushOption.transformable;
  53926. var mainEl = cover.childAt(0);
  53927. mainEl.useStyle(makeStyle(brushOption));
  53928. mainEl.attr({
  53929. silent: !transformable,
  53930. cursor: transformable ? 'move' : 'default'
  53931. });
  53932. each$12(
  53933. ['w', 'e', 'n', 's', 'se', 'sw', 'ne', 'nw'],
  53934. function (name) {
  53935. var el = cover.childOfName(name);
  53936. var globalDir = getGlobalDirection(controller, name);
  53937. el && el.attr({
  53938. silent: !transformable,
  53939. invisible: !transformable,
  53940. cursor: transformable ? CURSOR_MAP[globalDir] + '-resize' : null
  53941. });
  53942. }
  53943. );
  53944. }
  53945. function updateRectShape(controller, cover, name, x, y, w, h) {
  53946. var el = cover.childOfName(name);
  53947. el && el.setShape(pointsToRect(
  53948. clipByPanel(controller, cover, [[x, y], [x + w, y + h]])
  53949. ));
  53950. }
  53951. function makeStyle(brushOption) {
  53952. return defaults({strokeNoScale: true}, brushOption.brushStyle);
  53953. }
  53954. function formatRectRange(x, y, x2, y2) {
  53955. var min = [mathMin$7(x, x2), mathMin$7(y, y2)];
  53956. var max = [mathMax$7(x, x2), mathMax$7(y, y2)];
  53957. return [
  53958. [min[0], max[0]], // x range
  53959. [min[1], max[1]] // y range
  53960. ];
  53961. }
  53962. function getTransform$1(controller) {
  53963. return getTransform(controller.group);
  53964. }
  53965. function getGlobalDirection(controller, localDirection) {
  53966. if (localDirection.length > 1) {
  53967. localDirection = localDirection.split('');
  53968. var globalDir = [
  53969. getGlobalDirection(controller, localDirection[0]),
  53970. getGlobalDirection(controller, localDirection[1])
  53971. ];
  53972. (globalDir[0] === 'e' || globalDir[0] === 'w') && globalDir.reverse();
  53973. return globalDir.join('');
  53974. }
  53975. else {
  53976. var map$$1 = {w: 'left', e: 'right', n: 'top', s: 'bottom'};
  53977. var inverseMap = {left: 'w', right: 'e', top: 'n', bottom: 's'};
  53978. var globalDir = transformDirection(
  53979. map$$1[localDirection], getTransform$1(controller)
  53980. );
  53981. return inverseMap[globalDir];
  53982. }
  53983. }
  53984. function driftRect(toRectRange, fromRectRange, controller, cover, name, dx, dy, e) {
  53985. var brushOption = cover.__brushOption;
  53986. var rectRange = toRectRange(brushOption.range);
  53987. var localDelta = toLocalDelta(controller, dx, dy);
  53988. each$12(name.split(''), function (namePart) {
  53989. var ind = DIRECTION_MAP[namePart];
  53990. rectRange[ind[0]][ind[1]] += localDelta[ind[0]];
  53991. });
  53992. brushOption.range = fromRectRange(formatRectRange(
  53993. rectRange[0][0], rectRange[1][0], rectRange[0][1], rectRange[1][1]
  53994. ));
  53995. updateCoverAfterCreation(controller, cover);
  53996. trigger$1(controller, {isEnd: false});
  53997. }
  53998. function driftPolygon(controller, cover, dx, dy, e) {
  53999. var range = cover.__brushOption.range;
  54000. var localDelta = toLocalDelta(controller, dx, dy);
  54001. each$12(range, function (point) {
  54002. point[0] += localDelta[0];
  54003. point[1] += localDelta[1];
  54004. });
  54005. updateCoverAfterCreation(controller, cover);
  54006. trigger$1(controller, {isEnd: false});
  54007. }
  54008. function toLocalDelta(controller, dx, dy) {
  54009. var thisGroup = controller.group;
  54010. var localD = thisGroup.transformCoordToLocal(dx, dy);
  54011. var localZero = thisGroup.transformCoordToLocal(0, 0);
  54012. return [localD[0] - localZero[0], localD[1] - localZero[1]];
  54013. }
  54014. function clipByPanel(controller, cover, data) {
  54015. var panel = getPanelByCover(controller, cover);
  54016. return (panel && panel !== true)
  54017. ? panel.clipPath(data, controller._transform)
  54018. : clone(data);
  54019. }
  54020. function pointsToRect(points) {
  54021. var xmin = mathMin$7(points[0][0], points[1][0]);
  54022. var ymin = mathMin$7(points[0][1], points[1][1]);
  54023. var xmax = mathMax$7(points[0][0], points[1][0]);
  54024. var ymax = mathMax$7(points[0][1], points[1][1]);
  54025. return {
  54026. x: xmin,
  54027. y: ymin,
  54028. width: xmax - xmin,
  54029. height: ymax - ymin
  54030. };
  54031. }
  54032. function resetCursor(controller, e, localCursorPoint) {
  54033. if (
  54034. // Check active
  54035. !controller._brushType
  54036. // resetCursor should be always called when mouse is in zr area,
  54037. // but not called when mouse is out of zr area to avoid bad influence
  54038. // if `mousemove`, `mouseup` are triggered from `document` event.
  54039. || isOutsideZrArea(controller, e)
  54040. ) {
  54041. return;
  54042. }
  54043. var zr = controller._zr;
  54044. var covers = controller._covers;
  54045. var currPanel = getPanelByPoint(controller, e, localCursorPoint);
  54046. // Check whether in covers.
  54047. if (!controller._dragging) {
  54048. for (var i = 0; i < covers.length; i++) {
  54049. var brushOption = covers[i].__brushOption;
  54050. if (currPanel
  54051. && (currPanel === true || brushOption.panelId === currPanel.panelId)
  54052. && coverRenderers[brushOption.brushType].contain(
  54053. covers[i], localCursorPoint[0], localCursorPoint[1]
  54054. )
  54055. ) {
  54056. // Use cursor style set on cover.
  54057. return;
  54058. }
  54059. }
  54060. }
  54061. currPanel && zr.setCursorStyle('crosshair');
  54062. }
  54063. function preventDefault(e) {
  54064. var rawE = e.event;
  54065. rawE.preventDefault && rawE.preventDefault();
  54066. }
  54067. function mainShapeContain(cover, x, y) {
  54068. return cover.childOfName('main').contain(x, y);
  54069. }
  54070. function updateCoverByMouse(controller, e, localCursorPoint, isEnd) {
  54071. var creatingCover = controller._creatingCover;
  54072. var panel = controller._creatingPanel;
  54073. var thisBrushOption = controller._brushOption;
  54074. var eventParams;
  54075. controller._track.push(localCursorPoint.slice());
  54076. if (shouldShowCover(controller) || creatingCover) {
  54077. if (panel && !creatingCover) {
  54078. thisBrushOption.brushMode === 'single' && clearCovers(controller);
  54079. var brushOption = clone(thisBrushOption);
  54080. brushOption.brushType = determineBrushType(brushOption.brushType, panel);
  54081. brushOption.panelId = panel === true ? null : panel.panelId;
  54082. creatingCover = controller._creatingCover = createCover(controller, brushOption);
  54083. controller._covers.push(creatingCover);
  54084. }
  54085. if (creatingCover) {
  54086. var coverRenderer = coverRenderers[determineBrushType(controller._brushType, panel)];
  54087. var coverBrushOption = creatingCover.__brushOption;
  54088. coverBrushOption.range = coverRenderer.getCreatingRange(
  54089. clipByPanel(controller, creatingCover, controller._track)
  54090. );
  54091. if (isEnd) {
  54092. endCreating(controller, creatingCover);
  54093. coverRenderer.updateCommon(controller, creatingCover);
  54094. }
  54095. updateCoverShape(controller, creatingCover);
  54096. eventParams = {isEnd: isEnd};
  54097. }
  54098. }
  54099. else if (
  54100. isEnd
  54101. && thisBrushOption.brushMode === 'single'
  54102. && thisBrushOption.removeOnClick
  54103. ) {
  54104. // Help user to remove covers easily, only by a tiny drag, in 'single' mode.
  54105. // But a single click do not clear covers, because user may have casual
  54106. // clicks (for example, click on other component and do not expect covers
  54107. // disappear).
  54108. // Only some cover removed, trigger action, but not every click trigger action.
  54109. if (getPanelByPoint(controller, e, localCursorPoint) && clearCovers(controller)) {
  54110. eventParams = {isEnd: isEnd, removeOnClick: true};
  54111. }
  54112. }
  54113. return eventParams;
  54114. }
  54115. function determineBrushType(brushType, panel) {
  54116. if (brushType === 'auto') {
  54117. if (__DEV__) {
  54118. assert$1(
  54119. panel && panel.defaultBrushType,
  54120. 'MUST have defaultBrushType when brushType is "atuo"'
  54121. );
  54122. }
  54123. return panel.defaultBrushType;
  54124. }
  54125. return brushType;
  54126. }
  54127. var pointerHandlers = {
  54128. mousedown: function (e) {
  54129. if (this._dragging) {
  54130. // In case some browser do not support globalOut,
  54131. // and release mose out side the browser.
  54132. handleDragEnd(this, e);
  54133. }
  54134. else if (!e.target || !e.target.draggable) {
  54135. preventDefault(e);
  54136. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  54137. this._creatingCover = null;
  54138. var panel = this._creatingPanel = getPanelByPoint(this, e, localCursorPoint);
  54139. if (panel) {
  54140. this._dragging = true;
  54141. this._track = [localCursorPoint.slice()];
  54142. }
  54143. }
  54144. },
  54145. mousemove: function (e) {
  54146. var x = e.offsetX;
  54147. var y = e.offsetY;
  54148. var localCursorPoint = this.group.transformCoordToLocal(x, y);
  54149. resetCursor(this, e, localCursorPoint);
  54150. if (this._dragging) {
  54151. preventDefault(e);
  54152. var eventParams = updateCoverByMouse(this, e, localCursorPoint, false);
  54153. eventParams && trigger$1(this, eventParams);
  54154. }
  54155. },
  54156. mouseup: function (e) {
  54157. handleDragEnd(this, e);
  54158. }
  54159. };
  54160. function handleDragEnd(controller, e) {
  54161. if (controller._dragging) {
  54162. preventDefault(e);
  54163. var x = e.offsetX;
  54164. var y = e.offsetY;
  54165. var localCursorPoint = controller.group.transformCoordToLocal(x, y);
  54166. var eventParams = updateCoverByMouse(controller, e, localCursorPoint, true);
  54167. controller._dragging = false;
  54168. controller._track = [];
  54169. controller._creatingCover = null;
  54170. // trigger event shoule be at final, after procedure will be nested.
  54171. eventParams && trigger$1(controller, eventParams);
  54172. }
  54173. }
  54174. function isOutsideZrArea(controller, x, y) {
  54175. var zr = controller._zr;
  54176. return x < 0 || x > zr.getWidth() || y < 0 || y > zr.getHeight();
  54177. }
  54178. /**
  54179. * key: brushType
  54180. * @type {Object}
  54181. */
  54182. var coverRenderers = {
  54183. lineX: getLineRenderer(0),
  54184. lineY: getLineRenderer(1),
  54185. rect: {
  54186. createCover: function (controller, brushOption) {
  54187. return createBaseRectCover(
  54188. curry$2(
  54189. driftRect,
  54190. function (range) {
  54191. return range;
  54192. },
  54193. function (range) {
  54194. return range;
  54195. }
  54196. ),
  54197. controller,
  54198. brushOption,
  54199. ['w', 'e', 'n', 's', 'se', 'sw', 'ne', 'nw']
  54200. );
  54201. },
  54202. getCreatingRange: function (localTrack) {
  54203. var ends = getTrackEnds(localTrack);
  54204. return formatRectRange(ends[1][0], ends[1][1], ends[0][0], ends[0][1]);
  54205. },
  54206. updateCoverShape: function (controller, cover, localRange, brushOption) {
  54207. updateBaseRect(controller, cover, localRange, brushOption);
  54208. },
  54209. updateCommon: updateCommon,
  54210. contain: mainShapeContain
  54211. },
  54212. polygon: {
  54213. createCover: function (controller, brushOption) {
  54214. var cover = new Group();
  54215. // Do not use graphic.Polygon because graphic.Polyline do not close the
  54216. // border of the shape when drawing, which is a better experience for user.
  54217. cover.add(new Polyline({
  54218. name: 'main',
  54219. style: makeStyle(brushOption),
  54220. silent: true
  54221. }));
  54222. return cover;
  54223. },
  54224. getCreatingRange: function (localTrack) {
  54225. return localTrack;
  54226. },
  54227. endCreating: function (controller, cover) {
  54228. cover.remove(cover.childAt(0));
  54229. // Use graphic.Polygon close the shape.
  54230. cover.add(new Polygon({
  54231. name: 'main',
  54232. draggable: true,
  54233. drift: curry$2(driftPolygon, controller, cover),
  54234. ondragend: curry$2(trigger$1, controller, {isEnd: true})
  54235. }));
  54236. },
  54237. updateCoverShape: function (controller, cover, localRange, brushOption) {
  54238. cover.childAt(0).setShape({
  54239. points: clipByPanel(controller, cover, localRange)
  54240. });
  54241. },
  54242. updateCommon: updateCommon,
  54243. contain: mainShapeContain
  54244. }
  54245. };
  54246. function getLineRenderer(xyIndex) {
  54247. return {
  54248. createCover: function (controller, brushOption) {
  54249. return createBaseRectCover(
  54250. curry$2(
  54251. driftRect,
  54252. function (range) {
  54253. var rectRange = [range, [0, 100]];
  54254. xyIndex && rectRange.reverse();
  54255. return rectRange;
  54256. },
  54257. function (rectRange) {
  54258. return rectRange[xyIndex];
  54259. }
  54260. ),
  54261. controller,
  54262. brushOption,
  54263. [['w', 'e'], ['n', 's']][xyIndex]
  54264. );
  54265. },
  54266. getCreatingRange: function (localTrack) {
  54267. var ends = getTrackEnds(localTrack);
  54268. var min = mathMin$7(ends[0][xyIndex], ends[1][xyIndex]);
  54269. var max = mathMax$7(ends[0][xyIndex], ends[1][xyIndex]);
  54270. return [min, max];
  54271. },
  54272. updateCoverShape: function (controller, cover, localRange, brushOption) {
  54273. var otherExtent;
  54274. // If brushWidth not specified, fit the panel.
  54275. var panel = getPanelByCover(controller, cover);
  54276. if (panel !== true && panel.getLinearBrushOtherExtent) {
  54277. otherExtent = panel.getLinearBrushOtherExtent(
  54278. xyIndex, controller._transform
  54279. );
  54280. }
  54281. else {
  54282. var zr = controller._zr;
  54283. otherExtent = [0, [zr.getWidth(), zr.getHeight()][1 - xyIndex]];
  54284. }
  54285. var rectRange = [localRange, otherExtent];
  54286. xyIndex && rectRange.reverse();
  54287. updateBaseRect(controller, cover, rectRange, brushOption);
  54288. },
  54289. updateCommon: updateCommon,
  54290. contain: mainShapeContain
  54291. };
  54292. }
  54293. /*
  54294. * Licensed to the Apache Software Foundation (ASF) under one
  54295. * or more contributor license agreements. See the NOTICE file
  54296. * distributed with this work for additional information
  54297. * regarding copyright ownership. The ASF licenses this file
  54298. * to you under the Apache License, Version 2.0 (the
  54299. * "License"); you may not use this file except in compliance
  54300. * with the License. You may obtain a copy of the License at
  54301. *
  54302. * http://www.apache.org/licenses/LICENSE-2.0
  54303. *
  54304. * Unless required by applicable law or agreed to in writing,
  54305. * software distributed under the License is distributed on an
  54306. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54307. * KIND, either express or implied. See the License for the
  54308. * specific language governing permissions and limitations
  54309. * under the License.
  54310. */
  54311. function makeRectPanelClipPath(rect) {
  54312. rect = normalizeRect(rect);
  54313. return function (localPoints, transform) {
  54314. return clipPointsByRect(localPoints, rect);
  54315. };
  54316. }
  54317. function makeLinearBrushOtherExtent(rect, specifiedXYIndex) {
  54318. rect = normalizeRect(rect);
  54319. return function (xyIndex) {
  54320. var idx = specifiedXYIndex != null ? specifiedXYIndex : xyIndex;
  54321. var brushWidth = idx ? rect.width : rect.height;
  54322. var base = idx ? rect.x : rect.y;
  54323. return [base, base + (brushWidth || 0)];
  54324. };
  54325. }
  54326. function makeRectIsTargetByCursor(rect, api, targetModel) {
  54327. rect = normalizeRect(rect);
  54328. return function (e, localCursorPoint, transform) {
  54329. return rect.contain(localCursorPoint[0], localCursorPoint[1])
  54330. && !onIrrelevantElement(e, api, targetModel);
  54331. };
  54332. }
  54333. // Consider width/height is negative.
  54334. function normalizeRect(rect) {
  54335. return BoundingRect.create(rect);
  54336. }
  54337. /*
  54338. * Licensed to the Apache Software Foundation (ASF) under one
  54339. * or more contributor license agreements. See the NOTICE file
  54340. * distributed with this work for additional information
  54341. * regarding copyright ownership. The ASF licenses this file
  54342. * to you under the Apache License, Version 2.0 (the
  54343. * "License"); you may not use this file except in compliance
  54344. * with the License. You may obtain a copy of the License at
  54345. *
  54346. * http://www.apache.org/licenses/LICENSE-2.0
  54347. *
  54348. * Unless required by applicable law or agreed to in writing,
  54349. * software distributed under the License is distributed on an
  54350. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54351. * KIND, either express or implied. See the License for the
  54352. * specific language governing permissions and limitations
  54353. * under the License.
  54354. */
  54355. var elementList = ['axisLine', 'axisTickLabel', 'axisName'];
  54356. var AxisView$2 = extendComponentView({
  54357. type: 'parallelAxis',
  54358. /**
  54359. * @override
  54360. */
  54361. init: function (ecModel, api) {
  54362. AxisView$2.superApply(this, 'init', arguments);
  54363. /**
  54364. * @type {module:echarts/component/helper/BrushController}
  54365. */
  54366. (this._brushController = new BrushController(api.getZr()))
  54367. .on('brush', bind(this._onBrush, this));
  54368. },
  54369. /**
  54370. * @override
  54371. */
  54372. render: function (axisModel, ecModel, api, payload) {
  54373. if (fromAxisAreaSelect(axisModel, ecModel, payload)) {
  54374. return;
  54375. }
  54376. this.axisModel = axisModel;
  54377. this.api = api;
  54378. this.group.removeAll();
  54379. var oldAxisGroup = this._axisGroup;
  54380. this._axisGroup = new Group();
  54381. this.group.add(this._axisGroup);
  54382. if (!axisModel.get('show')) {
  54383. return;
  54384. }
  54385. var coordSysModel = getCoordSysModel(axisModel, ecModel);
  54386. var coordSys = coordSysModel.coordinateSystem;
  54387. var areaSelectStyle = axisModel.getAreaSelectStyle();
  54388. var areaWidth = areaSelectStyle.width;
  54389. var dim = axisModel.axis.dim;
  54390. var axisLayout = coordSys.getAxisLayout(dim);
  54391. var builderOpt = extend(
  54392. {strokeContainThreshold: areaWidth},
  54393. axisLayout
  54394. );
  54395. var axisBuilder = new AxisBuilder(axisModel, builderOpt);
  54396. each$1(elementList, axisBuilder.add, axisBuilder);
  54397. this._axisGroup.add(axisBuilder.getGroup());
  54398. this._refreshBrushController(
  54399. builderOpt, areaSelectStyle, axisModel, coordSysModel, areaWidth, api
  54400. );
  54401. var animationModel = (payload && payload.animation === false) ? null : axisModel;
  54402. groupTransition(oldAxisGroup, this._axisGroup, animationModel);
  54403. },
  54404. // /**
  54405. // * @override
  54406. // */
  54407. // updateVisual: function (axisModel, ecModel, api, payload) {
  54408. // this._brushController && this._brushController
  54409. // .updateCovers(getCoverInfoList(axisModel));
  54410. // },
  54411. _refreshBrushController: function (
  54412. builderOpt, areaSelectStyle, axisModel, coordSysModel, areaWidth, api
  54413. ) {
  54414. // After filtering, axis may change, select area needs to be update.
  54415. var extent = axisModel.axis.getExtent();
  54416. var extentLen = extent[1] - extent[0];
  54417. var extra = Math.min(30, Math.abs(extentLen) * 0.1); // Arbitrary value.
  54418. // width/height might be negative, which will be
  54419. // normalized in BoundingRect.
  54420. var rect = BoundingRect.create({
  54421. x: extent[0],
  54422. y: -areaWidth / 2,
  54423. width: extentLen,
  54424. height: areaWidth
  54425. });
  54426. rect.x -= extra;
  54427. rect.width += 2 * extra;
  54428. this._brushController
  54429. .mount({
  54430. enableGlobalPan: true,
  54431. rotation: builderOpt.rotation,
  54432. position: builderOpt.position
  54433. })
  54434. .setPanels([{
  54435. panelId: 'pl',
  54436. clipPath: makeRectPanelClipPath(rect),
  54437. isTargetByCursor: makeRectIsTargetByCursor(rect, api, coordSysModel),
  54438. getLinearBrushOtherExtent: makeLinearBrushOtherExtent(rect, 0)
  54439. }])
  54440. .enableBrush({
  54441. brushType: 'lineX',
  54442. brushStyle: areaSelectStyle,
  54443. removeOnClick: true
  54444. })
  54445. .updateCovers(getCoverInfoList(axisModel));
  54446. },
  54447. _onBrush: function (coverInfoList, opt) {
  54448. // Do not cache these object, because the mey be changed.
  54449. var axisModel = this.axisModel;
  54450. var axis = axisModel.axis;
  54451. var intervals = map(coverInfoList, function (coverInfo) {
  54452. return [
  54453. axis.coordToData(coverInfo.range[0], true),
  54454. axis.coordToData(coverInfo.range[1], true)
  54455. ];
  54456. });
  54457. // If realtime is true, action is not dispatched on drag end, because
  54458. // the drag end emits the same params with the last drag move event,
  54459. // and may have some delay when using touch pad.
  54460. if (!axisModel.option.realtime === opt.isEnd || opt.removeOnClick) { // jshint ignore:line
  54461. this.api.dispatchAction({
  54462. type: 'axisAreaSelect',
  54463. parallelAxisId: axisModel.id,
  54464. intervals: intervals
  54465. });
  54466. }
  54467. },
  54468. /**
  54469. * @override
  54470. */
  54471. dispose: function () {
  54472. this._brushController.dispose();
  54473. }
  54474. });
  54475. function fromAxisAreaSelect(axisModel, ecModel, payload) {
  54476. return payload
  54477. && payload.type === 'axisAreaSelect'
  54478. && ecModel.findComponents(
  54479. {mainType: 'parallelAxis', query: payload}
  54480. )[0] === axisModel;
  54481. }
  54482. function getCoverInfoList(axisModel) {
  54483. var axis = axisModel.axis;
  54484. return map(axisModel.activeIntervals, function (interval) {
  54485. return {
  54486. brushType: 'lineX',
  54487. panelId: 'pl',
  54488. range: [
  54489. axis.dataToCoord(interval[0], true),
  54490. axis.dataToCoord(interval[1], true)
  54491. ]
  54492. };
  54493. });
  54494. }
  54495. function getCoordSysModel(axisModel, ecModel) {
  54496. return ecModel.getComponent(
  54497. 'parallel', axisModel.get('parallelIndex')
  54498. );
  54499. }
  54500. /*
  54501. * Licensed to the Apache Software Foundation (ASF) under one
  54502. * or more contributor license agreements. See the NOTICE file
  54503. * distributed with this work for additional information
  54504. * regarding copyright ownership. The ASF licenses this file
  54505. * to you under the Apache License, Version 2.0 (the
  54506. * "License"); you may not use this file except in compliance
  54507. * with the License. You may obtain a copy of the License at
  54508. *
  54509. * http://www.apache.org/licenses/LICENSE-2.0
  54510. *
  54511. * Unless required by applicable law or agreed to in writing,
  54512. * software distributed under the License is distributed on an
  54513. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54514. * KIND, either express or implied. See the License for the
  54515. * specific language governing permissions and limitations
  54516. * under the License.
  54517. */
  54518. /*
  54519. * Licensed to the Apache Software Foundation (ASF) under one
  54520. * or more contributor license agreements. See the NOTICE file
  54521. * distributed with this work for additional information
  54522. * regarding copyright ownership. The ASF licenses this file
  54523. * to you under the Apache License, Version 2.0 (the
  54524. * "License"); you may not use this file except in compliance
  54525. * with the License. You may obtain a copy of the License at
  54526. *
  54527. * http://www.apache.org/licenses/LICENSE-2.0
  54528. *
  54529. * Unless required by applicable law or agreed to in writing,
  54530. * software distributed under the License is distributed on an
  54531. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54532. * KIND, either express or implied. See the License for the
  54533. * specific language governing permissions and limitations
  54534. * under the License.
  54535. */
  54536. var CLICK_THRESHOLD = 5; // > 4
  54537. // Parallel view
  54538. extendComponentView({
  54539. type: 'parallel',
  54540. render: function (parallelModel, ecModel, api) {
  54541. this._model = parallelModel;
  54542. this._api = api;
  54543. if (!this._handlers) {
  54544. this._handlers = {};
  54545. each$1(handlers, function (handler, eventName) {
  54546. api.getZr().on(eventName, this._handlers[eventName] = bind(handler, this));
  54547. }, this);
  54548. }
  54549. createOrUpdate(
  54550. this,
  54551. '_throttledDispatchExpand',
  54552. parallelModel.get('axisExpandRate'),
  54553. 'fixRate'
  54554. );
  54555. },
  54556. dispose: function (ecModel, api) {
  54557. each$1(this._handlers, function (handler, eventName) {
  54558. api.getZr().off(eventName, handler);
  54559. });
  54560. this._handlers = null;
  54561. },
  54562. /**
  54563. * @param {Object} [opt] If null, cancle the last action triggering for debounce.
  54564. */
  54565. _throttledDispatchExpand: function (opt) {
  54566. this._dispatchExpand(opt);
  54567. },
  54568. _dispatchExpand: function (opt) {
  54569. opt && this._api.dispatchAction(
  54570. extend({type: 'parallelAxisExpand'}, opt)
  54571. );
  54572. }
  54573. });
  54574. var handlers = {
  54575. mousedown: function (e) {
  54576. if (checkTrigger(this, 'click')) {
  54577. this._mouseDownPoint = [e.offsetX, e.offsetY];
  54578. }
  54579. },
  54580. mouseup: function (e) {
  54581. var mouseDownPoint = this._mouseDownPoint;
  54582. if (checkTrigger(this, 'click') && mouseDownPoint) {
  54583. var point = [e.offsetX, e.offsetY];
  54584. var dist = Math.pow(mouseDownPoint[0] - point[0], 2)
  54585. + Math.pow(mouseDownPoint[1] - point[1], 2);
  54586. if (dist > CLICK_THRESHOLD) {
  54587. return;
  54588. }
  54589. var result = this._model.coordinateSystem.getSlidedAxisExpandWindow(
  54590. [e.offsetX, e.offsetY]
  54591. );
  54592. result.behavior !== 'none' && this._dispatchExpand({
  54593. axisExpandWindow: result.axisExpandWindow
  54594. });
  54595. }
  54596. this._mouseDownPoint = null;
  54597. },
  54598. mousemove: function (e) {
  54599. // Should do nothing when brushing.
  54600. if (this._mouseDownPoint || !checkTrigger(this, 'mousemove')) {
  54601. return;
  54602. }
  54603. var model = this._model;
  54604. var result = model.coordinateSystem.getSlidedAxisExpandWindow(
  54605. [e.offsetX, e.offsetY]
  54606. );
  54607. var behavior = result.behavior;
  54608. behavior === 'jump' && this._throttledDispatchExpand.debounceNextCall(model.get('axisExpandDebounce'));
  54609. this._throttledDispatchExpand(
  54610. behavior === 'none'
  54611. ? null // Cancle the last trigger, in case that mouse slide out of the area quickly.
  54612. : {
  54613. axisExpandWindow: result.axisExpandWindow,
  54614. // Jumping uses animation, and sliding suppresses animation.
  54615. animation: behavior === 'jump' ? null : false
  54616. }
  54617. );
  54618. }
  54619. };
  54620. function checkTrigger(view, triggerOn) {
  54621. var model = view._model;
  54622. return model.get('axisExpandable') && model.get('axisExpandTriggerOn') === triggerOn;
  54623. }
  54624. registerPreprocessor(parallelPreprocessor);
  54625. /*
  54626. * Licensed to the Apache Software Foundation (ASF) under one
  54627. * or more contributor license agreements. See the NOTICE file
  54628. * distributed with this work for additional information
  54629. * regarding copyright ownership. The ASF licenses this file
  54630. * to you under the Apache License, Version 2.0 (the
  54631. * "License"); you may not use this file except in compliance
  54632. * with the License. You may obtain a copy of the License at
  54633. *
  54634. * http://www.apache.org/licenses/LICENSE-2.0
  54635. *
  54636. * Unless required by applicable law or agreed to in writing,
  54637. * software distributed under the License is distributed on an
  54638. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54639. * KIND, either express or implied. See the License for the
  54640. * specific language governing permissions and limitations
  54641. * under the License.
  54642. */
  54643. SeriesModel.extend({
  54644. type: 'series.parallel',
  54645. dependencies: ['parallel'],
  54646. visualColorAccessPath: 'lineStyle.color',
  54647. getInitialData: function (option, ecModel) {
  54648. var source = this.getSource();
  54649. setEncodeAndDimensions(source, this);
  54650. return createListFromArray(source, this);
  54651. },
  54652. /**
  54653. * User can get data raw indices on 'axisAreaSelected' event received.
  54654. *
  54655. * @public
  54656. * @param {string} activeState 'active' or 'inactive' or 'normal'
  54657. * @return {Array.<number>} Raw indices
  54658. */
  54659. getRawIndicesByActiveState: function (activeState) {
  54660. var coordSys = this.coordinateSystem;
  54661. var data = this.getData();
  54662. var indices = [];
  54663. coordSys.eachActiveState(data, function (theActiveState, dataIndex) {
  54664. if (activeState === theActiveState) {
  54665. indices.push(data.getRawIndex(dataIndex));
  54666. }
  54667. });
  54668. return indices;
  54669. },
  54670. defaultOption: {
  54671. zlevel: 0, // 一级层叠
  54672. z: 2, // 二级层叠
  54673. coordinateSystem: 'parallel',
  54674. parallelIndex: 0,
  54675. label: {
  54676. show: false
  54677. },
  54678. inactiveOpacity: 0.05,
  54679. activeOpacity: 1,
  54680. lineStyle: {
  54681. width: 1,
  54682. opacity: 0.45,
  54683. type: 'solid'
  54684. },
  54685. emphasis: {
  54686. label: {
  54687. show: false
  54688. }
  54689. },
  54690. progressive: 500,
  54691. smooth: false, // true | false | number
  54692. animationEasing: 'linear'
  54693. }
  54694. });
  54695. function setEncodeAndDimensions(source, seriesModel) {
  54696. // The mapping of parallelAxis dimension to data dimension can
  54697. // be specified in parallelAxis.option.dim. For example, if
  54698. // parallelAxis.option.dim is 'dim3', it mapping to the third
  54699. // dimension of data. But `data.encode` has higher priority.
  54700. // Moreover, parallelModel.dimension should not be regarded as data
  54701. // dimensions. Consider dimensions = ['dim4', 'dim2', 'dim6'];
  54702. if (source.encodeDefine) {
  54703. return;
  54704. }
  54705. var parallelModel = seriesModel.ecModel.getComponent(
  54706. 'parallel', seriesModel.get('parallelIndex')
  54707. );
  54708. if (!parallelModel) {
  54709. return;
  54710. }
  54711. var encodeDefine = source.encodeDefine = createHashMap();
  54712. each$1(parallelModel.dimensions, function (axisDim) {
  54713. var dataDimIndex = convertDimNameToNumber(axisDim);
  54714. encodeDefine.set(axisDim, dataDimIndex);
  54715. });
  54716. }
  54717. function convertDimNameToNumber(dimName) {
  54718. return +dimName.replace('dim', '');
  54719. }
  54720. /*
  54721. * Licensed to the Apache Software Foundation (ASF) under one
  54722. * or more contributor license agreements. See the NOTICE file
  54723. * distributed with this work for additional information
  54724. * regarding copyright ownership. The ASF licenses this file
  54725. * to you under the Apache License, Version 2.0 (the
  54726. * "License"); you may not use this file except in compliance
  54727. * with the License. You may obtain a copy of the License at
  54728. *
  54729. * http://www.apache.org/licenses/LICENSE-2.0
  54730. *
  54731. * Unless required by applicable law or agreed to in writing,
  54732. * software distributed under the License is distributed on an
  54733. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54734. * KIND, either express or implied. See the License for the
  54735. * specific language governing permissions and limitations
  54736. * under the License.
  54737. */
  54738. var DEFAULT_SMOOTH = 0.3;
  54739. var ParallelView = Chart.extend({
  54740. type: 'parallel',
  54741. init: function () {
  54742. /**
  54743. * @type {module:zrender/container/Group}
  54744. * @private
  54745. */
  54746. this._dataGroup = new Group();
  54747. this.group.add(this._dataGroup);
  54748. /**
  54749. * @type {module:echarts/data/List}
  54750. */
  54751. this._data;
  54752. /**
  54753. * @type {boolean}
  54754. */
  54755. this._initialized;
  54756. },
  54757. /**
  54758. * @override
  54759. */
  54760. render: function (seriesModel, ecModel, api, payload) {
  54761. var dataGroup = this._dataGroup;
  54762. var data = seriesModel.getData();
  54763. var oldData = this._data;
  54764. var coordSys = seriesModel.coordinateSystem;
  54765. var dimensions = coordSys.dimensions;
  54766. var seriesScope = makeSeriesScope$2(seriesModel);
  54767. data.diff(oldData)
  54768. .add(add)
  54769. .update(update)
  54770. .remove(remove)
  54771. .execute();
  54772. function add(newDataIndex) {
  54773. var line = addEl(data, dataGroup, newDataIndex, dimensions, coordSys);
  54774. updateElCommon(line, data, newDataIndex, seriesScope);
  54775. }
  54776. function update(newDataIndex, oldDataIndex) {
  54777. var line = oldData.getItemGraphicEl(oldDataIndex);
  54778. var points = createLinePoints(data, newDataIndex, dimensions, coordSys);
  54779. data.setItemGraphicEl(newDataIndex, line);
  54780. var animationModel = (payload && payload.animation === false) ? null : seriesModel;
  54781. updateProps(line, {shape: {points: points}}, animationModel, newDataIndex);
  54782. updateElCommon(line, data, newDataIndex, seriesScope);
  54783. }
  54784. function remove(oldDataIndex) {
  54785. var line = oldData.getItemGraphicEl(oldDataIndex);
  54786. dataGroup.remove(line);
  54787. }
  54788. // First create
  54789. if (!this._initialized) {
  54790. this._initialized = true;
  54791. var clipPath = createGridClipShape(
  54792. coordSys, seriesModel, function () {
  54793. // Callback will be invoked immediately if there is no animation
  54794. setTimeout(function () {
  54795. dataGroup.removeClipPath();
  54796. });
  54797. }
  54798. );
  54799. dataGroup.setClipPath(clipPath);
  54800. }
  54801. this._data = data;
  54802. },
  54803. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  54804. this._initialized = true;
  54805. this._data = null;
  54806. this._dataGroup.removeAll();
  54807. },
  54808. incrementalRender: function (taskParams, seriesModel, ecModel) {
  54809. var data = seriesModel.getData();
  54810. var coordSys = seriesModel.coordinateSystem;
  54811. var dimensions = coordSys.dimensions;
  54812. var seriesScope = makeSeriesScope$2(seriesModel);
  54813. for (var dataIndex = taskParams.start; dataIndex < taskParams.end; dataIndex++) {
  54814. var line = addEl(data, this._dataGroup, dataIndex, dimensions, coordSys);
  54815. line.incremental = true;
  54816. updateElCommon(line, data, dataIndex, seriesScope);
  54817. }
  54818. },
  54819. dispose: function () {},
  54820. // _renderForProgressive: function (seriesModel) {
  54821. // var dataGroup = this._dataGroup;
  54822. // var data = seriesModel.getData();
  54823. // var oldData = this._data;
  54824. // var coordSys = seriesModel.coordinateSystem;
  54825. // var dimensions = coordSys.dimensions;
  54826. // var option = seriesModel.option;
  54827. // var progressive = option.progressive;
  54828. // var smooth = option.smooth ? SMOOTH : null;
  54829. // // In progressive animation is disabled, so use simple data diff,
  54830. // // which effects performance less.
  54831. // // (Typically performance for data with length 7000+ like:
  54832. // // simpleDiff: 60ms, addEl: 184ms,
  54833. // // in RMBP 2.4GHz intel i7, OSX 10.9 chrome 50.0.2661.102 (64-bit))
  54834. // if (simpleDiff(oldData, data, dimensions)) {
  54835. // dataGroup.removeAll();
  54836. // data.each(function (dataIndex) {
  54837. // addEl(data, dataGroup, dataIndex, dimensions, coordSys);
  54838. // });
  54839. // }
  54840. // updateElCommon(data, progressive, smooth);
  54841. // // Consider switch between progressive and not.
  54842. // data.__plProgressive = true;
  54843. // this._data = data;
  54844. // },
  54845. /**
  54846. * @override
  54847. */
  54848. remove: function () {
  54849. this._dataGroup && this._dataGroup.removeAll();
  54850. this._data = null;
  54851. }
  54852. });
  54853. function createGridClipShape(coordSys, seriesModel, cb) {
  54854. var parallelModel = coordSys.model;
  54855. var rect = coordSys.getRect();
  54856. var rectEl = new Rect({
  54857. shape: {
  54858. x: rect.x,
  54859. y: rect.y,
  54860. width: rect.width,
  54861. height: rect.height
  54862. }
  54863. });
  54864. var dim = parallelModel.get('layout') === 'horizontal' ? 'width' : 'height';
  54865. rectEl.setShape(dim, 0);
  54866. initProps(rectEl, {
  54867. shape: {
  54868. width: rect.width,
  54869. height: rect.height
  54870. }
  54871. }, seriesModel, cb);
  54872. return rectEl;
  54873. }
  54874. function createLinePoints(data, dataIndex, dimensions, coordSys) {
  54875. var points = [];
  54876. for (var i = 0; i < dimensions.length; i++) {
  54877. var dimName = dimensions[i];
  54878. var value = data.get(data.mapDimension(dimName), dataIndex);
  54879. if (!isEmptyValue(value, coordSys.getAxis(dimName).type)) {
  54880. points.push(coordSys.dataToPoint(value, dimName));
  54881. }
  54882. }
  54883. return points;
  54884. }
  54885. function addEl(data, dataGroup, dataIndex, dimensions, coordSys) {
  54886. var points = createLinePoints(data, dataIndex, dimensions, coordSys);
  54887. var line = new Polyline({
  54888. shape: {points: points},
  54889. silent: true,
  54890. z2: 10
  54891. });
  54892. dataGroup.add(line);
  54893. data.setItemGraphicEl(dataIndex, line);
  54894. return line;
  54895. }
  54896. function makeSeriesScope$2(seriesModel) {
  54897. var smooth = seriesModel.get('smooth', true);
  54898. smooth === true && (smooth = DEFAULT_SMOOTH);
  54899. return {
  54900. lineStyle: seriesModel.getModel('lineStyle').getLineStyle(),
  54901. smooth: smooth != null ? smooth : DEFAULT_SMOOTH
  54902. };
  54903. }
  54904. function updateElCommon(el, data, dataIndex, seriesScope) {
  54905. var lineStyle = seriesScope.lineStyle;
  54906. if (data.hasItemOption) {
  54907. var lineStyleModel = data.getItemModel(dataIndex).getModel('lineStyle');
  54908. lineStyle = lineStyleModel.getLineStyle();
  54909. }
  54910. el.useStyle(lineStyle);
  54911. var elStyle = el.style;
  54912. elStyle.fill = null;
  54913. // lineStyle.color have been set to itemVisual in module:echarts/visual/seriesColor.
  54914. elStyle.stroke = data.getItemVisual(dataIndex, 'color');
  54915. // lineStyle.opacity have been set to itemVisual in parallelVisual.
  54916. elStyle.opacity = data.getItemVisual(dataIndex, 'opacity');
  54917. seriesScope.smooth && (el.shape.smooth = seriesScope.smooth);
  54918. }
  54919. // function simpleDiff(oldData, newData, dimensions) {
  54920. // var oldLen;
  54921. // if (!oldData
  54922. // || !oldData.__plProgressive
  54923. // || (oldLen = oldData.count()) !== newData.count()
  54924. // ) {
  54925. // return true;
  54926. // }
  54927. // var dimLen = dimensions.length;
  54928. // for (var i = 0; i < oldLen; i++) {
  54929. // for (var j = 0; j < dimLen; j++) {
  54930. // if (oldData.get(dimensions[j], i) !== newData.get(dimensions[j], i)) {
  54931. // return true;
  54932. // }
  54933. // }
  54934. // }
  54935. // return false;
  54936. // }
  54937. // FIXME
  54938. // 公用方法?
  54939. function isEmptyValue(val, axisType) {
  54940. return axisType === 'category'
  54941. ? val == null
  54942. : (val == null || isNaN(val)); // axisType === 'value'
  54943. }
  54944. /*
  54945. * Licensed to the Apache Software Foundation (ASF) under one
  54946. * or more contributor license agreements. See the NOTICE file
  54947. * distributed with this work for additional information
  54948. * regarding copyright ownership. The ASF licenses this file
  54949. * to you under the Apache License, Version 2.0 (the
  54950. * "License"); you may not use this file except in compliance
  54951. * with the License. You may obtain a copy of the License at
  54952. *
  54953. * http://www.apache.org/licenses/LICENSE-2.0
  54954. *
  54955. * Unless required by applicable law or agreed to in writing,
  54956. * software distributed under the License is distributed on an
  54957. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54958. * KIND, either express or implied. See the License for the
  54959. * specific language governing permissions and limitations
  54960. * under the License.
  54961. */
  54962. var opacityAccessPath$1 = ['lineStyle', 'normal', 'opacity'];
  54963. var parallelVisual = {
  54964. seriesType: 'parallel',
  54965. reset: function (seriesModel, ecModel, api) {
  54966. var itemStyleModel = seriesModel.getModel('itemStyle');
  54967. var lineStyleModel = seriesModel.getModel('lineStyle');
  54968. var globalColors = ecModel.get('color');
  54969. var color = lineStyleModel.get('color')
  54970. || itemStyleModel.get('color')
  54971. || globalColors[seriesModel.seriesIndex % globalColors.length];
  54972. var inactiveOpacity = seriesModel.get('inactiveOpacity');
  54973. var activeOpacity = seriesModel.get('activeOpacity');
  54974. var lineStyle = seriesModel.getModel('lineStyle').getLineStyle();
  54975. var coordSys = seriesModel.coordinateSystem;
  54976. var data = seriesModel.getData();
  54977. var opacityMap = {
  54978. normal: lineStyle.opacity,
  54979. active: activeOpacity,
  54980. inactive: inactiveOpacity
  54981. };
  54982. data.setVisual('color', color);
  54983. function progress(params, data) {
  54984. coordSys.eachActiveState(data, function (activeState, dataIndex) {
  54985. var opacity = opacityMap[activeState];
  54986. if (activeState === 'normal' && data.hasItemOption) {
  54987. var itemOpacity = data.getItemModel(dataIndex).get(opacityAccessPath$1, true);
  54988. itemOpacity != null && (opacity = itemOpacity);
  54989. }
  54990. data.setItemVisual(dataIndex, 'opacity', opacity);
  54991. }, params.start, params.end);
  54992. }
  54993. return {progress: progress};
  54994. }
  54995. };
  54996. /*
  54997. * Licensed to the Apache Software Foundation (ASF) under one
  54998. * or more contributor license agreements. See the NOTICE file
  54999. * distributed with this work for additional information
  55000. * regarding copyright ownership. The ASF licenses this file
  55001. * to you under the Apache License, Version 2.0 (the
  55002. * "License"); you may not use this file except in compliance
  55003. * with the License. You may obtain a copy of the License at
  55004. *
  55005. * http://www.apache.org/licenses/LICENSE-2.0
  55006. *
  55007. * Unless required by applicable law or agreed to in writing,
  55008. * software distributed under the License is distributed on an
  55009. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55010. * KIND, either express or implied. See the License for the
  55011. * specific language governing permissions and limitations
  55012. * under the License.
  55013. */
  55014. registerVisual(parallelVisual);
  55015. /*
  55016. * Licensed to the Apache Software Foundation (ASF) under one
  55017. * or more contributor license agreements. See the NOTICE file
  55018. * distributed with this work for additional information
  55019. * regarding copyright ownership. The ASF licenses this file
  55020. * to you under the Apache License, Version 2.0 (the
  55021. * "License"); you may not use this file except in compliance
  55022. * with the License. You may obtain a copy of the License at
  55023. *
  55024. * http://www.apache.org/licenses/LICENSE-2.0
  55025. *
  55026. * Unless required by applicable law or agreed to in writing,
  55027. * software distributed under the License is distributed on an
  55028. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55029. * KIND, either express or implied. See the License for the
  55030. * specific language governing permissions and limitations
  55031. * under the License.
  55032. */
  55033. var SankeySeries = SeriesModel.extend({
  55034. type: 'series.sankey',
  55035. layoutInfo: null,
  55036. levelModels: null,
  55037. /**
  55038. * Init a graph data structure from data in option series
  55039. *
  55040. * @param {Object} option the object used to config echarts view
  55041. * @return {module:echarts/data/List} storage initial data
  55042. */
  55043. getInitialData: function (option, ecModel) {
  55044. var links = option.edges || option.links;
  55045. var nodes = option.data || option.nodes;
  55046. var levels = option.levels;
  55047. var levelModels = this.levelModels = {};
  55048. for (var i = 0; i < levels.length; i++) {
  55049. if (levels[i].depth != null && levels[i].depth >= 0) {
  55050. levelModels[levels[i].depth] = new Model(levels[i], this, ecModel);
  55051. }
  55052. else {
  55053. if (__DEV__) {
  55054. throw new Error('levels[i].depth is mandatory and should be natural number');
  55055. }
  55056. }
  55057. }
  55058. if (nodes && links) {
  55059. var graph = createGraphFromNodeEdge(nodes, links, this, true, beforeLink);
  55060. return graph.data;
  55061. }
  55062. function beforeLink(nodeData, edgeData) {
  55063. nodeData.wrapMethod('getItemModel', function (model, idx) {
  55064. model.customizeGetParent(function (path) {
  55065. var parentModel = this.parentModel;
  55066. var nodeDepth = parentModel.getData().getItemLayout(idx).depth;
  55067. var levelModel = parentModel.levelModels[nodeDepth];
  55068. return levelModel || this.parentModel;
  55069. });
  55070. return model;
  55071. });
  55072. edgeData.wrapMethod('getItemModel', function (model, idx) {
  55073. model.customizeGetParent(function (path) {
  55074. var parentModel = this.parentModel;
  55075. var edge = parentModel.getGraph().getEdgeByIndex(idx);
  55076. var depth = edge.node1.getLayout().depth;
  55077. var levelModel = parentModel.levelModels[depth];
  55078. return levelModel || this.parentModel;
  55079. });
  55080. return model;
  55081. });
  55082. }
  55083. },
  55084. setNodePosition: function (dataIndex, localPosition) {
  55085. var dataItem = this.option.data[dataIndex];
  55086. dataItem.localX = localPosition[0];
  55087. dataItem.localY = localPosition[1];
  55088. },
  55089. /**
  55090. * Return the graphic data structure
  55091. *
  55092. * @return {module:echarts/data/Graph} graphic data structure
  55093. */
  55094. getGraph: function () {
  55095. return this.getData().graph;
  55096. },
  55097. /**
  55098. * Get edge data of graphic data structure
  55099. *
  55100. * @return {module:echarts/data/List} data structure of list
  55101. */
  55102. getEdgeData: function () {
  55103. return this.getGraph().edgeData;
  55104. },
  55105. /**
  55106. * @override
  55107. */
  55108. formatTooltip: function (dataIndex, multipleSeries, dataType) {
  55109. // dataType === 'node' or empty do not show tooltip by default
  55110. if (dataType === 'edge') {
  55111. var params = this.getDataParams(dataIndex, dataType);
  55112. var rawDataOpt = params.data;
  55113. var html = rawDataOpt.source + ' -- ' + rawDataOpt.target;
  55114. if (params.value) {
  55115. html += ' : ' + params.value;
  55116. }
  55117. return encodeHTML(html);
  55118. }
  55119. else if (dataType === 'node') {
  55120. var node = this.getGraph().getNodeByIndex(dataIndex);
  55121. var value = node.getLayout().value;
  55122. var name = this.getDataParams(dataIndex, dataType).data.name;
  55123. if (value) {
  55124. var html = name + ' : ' + value;
  55125. }
  55126. return encodeHTML(html);
  55127. }
  55128. return SankeySeries.superCall(this, 'formatTooltip', dataIndex, multipleSeries);
  55129. },
  55130. optionUpdated: function () {
  55131. var option = this.option;
  55132. if (option.focusNodeAdjacency === true) {
  55133. option.focusNodeAdjacency = 'allEdges';
  55134. }
  55135. },
  55136. // Override Series.getDataParams()
  55137. getDataParams: function (dataIndex, dataType) {
  55138. var params = SankeySeries.superCall(this, 'getDataParams', dataIndex, dataType);
  55139. if (params.value == null && dataType === 'node') {
  55140. var node = this.getGraph().getNodeByIndex(dataIndex);
  55141. var nodeValue = node.getLayout().value;
  55142. params.value = nodeValue;
  55143. }
  55144. return params;
  55145. },
  55146. defaultOption: {
  55147. zlevel: 0,
  55148. z: 2,
  55149. coordinateSystem: 'view',
  55150. layout: null,
  55151. // The position of the whole view
  55152. left: '5%',
  55153. top: '5%',
  55154. right: '20%',
  55155. bottom: '5%',
  55156. // Value can be 'vertical'
  55157. orient: 'horizontal',
  55158. // The dx of the node
  55159. nodeWidth: 20,
  55160. // The vertical distance between two nodes
  55161. nodeGap: 8,
  55162. // Control if the node can move or not
  55163. draggable: true,
  55164. // Value can be 'inEdges', 'outEdges', 'allEdges', true (the same as 'allEdges').
  55165. focusNodeAdjacency: false,
  55166. // The number of iterations to change the position of the node
  55167. layoutIterations: 32,
  55168. label: {
  55169. show: true,
  55170. position: 'right',
  55171. color: '#000',
  55172. fontSize: 12
  55173. },
  55174. levels: [],
  55175. // Value can be 'left' or 'right'
  55176. nodeAlign: 'justify',
  55177. itemStyle: {
  55178. borderWidth: 1,
  55179. borderColor: '#333'
  55180. },
  55181. lineStyle: {
  55182. color: '#314656',
  55183. opacity: 0.2,
  55184. curveness: 0.5
  55185. },
  55186. emphasis: {
  55187. label: {
  55188. show: true
  55189. },
  55190. lineStyle: {
  55191. opacity: 0.5
  55192. }
  55193. },
  55194. animationEasing: 'linear',
  55195. animationDuration: 1000
  55196. }
  55197. });
  55198. /*
  55199. * Licensed to the Apache Software Foundation (ASF) under one
  55200. * or more contributor license agreements. See the NOTICE file
  55201. * distributed with this work for additional information
  55202. * regarding copyright ownership. The ASF licenses this file
  55203. * to you under the Apache License, Version 2.0 (the
  55204. * "License"); you may not use this file except in compliance
  55205. * with the License. You may obtain a copy of the License at
  55206. *
  55207. * http://www.apache.org/licenses/LICENSE-2.0
  55208. *
  55209. * Unless required by applicable law or agreed to in writing,
  55210. * software distributed under the License is distributed on an
  55211. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55212. * KIND, either express or implied. See the License for the
  55213. * specific language governing permissions and limitations
  55214. * under the License.
  55215. */
  55216. var nodeOpacityPath$1 = ['itemStyle', 'opacity'];
  55217. var hoverNodeOpacityPath = ['emphasis', 'itemStyle', 'opacity'];
  55218. var lineOpacityPath$1 = ['lineStyle', 'opacity'];
  55219. var hoverLineOpacityPath = ['emphasis', 'lineStyle', 'opacity'];
  55220. function getItemOpacity$1(item, opacityPath) {
  55221. return item.getVisual('opacity') || item.getModel().get(opacityPath);
  55222. }
  55223. function fadeOutItem$1(item, opacityPath, opacityRatio) {
  55224. var el = item.getGraphicEl();
  55225. var opacity = getItemOpacity$1(item, opacityPath);
  55226. if (opacityRatio != null) {
  55227. opacity == null && (opacity = 1);
  55228. opacity *= opacityRatio;
  55229. }
  55230. el.downplay && el.downplay();
  55231. el.traverse(function (child) {
  55232. if (child.type !== 'group') {
  55233. child.setStyle('opacity', opacity);
  55234. }
  55235. });
  55236. }
  55237. function fadeInItem$1(item, opacityPath) {
  55238. var opacity = getItemOpacity$1(item, opacityPath);
  55239. var el = item.getGraphicEl();
  55240. el.traverse(function (child) {
  55241. if (child.type !== 'group') {
  55242. child.setStyle('opacity', opacity);
  55243. }
  55244. });
  55245. // Support emphasis here.
  55246. el.highlight && el.highlight();
  55247. }
  55248. var SankeyShape = extendShape({
  55249. shape: {
  55250. x1: 0, y1: 0,
  55251. x2: 0, y2: 0,
  55252. cpx1: 0, cpy1: 0,
  55253. cpx2: 0, cpy2: 0,
  55254. extent: 0,
  55255. orient: ''
  55256. },
  55257. buildPath: function (ctx, shape) {
  55258. var extent = shape.extent;
  55259. ctx.moveTo(shape.x1, shape.y1);
  55260. ctx.bezierCurveTo(
  55261. shape.cpx1, shape.cpy1,
  55262. shape.cpx2, shape.cpy2,
  55263. shape.x2, shape.y2
  55264. );
  55265. if (shape.orient === 'vertical') {
  55266. ctx.lineTo(shape.x2 + extent, shape.y2);
  55267. ctx.bezierCurveTo(
  55268. shape.cpx2 + extent, shape.cpy2,
  55269. shape.cpx1 + extent, shape.cpy1,
  55270. shape.x1 + extent, shape.y1
  55271. );
  55272. }
  55273. else {
  55274. ctx.lineTo(shape.x2, shape.y2 + extent);
  55275. ctx.bezierCurveTo(
  55276. shape.cpx2, shape.cpy2 + extent,
  55277. shape.cpx1, shape.cpy1 + extent,
  55278. shape.x1, shape.y1 + extent
  55279. );
  55280. }
  55281. ctx.closePath();
  55282. },
  55283. highlight: function () {
  55284. this.trigger('emphasis');
  55285. },
  55286. downplay: function () {
  55287. this.trigger('normal');
  55288. }
  55289. });
  55290. extendChartView({
  55291. type: 'sankey',
  55292. /**
  55293. * @private
  55294. * @type {module:echarts/chart/sankey/SankeySeries}
  55295. */
  55296. _model: null,
  55297. /**
  55298. * @private
  55299. * @type {boolean}
  55300. */
  55301. _focusAdjacencyDisabled: false,
  55302. render: function (seriesModel, ecModel, api) {
  55303. var sankeyView = this;
  55304. var graph = seriesModel.getGraph();
  55305. var group = this.group;
  55306. var layoutInfo = seriesModel.layoutInfo;
  55307. // view width
  55308. var width = layoutInfo.width;
  55309. // view height
  55310. var height = layoutInfo.height;
  55311. var nodeData = seriesModel.getData();
  55312. var edgeData = seriesModel.getData('edge');
  55313. var orient = seriesModel.get('orient');
  55314. this._model = seriesModel;
  55315. group.removeAll();
  55316. group.attr('position', [layoutInfo.x, layoutInfo.y]);
  55317. // generate a bezire Curve for each edge
  55318. graph.eachEdge(function (edge) {
  55319. var curve = new SankeyShape();
  55320. curve.dataIndex = edge.dataIndex;
  55321. curve.seriesIndex = seriesModel.seriesIndex;
  55322. curve.dataType = 'edge';
  55323. var lineStyleModel = edge.getModel('lineStyle');
  55324. var curvature = lineStyleModel.get('curveness');
  55325. var n1Layout = edge.node1.getLayout();
  55326. var node1Model = edge.node1.getModel();
  55327. var dragX1 = node1Model.get('localX');
  55328. var dragY1 = node1Model.get('localY');
  55329. var n2Layout = edge.node2.getLayout();
  55330. var node2Model = edge.node2.getModel();
  55331. var dragX2 = node2Model.get('localX');
  55332. var dragY2 = node2Model.get('localY');
  55333. var edgeLayout = edge.getLayout();
  55334. var x1;
  55335. var y1;
  55336. var x2;
  55337. var y2;
  55338. var cpx1;
  55339. var cpy1;
  55340. var cpx2;
  55341. var cpy2;
  55342. curve.shape.extent = Math.max(1, edgeLayout.dy);
  55343. curve.shape.orient = orient;
  55344. if (orient === 'vertical') {
  55345. x1 = (dragX1 != null ? dragX1 * width : n1Layout.x) + edgeLayout.sy;
  55346. y1 = (dragY1 != null ? dragY1 * height : n1Layout.y) + n1Layout.dy;
  55347. x2 = (dragX2 != null ? dragX2 * width : n2Layout.x) + edgeLayout.ty;
  55348. y2 = dragY2 != null ? dragY2 * height : n2Layout.y;
  55349. cpx1 = x1;
  55350. cpy1 = y1 * (1 - curvature) + y2 * curvature;
  55351. cpx2 = x2;
  55352. cpy2 = y1 * curvature + y2 * (1 - curvature);
  55353. }
  55354. else {
  55355. x1 = (dragX1 != null ? dragX1 * width : n1Layout.x) + n1Layout.dx;
  55356. y1 = (dragY1 != null ? dragY1 * height : n1Layout.y) + edgeLayout.sy;
  55357. x2 = dragX2 != null ? dragX2 * width : n2Layout.x;
  55358. y2 = (dragY2 != null ? dragY2 * height : n2Layout.y) + edgeLayout.ty;
  55359. cpx1 = x1 * (1 - curvature) + x2 * curvature;
  55360. cpy1 = y1;
  55361. cpx2 = x1 * curvature + x2 * (1 - curvature);
  55362. cpy2 = y2;
  55363. }
  55364. curve.setShape({
  55365. x1: x1,
  55366. y1: y1,
  55367. x2: x2,
  55368. y2: y2,
  55369. cpx1: cpx1,
  55370. cpy1: cpy1,
  55371. cpx2: cpx2,
  55372. cpy2: cpy2
  55373. });
  55374. curve.setStyle(lineStyleModel.getItemStyle());
  55375. // Special color, use source node color or target node color
  55376. switch (curve.style.fill) {
  55377. case 'source':
  55378. curve.style.fill = edge.node1.getVisual('color');
  55379. break;
  55380. case 'target':
  55381. curve.style.fill = edge.node2.getVisual('color');
  55382. break;
  55383. }
  55384. setHoverStyle(curve, edge.getModel('emphasis.lineStyle').getItemStyle());
  55385. group.add(curve);
  55386. edgeData.setItemGraphicEl(edge.dataIndex, curve);
  55387. });
  55388. // Generate a rect for each node
  55389. graph.eachNode(function (node) {
  55390. var layout = node.getLayout();
  55391. var itemModel = node.getModel();
  55392. var dragX = itemModel.get('localX');
  55393. var dragY = itemModel.get('localY');
  55394. var labelModel = itemModel.getModel('label');
  55395. var labelHoverModel = itemModel.getModel('emphasis.label');
  55396. var rect = new Rect({
  55397. shape: {
  55398. x: dragX != null ? dragX * width : layout.x,
  55399. y: dragY != null ? dragY * height : layout.y,
  55400. width: layout.dx,
  55401. height: layout.dy
  55402. },
  55403. style: itemModel.getModel('itemStyle').getItemStyle()
  55404. });
  55405. var hoverStyle = node.getModel('emphasis.itemStyle').getItemStyle();
  55406. setLabelStyle(
  55407. rect.style, hoverStyle, labelModel, labelHoverModel,
  55408. {
  55409. labelFetcher: seriesModel,
  55410. labelDataIndex: node.dataIndex,
  55411. defaultText: node.id,
  55412. isRectText: true
  55413. }
  55414. );
  55415. rect.setStyle('fill', node.getVisual('color'));
  55416. setHoverStyle(rect, hoverStyle);
  55417. group.add(rect);
  55418. nodeData.setItemGraphicEl(node.dataIndex, rect);
  55419. rect.dataType = 'node';
  55420. });
  55421. nodeData.eachItemGraphicEl(function (el, dataIndex) {
  55422. var itemModel = nodeData.getItemModel(dataIndex);
  55423. if (itemModel.get('draggable')) {
  55424. el.drift = function (dx, dy) {
  55425. sankeyView._focusAdjacencyDisabled = true;
  55426. this.shape.x += dx;
  55427. this.shape.y += dy;
  55428. this.dirty();
  55429. api.dispatchAction({
  55430. type: 'dragNode',
  55431. seriesId: seriesModel.id,
  55432. dataIndex: nodeData.getRawIndex(dataIndex),
  55433. localX: this.shape.x / width,
  55434. localY: this.shape.y / height
  55435. });
  55436. };
  55437. el.ondragend = function () {
  55438. sankeyView._focusAdjacencyDisabled = false;
  55439. };
  55440. el.draggable = true;
  55441. el.cursor = 'move';
  55442. }
  55443. el.highlight = function () {
  55444. this.trigger('emphasis');
  55445. };
  55446. el.downplay = function () {
  55447. this.trigger('normal');
  55448. };
  55449. el.focusNodeAdjHandler && el.off('mouseover', el.focusNodeAdjHandler);
  55450. el.unfocusNodeAdjHandler && el.off('mouseout', el.unfocusNodeAdjHandler);
  55451. if (itemModel.get('focusNodeAdjacency')) {
  55452. el.on('mouseover', el.focusNodeAdjHandler = function () {
  55453. if (!sankeyView._focusAdjacencyDisabled) {
  55454. sankeyView._clearTimer();
  55455. api.dispatchAction({
  55456. type: 'focusNodeAdjacency',
  55457. seriesId: seriesModel.id,
  55458. dataIndex: el.dataIndex
  55459. });
  55460. }
  55461. });
  55462. el.on('mouseout', el.unfocusNodeAdjHandler = function () {
  55463. if (!sankeyView._focusAdjacencyDisabled) {
  55464. sankeyView._dispatchUnfocus(api);
  55465. }
  55466. });
  55467. }
  55468. });
  55469. edgeData.eachItemGraphicEl(function (el, dataIndex) {
  55470. var edgeModel = edgeData.getItemModel(dataIndex);
  55471. el.focusNodeAdjHandler && el.off('mouseover', el.focusNodeAdjHandler);
  55472. el.unfocusNodeAdjHandler && el.off('mouseout', el.unfocusNodeAdjHandler);
  55473. if (edgeModel.get('focusNodeAdjacency')) {
  55474. el.on('mouseover', el.focusNodeAdjHandler = function () {
  55475. if (!sankeyView._focusAdjacencyDisabled) {
  55476. sankeyView._clearTimer();
  55477. api.dispatchAction({
  55478. type: 'focusNodeAdjacency',
  55479. seriesId: seriesModel.id,
  55480. edgeDataIndex: el.dataIndex
  55481. });
  55482. }
  55483. });
  55484. el.on('mouseout', el.unfocusNodeAdjHandler = function () {
  55485. if (!sankeyView._focusAdjacencyDisabled) {
  55486. sankeyView._dispatchUnfocus(api);
  55487. }
  55488. });
  55489. }
  55490. });
  55491. if (!this._data && seriesModel.get('animation')) {
  55492. group.setClipPath(createGridClipShape$1(group.getBoundingRect(), seriesModel, function () {
  55493. group.removeClipPath();
  55494. }));
  55495. }
  55496. this._data = seriesModel.getData();
  55497. },
  55498. dispose: function () {
  55499. this._clearTimer();
  55500. },
  55501. _dispatchUnfocus: function (api) {
  55502. var self = this;
  55503. this._clearTimer();
  55504. this._unfocusDelayTimer = setTimeout(function () {
  55505. self._unfocusDelayTimer = null;
  55506. api.dispatchAction({
  55507. type: 'unfocusNodeAdjacency',
  55508. seriesId: self._model.id
  55509. });
  55510. }, 500);
  55511. },
  55512. _clearTimer: function () {
  55513. if (this._unfocusDelayTimer) {
  55514. clearTimeout(this._unfocusDelayTimer);
  55515. this._unfocusDelayTimer = null;
  55516. }
  55517. },
  55518. focusNodeAdjacency: function (seriesModel, ecModel, api, payload) {
  55519. var data = seriesModel.getData();
  55520. var graph = data.graph;
  55521. var dataIndex = payload.dataIndex;
  55522. var itemModel = data.getItemModel(dataIndex);
  55523. var edgeDataIndex = payload.edgeDataIndex;
  55524. if (dataIndex == null && edgeDataIndex == null) {
  55525. return;
  55526. }
  55527. var node = graph.getNodeByIndex(dataIndex);
  55528. var edge = graph.getEdgeByIndex(edgeDataIndex);
  55529. graph.eachNode(function (node) {
  55530. fadeOutItem$1(node, nodeOpacityPath$1, 0.1);
  55531. });
  55532. graph.eachEdge(function (edge) {
  55533. fadeOutItem$1(edge, lineOpacityPath$1, 0.1);
  55534. });
  55535. if (node) {
  55536. fadeInItem$1(node, hoverNodeOpacityPath);
  55537. var focusNodeAdj = itemModel.get('focusNodeAdjacency');
  55538. if (focusNodeAdj === 'outEdges') {
  55539. each$1(node.outEdges, function (edge) {
  55540. if (edge.dataIndex < 0) {
  55541. return;
  55542. }
  55543. fadeInItem$1(edge, hoverLineOpacityPath);
  55544. fadeInItem$1(edge.node2, hoverNodeOpacityPath);
  55545. });
  55546. }
  55547. else if (focusNodeAdj === 'inEdges') {
  55548. each$1(node.inEdges, function (edge) {
  55549. if (edge.dataIndex < 0) {
  55550. return;
  55551. }
  55552. fadeInItem$1(edge, hoverLineOpacityPath);
  55553. fadeInItem$1(edge.node1, hoverNodeOpacityPath);
  55554. });
  55555. }
  55556. else if (focusNodeAdj === 'allEdges') {
  55557. each$1(node.edges, function (edge) {
  55558. if (edge.dataIndex < 0) {
  55559. return;
  55560. }
  55561. fadeInItem$1(edge, hoverLineOpacityPath);
  55562. (edge.node1 !== node) && fadeInItem$1(edge.node1, hoverNodeOpacityPath);
  55563. (edge.node2 !== node) && fadeInItem$1(edge.node2, hoverNodeOpacityPath);
  55564. });
  55565. }
  55566. }
  55567. if (edge) {
  55568. fadeInItem$1(edge, hoverLineOpacityPath);
  55569. fadeInItem$1(edge.node1, hoverNodeOpacityPath);
  55570. fadeInItem$1(edge.node2, hoverNodeOpacityPath);
  55571. }
  55572. },
  55573. unfocusNodeAdjacency: function (seriesModel, ecModel, api, payload) {
  55574. var graph = seriesModel.getGraph();
  55575. graph.eachNode(function (node) {
  55576. fadeOutItem$1(node, nodeOpacityPath$1);
  55577. });
  55578. graph.eachEdge(function (edge) {
  55579. fadeOutItem$1(edge, lineOpacityPath$1);
  55580. });
  55581. }
  55582. });
  55583. // Add animation to the view
  55584. function createGridClipShape$1(rect, seriesModel, cb) {
  55585. var rectEl = new Rect({
  55586. shape: {
  55587. x: rect.x - 10,
  55588. y: rect.y - 10,
  55589. width: 0,
  55590. height: rect.height + 20
  55591. }
  55592. });
  55593. initProps(rectEl, {
  55594. shape: {
  55595. width: rect.width + 20
  55596. }
  55597. }, seriesModel, cb);
  55598. return rectEl;
  55599. }
  55600. /*
  55601. * Licensed to the Apache Software Foundation (ASF) under one
  55602. * or more contributor license agreements. See the NOTICE file
  55603. * distributed with this work for additional information
  55604. * regarding copyright ownership. The ASF licenses this file
  55605. * to you under the Apache License, Version 2.0 (the
  55606. * "License"); you may not use this file except in compliance
  55607. * with the License. You may obtain a copy of the License at
  55608. *
  55609. * http://www.apache.org/licenses/LICENSE-2.0
  55610. *
  55611. * Unless required by applicable law or agreed to in writing,
  55612. * software distributed under the License is distributed on an
  55613. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55614. * KIND, either express or implied. See the License for the
  55615. * specific language governing permissions and limitations
  55616. * under the License.
  55617. */
  55618. registerAction({
  55619. type: 'dragNode',
  55620. event: 'dragnode',
  55621. // here can only use 'update' now, other value is not support in echarts.
  55622. update: 'update'
  55623. }, function (payload, ecModel) {
  55624. ecModel.eachComponent({mainType: 'series', subType: 'sankey', query: payload}, function (seriesModel) {
  55625. seriesModel.setNodePosition(payload.dataIndex, [payload.localX, payload.localY]);
  55626. });
  55627. });
  55628. /*
  55629. * Licensed to the Apache Software Foundation (ASF) under one
  55630. * or more contributor license agreements. See the NOTICE file
  55631. * distributed with this work for additional information
  55632. * regarding copyright ownership. The ASF licenses this file
  55633. * to you under the Apache License, Version 2.0 (the
  55634. * "License"); you may not use this file except in compliance
  55635. * with the License. You may obtain a copy of the License at
  55636. *
  55637. * http://www.apache.org/licenses/LICENSE-2.0
  55638. *
  55639. * Unless required by applicable law or agreed to in writing,
  55640. * software distributed under the License is distributed on an
  55641. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55642. * KIND, either express or implied. See the License for the
  55643. * specific language governing permissions and limitations
  55644. * under the License.
  55645. */
  55646. var sankeyLayout = function (ecModel, api, payload) {
  55647. ecModel.eachSeriesByType('sankey', function (seriesModel) {
  55648. var nodeWidth = seriesModel.get('nodeWidth');
  55649. var nodeGap = seriesModel.get('nodeGap');
  55650. var layoutInfo = getViewRect$4(seriesModel, api);
  55651. seriesModel.layoutInfo = layoutInfo;
  55652. var width = layoutInfo.width;
  55653. var height = layoutInfo.height;
  55654. var graph = seriesModel.getGraph();
  55655. var nodes = graph.nodes;
  55656. var edges = graph.edges;
  55657. computeNodeValues(nodes);
  55658. var filteredNodes = filter(nodes, function (node) {
  55659. return node.getLayout().value === 0;
  55660. });
  55661. var iterations = filteredNodes.length !== 0 ? 0 : seriesModel.get('layoutIterations');
  55662. var orient = seriesModel.get('orient');
  55663. var nodeAlign = seriesModel.get('nodeAlign');
  55664. layoutSankey(nodes, edges, nodeWidth, nodeGap, width, height, iterations, orient, nodeAlign);
  55665. });
  55666. };
  55667. /**
  55668. * Get the layout position of the whole view
  55669. *
  55670. * @param {module:echarts/model/Series} seriesModel the model object of sankey series
  55671. * @param {module:echarts/ExtensionAPI} api provide the API list that the developer can call
  55672. * @return {module:zrender/core/BoundingRect} size of rect to draw the sankey view
  55673. */
  55674. function getViewRect$4(seriesModel, api) {
  55675. return getLayoutRect(
  55676. seriesModel.getBoxLayoutParams(), {
  55677. width: api.getWidth(),
  55678. height: api.getHeight()
  55679. }
  55680. );
  55681. }
  55682. function layoutSankey(nodes, edges, nodeWidth, nodeGap, width, height, iterations, orient, nodeAlign) {
  55683. computeNodeBreadths(nodes, edges, nodeWidth, width, height, orient, nodeAlign);
  55684. computeNodeDepths(nodes, edges, height, width, nodeGap, iterations, orient);
  55685. computeEdgeDepths(nodes, orient);
  55686. }
  55687. /**
  55688. * Compute the value of each node by summing the associated edge's value
  55689. *
  55690. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  55691. */
  55692. function computeNodeValues(nodes) {
  55693. each$1(nodes, function (node) {
  55694. var value1 = sum(node.outEdges, getEdgeValue);
  55695. var value2 = sum(node.inEdges, getEdgeValue);
  55696. var nodeRawValue = node.getValue() || 0;
  55697. var value = Math.max(value1, value2, nodeRawValue);
  55698. node.setLayout({value: value}, true);
  55699. });
  55700. }
  55701. /**
  55702. * Compute the x-position for each node.
  55703. *
  55704. * Here we use Kahn algorithm to detect cycle when we traverse
  55705. * the node to computer the initial x position.
  55706. *
  55707. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  55708. * @param {number} nodeWidth the dx of the node
  55709. * @param {number} width the whole width of the area to draw the view
  55710. */
  55711. function computeNodeBreadths(nodes, edges, nodeWidth, width, height, orient, nodeAlign) {
  55712. // Used to mark whether the edge is deleted. if it is deleted,
  55713. // the value is 0, otherwise it is 1.
  55714. var remainEdges = [];
  55715. // Storage each node's indegree.
  55716. var indegreeArr = [];
  55717. //Used to storage the node with indegree is equal to 0.
  55718. var zeroIndegrees = [];
  55719. var nextTargetNode = [];
  55720. var x = 0;
  55721. var kx = 0;
  55722. for (var i = 0; i < edges.length; i++) {
  55723. remainEdges[i] = 1;
  55724. }
  55725. for (i = 0; i < nodes.length; i++) {
  55726. indegreeArr[i] = nodes[i].inEdges.length;
  55727. if (indegreeArr[i] === 0) {
  55728. zeroIndegrees.push(nodes[i]);
  55729. }
  55730. }
  55731. var maxNodeDepth = -1;
  55732. // Traversing nodes using topological sorting to calculate the
  55733. // horizontal(if orient === 'horizontal') or vertical(if orient === 'vertical')
  55734. // position of the nodes.
  55735. while (zeroIndegrees.length) {
  55736. for (var idx = 0; idx < zeroIndegrees.length; idx++) {
  55737. var node = zeroIndegrees[idx];
  55738. var item = node.hostGraph.data.getRawDataItem(node.dataIndex);
  55739. var isItemDepth = item.depth != null && item.depth >= 0;
  55740. if (isItemDepth && item.depth > maxNodeDepth) {
  55741. maxNodeDepth = item.depth;
  55742. }
  55743. node.setLayout({depth: isItemDepth ? item.depth : x}, true);
  55744. orient === 'vertical'
  55745. ? node.setLayout({dy: nodeWidth}, true)
  55746. : node.setLayout({dx: nodeWidth}, true);
  55747. for (var edgeIdx = 0; edgeIdx < node.outEdges.length; edgeIdx++) {
  55748. var edge = node.outEdges[edgeIdx];
  55749. var indexEdge = edges.indexOf(edge);
  55750. remainEdges[indexEdge] = 0;
  55751. var targetNode = edge.node2;
  55752. var nodeIndex = nodes.indexOf(targetNode);
  55753. if (--indegreeArr[nodeIndex] === 0 && nextTargetNode.indexOf(targetNode) < 0) {
  55754. nextTargetNode.push(targetNode);
  55755. }
  55756. }
  55757. }
  55758. ++x;
  55759. zeroIndegrees = nextTargetNode;
  55760. nextTargetNode = [];
  55761. }
  55762. for (i = 0; i < remainEdges.length; i++) {
  55763. if (remainEdges[i] === 1) {
  55764. throw new Error('Sankey is a DAG, the original data has cycle!');
  55765. }
  55766. }
  55767. var maxDepth = maxNodeDepth > x - 1 ? maxNodeDepth : x - 1;
  55768. if (nodeAlign && nodeAlign !== 'left') {
  55769. adjustNodeWithNodeAlign(nodes, nodeAlign, orient, maxDepth);
  55770. }
  55771. var kx = orient === 'vertical'
  55772. ? (height - nodeWidth) / maxDepth
  55773. : (width - nodeWidth) / maxDepth;
  55774. scaleNodeBreadths(nodes, kx, orient);
  55775. }
  55776. function isNodeDepth(node) {
  55777. var item = node.hostGraph.data.getRawDataItem(node.dataIndex);
  55778. return item.depth != null && item.depth >= 0;
  55779. }
  55780. function adjustNodeWithNodeAlign(nodes, nodeAlign, orient, maxDepth) {
  55781. if (nodeAlign === 'right') {
  55782. var nextSourceNode = [];
  55783. var remainNodes = nodes;
  55784. var nodeHeight = 0;
  55785. while (remainNodes.length) {
  55786. for (var i = 0; i < remainNodes.length; i++) {
  55787. var node = remainNodes[i];
  55788. node.setLayout({skNodeHeight: nodeHeight}, true);
  55789. for (var j = 0; j < node.inEdges.length; j++) {
  55790. var edge = node.inEdges[j];
  55791. if (nextSourceNode.indexOf(edge.node1) < 0) {
  55792. nextSourceNode.push(edge.node1);
  55793. }
  55794. }
  55795. }
  55796. remainNodes = nextSourceNode;
  55797. nextSourceNode = [];
  55798. ++nodeHeight;
  55799. }
  55800. each$1(nodes, function (node) {
  55801. if (!isNodeDepth(node)) {
  55802. node.setLayout({depth: Math.max(0, maxDepth - node.getLayout().skNodeHeight)}, true);
  55803. }
  55804. });
  55805. }
  55806. else if (nodeAlign === 'justify') {
  55807. moveSinksRight(nodes, maxDepth);
  55808. }
  55809. }
  55810. /**
  55811. * All the node without outEgdes are assigned maximum x-position and
  55812. * be aligned in the last column.
  55813. *
  55814. * @param {module:echarts/data/Graph~Node} nodes. node of sankey view.
  55815. * @param {number} maxDepth. use to assign to node without outEdges as x-position.
  55816. */
  55817. function moveSinksRight(nodes, maxDepth) {
  55818. each$1(nodes, function (node) {
  55819. if (!isNodeDepth(node) && !node.outEdges.length) {
  55820. node.setLayout({depth: maxDepth}, true);
  55821. }
  55822. });
  55823. }
  55824. /**
  55825. * Scale node x-position to the width
  55826. *
  55827. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  55828. * @param {number} kx multiple used to scale nodes
  55829. */
  55830. function scaleNodeBreadths(nodes, kx, orient) {
  55831. each$1(nodes, function (node) {
  55832. var nodeDepth = node.getLayout().depth * kx;
  55833. orient === 'vertical'
  55834. ? node.setLayout({y: nodeDepth}, true)
  55835. : node.setLayout({x: nodeDepth}, true);
  55836. });
  55837. }
  55838. /**
  55839. * Using Gauss-Seidel iterations method to compute the node depth(y-position)
  55840. *
  55841. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  55842. * @param {module:echarts/data/Graph~Edge} edges edge of sankey view
  55843. * @param {number} height the whole height of the area to draw the view
  55844. * @param {number} nodeGap the vertical distance between two nodes
  55845. * in the same column.
  55846. * @param {number} iterations the number of iterations for the algorithm
  55847. */
  55848. function computeNodeDepths(nodes, edges, height, width, nodeGap, iterations, orient) {
  55849. var nodesByBreadth = prepareNodesByBreadth(nodes, orient);
  55850. initializeNodeDepth(nodesByBreadth, edges, height, width, nodeGap, orient);
  55851. resolveCollisions(nodesByBreadth, nodeGap, height, width, orient);
  55852. for (var alpha = 1; iterations > 0; iterations--) {
  55853. // 0.99 is a experience parameter, ensure that each iterations of
  55854. // changes as small as possible.
  55855. alpha *= 0.99;
  55856. relaxRightToLeft(nodesByBreadth, alpha, orient);
  55857. resolveCollisions(nodesByBreadth, nodeGap, height, width, orient);
  55858. relaxLeftToRight(nodesByBreadth, alpha, orient);
  55859. resolveCollisions(nodesByBreadth, nodeGap, height, width, orient);
  55860. }
  55861. }
  55862. function prepareNodesByBreadth(nodes, orient) {
  55863. var nodesByBreadth = [];
  55864. var keyAttr = orient === 'vertical' ? 'y' : 'x';
  55865. var groupResult = groupData(nodes, function (node) {
  55866. return node.getLayout()[keyAttr];
  55867. });
  55868. groupResult.keys.sort(function (a, b) {
  55869. return a - b;
  55870. });
  55871. each$1(groupResult.keys, function (key) {
  55872. nodesByBreadth.push(groupResult.buckets.get(key));
  55873. });
  55874. return nodesByBreadth;
  55875. }
  55876. /**
  55877. * Compute the original y-position for each node
  55878. *
  55879. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  55880. * @param {Array.<Array.<module:echarts/data/Graph~Node>>} nodesByBreadth
  55881. * group by the array of all sankey nodes based on the nodes x-position.
  55882. * @param {module:echarts/data/Graph~Edge} edges edge of sankey view
  55883. * @param {number} height the whole height of the area to draw the view
  55884. * @param {number} nodeGap the vertical distance between two nodes
  55885. */
  55886. function initializeNodeDepth(nodesByBreadth, edges, height, width, nodeGap, orient) {
  55887. var minKy = Infinity;
  55888. each$1(nodesByBreadth, function (nodes) {
  55889. var n = nodes.length;
  55890. var sum = 0;
  55891. each$1(nodes, function (node) {
  55892. sum += node.getLayout().value;
  55893. });
  55894. var ky = orient === 'vertical'
  55895. ? (width - (n - 1) * nodeGap) / sum
  55896. : (height - (n - 1) * nodeGap) / sum;
  55897. if (ky < minKy) {
  55898. minKy = ky;
  55899. }
  55900. });
  55901. each$1(nodesByBreadth, function (nodes) {
  55902. each$1(nodes, function (node, i) {
  55903. var nodeDy = node.getLayout().value * minKy;
  55904. if (orient === 'vertical') {
  55905. node.setLayout({x: i}, true);
  55906. node.setLayout({dx: nodeDy}, true);
  55907. }
  55908. else {
  55909. node.setLayout({y: i}, true);
  55910. node.setLayout({dy: nodeDy}, true);
  55911. }
  55912. });
  55913. });
  55914. each$1(edges, function (edge) {
  55915. var edgeDy = +edge.getValue() * minKy;
  55916. edge.setLayout({dy: edgeDy}, true);
  55917. });
  55918. }
  55919. /**
  55920. * Resolve the collision of initialized depth (y-position)
  55921. *
  55922. * @param {Array.<Array.<module:echarts/data/Graph~Node>>} nodesByBreadth
  55923. * group by the array of all sankey nodes based on the nodes x-position.
  55924. * @param {number} nodeGap the vertical distance between two nodes
  55925. * @param {number} height the whole height of the area to draw the view
  55926. */
  55927. function resolveCollisions(nodesByBreadth, nodeGap, height, width, orient) {
  55928. var keyAttr = orient === 'vertical' ? 'x' : 'y';
  55929. each$1(nodesByBreadth, function (nodes) {
  55930. nodes.sort(function (a, b) {
  55931. return a.getLayout()[keyAttr] - b.getLayout()[keyAttr];
  55932. });
  55933. var nodeX;
  55934. var node;
  55935. var dy;
  55936. var y0 = 0;
  55937. var n = nodes.length;
  55938. var nodeDyAttr = orient === 'vertical' ? 'dx' : 'dy';
  55939. for (var i = 0; i < n; i++) {
  55940. node = nodes[i];
  55941. dy = y0 - node.getLayout()[keyAttr];
  55942. if (dy > 0) {
  55943. nodeX = node.getLayout()[keyAttr] + dy;
  55944. orient === 'vertical'
  55945. ? node.setLayout({x: nodeX}, true)
  55946. : node.setLayout({y: nodeX}, true);
  55947. }
  55948. y0 = node.getLayout()[keyAttr] + node.getLayout()[nodeDyAttr] + nodeGap;
  55949. }
  55950. var viewWidth = orient === 'vertical' ? width : height;
  55951. // If the bottommost node goes outside the bounds, push it back up
  55952. dy = y0 - nodeGap - viewWidth;
  55953. if (dy > 0) {
  55954. nodeX = node.getLayout()[keyAttr] - dy;
  55955. orient === 'vertical'
  55956. ? node.setLayout({x: nodeX}, true)
  55957. : node.setLayout({y: nodeX}, true);
  55958. y0 = nodeX;
  55959. for (i = n - 2; i >= 0; --i) {
  55960. node = nodes[i];
  55961. dy = node.getLayout()[keyAttr] + node.getLayout()[nodeDyAttr] + nodeGap - y0;
  55962. if (dy > 0) {
  55963. nodeX = node.getLayout()[keyAttr] - dy;
  55964. orient === 'vertical'
  55965. ? node.setLayout({x: nodeX}, true)
  55966. : node.setLayout({y: nodeX}, true);
  55967. }
  55968. y0 = node.getLayout()[keyAttr];
  55969. }
  55970. }
  55971. });
  55972. }
  55973. /**
  55974. * Change the y-position of the nodes, except most the right side nodes
  55975. *
  55976. * @param {Array.<Array.<module:echarts/data/Graph~Node>>} nodesByBreadth
  55977. * group by the array of all sankey nodes based on the node x-position.
  55978. * @param {number} alpha parameter used to adjust the nodes y-position
  55979. */
  55980. function relaxRightToLeft(nodesByBreadth, alpha, orient) {
  55981. each$1(nodesByBreadth.slice().reverse(), function (nodes) {
  55982. each$1(nodes, function (node) {
  55983. if (node.outEdges.length) {
  55984. var y = sum(node.outEdges, weightedTarget, orient)
  55985. / sum(node.outEdges, getEdgeValue, orient);
  55986. if (isNaN(y)) {
  55987. var len = node.outEdges.length;
  55988. y = len ? sum(node.outEdges, centerTarget, orient) / len : 0;
  55989. }
  55990. if (orient === 'vertical') {
  55991. var nodeX = node.getLayout().x + (y - center$1(node, orient)) * alpha;
  55992. node.setLayout({x: nodeX}, true);
  55993. }
  55994. else {
  55995. var nodeY = node.getLayout().y + (y - center$1(node, orient)) * alpha;
  55996. node.setLayout({y: nodeY}, true);
  55997. }
  55998. }
  55999. });
  56000. });
  56001. }
  56002. function weightedTarget(edge, orient) {
  56003. return center$1(edge.node2, orient) * edge.getValue();
  56004. }
  56005. function centerTarget(edge, orient) {
  56006. return center$1(edge.node2, orient);
  56007. }
  56008. function weightedSource(edge, orient) {
  56009. return center$1(edge.node1, orient) * edge.getValue();
  56010. }
  56011. function centerSource(edge, orient) {
  56012. return center$1(edge.node1, orient);
  56013. }
  56014. function center$1(node, orient) {
  56015. return orient === 'vertical'
  56016. ? node.getLayout().x + node.getLayout().dx / 2
  56017. : node.getLayout().y + node.getLayout().dy / 2;
  56018. }
  56019. function getEdgeValue(edge) {
  56020. return edge.getValue();
  56021. }
  56022. function sum(array, cb, orient) {
  56023. var sum = 0;
  56024. var len = array.length;
  56025. var i = -1;
  56026. while (++i < len) {
  56027. var value = +cb.call(array, array[i], orient);
  56028. if (!isNaN(value)) {
  56029. sum += value;
  56030. }
  56031. }
  56032. return sum;
  56033. }
  56034. /**
  56035. * Change the y-position of the nodes, except most the left side nodes
  56036. *
  56037. * @param {Array.<Array.<module:echarts/data/Graph~Node>>} nodesByBreadth
  56038. * group by the array of all sankey nodes based on the node x-position.
  56039. * @param {number} alpha parameter used to adjust the nodes y-position
  56040. */
  56041. function relaxLeftToRight(nodesByBreadth, alpha, orient) {
  56042. each$1(nodesByBreadth, function (nodes) {
  56043. each$1(nodes, function (node) {
  56044. if (node.inEdges.length) {
  56045. var y = sum(node.inEdges, weightedSource, orient)
  56046. / sum(node.inEdges, getEdgeValue, orient);
  56047. if (isNaN(y)) {
  56048. var len = node.inEdges.length;
  56049. y = len ? sum(node.inEdges, centerSource, orient) / len : 0;
  56050. }
  56051. if (orient === 'vertical') {
  56052. var nodeX = node.getLayout().x + (y - center$1(node, orient)) * alpha;
  56053. node.setLayout({x: nodeX}, true);
  56054. }
  56055. else {
  56056. var nodeY = node.getLayout().y + (y - center$1(node, orient)) * alpha;
  56057. node.setLayout({y: nodeY}, true);
  56058. }
  56059. }
  56060. });
  56061. });
  56062. }
  56063. /**
  56064. * Compute the depth(y-position) of each edge
  56065. *
  56066. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  56067. */
  56068. function computeEdgeDepths(nodes, orient) {
  56069. var keyAttr = orient === 'vertical' ? 'x' : 'y';
  56070. each$1(nodes, function (node) {
  56071. node.outEdges.sort(function (a, b) {
  56072. return a.node2.getLayout()[keyAttr] - b.node2.getLayout()[keyAttr];
  56073. });
  56074. node.inEdges.sort(function (a, b) {
  56075. return a.node1.getLayout()[keyAttr] - b.node1.getLayout()[keyAttr];
  56076. });
  56077. });
  56078. each$1(nodes, function (node) {
  56079. var sy = 0;
  56080. var ty = 0;
  56081. each$1(node.outEdges, function (edge) {
  56082. edge.setLayout({sy: sy}, true);
  56083. sy += edge.getLayout().dy;
  56084. });
  56085. each$1(node.inEdges, function (edge) {
  56086. edge.setLayout({ty: ty}, true);
  56087. ty += edge.getLayout().dy;
  56088. });
  56089. });
  56090. }
  56091. /*
  56092. * Licensed to the Apache Software Foundation (ASF) under one
  56093. * or more contributor license agreements. See the NOTICE file
  56094. * distributed with this work for additional information
  56095. * regarding copyright ownership. The ASF licenses this file
  56096. * to you under the Apache License, Version 2.0 (the
  56097. * "License"); you may not use this file except in compliance
  56098. * with the License. You may obtain a copy of the License at
  56099. *
  56100. * http://www.apache.org/licenses/LICENSE-2.0
  56101. *
  56102. * Unless required by applicable law or agreed to in writing,
  56103. * software distributed under the License is distributed on an
  56104. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56105. * KIND, either express or implied. See the License for the
  56106. * specific language governing permissions and limitations
  56107. * under the License.
  56108. */
  56109. var sankeyVisual = function (ecModel, payload) {
  56110. ecModel.eachSeriesByType('sankey', function (seriesModel) {
  56111. var graph = seriesModel.getGraph();
  56112. var nodes = graph.nodes;
  56113. if (nodes.length) {
  56114. var minValue = Infinity;
  56115. var maxValue = -Infinity;
  56116. each$1(nodes, function (node) {
  56117. var nodeValue = node.getLayout().value;
  56118. if (nodeValue < minValue) {
  56119. minValue = nodeValue;
  56120. }
  56121. if (nodeValue > maxValue) {
  56122. maxValue = nodeValue;
  56123. }
  56124. });
  56125. each$1(nodes, function (node) {
  56126. var mapping = new VisualMapping({
  56127. type: 'color',
  56128. mappingMethod: 'linear',
  56129. dataExtent: [minValue, maxValue],
  56130. visual: seriesModel.get('color')
  56131. });
  56132. var mapValueToColor = mapping.mapValueToVisual(node.getLayout().value);
  56133. var customColor = node.getModel().get('itemStyle.color');
  56134. customColor != null
  56135. ? node.setVisual('color', customColor)
  56136. : node.setVisual('color', mapValueToColor);
  56137. });
  56138. }
  56139. });
  56140. };
  56141. /*
  56142. * Licensed to the Apache Software Foundation (ASF) under one
  56143. * or more contributor license agreements. See the NOTICE file
  56144. * distributed with this work for additional information
  56145. * regarding copyright ownership. The ASF licenses this file
  56146. * to you under the Apache License, Version 2.0 (the
  56147. * "License"); you may not use this file except in compliance
  56148. * with the License. You may obtain a copy of the License at
  56149. *
  56150. * http://www.apache.org/licenses/LICENSE-2.0
  56151. *
  56152. * Unless required by applicable law or agreed to in writing,
  56153. * software distributed under the License is distributed on an
  56154. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56155. * KIND, either express or implied. See the License for the
  56156. * specific language governing permissions and limitations
  56157. * under the License.
  56158. */
  56159. registerLayout(sankeyLayout);
  56160. registerVisual(sankeyVisual);
  56161. /*
  56162. * Licensed to the Apache Software Foundation (ASF) under one
  56163. * or more contributor license agreements. See the NOTICE file
  56164. * distributed with this work for additional information
  56165. * regarding copyright ownership. The ASF licenses this file
  56166. * to you under the Apache License, Version 2.0 (the
  56167. * "License"); you may not use this file except in compliance
  56168. * with the License. You may obtain a copy of the License at
  56169. *
  56170. * http://www.apache.org/licenses/LICENSE-2.0
  56171. *
  56172. * Unless required by applicable law or agreed to in writing,
  56173. * software distributed under the License is distributed on an
  56174. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56175. * KIND, either express or implied. See the License for the
  56176. * specific language governing permissions and limitations
  56177. * under the License.
  56178. */
  56179. var seriesModelMixin = {
  56180. /**
  56181. * @private
  56182. * @type {string}
  56183. */
  56184. _baseAxisDim: null,
  56185. /**
  56186. * @override
  56187. */
  56188. getInitialData: function (option, ecModel) {
  56189. // When both types of xAxis and yAxis are 'value', layout is
  56190. // needed to be specified by user. Otherwise, layout can be
  56191. // judged by which axis is category.
  56192. var ordinalMeta;
  56193. var xAxisModel = ecModel.getComponent('xAxis', this.get('xAxisIndex'));
  56194. var yAxisModel = ecModel.getComponent('yAxis', this.get('yAxisIndex'));
  56195. var xAxisType = xAxisModel.get('type');
  56196. var yAxisType = yAxisModel.get('type');
  56197. var addOrdinal;
  56198. // FIXME
  56199. // Consider time axis.
  56200. if (xAxisType === 'category') {
  56201. option.layout = 'horizontal';
  56202. ordinalMeta = xAxisModel.getOrdinalMeta();
  56203. addOrdinal = true;
  56204. }
  56205. else if (yAxisType === 'category') {
  56206. option.layout = 'vertical';
  56207. ordinalMeta = yAxisModel.getOrdinalMeta();
  56208. addOrdinal = true;
  56209. }
  56210. else {
  56211. option.layout = option.layout || 'horizontal';
  56212. }
  56213. var coordDims = ['x', 'y'];
  56214. var baseAxisDimIndex = option.layout === 'horizontal' ? 0 : 1;
  56215. var baseAxisDim = this._baseAxisDim = coordDims[baseAxisDimIndex];
  56216. var otherAxisDim = coordDims[1 - baseAxisDimIndex];
  56217. var axisModels = [xAxisModel, yAxisModel];
  56218. var baseAxisType = axisModels[baseAxisDimIndex].get('type');
  56219. var otherAxisType = axisModels[1 - baseAxisDimIndex].get('type');
  56220. var data = option.data;
  56221. // ??? FIXME make a stage to perform data transfrom.
  56222. // MUST create a new data, consider setOption({}) again.
  56223. if (data && addOrdinal) {
  56224. var newOptionData = [];
  56225. each$1(data, function (item, index) {
  56226. var newItem;
  56227. if (item.value && isArray(item.value)) {
  56228. newItem = item.value.slice();
  56229. item.value.unshift(index);
  56230. }
  56231. else if (isArray(item)) {
  56232. newItem = item.slice();
  56233. item.unshift(index);
  56234. }
  56235. else {
  56236. newItem = item;
  56237. }
  56238. newOptionData.push(newItem);
  56239. });
  56240. option.data = newOptionData;
  56241. }
  56242. var defaultValueDimensions = this.defaultValueDimensions;
  56243. var coordDimensions = [{
  56244. name: baseAxisDim,
  56245. type: getDimensionTypeByAxis(baseAxisType),
  56246. ordinalMeta: ordinalMeta,
  56247. otherDims: {
  56248. tooltip: false,
  56249. itemName: 0
  56250. },
  56251. dimsDef: ['base']
  56252. }, {
  56253. name: otherAxisDim,
  56254. type: getDimensionTypeByAxis(otherAxisType),
  56255. dimsDef: defaultValueDimensions.slice()
  56256. }];
  56257. return createListSimply(
  56258. this,
  56259. {
  56260. coordDimensions: coordDimensions,
  56261. dimensionsCount: defaultValueDimensions.length + 1,
  56262. encodeDefaulter: curry(
  56263. makeSeriesEncodeForAxisCoordSys, coordDimensions, this
  56264. )
  56265. }
  56266. );
  56267. },
  56268. /**
  56269. * If horizontal, base axis is x, otherwise y.
  56270. * @override
  56271. */
  56272. getBaseAxis: function () {
  56273. var dim = this._baseAxisDim;
  56274. return this.ecModel.getComponent(dim + 'Axis', this.get(dim + 'AxisIndex')).axis;
  56275. }
  56276. };
  56277. /*
  56278. * Licensed to the Apache Software Foundation (ASF) under one
  56279. * or more contributor license agreements. See the NOTICE file
  56280. * distributed with this work for additional information
  56281. * regarding copyright ownership. The ASF licenses this file
  56282. * to you under the Apache License, Version 2.0 (the
  56283. * "License"); you may not use this file except in compliance
  56284. * with the License. You may obtain a copy of the License at
  56285. *
  56286. * http://www.apache.org/licenses/LICENSE-2.0
  56287. *
  56288. * Unless required by applicable law or agreed to in writing,
  56289. * software distributed under the License is distributed on an
  56290. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56291. * KIND, either express or implied. See the License for the
  56292. * specific language governing permissions and limitations
  56293. * under the License.
  56294. */
  56295. var BoxplotSeries = SeriesModel.extend({
  56296. type: 'series.boxplot',
  56297. dependencies: ['xAxis', 'yAxis', 'grid'],
  56298. // TODO
  56299. // box width represents group size, so dimension should have 'size'.
  56300. /**
  56301. * @see <https://en.wikipedia.org/wiki/Box_plot>
  56302. * The meanings of 'min' and 'max' depend on user,
  56303. * and echarts do not need to know it.
  56304. * @readOnly
  56305. */
  56306. defaultValueDimensions: [
  56307. {name: 'min', defaultTooltip: true},
  56308. {name: 'Q1', defaultTooltip: true},
  56309. {name: 'median', defaultTooltip: true},
  56310. {name: 'Q3', defaultTooltip: true},
  56311. {name: 'max', defaultTooltip: true}
  56312. ],
  56313. /**
  56314. * @type {Array.<string>}
  56315. * @readOnly
  56316. */
  56317. dimensions: null,
  56318. /**
  56319. * @override
  56320. */
  56321. defaultOption: {
  56322. zlevel: 0, // 一级层叠
  56323. z: 2, // 二级层叠
  56324. coordinateSystem: 'cartesian2d',
  56325. legendHoverLink: true,
  56326. hoverAnimation: true,
  56327. // xAxisIndex: 0,
  56328. // yAxisIndex: 0,
  56329. layout: null, // 'horizontal' or 'vertical'
  56330. boxWidth: [7, 50], // [min, max] can be percent of band width.
  56331. itemStyle: {
  56332. color: '#fff',
  56333. borderWidth: 1
  56334. },
  56335. emphasis: {
  56336. itemStyle: {
  56337. borderWidth: 2,
  56338. shadowBlur: 5,
  56339. shadowOffsetX: 2,
  56340. shadowOffsetY: 2,
  56341. shadowColor: 'rgba(0,0,0,0.4)'
  56342. }
  56343. },
  56344. animationEasing: 'elasticOut',
  56345. animationDuration: 800
  56346. }
  56347. });
  56348. mixin(BoxplotSeries, seriesModelMixin, true);
  56349. /*
  56350. * Licensed to the Apache Software Foundation (ASF) under one
  56351. * or more contributor license agreements. See the NOTICE file
  56352. * distributed with this work for additional information
  56353. * regarding copyright ownership. The ASF licenses this file
  56354. * to you under the Apache License, Version 2.0 (the
  56355. * "License"); you may not use this file except in compliance
  56356. * with the License. You may obtain a copy of the License at
  56357. *
  56358. * http://www.apache.org/licenses/LICENSE-2.0
  56359. *
  56360. * Unless required by applicable law or agreed to in writing,
  56361. * software distributed under the License is distributed on an
  56362. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56363. * KIND, either express or implied. See the License for the
  56364. * specific language governing permissions and limitations
  56365. * under the License.
  56366. */
  56367. // Update common properties
  56368. var NORMAL_ITEM_STYLE_PATH = ['itemStyle'];
  56369. var EMPHASIS_ITEM_STYLE_PATH = ['emphasis', 'itemStyle'];
  56370. var BoxplotView = Chart.extend({
  56371. type: 'boxplot',
  56372. render: function (seriesModel, ecModel, api) {
  56373. var data = seriesModel.getData();
  56374. var group = this.group;
  56375. var oldData = this._data;
  56376. // There is no old data only when first rendering or switching from
  56377. // stream mode to normal mode, where previous elements should be removed.
  56378. if (!this._data) {
  56379. group.removeAll();
  56380. }
  56381. var constDim = seriesModel.get('layout') === 'horizontal' ? 1 : 0;
  56382. data.diff(oldData)
  56383. .add(function (newIdx) {
  56384. if (data.hasValue(newIdx)) {
  56385. var itemLayout = data.getItemLayout(newIdx);
  56386. var symbolEl = createNormalBox(itemLayout, data, newIdx, constDim, true);
  56387. data.setItemGraphicEl(newIdx, symbolEl);
  56388. group.add(symbolEl);
  56389. }
  56390. })
  56391. .update(function (newIdx, oldIdx) {
  56392. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  56393. // Empty data
  56394. if (!data.hasValue(newIdx)) {
  56395. group.remove(symbolEl);
  56396. return;
  56397. }
  56398. var itemLayout = data.getItemLayout(newIdx);
  56399. if (!symbolEl) {
  56400. symbolEl = createNormalBox(itemLayout, data, newIdx, constDim);
  56401. }
  56402. else {
  56403. updateNormalBoxData(itemLayout, symbolEl, data, newIdx);
  56404. }
  56405. group.add(symbolEl);
  56406. data.setItemGraphicEl(newIdx, symbolEl);
  56407. })
  56408. .remove(function (oldIdx) {
  56409. var el = oldData.getItemGraphicEl(oldIdx);
  56410. el && group.remove(el);
  56411. })
  56412. .execute();
  56413. this._data = data;
  56414. },
  56415. remove: function (ecModel) {
  56416. var group = this.group;
  56417. var data = this._data;
  56418. this._data = null;
  56419. data && data.eachItemGraphicEl(function (el) {
  56420. el && group.remove(el);
  56421. });
  56422. },
  56423. dispose: noop
  56424. });
  56425. var BoxPath = Path.extend({
  56426. type: 'boxplotBoxPath',
  56427. shape: {},
  56428. buildPath: function (ctx, shape) {
  56429. var ends = shape.points;
  56430. var i = 0;
  56431. ctx.moveTo(ends[i][0], ends[i][1]);
  56432. i++;
  56433. for (; i < 4; i++) {
  56434. ctx.lineTo(ends[i][0], ends[i][1]);
  56435. }
  56436. ctx.closePath();
  56437. for (; i < ends.length; i++) {
  56438. ctx.moveTo(ends[i][0], ends[i][1]);
  56439. i++;
  56440. ctx.lineTo(ends[i][0], ends[i][1]);
  56441. }
  56442. }
  56443. });
  56444. function createNormalBox(itemLayout, data, dataIndex, constDim, isInit) {
  56445. var ends = itemLayout.ends;
  56446. var el = new BoxPath({
  56447. shape: {
  56448. points: isInit
  56449. ? transInit(ends, constDim, itemLayout)
  56450. : ends
  56451. }
  56452. });
  56453. updateNormalBoxData(itemLayout, el, data, dataIndex, isInit);
  56454. return el;
  56455. }
  56456. function updateNormalBoxData(itemLayout, el, data, dataIndex, isInit) {
  56457. var seriesModel = data.hostModel;
  56458. var updateMethod = graphic[isInit ? 'initProps' : 'updateProps'];
  56459. updateMethod(
  56460. el,
  56461. {shape: {points: itemLayout.ends}},
  56462. seriesModel,
  56463. dataIndex
  56464. );
  56465. var itemModel = data.getItemModel(dataIndex);
  56466. var normalItemStyleModel = itemModel.getModel(NORMAL_ITEM_STYLE_PATH);
  56467. var borderColor = data.getItemVisual(dataIndex, 'color');
  56468. // Exclude borderColor.
  56469. var itemStyle = normalItemStyleModel.getItemStyle(['borderColor']);
  56470. itemStyle.stroke = borderColor;
  56471. itemStyle.strokeNoScale = true;
  56472. el.useStyle(itemStyle);
  56473. el.z2 = 100;
  56474. var hoverStyle = itemModel.getModel(EMPHASIS_ITEM_STYLE_PATH).getItemStyle();
  56475. setHoverStyle(el, hoverStyle);
  56476. }
  56477. function transInit(points, dim, itemLayout) {
  56478. return map(points, function (point) {
  56479. point = point.slice();
  56480. point[dim] = itemLayout.initBaseline;
  56481. return point;
  56482. });
  56483. }
  56484. /*
  56485. * Licensed to the Apache Software Foundation (ASF) under one
  56486. * or more contributor license agreements. See the NOTICE file
  56487. * distributed with this work for additional information
  56488. * regarding copyright ownership. The ASF licenses this file
  56489. * to you under the Apache License, Version 2.0 (the
  56490. * "License"); you may not use this file except in compliance
  56491. * with the License. You may obtain a copy of the License at
  56492. *
  56493. * http://www.apache.org/licenses/LICENSE-2.0
  56494. *
  56495. * Unless required by applicable law or agreed to in writing,
  56496. * software distributed under the License is distributed on an
  56497. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56498. * KIND, either express or implied. See the License for the
  56499. * specific language governing permissions and limitations
  56500. * under the License.
  56501. */
  56502. var borderColorQuery = ['itemStyle', 'borderColor'];
  56503. var boxplotVisual = function (ecModel, api) {
  56504. var globalColors = ecModel.get('color');
  56505. ecModel.eachRawSeriesByType('boxplot', function (seriesModel) {
  56506. var defaulColor = globalColors[seriesModel.seriesIndex % globalColors.length];
  56507. var data = seriesModel.getData();
  56508. data.setVisual({
  56509. legendSymbol: 'roundRect',
  56510. // Use name 'color' but not 'borderColor' for legend usage and
  56511. // visual coding from other component like dataRange.
  56512. color: seriesModel.get(borderColorQuery) || defaulColor
  56513. });
  56514. // Only visible series has each data be visual encoded
  56515. if (!ecModel.isSeriesFiltered(seriesModel)) {
  56516. data.each(function (idx) {
  56517. var itemModel = data.getItemModel(idx);
  56518. data.setItemVisual(
  56519. idx,
  56520. {color: itemModel.get(borderColorQuery, true)}
  56521. );
  56522. });
  56523. }
  56524. });
  56525. };
  56526. /*
  56527. * Licensed to the Apache Software Foundation (ASF) under one
  56528. * or more contributor license agreements. See the NOTICE file
  56529. * distributed with this work for additional information
  56530. * regarding copyright ownership. The ASF licenses this file
  56531. * to you under the Apache License, Version 2.0 (the
  56532. * "License"); you may not use this file except in compliance
  56533. * with the License. You may obtain a copy of the License at
  56534. *
  56535. * http://www.apache.org/licenses/LICENSE-2.0
  56536. *
  56537. * Unless required by applicable law or agreed to in writing,
  56538. * software distributed under the License is distributed on an
  56539. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56540. * KIND, either express or implied. See the License for the
  56541. * specific language governing permissions and limitations
  56542. * under the License.
  56543. */
  56544. var each$13 = each$1;
  56545. var boxplotLayout = function (ecModel) {
  56546. var groupResult = groupSeriesByAxis(ecModel);
  56547. each$13(groupResult, function (groupItem) {
  56548. var seriesModels = groupItem.seriesModels;
  56549. if (!seriesModels.length) {
  56550. return;
  56551. }
  56552. calculateBase(groupItem);
  56553. each$13(seriesModels, function (seriesModel, idx) {
  56554. layoutSingleSeries(
  56555. seriesModel,
  56556. groupItem.boxOffsetList[idx],
  56557. groupItem.boxWidthList[idx]
  56558. );
  56559. });
  56560. });
  56561. };
  56562. /**
  56563. * Group series by axis.
  56564. */
  56565. function groupSeriesByAxis(ecModel) {
  56566. var result = [];
  56567. var axisList = [];
  56568. ecModel.eachSeriesByType('boxplot', function (seriesModel) {
  56569. var baseAxis = seriesModel.getBaseAxis();
  56570. var idx = indexOf(axisList, baseAxis);
  56571. if (idx < 0) {
  56572. idx = axisList.length;
  56573. axisList[idx] = baseAxis;
  56574. result[idx] = {axis: baseAxis, seriesModels: []};
  56575. }
  56576. result[idx].seriesModels.push(seriesModel);
  56577. });
  56578. return result;
  56579. }
  56580. /**
  56581. * Calculate offset and box width for each series.
  56582. */
  56583. function calculateBase(groupItem) {
  56584. var extent;
  56585. var baseAxis = groupItem.axis;
  56586. var seriesModels = groupItem.seriesModels;
  56587. var seriesCount = seriesModels.length;
  56588. var boxWidthList = groupItem.boxWidthList = [];
  56589. var boxOffsetList = groupItem.boxOffsetList = [];
  56590. var boundList = [];
  56591. var bandWidth;
  56592. if (baseAxis.type === 'category') {
  56593. bandWidth = baseAxis.getBandWidth();
  56594. }
  56595. else {
  56596. var maxDataCount = 0;
  56597. each$13(seriesModels, function (seriesModel) {
  56598. maxDataCount = Math.max(maxDataCount, seriesModel.getData().count());
  56599. });
  56600. extent = baseAxis.getExtent(),
  56601. Math.abs(extent[1] - extent[0]) / maxDataCount;
  56602. }
  56603. each$13(seriesModels, function (seriesModel) {
  56604. var boxWidthBound = seriesModel.get('boxWidth');
  56605. if (!isArray(boxWidthBound)) {
  56606. boxWidthBound = [boxWidthBound, boxWidthBound];
  56607. }
  56608. boundList.push([
  56609. parsePercent$1(boxWidthBound[0], bandWidth) || 0,
  56610. parsePercent$1(boxWidthBound[1], bandWidth) || 0
  56611. ]);
  56612. });
  56613. var availableWidth = bandWidth * 0.8 - 2;
  56614. var boxGap = availableWidth / seriesCount * 0.3;
  56615. var boxWidth = (availableWidth - boxGap * (seriesCount - 1)) / seriesCount;
  56616. var base = boxWidth / 2 - availableWidth / 2;
  56617. each$13(seriesModels, function (seriesModel, idx) {
  56618. boxOffsetList.push(base);
  56619. base += boxGap + boxWidth;
  56620. boxWidthList.push(
  56621. Math.min(Math.max(boxWidth, boundList[idx][0]), boundList[idx][1])
  56622. );
  56623. });
  56624. }
  56625. /**
  56626. * Calculate points location for each series.
  56627. */
  56628. function layoutSingleSeries(seriesModel, offset, boxWidth) {
  56629. var coordSys = seriesModel.coordinateSystem;
  56630. var data = seriesModel.getData();
  56631. var halfWidth = boxWidth / 2;
  56632. var cDimIdx = seriesModel.get('layout') === 'horizontal' ? 0 : 1;
  56633. var vDimIdx = 1 - cDimIdx;
  56634. var coordDims = ['x', 'y'];
  56635. var cDim = data.mapDimension(coordDims[cDimIdx]);
  56636. var vDims = data.mapDimension(coordDims[vDimIdx], true);
  56637. if (cDim == null || vDims.length < 5) {
  56638. return;
  56639. }
  56640. for (var dataIndex = 0; dataIndex < data.count(); dataIndex++) {
  56641. var axisDimVal = data.get(cDim, dataIndex);
  56642. var median = getPoint(axisDimVal, vDims[2], dataIndex);
  56643. var end1 = getPoint(axisDimVal, vDims[0], dataIndex);
  56644. var end2 = getPoint(axisDimVal, vDims[1], dataIndex);
  56645. var end4 = getPoint(axisDimVal, vDims[3], dataIndex);
  56646. var end5 = getPoint(axisDimVal, vDims[4], dataIndex);
  56647. var ends = [];
  56648. addBodyEnd(ends, end2, 0);
  56649. addBodyEnd(ends, end4, 1);
  56650. ends.push(end1, end2, end5, end4);
  56651. layEndLine(ends, end1);
  56652. layEndLine(ends, end5);
  56653. layEndLine(ends, median);
  56654. data.setItemLayout(dataIndex, {
  56655. initBaseline: median[vDimIdx],
  56656. ends: ends
  56657. });
  56658. }
  56659. function getPoint(axisDimVal, dimIdx, dataIndex) {
  56660. var val = data.get(dimIdx, dataIndex);
  56661. var p = [];
  56662. p[cDimIdx] = axisDimVal;
  56663. p[vDimIdx] = val;
  56664. var point;
  56665. if (isNaN(axisDimVal) || isNaN(val)) {
  56666. point = [NaN, NaN];
  56667. }
  56668. else {
  56669. point = coordSys.dataToPoint(p);
  56670. point[cDimIdx] += offset;
  56671. }
  56672. return point;
  56673. }
  56674. function addBodyEnd(ends, point, start) {
  56675. var point1 = point.slice();
  56676. var point2 = point.slice();
  56677. point1[cDimIdx] += halfWidth;
  56678. point2[cDimIdx] -= halfWidth;
  56679. start
  56680. ? ends.push(point1, point2)
  56681. : ends.push(point2, point1);
  56682. }
  56683. function layEndLine(ends, endCenter) {
  56684. var from = endCenter.slice();
  56685. var to = endCenter.slice();
  56686. from[cDimIdx] -= halfWidth;
  56687. to[cDimIdx] += halfWidth;
  56688. ends.push(from, to);
  56689. }
  56690. }
  56691. /*
  56692. * Licensed to the Apache Software Foundation (ASF) under one
  56693. * or more contributor license agreements. See the NOTICE file
  56694. * distributed with this work for additional information
  56695. * regarding copyright ownership. The ASF licenses this file
  56696. * to you under the Apache License, Version 2.0 (the
  56697. * "License"); you may not use this file except in compliance
  56698. * with the License. You may obtain a copy of the License at
  56699. *
  56700. * http://www.apache.org/licenses/LICENSE-2.0
  56701. *
  56702. * Unless required by applicable law or agreed to in writing,
  56703. * software distributed under the License is distributed on an
  56704. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56705. * KIND, either express or implied. See the License for the
  56706. * specific language governing permissions and limitations
  56707. * under the License.
  56708. */
  56709. registerVisual(boxplotVisual);
  56710. registerLayout(boxplotLayout);
  56711. /*
  56712. * Licensed to the Apache Software Foundation (ASF) under one
  56713. * or more contributor license agreements. See the NOTICE file
  56714. * distributed with this work for additional information
  56715. * regarding copyright ownership. The ASF licenses this file
  56716. * to you under the Apache License, Version 2.0 (the
  56717. * "License"); you may not use this file except in compliance
  56718. * with the License. You may obtain a copy of the License at
  56719. *
  56720. * http://www.apache.org/licenses/LICENSE-2.0
  56721. *
  56722. * Unless required by applicable law or agreed to in writing,
  56723. * software distributed under the License is distributed on an
  56724. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56725. * KIND, either express or implied. See the License for the
  56726. * specific language governing permissions and limitations
  56727. * under the License.
  56728. */
  56729. var CandlestickSeries = SeriesModel.extend({
  56730. type: 'series.candlestick',
  56731. dependencies: ['xAxis', 'yAxis', 'grid'],
  56732. /**
  56733. * @readOnly
  56734. */
  56735. defaultValueDimensions: [
  56736. {name: 'open', defaultTooltip: true},
  56737. {name: 'close', defaultTooltip: true},
  56738. {name: 'lowest', defaultTooltip: true},
  56739. {name: 'highest', defaultTooltip: true}
  56740. ],
  56741. /**
  56742. * @type {Array.<string>}
  56743. * @readOnly
  56744. */
  56745. dimensions: null,
  56746. /**
  56747. * @override
  56748. */
  56749. defaultOption: {
  56750. zlevel: 0,
  56751. z: 2,
  56752. coordinateSystem: 'cartesian2d',
  56753. legendHoverLink: true,
  56754. hoverAnimation: true,
  56755. // xAxisIndex: 0,
  56756. // yAxisIndex: 0,
  56757. layout: null, // 'horizontal' or 'vertical'
  56758. clip: true,
  56759. itemStyle: {
  56760. color: '#c23531', // 阳线 positive
  56761. color0: '#314656', // 阴线 negative '#c23531', '#314656'
  56762. borderWidth: 1,
  56763. // FIXME
  56764. // ec2中使用的是lineStyle.color 和 lineStyle.color0
  56765. borderColor: '#c23531',
  56766. borderColor0: '#314656'
  56767. },
  56768. emphasis: {
  56769. itemStyle: {
  56770. borderWidth: 2
  56771. }
  56772. },
  56773. barMaxWidth: null,
  56774. barMinWidth: null,
  56775. barWidth: null,
  56776. large: true,
  56777. largeThreshold: 600,
  56778. progressive: 3e3,
  56779. progressiveThreshold: 1e4,
  56780. progressiveChunkMode: 'mod',
  56781. animationUpdate: false,
  56782. animationEasing: 'linear',
  56783. animationDuration: 300
  56784. },
  56785. /**
  56786. * Get dimension for shadow in dataZoom
  56787. * @return {string} dimension name
  56788. */
  56789. getShadowDim: function () {
  56790. return 'open';
  56791. },
  56792. brushSelector: function (dataIndex, data, selectors) {
  56793. var itemLayout = data.getItemLayout(dataIndex);
  56794. return itemLayout && selectors.rect(itemLayout.brushRect);
  56795. }
  56796. });
  56797. mixin(CandlestickSeries, seriesModelMixin, true);
  56798. /*
  56799. * Licensed to the Apache Software Foundation (ASF) under one
  56800. * or more contributor license agreements. See the NOTICE file
  56801. * distributed with this work for additional information
  56802. * regarding copyright ownership. The ASF licenses this file
  56803. * to you under the Apache License, Version 2.0 (the
  56804. * "License"); you may not use this file except in compliance
  56805. * with the License. You may obtain a copy of the License at
  56806. *
  56807. * http://www.apache.org/licenses/LICENSE-2.0
  56808. *
  56809. * Unless required by applicable law or agreed to in writing,
  56810. * software distributed under the License is distributed on an
  56811. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56812. * KIND, either express or implied. See the License for the
  56813. * specific language governing permissions and limitations
  56814. * under the License.
  56815. */
  56816. var NORMAL_ITEM_STYLE_PATH$1 = ['itemStyle'];
  56817. var EMPHASIS_ITEM_STYLE_PATH$1 = ['emphasis', 'itemStyle'];
  56818. var SKIP_PROPS = ['color', 'color0', 'borderColor', 'borderColor0'];
  56819. var CandlestickView = Chart.extend({
  56820. type: 'candlestick',
  56821. render: function (seriesModel, ecModel, api) {
  56822. // If there is clipPath created in large mode. Remove it.
  56823. this.group.removeClipPath();
  56824. this._updateDrawMode(seriesModel);
  56825. this._isLargeDraw
  56826. ? this._renderLarge(seriesModel)
  56827. : this._renderNormal(seriesModel);
  56828. },
  56829. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  56830. this._clear();
  56831. this._updateDrawMode(seriesModel);
  56832. },
  56833. incrementalRender: function (params, seriesModel, ecModel, api) {
  56834. this._isLargeDraw
  56835. ? this._incrementalRenderLarge(params, seriesModel)
  56836. : this._incrementalRenderNormal(params, seriesModel);
  56837. },
  56838. _updateDrawMode: function (seriesModel) {
  56839. var isLargeDraw = seriesModel.pipelineContext.large;
  56840. if (this._isLargeDraw == null || isLargeDraw ^ this._isLargeDraw) {
  56841. this._isLargeDraw = isLargeDraw;
  56842. this._clear();
  56843. }
  56844. },
  56845. _renderNormal: function (seriesModel) {
  56846. var data = seriesModel.getData();
  56847. var oldData = this._data;
  56848. var group = this.group;
  56849. var isSimpleBox = data.getLayout('isSimpleBox');
  56850. var needsClip = seriesModel.get('clip', true);
  56851. var coord = seriesModel.coordinateSystem;
  56852. var clipArea = coord.getArea && coord.getArea();
  56853. // There is no old data only when first rendering or switching from
  56854. // stream mode to normal mode, where previous elements should be removed.
  56855. if (!this._data) {
  56856. group.removeAll();
  56857. }
  56858. data.diff(oldData)
  56859. .add(function (newIdx) {
  56860. if (data.hasValue(newIdx)) {
  56861. var el;
  56862. var itemLayout = data.getItemLayout(newIdx);
  56863. if (needsClip && isNormalBoxClipped(clipArea, itemLayout)) {
  56864. return;
  56865. }
  56866. el = createNormalBox$1(itemLayout, newIdx, true);
  56867. initProps(el, {shape: {points: itemLayout.ends}}, seriesModel, newIdx);
  56868. setBoxCommon(el, data, newIdx, isSimpleBox);
  56869. group.add(el);
  56870. data.setItemGraphicEl(newIdx, el);
  56871. }
  56872. })
  56873. .update(function (newIdx, oldIdx) {
  56874. var el = oldData.getItemGraphicEl(oldIdx);
  56875. // Empty data
  56876. if (!data.hasValue(newIdx)) {
  56877. group.remove(el);
  56878. return;
  56879. }
  56880. var itemLayout = data.getItemLayout(newIdx);
  56881. if (needsClip && isNormalBoxClipped(clipArea, itemLayout)) {
  56882. group.remove(el);
  56883. return;
  56884. }
  56885. if (!el) {
  56886. el = createNormalBox$1(itemLayout, newIdx);
  56887. }
  56888. else {
  56889. updateProps(el, {shape: {points: itemLayout.ends}}, seriesModel, newIdx);
  56890. }
  56891. setBoxCommon(el, data, newIdx, isSimpleBox);
  56892. group.add(el);
  56893. data.setItemGraphicEl(newIdx, el);
  56894. })
  56895. .remove(function (oldIdx) {
  56896. var el = oldData.getItemGraphicEl(oldIdx);
  56897. el && group.remove(el);
  56898. })
  56899. .execute();
  56900. this._data = data;
  56901. },
  56902. _renderLarge: function (seriesModel) {
  56903. this._clear();
  56904. createLarge$1(seriesModel, this.group);
  56905. var clipPath = seriesModel.get('clip', true)
  56906. ? createClipPath(seriesModel.coordinateSystem, false, seriesModel)
  56907. : null;
  56908. if (clipPath) {
  56909. this.group.setClipPath(clipPath);
  56910. }
  56911. else {
  56912. this.group.removeClipPath();
  56913. }
  56914. },
  56915. _incrementalRenderNormal: function (params, seriesModel) {
  56916. var data = seriesModel.getData();
  56917. var isSimpleBox = data.getLayout('isSimpleBox');
  56918. var dataIndex;
  56919. while ((dataIndex = params.next()) != null) {
  56920. var el;
  56921. var itemLayout = data.getItemLayout(dataIndex);
  56922. el = createNormalBox$1(itemLayout, dataIndex);
  56923. setBoxCommon(el, data, dataIndex, isSimpleBox);
  56924. el.incremental = true;
  56925. this.group.add(el);
  56926. }
  56927. },
  56928. _incrementalRenderLarge: function (params, seriesModel) {
  56929. createLarge$1(seriesModel, this.group, true);
  56930. },
  56931. remove: function (ecModel) {
  56932. this._clear();
  56933. },
  56934. _clear: function () {
  56935. this.group.removeAll();
  56936. this._data = null;
  56937. },
  56938. dispose: noop
  56939. });
  56940. var NormalBoxPath = Path.extend({
  56941. type: 'normalCandlestickBox',
  56942. shape: {},
  56943. buildPath: function (ctx, shape) {
  56944. var ends = shape.points;
  56945. if (this.__simpleBox) {
  56946. ctx.moveTo(ends[4][0], ends[4][1]);
  56947. ctx.lineTo(ends[6][0], ends[6][1]);
  56948. }
  56949. else {
  56950. ctx.moveTo(ends[0][0], ends[0][1]);
  56951. ctx.lineTo(ends[1][0], ends[1][1]);
  56952. ctx.lineTo(ends[2][0], ends[2][1]);
  56953. ctx.lineTo(ends[3][0], ends[3][1]);
  56954. ctx.closePath();
  56955. ctx.moveTo(ends[4][0], ends[4][1]);
  56956. ctx.lineTo(ends[5][0], ends[5][1]);
  56957. ctx.moveTo(ends[6][0], ends[6][1]);
  56958. ctx.lineTo(ends[7][0], ends[7][1]);
  56959. }
  56960. }
  56961. });
  56962. function createNormalBox$1(itemLayout, dataIndex, isInit) {
  56963. var ends = itemLayout.ends;
  56964. return new NormalBoxPath({
  56965. shape: {
  56966. points: isInit
  56967. ? transInit$1(ends, itemLayout)
  56968. : ends
  56969. },
  56970. z2: 100
  56971. });
  56972. }
  56973. function isNormalBoxClipped(clipArea, itemLayout) {
  56974. var clipped = true;
  56975. for (var i = 0; i < itemLayout.ends.length; i++) {
  56976. // If any point are in the region.
  56977. if (clipArea.contain(itemLayout.ends[i][0], itemLayout.ends[i][1])) {
  56978. clipped = false;
  56979. break;
  56980. }
  56981. }
  56982. return clipped;
  56983. }
  56984. function setBoxCommon(el, data, dataIndex, isSimpleBox) {
  56985. var itemModel = data.getItemModel(dataIndex);
  56986. var normalItemStyleModel = itemModel.getModel(NORMAL_ITEM_STYLE_PATH$1);
  56987. var color = data.getItemVisual(dataIndex, 'color');
  56988. var borderColor = data.getItemVisual(dataIndex, 'borderColor') || color;
  56989. // Color must be excluded.
  56990. // Because symbol provide setColor individually to set fill and stroke
  56991. var itemStyle = normalItemStyleModel.getItemStyle(SKIP_PROPS);
  56992. el.useStyle(itemStyle);
  56993. el.style.strokeNoScale = true;
  56994. el.style.fill = color;
  56995. el.style.stroke = borderColor;
  56996. el.__simpleBox = isSimpleBox;
  56997. var hoverStyle = itemModel.getModel(EMPHASIS_ITEM_STYLE_PATH$1).getItemStyle();
  56998. setHoverStyle(el, hoverStyle);
  56999. }
  57000. function transInit$1(points, itemLayout) {
  57001. return map(points, function (point) {
  57002. point = point.slice();
  57003. point[1] = itemLayout.initBaseline;
  57004. return point;
  57005. });
  57006. }
  57007. var LargeBoxPath = Path.extend({
  57008. type: 'largeCandlestickBox',
  57009. shape: {},
  57010. buildPath: function (ctx, shape) {
  57011. // Drawing lines is more efficient than drawing
  57012. // a whole line or drawing rects.
  57013. var points = shape.points;
  57014. for (var i = 0; i < points.length;) {
  57015. if (this.__sign === points[i++]) {
  57016. var x = points[i++];
  57017. ctx.moveTo(x, points[i++]);
  57018. ctx.lineTo(x, points[i++]);
  57019. }
  57020. else {
  57021. i += 3;
  57022. }
  57023. }
  57024. }
  57025. });
  57026. function createLarge$1(seriesModel, group, incremental) {
  57027. var data = seriesModel.getData();
  57028. var largePoints = data.getLayout('largePoints');
  57029. var elP = new LargeBoxPath({
  57030. shape: {points: largePoints},
  57031. __sign: 1
  57032. });
  57033. group.add(elP);
  57034. var elN = new LargeBoxPath({
  57035. shape: {points: largePoints},
  57036. __sign: -1
  57037. });
  57038. group.add(elN);
  57039. setLargeStyle$1(1, elP, seriesModel, data);
  57040. setLargeStyle$1(-1, elN, seriesModel, data);
  57041. if (incremental) {
  57042. elP.incremental = true;
  57043. elN.incremental = true;
  57044. }
  57045. }
  57046. function setLargeStyle$1(sign, el, seriesModel, data) {
  57047. var suffix = sign > 0 ? 'P' : 'N';
  57048. var borderColor = data.getVisual('borderColor' + suffix)
  57049. || data.getVisual('color' + suffix);
  57050. // Color must be excluded.
  57051. // Because symbol provide setColor individually to set fill and stroke
  57052. var itemStyle = seriesModel.getModel(NORMAL_ITEM_STYLE_PATH$1).getItemStyle(SKIP_PROPS);
  57053. el.useStyle(itemStyle);
  57054. el.style.fill = null;
  57055. el.style.stroke = borderColor;
  57056. // No different
  57057. // el.style.lineWidth = .5;
  57058. }
  57059. /*
  57060. * Licensed to the Apache Software Foundation (ASF) under one
  57061. * or more contributor license agreements. See the NOTICE file
  57062. * distributed with this work for additional information
  57063. * regarding copyright ownership. The ASF licenses this file
  57064. * to you under the Apache License, Version 2.0 (the
  57065. * "License"); you may not use this file except in compliance
  57066. * with the License. You may obtain a copy of the License at
  57067. *
  57068. * http://www.apache.org/licenses/LICENSE-2.0
  57069. *
  57070. * Unless required by applicable law or agreed to in writing,
  57071. * software distributed under the License is distributed on an
  57072. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57073. * KIND, either express or implied. See the License for the
  57074. * specific language governing permissions and limitations
  57075. * under the License.
  57076. */
  57077. var preprocessor = function (option) {
  57078. if (!option || !isArray(option.series)) {
  57079. return;
  57080. }
  57081. // Translate 'k' to 'candlestick'.
  57082. each$1(option.series, function (seriesItem) {
  57083. if (isObject$1(seriesItem) && seriesItem.type === 'k') {
  57084. seriesItem.type = 'candlestick';
  57085. }
  57086. });
  57087. };
  57088. /*
  57089. * Licensed to the Apache Software Foundation (ASF) under one
  57090. * or more contributor license agreements. See the NOTICE file
  57091. * distributed with this work for additional information
  57092. * regarding copyright ownership. The ASF licenses this file
  57093. * to you under the Apache License, Version 2.0 (the
  57094. * "License"); you may not use this file except in compliance
  57095. * with the License. You may obtain a copy of the License at
  57096. *
  57097. * http://www.apache.org/licenses/LICENSE-2.0
  57098. *
  57099. * Unless required by applicable law or agreed to in writing,
  57100. * software distributed under the License is distributed on an
  57101. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57102. * KIND, either express or implied. See the License for the
  57103. * specific language governing permissions and limitations
  57104. * under the License.
  57105. */
  57106. var positiveBorderColorQuery = ['itemStyle', 'borderColor'];
  57107. var negativeBorderColorQuery = ['itemStyle', 'borderColor0'];
  57108. var positiveColorQuery = ['itemStyle', 'color'];
  57109. var negativeColorQuery = ['itemStyle', 'color0'];
  57110. var candlestickVisual = {
  57111. seriesType: 'candlestick',
  57112. plan: createRenderPlanner(),
  57113. // For legend.
  57114. performRawSeries: true,
  57115. reset: function (seriesModel, ecModel) {
  57116. var data = seriesModel.getData();
  57117. data.setVisual({
  57118. legendSymbol: 'roundRect',
  57119. colorP: getColor(1, seriesModel),
  57120. colorN: getColor(-1, seriesModel),
  57121. borderColorP: getBorderColor(1, seriesModel),
  57122. borderColorN: getBorderColor(-1, seriesModel)
  57123. });
  57124. // Only visible series has each data be visual encoded
  57125. if (ecModel.isSeriesFiltered(seriesModel)) {
  57126. return;
  57127. }
  57128. var isLargeRender = seriesModel.pipelineContext.large;
  57129. return !isLargeRender && {progress: progress};
  57130. function progress(params, data) {
  57131. var dataIndex;
  57132. while ((dataIndex = params.next()) != null) {
  57133. var itemModel = data.getItemModel(dataIndex);
  57134. var sign = data.getItemLayout(dataIndex).sign;
  57135. data.setItemVisual(
  57136. dataIndex,
  57137. {
  57138. color: getColor(sign, itemModel),
  57139. borderColor: getBorderColor(sign, itemModel)
  57140. }
  57141. );
  57142. }
  57143. }
  57144. function getColor(sign, model) {
  57145. return model.get(
  57146. sign > 0 ? positiveColorQuery : negativeColorQuery
  57147. );
  57148. }
  57149. function getBorderColor(sign, model) {
  57150. return model.get(
  57151. sign > 0 ? positiveBorderColorQuery : negativeBorderColorQuery
  57152. );
  57153. }
  57154. }
  57155. };
  57156. /*
  57157. * Licensed to the Apache Software Foundation (ASF) under one
  57158. * or more contributor license agreements. See the NOTICE file
  57159. * distributed with this work for additional information
  57160. * regarding copyright ownership. The ASF licenses this file
  57161. * to you under the Apache License, Version 2.0 (the
  57162. * "License"); you may not use this file except in compliance
  57163. * with the License. You may obtain a copy of the License at
  57164. *
  57165. * http://www.apache.org/licenses/LICENSE-2.0
  57166. *
  57167. * Unless required by applicable law or agreed to in writing,
  57168. * software distributed under the License is distributed on an
  57169. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57170. * KIND, either express or implied. See the License for the
  57171. * specific language governing permissions and limitations
  57172. * under the License.
  57173. */
  57174. /* global Float32Array */
  57175. var LargeArr$1 = typeof Float32Array !== 'undefined' ? Float32Array : Array;
  57176. var candlestickLayout = {
  57177. seriesType: 'candlestick',
  57178. plan: createRenderPlanner(),
  57179. reset: function (seriesModel) {
  57180. var coordSys = seriesModel.coordinateSystem;
  57181. var data = seriesModel.getData();
  57182. var candleWidth = calculateCandleWidth(seriesModel, data);
  57183. var cDimIdx = 0;
  57184. var vDimIdx = 1;
  57185. var coordDims = ['x', 'y'];
  57186. var cDim = data.mapDimension(coordDims[cDimIdx]);
  57187. var vDims = data.mapDimension(coordDims[vDimIdx], true);
  57188. var openDim = vDims[0];
  57189. var closeDim = vDims[1];
  57190. var lowestDim = vDims[2];
  57191. var highestDim = vDims[3];
  57192. data.setLayout({
  57193. candleWidth: candleWidth,
  57194. // The value is experimented visually.
  57195. isSimpleBox: candleWidth <= 1.3
  57196. });
  57197. if (cDim == null || vDims.length < 4) {
  57198. return;
  57199. }
  57200. return {
  57201. progress: seriesModel.pipelineContext.large
  57202. ? largeProgress : normalProgress
  57203. };
  57204. function normalProgress(params, data) {
  57205. var dataIndex;
  57206. while ((dataIndex = params.next()) != null) {
  57207. var axisDimVal = data.get(cDim, dataIndex);
  57208. var openVal = data.get(openDim, dataIndex);
  57209. var closeVal = data.get(closeDim, dataIndex);
  57210. var lowestVal = data.get(lowestDim, dataIndex);
  57211. var highestVal = data.get(highestDim, dataIndex);
  57212. var ocLow = Math.min(openVal, closeVal);
  57213. var ocHigh = Math.max(openVal, closeVal);
  57214. var ocLowPoint = getPoint(ocLow, axisDimVal);
  57215. var ocHighPoint = getPoint(ocHigh, axisDimVal);
  57216. var lowestPoint = getPoint(lowestVal, axisDimVal);
  57217. var highestPoint = getPoint(highestVal, axisDimVal);
  57218. var ends = [];
  57219. addBodyEnd(ends, ocHighPoint, 0);
  57220. addBodyEnd(ends, ocLowPoint, 1);
  57221. ends.push(
  57222. subPixelOptimizePoint(highestPoint),
  57223. subPixelOptimizePoint(ocHighPoint),
  57224. subPixelOptimizePoint(lowestPoint),
  57225. subPixelOptimizePoint(ocLowPoint)
  57226. );
  57227. data.setItemLayout(dataIndex, {
  57228. sign: getSign(data, dataIndex, openVal, closeVal, closeDim),
  57229. initBaseline: openVal > closeVal
  57230. ? ocHighPoint[vDimIdx] : ocLowPoint[vDimIdx], // open point.
  57231. ends: ends,
  57232. brushRect: makeBrushRect(lowestVal, highestVal, axisDimVal)
  57233. });
  57234. }
  57235. function getPoint(val, axisDimVal) {
  57236. var p = [];
  57237. p[cDimIdx] = axisDimVal;
  57238. p[vDimIdx] = val;
  57239. return (isNaN(axisDimVal) || isNaN(val))
  57240. ? [NaN, NaN]
  57241. : coordSys.dataToPoint(p);
  57242. }
  57243. function addBodyEnd(ends, point, start) {
  57244. var point1 = point.slice();
  57245. var point2 = point.slice();
  57246. point1[cDimIdx] = subPixelOptimize(
  57247. point1[cDimIdx] + candleWidth / 2, 1, false
  57248. );
  57249. point2[cDimIdx] = subPixelOptimize(
  57250. point2[cDimIdx] - candleWidth / 2, 1, true
  57251. );
  57252. start
  57253. ? ends.push(point1, point2)
  57254. : ends.push(point2, point1);
  57255. }
  57256. function makeBrushRect(lowestVal, highestVal, axisDimVal) {
  57257. var pmin = getPoint(lowestVal, axisDimVal);
  57258. var pmax = getPoint(highestVal, axisDimVal);
  57259. pmin[cDimIdx] -= candleWidth / 2;
  57260. pmax[cDimIdx] -= candleWidth / 2;
  57261. return {
  57262. x: pmin[0],
  57263. y: pmin[1],
  57264. width: vDimIdx ? candleWidth : pmax[0] - pmin[0],
  57265. height: vDimIdx ? pmax[1] - pmin[1] : candleWidth
  57266. };
  57267. }
  57268. function subPixelOptimizePoint(point) {
  57269. point[cDimIdx] = subPixelOptimize(point[cDimIdx], 1);
  57270. return point;
  57271. }
  57272. }
  57273. function largeProgress(params, data) {
  57274. // Structure: [sign, x, yhigh, ylow, sign, x, yhigh, ylow, ...]
  57275. var points = new LargeArr$1(params.count * 4);
  57276. var offset = 0;
  57277. var point;
  57278. var tmpIn = [];
  57279. var tmpOut = [];
  57280. var dataIndex;
  57281. while ((dataIndex = params.next()) != null) {
  57282. var axisDimVal = data.get(cDim, dataIndex);
  57283. var openVal = data.get(openDim, dataIndex);
  57284. var closeVal = data.get(closeDim, dataIndex);
  57285. var lowestVal = data.get(lowestDim, dataIndex);
  57286. var highestVal = data.get(highestDim, dataIndex);
  57287. if (isNaN(axisDimVal) || isNaN(lowestVal) || isNaN(highestVal)) {
  57288. points[offset++] = NaN;
  57289. offset += 3;
  57290. continue;
  57291. }
  57292. points[offset++] = getSign(data, dataIndex, openVal, closeVal, closeDim);
  57293. tmpIn[cDimIdx] = axisDimVal;
  57294. tmpIn[vDimIdx] = lowestVal;
  57295. point = coordSys.dataToPoint(tmpIn, null, tmpOut);
  57296. points[offset++] = point ? point[0] : NaN;
  57297. points[offset++] = point ? point[1] : NaN;
  57298. tmpIn[vDimIdx] = highestVal;
  57299. point = coordSys.dataToPoint(tmpIn, null, tmpOut);
  57300. points[offset++] = point ? point[1] : NaN;
  57301. }
  57302. data.setLayout('largePoints', points);
  57303. }
  57304. }
  57305. };
  57306. function getSign(data, dataIndex, openVal, closeVal, closeDim) {
  57307. var sign;
  57308. if (openVal > closeVal) {
  57309. sign = -1;
  57310. }
  57311. else if (openVal < closeVal) {
  57312. sign = 1;
  57313. }
  57314. else {
  57315. sign = dataIndex > 0
  57316. // If close === open, compare with close of last record
  57317. ? (data.get(closeDim, dataIndex - 1) <= closeVal ? 1 : -1)
  57318. // No record of previous, set to be positive
  57319. : 1;
  57320. }
  57321. return sign;
  57322. }
  57323. function calculateCandleWidth(seriesModel, data) {
  57324. var baseAxis = seriesModel.getBaseAxis();
  57325. var extent;
  57326. var bandWidth = baseAxis.type === 'category'
  57327. ? baseAxis.getBandWidth()
  57328. : (
  57329. extent = baseAxis.getExtent(),
  57330. Math.abs(extent[1] - extent[0]) / data.count()
  57331. );
  57332. var barMaxWidth = parsePercent$1(
  57333. retrieve2(seriesModel.get('barMaxWidth'), bandWidth),
  57334. bandWidth
  57335. );
  57336. var barMinWidth = parsePercent$1(
  57337. retrieve2(seriesModel.get('barMinWidth'), 1),
  57338. bandWidth
  57339. );
  57340. var barWidth = seriesModel.get('barWidth');
  57341. return barWidth != null
  57342. ? parsePercent$1(barWidth, bandWidth)
  57343. // Put max outer to ensure bar visible in spite of overlap.
  57344. : Math.max(Math.min(bandWidth / 2, barMaxWidth), barMinWidth);
  57345. }
  57346. /*
  57347. * Licensed to the Apache Software Foundation (ASF) under one
  57348. * or more contributor license agreements. See the NOTICE file
  57349. * distributed with this work for additional information
  57350. * regarding copyright ownership. The ASF licenses this file
  57351. * to you under the Apache License, Version 2.0 (the
  57352. * "License"); you may not use this file except in compliance
  57353. * with the License. You may obtain a copy of the License at
  57354. *
  57355. * http://www.apache.org/licenses/LICENSE-2.0
  57356. *
  57357. * Unless required by applicable law or agreed to in writing,
  57358. * software distributed under the License is distributed on an
  57359. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57360. * KIND, either express or implied. See the License for the
  57361. * specific language governing permissions and limitations
  57362. * under the License.
  57363. */
  57364. registerPreprocessor(preprocessor);
  57365. registerVisual(candlestickVisual);
  57366. registerLayout(candlestickLayout);
  57367. /*
  57368. * Licensed to the Apache Software Foundation (ASF) under one
  57369. * or more contributor license agreements. See the NOTICE file
  57370. * distributed with this work for additional information
  57371. * regarding copyright ownership. The ASF licenses this file
  57372. * to you under the Apache License, Version 2.0 (the
  57373. * "License"); you may not use this file except in compliance
  57374. * with the License. You may obtain a copy of the License at
  57375. *
  57376. * http://www.apache.org/licenses/LICENSE-2.0
  57377. *
  57378. * Unless required by applicable law or agreed to in writing,
  57379. * software distributed under the License is distributed on an
  57380. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57381. * KIND, either express or implied. See the License for the
  57382. * specific language governing permissions and limitations
  57383. * under the License.
  57384. */
  57385. SeriesModel.extend({
  57386. type: 'series.effectScatter',
  57387. dependencies: ['grid', 'polar'],
  57388. getInitialData: function (option, ecModel) {
  57389. return createListFromArray(this.getSource(), this, {useEncodeDefaulter: true});
  57390. },
  57391. brushSelector: 'point',
  57392. defaultOption: {
  57393. coordinateSystem: 'cartesian2d',
  57394. zlevel: 0,
  57395. z: 2,
  57396. legendHoverLink: true,
  57397. effectType: 'ripple',
  57398. progressive: 0,
  57399. // When to show the effect, option: 'render'|'emphasis'
  57400. showEffectOn: 'render',
  57401. // Ripple effect config
  57402. rippleEffect: {
  57403. period: 4,
  57404. // Scale of ripple
  57405. scale: 2.5,
  57406. // Brush type can be fill or stroke
  57407. brushType: 'fill'
  57408. },
  57409. // Cartesian coordinate system
  57410. // xAxisIndex: 0,
  57411. // yAxisIndex: 0,
  57412. // Polar coordinate system
  57413. // polarIndex: 0,
  57414. // Geo coordinate system
  57415. // geoIndex: 0,
  57416. // symbol: null, // 图形类型
  57417. symbolSize: 10 // 图形大小,半宽(半径)参数,当图形为方向或菱形则总宽度为symbolSize * 2
  57418. // symbolRotate: null, // 图形旋转控制
  57419. // large: false,
  57420. // Available when large is true
  57421. // largeThreshold: 2000,
  57422. // itemStyle: {
  57423. // opacity: 1
  57424. // }
  57425. }
  57426. });
  57427. /*
  57428. * Licensed to the Apache Software Foundation (ASF) under one
  57429. * or more contributor license agreements. See the NOTICE file
  57430. * distributed with this work for additional information
  57431. * regarding copyright ownership. The ASF licenses this file
  57432. * to you under the Apache License, Version 2.0 (the
  57433. * "License"); you may not use this file except in compliance
  57434. * with the License. You may obtain a copy of the License at
  57435. *
  57436. * http://www.apache.org/licenses/LICENSE-2.0
  57437. *
  57438. * Unless required by applicable law or agreed to in writing,
  57439. * software distributed under the License is distributed on an
  57440. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57441. * KIND, either express or implied. See the License for the
  57442. * specific language governing permissions and limitations
  57443. * under the License.
  57444. */
  57445. /**
  57446. * Symbol with ripple effect
  57447. * @module echarts/chart/helper/EffectSymbol
  57448. */
  57449. var EFFECT_RIPPLE_NUMBER = 3;
  57450. function normalizeSymbolSize$1(symbolSize) {
  57451. if (!isArray(symbolSize)) {
  57452. symbolSize = [+symbolSize, +symbolSize];
  57453. }
  57454. return symbolSize;
  57455. }
  57456. function updateRipplePath(rippleGroup, effectCfg) {
  57457. var color = effectCfg.rippleEffectColor || effectCfg.color;
  57458. rippleGroup.eachChild(function (ripplePath) {
  57459. ripplePath.attr({
  57460. z: effectCfg.z,
  57461. zlevel: effectCfg.zlevel,
  57462. style: {
  57463. stroke: effectCfg.brushType === 'stroke' ? color : null,
  57464. fill: effectCfg.brushType === 'fill' ? color : null
  57465. }
  57466. });
  57467. });
  57468. }
  57469. /**
  57470. * @constructor
  57471. * @param {module:echarts/data/List} data
  57472. * @param {number} idx
  57473. * @extends {module:zrender/graphic/Group}
  57474. */
  57475. function EffectSymbol(data, idx) {
  57476. Group.call(this);
  57477. var symbol = new SymbolClz$1(data, idx);
  57478. var rippleGroup = new Group();
  57479. this.add(symbol);
  57480. this.add(rippleGroup);
  57481. rippleGroup.beforeUpdate = function () {
  57482. this.attr(symbol.getScale());
  57483. };
  57484. this.updateData(data, idx);
  57485. }
  57486. var effectSymbolProto = EffectSymbol.prototype;
  57487. effectSymbolProto.stopEffectAnimation = function () {
  57488. this.childAt(1).removeAll();
  57489. };
  57490. effectSymbolProto.startEffectAnimation = function (effectCfg) {
  57491. var symbolType = effectCfg.symbolType;
  57492. var color = effectCfg.color;
  57493. var rippleGroup = this.childAt(1);
  57494. for (var i = 0; i < EFFECT_RIPPLE_NUMBER; i++) {
  57495. // If width/height are set too small (e.g., set to 1) on ios10
  57496. // and macOS Sierra, a circle stroke become a rect, no matter what
  57497. // the scale is set. So we set width/height as 2. See #4136.
  57498. var ripplePath = createSymbol(
  57499. symbolType, -1, -1, 2, 2, color
  57500. );
  57501. ripplePath.attr({
  57502. style: {
  57503. strokeNoScale: true
  57504. },
  57505. z2: 99,
  57506. silent: true,
  57507. scale: [0.5, 0.5]
  57508. });
  57509. var delay = -i / EFFECT_RIPPLE_NUMBER * effectCfg.period + effectCfg.effectOffset;
  57510. // TODO Configurable effectCfg.period
  57511. ripplePath.animate('', true)
  57512. .when(effectCfg.period, {
  57513. scale: [effectCfg.rippleScale / 2, effectCfg.rippleScale / 2]
  57514. })
  57515. .delay(delay)
  57516. .start();
  57517. ripplePath.animateStyle(true)
  57518. .when(effectCfg.period, {
  57519. opacity: 0
  57520. })
  57521. .delay(delay)
  57522. .start();
  57523. rippleGroup.add(ripplePath);
  57524. }
  57525. updateRipplePath(rippleGroup, effectCfg);
  57526. };
  57527. /**
  57528. * Update effect symbol
  57529. */
  57530. effectSymbolProto.updateEffectAnimation = function (effectCfg) {
  57531. var oldEffectCfg = this._effectCfg;
  57532. var rippleGroup = this.childAt(1);
  57533. // Must reinitialize effect if following configuration changed
  57534. var DIFFICULT_PROPS = ['symbolType', 'period', 'rippleScale'];
  57535. for (var i = 0; i < DIFFICULT_PROPS.length; i++) {
  57536. var propName = DIFFICULT_PROPS[i];
  57537. if (oldEffectCfg[propName] !== effectCfg[propName]) {
  57538. this.stopEffectAnimation();
  57539. this.startEffectAnimation(effectCfg);
  57540. return;
  57541. }
  57542. }
  57543. updateRipplePath(rippleGroup, effectCfg);
  57544. };
  57545. /**
  57546. * Highlight symbol
  57547. */
  57548. effectSymbolProto.highlight = function () {
  57549. this.trigger('emphasis');
  57550. };
  57551. /**
  57552. * Downplay symbol
  57553. */
  57554. effectSymbolProto.downplay = function () {
  57555. this.trigger('normal');
  57556. };
  57557. /**
  57558. * Update symbol properties
  57559. * @param {module:echarts/data/List} data
  57560. * @param {number} idx
  57561. */
  57562. effectSymbolProto.updateData = function (data, idx) {
  57563. var seriesModel = data.hostModel;
  57564. this.childAt(0).updateData(data, idx);
  57565. var rippleGroup = this.childAt(1);
  57566. var itemModel = data.getItemModel(idx);
  57567. var symbolType = data.getItemVisual(idx, 'symbol');
  57568. var symbolSize = normalizeSymbolSize$1(data.getItemVisual(idx, 'symbolSize'));
  57569. var color = data.getItemVisual(idx, 'color');
  57570. rippleGroup.attr('scale', symbolSize);
  57571. rippleGroup.traverse(function (ripplePath) {
  57572. ripplePath.attr({
  57573. fill: color
  57574. });
  57575. });
  57576. var symbolOffset = itemModel.getShallow('symbolOffset');
  57577. if (symbolOffset) {
  57578. var pos = rippleGroup.position;
  57579. pos[0] = parsePercent$1(symbolOffset[0], symbolSize[0]);
  57580. pos[1] = parsePercent$1(symbolOffset[1], symbolSize[1]);
  57581. }
  57582. var symbolRotate = data.getItemVisual(idx, 'symbolRotate');
  57583. rippleGroup.rotation = (symbolRotate || 0) * Math.PI / 180 || 0;
  57584. var effectCfg = {};
  57585. effectCfg.showEffectOn = seriesModel.get('showEffectOn');
  57586. effectCfg.rippleScale = itemModel.get('rippleEffect.scale');
  57587. effectCfg.brushType = itemModel.get('rippleEffect.brushType');
  57588. effectCfg.period = itemModel.get('rippleEffect.period') * 1000;
  57589. effectCfg.effectOffset = idx / data.count();
  57590. effectCfg.z = itemModel.getShallow('z') || 0;
  57591. effectCfg.zlevel = itemModel.getShallow('zlevel') || 0;
  57592. effectCfg.symbolType = symbolType;
  57593. effectCfg.color = color;
  57594. effectCfg.rippleEffectColor = itemModel.get('rippleEffect.color');
  57595. this.off('mouseover').off('mouseout').off('emphasis').off('normal');
  57596. if (effectCfg.showEffectOn === 'render') {
  57597. this._effectCfg
  57598. ? this.updateEffectAnimation(effectCfg)
  57599. : this.startEffectAnimation(effectCfg);
  57600. this._effectCfg = effectCfg;
  57601. }
  57602. else {
  57603. // Not keep old effect config
  57604. this._effectCfg = null;
  57605. this.stopEffectAnimation();
  57606. var symbol = this.childAt(0);
  57607. var onEmphasis = function () {
  57608. symbol.highlight();
  57609. if (effectCfg.showEffectOn !== 'render') {
  57610. this.startEffectAnimation(effectCfg);
  57611. }
  57612. };
  57613. var onNormal = function () {
  57614. symbol.downplay();
  57615. if (effectCfg.showEffectOn !== 'render') {
  57616. this.stopEffectAnimation();
  57617. }
  57618. };
  57619. this.on('mouseover', onEmphasis, this)
  57620. .on('mouseout', onNormal, this)
  57621. .on('emphasis', onEmphasis, this)
  57622. .on('normal', onNormal, this);
  57623. }
  57624. this._effectCfg = effectCfg;
  57625. };
  57626. effectSymbolProto.fadeOut = function (cb) {
  57627. this.off('mouseover').off('mouseout').off('emphasis').off('normal');
  57628. cb && cb();
  57629. };
  57630. inherits(EffectSymbol, Group);
  57631. /*
  57632. * Licensed to the Apache Software Foundation (ASF) under one
  57633. * or more contributor license agreements. See the NOTICE file
  57634. * distributed with this work for additional information
  57635. * regarding copyright ownership. The ASF licenses this file
  57636. * to you under the Apache License, Version 2.0 (the
  57637. * "License"); you may not use this file except in compliance
  57638. * with the License. You may obtain a copy of the License at
  57639. *
  57640. * http://www.apache.org/licenses/LICENSE-2.0
  57641. *
  57642. * Unless required by applicable law or agreed to in writing,
  57643. * software distributed under the License is distributed on an
  57644. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57645. * KIND, either express or implied. See the License for the
  57646. * specific language governing permissions and limitations
  57647. * under the License.
  57648. */
  57649. extendChartView({
  57650. type: 'effectScatter',
  57651. init: function () {
  57652. this._symbolDraw = new SymbolDraw(EffectSymbol);
  57653. },
  57654. render: function (seriesModel, ecModel, api) {
  57655. var data = seriesModel.getData();
  57656. var effectSymbolDraw = this._symbolDraw;
  57657. effectSymbolDraw.updateData(data);
  57658. this.group.add(effectSymbolDraw.group);
  57659. },
  57660. updateTransform: function (seriesModel, ecModel, api) {
  57661. var data = seriesModel.getData();
  57662. this.group.dirty();
  57663. var res = pointsLayout().reset(seriesModel);
  57664. if (res.progress) {
  57665. res.progress({ start: 0, end: data.count() }, data);
  57666. }
  57667. this._symbolDraw.updateLayout(data);
  57668. },
  57669. _updateGroupTransform: function (seriesModel) {
  57670. var coordSys = seriesModel.coordinateSystem;
  57671. if (coordSys && coordSys.getRoamTransform) {
  57672. this.group.transform = clone$2(coordSys.getRoamTransform());
  57673. this.group.decomposeTransform();
  57674. }
  57675. },
  57676. remove: function (ecModel, api) {
  57677. this._symbolDraw && this._symbolDraw.remove(api);
  57678. },
  57679. dispose: function () {}
  57680. });
  57681. /*
  57682. * Licensed to the Apache Software Foundation (ASF) under one
  57683. * or more contributor license agreements. See the NOTICE file
  57684. * distributed with this work for additional information
  57685. * regarding copyright ownership. The ASF licenses this file
  57686. * to you under the Apache License, Version 2.0 (the
  57687. * "License"); you may not use this file except in compliance
  57688. * with the License. You may obtain a copy of the License at
  57689. *
  57690. * http://www.apache.org/licenses/LICENSE-2.0
  57691. *
  57692. * Unless required by applicable law or agreed to in writing,
  57693. * software distributed under the License is distributed on an
  57694. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57695. * KIND, either express or implied. See the License for the
  57696. * specific language governing permissions and limitations
  57697. * under the License.
  57698. */
  57699. registerVisual(visualSymbol('effectScatter', 'circle'));
  57700. registerLayout(pointsLayout('effectScatter'));
  57701. /*
  57702. * Licensed to the Apache Software Foundation (ASF) under one
  57703. * or more contributor license agreements. See the NOTICE file
  57704. * distributed with this work for additional information
  57705. * regarding copyright ownership. The ASF licenses this file
  57706. * to you under the Apache License, Version 2.0 (the
  57707. * "License"); you may not use this file except in compliance
  57708. * with the License. You may obtain a copy of the License at
  57709. *
  57710. * http://www.apache.org/licenses/LICENSE-2.0
  57711. *
  57712. * Unless required by applicable law or agreed to in writing,
  57713. * software distributed under the License is distributed on an
  57714. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57715. * KIND, either express or implied. See the License for the
  57716. * specific language governing permissions and limitations
  57717. * under the License.
  57718. */
  57719. /* global Uint32Array, Float64Array, Float32Array */
  57720. var Uint32Arr = typeof Uint32Array === 'undefined' ? Array : Uint32Array;
  57721. var Float64Arr = typeof Float64Array === 'undefined' ? Array : Float64Array;
  57722. function compatEc2(seriesOpt) {
  57723. var data = seriesOpt.data;
  57724. if (data && data[0] && data[0][0] && data[0][0].coord) {
  57725. if (__DEV__) {
  57726. console.warn('Lines data configuration has been changed to'
  57727. + ' { coords:[[1,2],[2,3]] }');
  57728. }
  57729. seriesOpt.data = map(data, function (itemOpt) {
  57730. var coords = [
  57731. itemOpt[0].coord, itemOpt[1].coord
  57732. ];
  57733. var target = {
  57734. coords: coords
  57735. };
  57736. if (itemOpt[0].name) {
  57737. target.fromName = itemOpt[0].name;
  57738. }
  57739. if (itemOpt[1].name) {
  57740. target.toName = itemOpt[1].name;
  57741. }
  57742. return mergeAll([target, itemOpt[0], itemOpt[1]]);
  57743. });
  57744. }
  57745. }
  57746. var LinesSeries = SeriesModel.extend({
  57747. type: 'series.lines',
  57748. dependencies: ['grid', 'polar'],
  57749. visualColorAccessPath: 'lineStyle.color',
  57750. init: function (option) {
  57751. // The input data may be null/undefined.
  57752. option.data = option.data || [];
  57753. // Not using preprocessor because mergeOption may not have series.type
  57754. compatEc2(option);
  57755. var result = this._processFlatCoordsArray(option.data);
  57756. this._flatCoords = result.flatCoords;
  57757. this._flatCoordsOffset = result.flatCoordsOffset;
  57758. if (result.flatCoords) {
  57759. option.data = new Float32Array(result.count);
  57760. }
  57761. LinesSeries.superApply(this, 'init', arguments);
  57762. },
  57763. mergeOption: function (option) {
  57764. // The input data may be null/undefined.
  57765. option.data = option.data || [];
  57766. compatEc2(option);
  57767. if (option.data) {
  57768. // Only update when have option data to merge.
  57769. var result = this._processFlatCoordsArray(option.data);
  57770. this._flatCoords = result.flatCoords;
  57771. this._flatCoordsOffset = result.flatCoordsOffset;
  57772. if (result.flatCoords) {
  57773. option.data = new Float32Array(result.count);
  57774. }
  57775. }
  57776. LinesSeries.superApply(this, 'mergeOption', arguments);
  57777. },
  57778. appendData: function (params) {
  57779. var result = this._processFlatCoordsArray(params.data);
  57780. if (result.flatCoords) {
  57781. if (!this._flatCoords) {
  57782. this._flatCoords = result.flatCoords;
  57783. this._flatCoordsOffset = result.flatCoordsOffset;
  57784. }
  57785. else {
  57786. this._flatCoords = concatArray(this._flatCoords, result.flatCoords);
  57787. this._flatCoordsOffset = concatArray(this._flatCoordsOffset, result.flatCoordsOffset);
  57788. }
  57789. params.data = new Float32Array(result.count);
  57790. }
  57791. this.getRawData().appendData(params.data);
  57792. },
  57793. _getCoordsFromItemModel: function (idx) {
  57794. var itemModel = this.getData().getItemModel(idx);
  57795. var coords = (itemModel.option instanceof Array)
  57796. ? itemModel.option : itemModel.getShallow('coords');
  57797. if (__DEV__) {
  57798. if (!(coords instanceof Array && coords.length > 0 && coords[0] instanceof Array)) {
  57799. throw new Error(
  57800. 'Invalid coords ' + JSON.stringify(coords) + '. Lines must have 2d coords array in data item.'
  57801. );
  57802. }
  57803. }
  57804. return coords;
  57805. },
  57806. getLineCoordsCount: function (idx) {
  57807. if (this._flatCoordsOffset) {
  57808. return this._flatCoordsOffset[idx * 2 + 1];
  57809. }
  57810. else {
  57811. return this._getCoordsFromItemModel(idx).length;
  57812. }
  57813. },
  57814. getLineCoords: function (idx, out) {
  57815. if (this._flatCoordsOffset) {
  57816. var offset = this._flatCoordsOffset[idx * 2];
  57817. var len = this._flatCoordsOffset[idx * 2 + 1];
  57818. for (var i = 0; i < len; i++) {
  57819. out[i] = out[i] || [];
  57820. out[i][0] = this._flatCoords[offset + i * 2];
  57821. out[i][1] = this._flatCoords[offset + i * 2 + 1];
  57822. }
  57823. return len;
  57824. }
  57825. else {
  57826. var coords = this._getCoordsFromItemModel(idx);
  57827. for (var i = 0; i < coords.length; i++) {
  57828. out[i] = out[i] || [];
  57829. out[i][0] = coords[i][0];
  57830. out[i][1] = coords[i][1];
  57831. }
  57832. return coords.length;
  57833. }
  57834. },
  57835. _processFlatCoordsArray: function (data) {
  57836. var startOffset = 0;
  57837. if (this._flatCoords) {
  57838. startOffset = this._flatCoords.length;
  57839. }
  57840. // Stored as a typed array. In format
  57841. // Points Count(2) | x | y | x | y | Points Count(3) | x | y | x | y | x | y |
  57842. if (typeof data[0] === 'number') {
  57843. var len = data.length;
  57844. // Store offset and len of each segment
  57845. var coordsOffsetAndLenStorage = new Uint32Arr(len);
  57846. var coordsStorage = new Float64Arr(len);
  57847. var coordsCursor = 0;
  57848. var offsetCursor = 0;
  57849. var dataCount = 0;
  57850. for (var i = 0; i < len;) {
  57851. dataCount++;
  57852. var count = data[i++];
  57853. // Offset
  57854. coordsOffsetAndLenStorage[offsetCursor++] = coordsCursor + startOffset;
  57855. // Len
  57856. coordsOffsetAndLenStorage[offsetCursor++] = count;
  57857. for (var k = 0; k < count; k++) {
  57858. var x = data[i++];
  57859. var y = data[i++];
  57860. coordsStorage[coordsCursor++] = x;
  57861. coordsStorage[coordsCursor++] = y;
  57862. if (i > len) {
  57863. if (__DEV__) {
  57864. throw new Error('Invalid data format.');
  57865. }
  57866. }
  57867. }
  57868. }
  57869. return {
  57870. flatCoordsOffset: new Uint32Array(coordsOffsetAndLenStorage.buffer, 0, offsetCursor),
  57871. flatCoords: coordsStorage,
  57872. count: dataCount
  57873. };
  57874. }
  57875. return {
  57876. flatCoordsOffset: null,
  57877. flatCoords: null,
  57878. count: data.length
  57879. };
  57880. },
  57881. getInitialData: function (option, ecModel) {
  57882. if (__DEV__) {
  57883. var CoordSys = CoordinateSystemManager.get(option.coordinateSystem);
  57884. if (!CoordSys) {
  57885. throw new Error('Unkown coordinate system ' + option.coordinateSystem);
  57886. }
  57887. }
  57888. var lineData = new List(['value'], this);
  57889. lineData.hasItemOption = false;
  57890. lineData.initData(option.data, [], function (dataItem, dimName, dataIndex, dimIndex) {
  57891. // dataItem is simply coords
  57892. if (dataItem instanceof Array) {
  57893. return NaN;
  57894. }
  57895. else {
  57896. lineData.hasItemOption = true;
  57897. var value = dataItem.value;
  57898. if (value != null) {
  57899. return value instanceof Array ? value[dimIndex] : value;
  57900. }
  57901. }
  57902. });
  57903. return lineData;
  57904. },
  57905. formatTooltip: function (dataIndex) {
  57906. var data = this.getData();
  57907. var itemModel = data.getItemModel(dataIndex);
  57908. var name = itemModel.get('name');
  57909. if (name) {
  57910. return name;
  57911. }
  57912. var fromName = itemModel.get('fromName');
  57913. var toName = itemModel.get('toName');
  57914. var html = [];
  57915. fromName != null && html.push(fromName);
  57916. toName != null && html.push(toName);
  57917. return encodeHTML(html.join(' > '));
  57918. },
  57919. preventIncremental: function () {
  57920. return !!this.get('effect.show');
  57921. },
  57922. getProgressive: function () {
  57923. var progressive = this.option.progressive;
  57924. if (progressive == null) {
  57925. return this.option.large ? 1e4 : this.get('progressive');
  57926. }
  57927. return progressive;
  57928. },
  57929. getProgressiveThreshold: function () {
  57930. var progressiveThreshold = this.option.progressiveThreshold;
  57931. if (progressiveThreshold == null) {
  57932. return this.option.large ? 2e4 : this.get('progressiveThreshold');
  57933. }
  57934. return progressiveThreshold;
  57935. },
  57936. defaultOption: {
  57937. coordinateSystem: 'geo',
  57938. zlevel: 0,
  57939. z: 2,
  57940. legendHoverLink: true,
  57941. hoverAnimation: true,
  57942. // Cartesian coordinate system
  57943. xAxisIndex: 0,
  57944. yAxisIndex: 0,
  57945. symbol: ['none', 'none'],
  57946. symbolSize: [10, 10],
  57947. // Geo coordinate system
  57948. geoIndex: 0,
  57949. effect: {
  57950. show: false,
  57951. period: 4,
  57952. // Animation delay. support callback
  57953. // delay: 0,
  57954. // If move with constant speed px/sec
  57955. // period will be ignored if this property is > 0,
  57956. constantSpeed: 0,
  57957. symbol: 'circle',
  57958. symbolSize: 3,
  57959. loop: true,
  57960. // Length of trail, 0 - 1
  57961. trailLength: 0.2
  57962. // Same with lineStyle.color
  57963. // color
  57964. },
  57965. large: false,
  57966. // Available when large is true
  57967. largeThreshold: 2000,
  57968. // If lines are polyline
  57969. // polyline not support curveness, label, animation
  57970. polyline: false,
  57971. // If clip the overflow.
  57972. // Available when coordinateSystem is cartesian or polar.
  57973. clip: true,
  57974. label: {
  57975. show: false,
  57976. position: 'end'
  57977. // distance: 5,
  57978. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  57979. },
  57980. lineStyle: {
  57981. opacity: 0.5
  57982. }
  57983. }
  57984. });
  57985. /*
  57986. * Licensed to the Apache Software Foundation (ASF) under one
  57987. * or more contributor license agreements. See the NOTICE file
  57988. * distributed with this work for additional information
  57989. * regarding copyright ownership. The ASF licenses this file
  57990. * to you under the Apache License, Version 2.0 (the
  57991. * "License"); you may not use this file except in compliance
  57992. * with the License. You may obtain a copy of the License at
  57993. *
  57994. * http://www.apache.org/licenses/LICENSE-2.0
  57995. *
  57996. * Unless required by applicable law or agreed to in writing,
  57997. * software distributed under the License is distributed on an
  57998. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57999. * KIND, either express or implied. See the License for the
  58000. * specific language governing permissions and limitations
  58001. * under the License.
  58002. */
  58003. /**
  58004. * Provide effect for line
  58005. * @module echarts/chart/helper/EffectLine
  58006. */
  58007. /**
  58008. * @constructor
  58009. * @extends {module:zrender/graphic/Group}
  58010. * @alias {module:echarts/chart/helper/Line}
  58011. */
  58012. function EffectLine(lineData, idx, seriesScope) {
  58013. Group.call(this);
  58014. this.add(this.createLine(lineData, idx, seriesScope));
  58015. this._updateEffectSymbol(lineData, idx);
  58016. }
  58017. var effectLineProto = EffectLine.prototype;
  58018. effectLineProto.createLine = function (lineData, idx, seriesScope) {
  58019. return new Line$1(lineData, idx, seriesScope);
  58020. };
  58021. effectLineProto._updateEffectSymbol = function (lineData, idx) {
  58022. var itemModel = lineData.getItemModel(idx);
  58023. var effectModel = itemModel.getModel('effect');
  58024. var size = effectModel.get('symbolSize');
  58025. var symbolType = effectModel.get('symbol');
  58026. if (!isArray(size)) {
  58027. size = [size, size];
  58028. }
  58029. var color = effectModel.get('color') || lineData.getItemVisual(idx, 'color');
  58030. var symbol = this.childAt(1);
  58031. if (this._symbolType !== symbolType) {
  58032. // Remove previous
  58033. this.remove(symbol);
  58034. symbol = createSymbol(
  58035. symbolType, -0.5, -0.5, 1, 1, color
  58036. );
  58037. symbol.z2 = 100;
  58038. symbol.culling = true;
  58039. this.add(symbol);
  58040. }
  58041. // Symbol may be removed if loop is false
  58042. if (!symbol) {
  58043. return;
  58044. }
  58045. // Shadow color is same with color in default
  58046. symbol.setStyle('shadowColor', color);
  58047. symbol.setStyle(effectModel.getItemStyle(['color']));
  58048. symbol.attr('scale', size);
  58049. symbol.setColor(color);
  58050. symbol.attr('scale', size);
  58051. this._symbolType = symbolType;
  58052. this._symbolScale = size;
  58053. this._updateEffectAnimation(lineData, effectModel, idx);
  58054. };
  58055. effectLineProto._updateEffectAnimation = function (lineData, effectModel, idx) {
  58056. var symbol = this.childAt(1);
  58057. if (!symbol) {
  58058. return;
  58059. }
  58060. var self = this;
  58061. var points = lineData.getItemLayout(idx);
  58062. var period = effectModel.get('period') * 1000;
  58063. var loop = effectModel.get('loop');
  58064. var constantSpeed = effectModel.get('constantSpeed');
  58065. var delayExpr = retrieve(effectModel.get('delay'), function (idx) {
  58066. return idx / lineData.count() * period / 3;
  58067. });
  58068. var isDelayFunc = typeof delayExpr === 'function';
  58069. // Ignore when updating
  58070. symbol.ignore = true;
  58071. this.updateAnimationPoints(symbol, points);
  58072. if (constantSpeed > 0) {
  58073. period = this.getLineLength(symbol) / constantSpeed * 1000;
  58074. }
  58075. if (period !== this._period || loop !== this._loop) {
  58076. symbol.stopAnimation();
  58077. var delay = delayExpr;
  58078. if (isDelayFunc) {
  58079. delay = delayExpr(idx);
  58080. }
  58081. if (symbol.__t > 0) {
  58082. delay = -period * symbol.__t;
  58083. }
  58084. symbol.__t = 0;
  58085. var animator = symbol.animate('', loop)
  58086. .when(period, {
  58087. __t: 1
  58088. })
  58089. .delay(delay)
  58090. .during(function () {
  58091. self.updateSymbolPosition(symbol);
  58092. });
  58093. if (!loop) {
  58094. animator.done(function () {
  58095. self.remove(symbol);
  58096. });
  58097. }
  58098. animator.start();
  58099. }
  58100. this._period = period;
  58101. this._loop = loop;
  58102. };
  58103. effectLineProto.getLineLength = function (symbol) {
  58104. // Not so accurate
  58105. return (dist(symbol.__p1, symbol.__cp1)
  58106. + dist(symbol.__cp1, symbol.__p2));
  58107. };
  58108. effectLineProto.updateAnimationPoints = function (symbol, points) {
  58109. symbol.__p1 = points[0];
  58110. symbol.__p2 = points[1];
  58111. symbol.__cp1 = points[2] || [
  58112. (points[0][0] + points[1][0]) / 2,
  58113. (points[0][1] + points[1][1]) / 2
  58114. ];
  58115. };
  58116. effectLineProto.updateData = function (lineData, idx, seriesScope) {
  58117. this.childAt(0).updateData(lineData, idx, seriesScope);
  58118. this._updateEffectSymbol(lineData, idx);
  58119. };
  58120. effectLineProto.updateSymbolPosition = function (symbol) {
  58121. var p1 = symbol.__p1;
  58122. var p2 = symbol.__p2;
  58123. var cp1 = symbol.__cp1;
  58124. var t = symbol.__t;
  58125. var pos = symbol.position;
  58126. var lastPos = [pos[0], pos[1]];
  58127. var quadraticAt$$1 = quadraticAt;
  58128. var quadraticDerivativeAt$$1 = quadraticDerivativeAt;
  58129. pos[0] = quadraticAt$$1(p1[0], cp1[0], p2[0], t);
  58130. pos[1] = quadraticAt$$1(p1[1], cp1[1], p2[1], t);
  58131. // Tangent
  58132. var tx = quadraticDerivativeAt$$1(p1[0], cp1[0], p2[0], t);
  58133. var ty = quadraticDerivativeAt$$1(p1[1], cp1[1], p2[1], t);
  58134. symbol.rotation = -Math.atan2(ty, tx) - Math.PI / 2;
  58135. // enable continuity trail for 'line', 'rect', 'roundRect' symbolType
  58136. if (this._symbolType === 'line' || this._symbolType === 'rect' || this._symbolType === 'roundRect') {
  58137. if (symbol.__lastT !== undefined && symbol.__lastT < symbol.__t) {
  58138. var scaleY = dist(lastPos, pos) * 1.05;
  58139. symbol.attr('scale', [symbol.scale[0], scaleY]);
  58140. // make sure the last segment render within endPoint
  58141. if (t === 1) {
  58142. pos[0] = lastPos[0] + (pos[0] - lastPos[0]) / 2;
  58143. pos[1] = lastPos[1] + (pos[1] - lastPos[1]) / 2;
  58144. }
  58145. }
  58146. else if (symbol.__lastT === 1) {
  58147. // After first loop, symbol.__t does NOT start with 0, so connect p1 to pos directly.
  58148. var scaleY = 2 * dist(p1, pos);
  58149. symbol.attr('scale', [symbol.scale[0], scaleY ]);
  58150. }
  58151. else {
  58152. symbol.attr('scale', this._symbolScale);
  58153. }
  58154. }
  58155. symbol.__lastT = symbol.__t;
  58156. symbol.ignore = false;
  58157. };
  58158. effectLineProto.updateLayout = function (lineData, idx) {
  58159. this.childAt(0).updateLayout(lineData, idx);
  58160. var effectModel = lineData.getItemModel(idx).getModel('effect');
  58161. this._updateEffectAnimation(lineData, effectModel, idx);
  58162. };
  58163. inherits(EffectLine, Group);
  58164. /*
  58165. * Licensed to the Apache Software Foundation (ASF) under one
  58166. * or more contributor license agreements. See the NOTICE file
  58167. * distributed with this work for additional information
  58168. * regarding copyright ownership. The ASF licenses this file
  58169. * to you under the Apache License, Version 2.0 (the
  58170. * "License"); you may not use this file except in compliance
  58171. * with the License. You may obtain a copy of the License at
  58172. *
  58173. * http://www.apache.org/licenses/LICENSE-2.0
  58174. *
  58175. * Unless required by applicable law or agreed to in writing,
  58176. * software distributed under the License is distributed on an
  58177. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58178. * KIND, either express or implied. See the License for the
  58179. * specific language governing permissions and limitations
  58180. * under the License.
  58181. */
  58182. /**
  58183. * @module echarts/chart/helper/Line
  58184. */
  58185. /**
  58186. * @constructor
  58187. * @extends {module:zrender/graphic/Group}
  58188. * @alias {module:echarts/chart/helper/Polyline}
  58189. */
  58190. function Polyline$2(lineData, idx, seriesScope) {
  58191. Group.call(this);
  58192. this._createPolyline(lineData, idx, seriesScope);
  58193. }
  58194. var polylineProto = Polyline$2.prototype;
  58195. polylineProto._createPolyline = function (lineData, idx, seriesScope) {
  58196. // var seriesModel = lineData.hostModel;
  58197. var points = lineData.getItemLayout(idx);
  58198. var line = new Polyline({
  58199. shape: {
  58200. points: points
  58201. }
  58202. });
  58203. this.add(line);
  58204. this._updateCommonStl(lineData, idx, seriesScope);
  58205. };
  58206. polylineProto.updateData = function (lineData, idx, seriesScope) {
  58207. var seriesModel = lineData.hostModel;
  58208. var line = this.childAt(0);
  58209. var target = {
  58210. shape: {
  58211. points: lineData.getItemLayout(idx)
  58212. }
  58213. };
  58214. updateProps(line, target, seriesModel, idx);
  58215. this._updateCommonStl(lineData, idx, seriesScope);
  58216. };
  58217. polylineProto._updateCommonStl = function (lineData, idx, seriesScope) {
  58218. var line = this.childAt(0);
  58219. var itemModel = lineData.getItemModel(idx);
  58220. var visualColor = lineData.getItemVisual(idx, 'color');
  58221. var lineStyle = seriesScope && seriesScope.lineStyle;
  58222. var hoverLineStyle = seriesScope && seriesScope.hoverLineStyle;
  58223. if (!seriesScope || lineData.hasItemOption) {
  58224. lineStyle = itemModel.getModel('lineStyle').getLineStyle();
  58225. hoverLineStyle = itemModel.getModel('emphasis.lineStyle').getLineStyle();
  58226. }
  58227. line.useStyle(defaults(
  58228. {
  58229. strokeNoScale: true,
  58230. fill: 'none',
  58231. stroke: visualColor
  58232. },
  58233. lineStyle
  58234. ));
  58235. line.hoverStyle = hoverLineStyle;
  58236. setHoverStyle(this);
  58237. };
  58238. polylineProto.updateLayout = function (lineData, idx) {
  58239. var polyline = this.childAt(0);
  58240. polyline.setShape('points', lineData.getItemLayout(idx));
  58241. };
  58242. inherits(Polyline$2, Group);
  58243. /*
  58244. * Licensed to the Apache Software Foundation (ASF) under one
  58245. * or more contributor license agreements. See the NOTICE file
  58246. * distributed with this work for additional information
  58247. * regarding copyright ownership. The ASF licenses this file
  58248. * to you under the Apache License, Version 2.0 (the
  58249. * "License"); you may not use this file except in compliance
  58250. * with the License. You may obtain a copy of the License at
  58251. *
  58252. * http://www.apache.org/licenses/LICENSE-2.0
  58253. *
  58254. * Unless required by applicable law or agreed to in writing,
  58255. * software distributed under the License is distributed on an
  58256. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58257. * KIND, either express or implied. See the License for the
  58258. * specific language governing permissions and limitations
  58259. * under the License.
  58260. */
  58261. /**
  58262. * Provide effect for line
  58263. * @module echarts/chart/helper/EffectLine
  58264. */
  58265. /**
  58266. * @constructor
  58267. * @extends {module:echarts/chart/helper/EffectLine}
  58268. * @alias {module:echarts/chart/helper/Polyline}
  58269. */
  58270. function EffectPolyline(lineData, idx, seriesScope) {
  58271. EffectLine.call(this, lineData, idx, seriesScope);
  58272. this._lastFrame = 0;
  58273. this._lastFramePercent = 0;
  58274. }
  58275. var effectPolylineProto = EffectPolyline.prototype;
  58276. // Overwrite
  58277. effectPolylineProto.createLine = function (lineData, idx, seriesScope) {
  58278. return new Polyline$2(lineData, idx, seriesScope);
  58279. };
  58280. // Overwrite
  58281. effectPolylineProto.updateAnimationPoints = function (symbol, points) {
  58282. this._points = points;
  58283. var accLenArr = [0];
  58284. var len$$1 = 0;
  58285. for (var i = 1; i < points.length; i++) {
  58286. var p1 = points[i - 1];
  58287. var p2 = points[i];
  58288. len$$1 += dist(p1, p2);
  58289. accLenArr.push(len$$1);
  58290. }
  58291. if (len$$1 === 0) {
  58292. return;
  58293. }
  58294. for (var i = 0; i < accLenArr.length; i++) {
  58295. accLenArr[i] /= len$$1;
  58296. }
  58297. this._offsets = accLenArr;
  58298. this._length = len$$1;
  58299. };
  58300. // Overwrite
  58301. effectPolylineProto.getLineLength = function (symbol) {
  58302. return this._length;
  58303. };
  58304. // Overwrite
  58305. effectPolylineProto.updateSymbolPosition = function (symbol) {
  58306. var t = symbol.__t;
  58307. var points = this._points;
  58308. var offsets = this._offsets;
  58309. var len$$1 = points.length;
  58310. if (!offsets) {
  58311. // Has length 0
  58312. return;
  58313. }
  58314. var lastFrame = this._lastFrame;
  58315. var frame;
  58316. if (t < this._lastFramePercent) {
  58317. // Start from the next frame
  58318. // PENDING start from lastFrame ?
  58319. var start = Math.min(lastFrame + 1, len$$1 - 1);
  58320. for (frame = start; frame >= 0; frame--) {
  58321. if (offsets[frame] <= t) {
  58322. break;
  58323. }
  58324. }
  58325. // PENDING really need to do this ?
  58326. frame = Math.min(frame, len$$1 - 2);
  58327. }
  58328. else {
  58329. for (var frame = lastFrame; frame < len$$1; frame++) {
  58330. if (offsets[frame] > t) {
  58331. break;
  58332. }
  58333. }
  58334. frame = Math.min(frame - 1, len$$1 - 2);
  58335. }
  58336. lerp(
  58337. symbol.position, points[frame], points[frame + 1],
  58338. (t - offsets[frame]) / (offsets[frame + 1] - offsets[frame])
  58339. );
  58340. var tx = points[frame + 1][0] - points[frame][0];
  58341. var ty = points[frame + 1][1] - points[frame][1];
  58342. symbol.rotation = -Math.atan2(ty, tx) - Math.PI / 2;
  58343. this._lastFrame = frame;
  58344. this._lastFramePercent = t;
  58345. symbol.ignore = false;
  58346. };
  58347. inherits(EffectPolyline, EffectLine);
  58348. /*
  58349. * Licensed to the Apache Software Foundation (ASF) under one
  58350. * or more contributor license agreements. See the NOTICE file
  58351. * distributed with this work for additional information
  58352. * regarding copyright ownership. The ASF licenses this file
  58353. * to you under the Apache License, Version 2.0 (the
  58354. * "License"); you may not use this file except in compliance
  58355. * with the License. You may obtain a copy of the License at
  58356. *
  58357. * http://www.apache.org/licenses/LICENSE-2.0
  58358. *
  58359. * Unless required by applicable law or agreed to in writing,
  58360. * software distributed under the License is distributed on an
  58361. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58362. * KIND, either express or implied. See the License for the
  58363. * specific language governing permissions and limitations
  58364. * under the License.
  58365. */
  58366. // TODO Batch by color
  58367. var LargeLineShape = extendShape({
  58368. shape: {
  58369. polyline: false,
  58370. curveness: 0,
  58371. segs: []
  58372. },
  58373. buildPath: function (path, shape) {
  58374. var segs = shape.segs;
  58375. var curveness = shape.curveness;
  58376. if (shape.polyline) {
  58377. for (var i = 0; i < segs.length;) {
  58378. var count = segs[i++];
  58379. if (count > 0) {
  58380. path.moveTo(segs[i++], segs[i++]);
  58381. for (var k = 1; k < count; k++) {
  58382. path.lineTo(segs[i++], segs[i++]);
  58383. }
  58384. }
  58385. }
  58386. }
  58387. else {
  58388. for (var i = 0; i < segs.length;) {
  58389. var x0 = segs[i++];
  58390. var y0 = segs[i++];
  58391. var x1 = segs[i++];
  58392. var y1 = segs[i++];
  58393. path.moveTo(x0, y0);
  58394. if (curveness > 0) {
  58395. var x2 = (x0 + x1) / 2 - (y0 - y1) * curveness;
  58396. var y2 = (y0 + y1) / 2 - (x1 - x0) * curveness;
  58397. path.quadraticCurveTo(x2, y2, x1, y1);
  58398. }
  58399. else {
  58400. path.lineTo(x1, y1);
  58401. }
  58402. }
  58403. }
  58404. },
  58405. findDataIndex: function (x, y) {
  58406. var shape = this.shape;
  58407. var segs = shape.segs;
  58408. var curveness = shape.curveness;
  58409. if (shape.polyline) {
  58410. var dataIndex = 0;
  58411. for (var i = 0; i < segs.length;) {
  58412. var count = segs[i++];
  58413. if (count > 0) {
  58414. var x0 = segs[i++];
  58415. var y0 = segs[i++];
  58416. for (var k = 1; k < count; k++) {
  58417. var x1 = segs[i++];
  58418. var y1 = segs[i++];
  58419. if (containStroke$1(x0, y0, x1, y1)) {
  58420. return dataIndex;
  58421. }
  58422. }
  58423. }
  58424. dataIndex++;
  58425. }
  58426. }
  58427. else {
  58428. var dataIndex = 0;
  58429. for (var i = 0; i < segs.length;) {
  58430. var x0 = segs[i++];
  58431. var y0 = segs[i++];
  58432. var x1 = segs[i++];
  58433. var y1 = segs[i++];
  58434. if (curveness > 0) {
  58435. var x2 = (x0 + x1) / 2 - (y0 - y1) * curveness;
  58436. var y2 = (y0 + y1) / 2 - (x1 - x0) * curveness;
  58437. if (containStroke$3(x0, y0, x2, y2, x1, y1)) {
  58438. return dataIndex;
  58439. }
  58440. }
  58441. else {
  58442. if (containStroke$1(x0, y0, x1, y1)) {
  58443. return dataIndex;
  58444. }
  58445. }
  58446. dataIndex++;
  58447. }
  58448. }
  58449. return -1;
  58450. }
  58451. });
  58452. function LargeLineDraw() {
  58453. this.group = new Group();
  58454. }
  58455. var largeLineProto = LargeLineDraw.prototype;
  58456. largeLineProto.isPersistent = function () {
  58457. return !this._incremental;
  58458. };
  58459. /**
  58460. * Update symbols draw by new data
  58461. * @param {module:echarts/data/List} data
  58462. */
  58463. largeLineProto.updateData = function (data) {
  58464. this.group.removeAll();
  58465. var lineEl = new LargeLineShape({
  58466. rectHover: true,
  58467. cursor: 'default'
  58468. });
  58469. lineEl.setShape({
  58470. segs: data.getLayout('linesPoints')
  58471. });
  58472. this._setCommon(lineEl, data);
  58473. // Add back
  58474. this.group.add(lineEl);
  58475. this._incremental = null;
  58476. };
  58477. /**
  58478. * @override
  58479. */
  58480. largeLineProto.incrementalPrepareUpdate = function (data) {
  58481. this.group.removeAll();
  58482. this._clearIncremental();
  58483. if (data.count() > 5e5) {
  58484. if (!this._incremental) {
  58485. this._incremental = new IncrementalDisplayble({
  58486. silent: true
  58487. });
  58488. }
  58489. this.group.add(this._incremental);
  58490. }
  58491. else {
  58492. this._incremental = null;
  58493. }
  58494. };
  58495. /**
  58496. * @override
  58497. */
  58498. largeLineProto.incrementalUpdate = function (taskParams, data) {
  58499. var lineEl = new LargeLineShape();
  58500. lineEl.setShape({
  58501. segs: data.getLayout('linesPoints')
  58502. });
  58503. this._setCommon(lineEl, data, !!this._incremental);
  58504. if (!this._incremental) {
  58505. lineEl.rectHover = true;
  58506. lineEl.cursor = 'default';
  58507. lineEl.__startIndex = taskParams.start;
  58508. this.group.add(lineEl);
  58509. }
  58510. else {
  58511. this._incremental.addDisplayable(lineEl, true);
  58512. }
  58513. };
  58514. /**
  58515. * @override
  58516. */
  58517. largeLineProto.remove = function () {
  58518. this._clearIncremental();
  58519. this._incremental = null;
  58520. this.group.removeAll();
  58521. };
  58522. largeLineProto._setCommon = function (lineEl, data, isIncremental) {
  58523. var hostModel = data.hostModel;
  58524. lineEl.setShape({
  58525. polyline: hostModel.get('polyline'),
  58526. curveness: hostModel.get('lineStyle.curveness')
  58527. });
  58528. lineEl.useStyle(
  58529. hostModel.getModel('lineStyle').getLineStyle()
  58530. );
  58531. lineEl.style.strokeNoScale = true;
  58532. var visualColor = data.getVisual('color');
  58533. if (visualColor) {
  58534. lineEl.setStyle('stroke', visualColor);
  58535. }
  58536. lineEl.setStyle('fill');
  58537. if (!isIncremental) {
  58538. // Enable tooltip
  58539. // PENDING May have performance issue when path is extremely large
  58540. lineEl.seriesIndex = hostModel.seriesIndex;
  58541. lineEl.on('mousemove', function (e) {
  58542. lineEl.dataIndex = null;
  58543. var dataIndex = lineEl.findDataIndex(e.offsetX, e.offsetY);
  58544. if (dataIndex > 0) {
  58545. // Provide dataIndex for tooltip
  58546. lineEl.dataIndex = dataIndex + lineEl.__startIndex;
  58547. }
  58548. });
  58549. }
  58550. };
  58551. largeLineProto._clearIncremental = function () {
  58552. var incremental = this._incremental;
  58553. if (incremental) {
  58554. incremental.clearDisplaybles();
  58555. }
  58556. };
  58557. /*
  58558. * Licensed to the Apache Software Foundation (ASF) under one
  58559. * or more contributor license agreements. See the NOTICE file
  58560. * distributed with this work for additional information
  58561. * regarding copyright ownership. The ASF licenses this file
  58562. * to you under the Apache License, Version 2.0 (the
  58563. * "License"); you may not use this file except in compliance
  58564. * with the License. You may obtain a copy of the License at
  58565. *
  58566. * http://www.apache.org/licenses/LICENSE-2.0
  58567. *
  58568. * Unless required by applicable law or agreed to in writing,
  58569. * software distributed under the License is distributed on an
  58570. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58571. * KIND, either express or implied. See the License for the
  58572. * specific language governing permissions and limitations
  58573. * under the License.
  58574. */
  58575. /* global Float32Array */
  58576. var linesLayout = {
  58577. seriesType: 'lines',
  58578. plan: createRenderPlanner(),
  58579. reset: function (seriesModel) {
  58580. var coordSys = seriesModel.coordinateSystem;
  58581. var isPolyline = seriesModel.get('polyline');
  58582. var isLarge = seriesModel.pipelineContext.large;
  58583. function progress(params, lineData) {
  58584. var lineCoords = [];
  58585. if (isLarge) {
  58586. var points;
  58587. var segCount = params.end - params.start;
  58588. if (isPolyline) {
  58589. var totalCoordsCount = 0;
  58590. for (var i = params.start; i < params.end; i++) {
  58591. totalCoordsCount += seriesModel.getLineCoordsCount(i);
  58592. }
  58593. points = new Float32Array(segCount + totalCoordsCount * 2);
  58594. }
  58595. else {
  58596. points = new Float32Array(segCount * 4);
  58597. }
  58598. var offset = 0;
  58599. var pt = [];
  58600. for (var i = params.start; i < params.end; i++) {
  58601. var len = seriesModel.getLineCoords(i, lineCoords);
  58602. if (isPolyline) {
  58603. points[offset++] = len;
  58604. }
  58605. for (var k = 0; k < len; k++) {
  58606. pt = coordSys.dataToPoint(lineCoords[k], false, pt);
  58607. points[offset++] = pt[0];
  58608. points[offset++] = pt[1];
  58609. }
  58610. }
  58611. lineData.setLayout('linesPoints', points);
  58612. }
  58613. else {
  58614. for (var i = params.start; i < params.end; i++) {
  58615. var itemModel = lineData.getItemModel(i);
  58616. var len = seriesModel.getLineCoords(i, lineCoords);
  58617. var pts = [];
  58618. if (isPolyline) {
  58619. for (var j = 0; j < len; j++) {
  58620. pts.push(coordSys.dataToPoint(lineCoords[j]));
  58621. }
  58622. }
  58623. else {
  58624. pts[0] = coordSys.dataToPoint(lineCoords[0]);
  58625. pts[1] = coordSys.dataToPoint(lineCoords[1]);
  58626. var curveness = itemModel.get('lineStyle.curveness');
  58627. if (+curveness) {
  58628. pts[2] = [
  58629. (pts[0][0] + pts[1][0]) / 2 - (pts[0][1] - pts[1][1]) * curveness,
  58630. (pts[0][1] + pts[1][1]) / 2 - (pts[1][0] - pts[0][0]) * curveness
  58631. ];
  58632. }
  58633. }
  58634. lineData.setItemLayout(i, pts);
  58635. }
  58636. }
  58637. }
  58638. return { progress: progress };
  58639. }
  58640. };
  58641. /*
  58642. * Licensed to the Apache Software Foundation (ASF) under one
  58643. * or more contributor license agreements. See the NOTICE file
  58644. * distributed with this work for additional information
  58645. * regarding copyright ownership. The ASF licenses this file
  58646. * to you under the Apache License, Version 2.0 (the
  58647. * "License"); you may not use this file except in compliance
  58648. * with the License. You may obtain a copy of the License at
  58649. *
  58650. * http://www.apache.org/licenses/LICENSE-2.0
  58651. *
  58652. * Unless required by applicable law or agreed to in writing,
  58653. * software distributed under the License is distributed on an
  58654. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58655. * KIND, either express or implied. See the License for the
  58656. * specific language governing permissions and limitations
  58657. * under the License.
  58658. */
  58659. extendChartView({
  58660. type: 'lines',
  58661. init: function () {},
  58662. render: function (seriesModel, ecModel, api) {
  58663. var data = seriesModel.getData();
  58664. var lineDraw = this._updateLineDraw(data, seriesModel);
  58665. var zlevel = seriesModel.get('zlevel');
  58666. var trailLength = seriesModel.get('effect.trailLength');
  58667. var zr = api.getZr();
  58668. // Avoid the drag cause ghost shadow
  58669. // FIXME Better way ?
  58670. // SVG doesn't support
  58671. var isSvg = zr.painter.getType() === 'svg';
  58672. if (!isSvg) {
  58673. zr.painter.getLayer(zlevel).clear(true);
  58674. }
  58675. // Config layer with motion blur
  58676. if (this._lastZlevel != null && !isSvg) {
  58677. zr.configLayer(this._lastZlevel, {
  58678. motionBlur: false
  58679. });
  58680. }
  58681. if (this._showEffect(seriesModel) && trailLength) {
  58682. if (__DEV__) {
  58683. var notInIndividual = false;
  58684. ecModel.eachSeries(function (otherSeriesModel) {
  58685. if (otherSeriesModel !== seriesModel && otherSeriesModel.get('zlevel') === zlevel) {
  58686. notInIndividual = true;
  58687. }
  58688. });
  58689. notInIndividual && console.warn('Lines with trail effect should have an individual zlevel');
  58690. }
  58691. if (!isSvg) {
  58692. zr.configLayer(zlevel, {
  58693. motionBlur: true,
  58694. lastFrameAlpha: Math.max(Math.min(trailLength / 10 + 0.9, 1), 0)
  58695. });
  58696. }
  58697. }
  58698. lineDraw.updateData(data);
  58699. var clipPath = seriesModel.get('clip', true) && createClipPath(
  58700. seriesModel.coordinateSystem, false, seriesModel
  58701. );
  58702. if (clipPath) {
  58703. this.group.setClipPath(clipPath);
  58704. }
  58705. else {
  58706. this.group.removeClipPath();
  58707. }
  58708. this._lastZlevel = zlevel;
  58709. this._finished = true;
  58710. },
  58711. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  58712. var data = seriesModel.getData();
  58713. var lineDraw = this._updateLineDraw(data, seriesModel);
  58714. lineDraw.incrementalPrepareUpdate(data);
  58715. this._clearLayer(api);
  58716. this._finished = false;
  58717. },
  58718. incrementalRender: function (taskParams, seriesModel, ecModel) {
  58719. this._lineDraw.incrementalUpdate(taskParams, seriesModel.getData());
  58720. this._finished = taskParams.end === seriesModel.getData().count();
  58721. },
  58722. updateTransform: function (seriesModel, ecModel, api) {
  58723. var data = seriesModel.getData();
  58724. var pipelineContext = seriesModel.pipelineContext;
  58725. if (!this._finished || pipelineContext.large || pipelineContext.progressiveRender) {
  58726. // TODO Don't have to do update in large mode. Only do it when there are millions of data.
  58727. return {
  58728. update: true
  58729. };
  58730. }
  58731. else {
  58732. // TODO Use same logic with ScatterView.
  58733. // Manually update layout
  58734. var res = linesLayout.reset(seriesModel);
  58735. if (res.progress) {
  58736. res.progress({ start: 0, end: data.count() }, data);
  58737. }
  58738. this._lineDraw.updateLayout();
  58739. this._clearLayer(api);
  58740. }
  58741. },
  58742. _updateLineDraw: function (data, seriesModel) {
  58743. var lineDraw = this._lineDraw;
  58744. var hasEffect = this._showEffect(seriesModel);
  58745. var isPolyline = !!seriesModel.get('polyline');
  58746. var pipelineContext = seriesModel.pipelineContext;
  58747. var isLargeDraw = pipelineContext.large;
  58748. if (__DEV__) {
  58749. if (hasEffect && isLargeDraw) {
  58750. console.warn('Large lines not support effect');
  58751. }
  58752. }
  58753. if (!lineDraw
  58754. || hasEffect !== this._hasEffet
  58755. || isPolyline !== this._isPolyline
  58756. || isLargeDraw !== this._isLargeDraw
  58757. ) {
  58758. if (lineDraw) {
  58759. lineDraw.remove();
  58760. }
  58761. lineDraw = this._lineDraw = isLargeDraw
  58762. ? new LargeLineDraw()
  58763. : new LineDraw(
  58764. isPolyline
  58765. ? (hasEffect ? EffectPolyline : Polyline$2)
  58766. : (hasEffect ? EffectLine : Line$1)
  58767. );
  58768. this._hasEffet = hasEffect;
  58769. this._isPolyline = isPolyline;
  58770. this._isLargeDraw = isLargeDraw;
  58771. this.group.removeAll();
  58772. }
  58773. this.group.add(lineDraw.group);
  58774. return lineDraw;
  58775. },
  58776. _showEffect: function (seriesModel) {
  58777. return !!seriesModel.get('effect.show');
  58778. },
  58779. _clearLayer: function (api) {
  58780. // Not use motion when dragging or zooming
  58781. var zr = api.getZr();
  58782. var isSvg = zr.painter.getType() === 'svg';
  58783. if (!isSvg && this._lastZlevel != null) {
  58784. zr.painter.getLayer(this._lastZlevel).clear(true);
  58785. }
  58786. },
  58787. remove: function (ecModel, api) {
  58788. this._lineDraw && this._lineDraw.remove();
  58789. this._lineDraw = null;
  58790. // Clear motion when lineDraw is removed
  58791. this._clearLayer(api);
  58792. },
  58793. dispose: function () {}
  58794. });
  58795. /*
  58796. * Licensed to the Apache Software Foundation (ASF) under one
  58797. * or more contributor license agreements. See the NOTICE file
  58798. * distributed with this work for additional information
  58799. * regarding copyright ownership. The ASF licenses this file
  58800. * to you under the Apache License, Version 2.0 (the
  58801. * "License"); you may not use this file except in compliance
  58802. * with the License. You may obtain a copy of the License at
  58803. *
  58804. * http://www.apache.org/licenses/LICENSE-2.0
  58805. *
  58806. * Unless required by applicable law or agreed to in writing,
  58807. * software distributed under the License is distributed on an
  58808. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58809. * KIND, either express or implied. See the License for the
  58810. * specific language governing permissions and limitations
  58811. * under the License.
  58812. */
  58813. function normalize$2(a) {
  58814. if (!(a instanceof Array)) {
  58815. a = [a, a];
  58816. }
  58817. return a;
  58818. }
  58819. var opacityQuery = 'lineStyle.opacity'.split('.');
  58820. var linesVisual = {
  58821. seriesType: 'lines',
  58822. reset: function (seriesModel, ecModel, api) {
  58823. var symbolType = normalize$2(seriesModel.get('symbol'));
  58824. var symbolSize = normalize$2(seriesModel.get('symbolSize'));
  58825. var data = seriesModel.getData();
  58826. data.setVisual('fromSymbol', symbolType && symbolType[0]);
  58827. data.setVisual('toSymbol', symbolType && symbolType[1]);
  58828. data.setVisual('fromSymbolSize', symbolSize && symbolSize[0]);
  58829. data.setVisual('toSymbolSize', symbolSize && symbolSize[1]);
  58830. data.setVisual('opacity', seriesModel.get(opacityQuery));
  58831. function dataEach(data, idx) {
  58832. var itemModel = data.getItemModel(idx);
  58833. var symbolType = normalize$2(itemModel.getShallow('symbol', true));
  58834. var symbolSize = normalize$2(itemModel.getShallow('symbolSize', true));
  58835. var opacity = itemModel.get(opacityQuery);
  58836. symbolType[0] && data.setItemVisual(idx, 'fromSymbol', symbolType[0]);
  58837. symbolType[1] && data.setItemVisual(idx, 'toSymbol', symbolType[1]);
  58838. symbolSize[0] && data.setItemVisual(idx, 'fromSymbolSize', symbolSize[0]);
  58839. symbolSize[1] && data.setItemVisual(idx, 'toSymbolSize', symbolSize[1]);
  58840. data.setItemVisual(idx, 'opacity', opacity);
  58841. }
  58842. return {dataEach: data.hasItemOption ? dataEach : null};
  58843. }
  58844. };
  58845. /*
  58846. * Licensed to the Apache Software Foundation (ASF) under one
  58847. * or more contributor license agreements. See the NOTICE file
  58848. * distributed with this work for additional information
  58849. * regarding copyright ownership. The ASF licenses this file
  58850. * to you under the Apache License, Version 2.0 (the
  58851. * "License"); you may not use this file except in compliance
  58852. * with the License. You may obtain a copy of the License at
  58853. *
  58854. * http://www.apache.org/licenses/LICENSE-2.0
  58855. *
  58856. * Unless required by applicable law or agreed to in writing,
  58857. * software distributed under the License is distributed on an
  58858. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58859. * KIND, either express or implied. See the License for the
  58860. * specific language governing permissions and limitations
  58861. * under the License.
  58862. */
  58863. registerLayout(linesLayout);
  58864. registerVisual(linesVisual);
  58865. /*
  58866. * Licensed to the Apache Software Foundation (ASF) under one
  58867. * or more contributor license agreements. See the NOTICE file
  58868. * distributed with this work for additional information
  58869. * regarding copyright ownership. The ASF licenses this file
  58870. * to you under the Apache License, Version 2.0 (the
  58871. * "License"); you may not use this file except in compliance
  58872. * with the License. You may obtain a copy of the License at
  58873. *
  58874. * http://www.apache.org/licenses/LICENSE-2.0
  58875. *
  58876. * Unless required by applicable law or agreed to in writing,
  58877. * software distributed under the License is distributed on an
  58878. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58879. * KIND, either express or implied. See the License for the
  58880. * specific language governing permissions and limitations
  58881. * under the License.
  58882. */
  58883. SeriesModel.extend({
  58884. type: 'series.heatmap',
  58885. getInitialData: function (option, ecModel) {
  58886. return createListFromArray(this.getSource(), this, {
  58887. generateCoord: 'value'
  58888. });
  58889. },
  58890. preventIncremental: function () {
  58891. var coordSysCreator = CoordinateSystemManager.get(this.get('coordinateSystem'));
  58892. if (coordSysCreator && coordSysCreator.dimensions) {
  58893. return coordSysCreator.dimensions[0] === 'lng' && coordSysCreator.dimensions[1] === 'lat';
  58894. }
  58895. },
  58896. defaultOption: {
  58897. // Cartesian2D or geo
  58898. coordinateSystem: 'cartesian2d',
  58899. zlevel: 0,
  58900. z: 2,
  58901. // Cartesian coordinate system
  58902. // xAxisIndex: 0,
  58903. // yAxisIndex: 0,
  58904. // Geo coordinate system
  58905. geoIndex: 0,
  58906. blurSize: 30,
  58907. pointSize: 20,
  58908. maxOpacity: 1,
  58909. minOpacity: 0
  58910. }
  58911. });
  58912. /*
  58913. * Licensed to the Apache Software Foundation (ASF) under one
  58914. * or more contributor license agreements. See the NOTICE file
  58915. * distributed with this work for additional information
  58916. * regarding copyright ownership. The ASF licenses this file
  58917. * to you under the Apache License, Version 2.0 (the
  58918. * "License"); you may not use this file except in compliance
  58919. * with the License. You may obtain a copy of the License at
  58920. *
  58921. * http://www.apache.org/licenses/LICENSE-2.0
  58922. *
  58923. * Unless required by applicable law or agreed to in writing,
  58924. * software distributed under the License is distributed on an
  58925. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58926. * KIND, either express or implied. See the License for the
  58927. * specific language governing permissions and limitations
  58928. * under the License.
  58929. */
  58930. /* global Uint8ClampedArray */
  58931. var GRADIENT_LEVELS = 256;
  58932. /**
  58933. * Heatmap Chart
  58934. *
  58935. * @class
  58936. */
  58937. function Heatmap() {
  58938. var canvas = createCanvas();
  58939. this.canvas = canvas;
  58940. this.blurSize = 30;
  58941. this.pointSize = 20;
  58942. this.maxOpacity = 1;
  58943. this.minOpacity = 0;
  58944. this._gradientPixels = {};
  58945. }
  58946. Heatmap.prototype = {
  58947. /**
  58948. * Renders Heatmap and returns the rendered canvas
  58949. * @param {Array} data array of data, each has x, y, value
  58950. * @param {number} width canvas width
  58951. * @param {number} height canvas height
  58952. */
  58953. update: function (data, width, height, normalize, colorFunc, isInRange) {
  58954. var brush = this._getBrush();
  58955. var gradientInRange = this._getGradient(data, colorFunc, 'inRange');
  58956. var gradientOutOfRange = this._getGradient(data, colorFunc, 'outOfRange');
  58957. var r = this.pointSize + this.blurSize;
  58958. var canvas = this.canvas;
  58959. var ctx = canvas.getContext('2d');
  58960. var len = data.length;
  58961. canvas.width = width;
  58962. canvas.height = height;
  58963. for (var i = 0; i < len; ++i) {
  58964. var p = data[i];
  58965. var x = p[0];
  58966. var y = p[1];
  58967. var value = p[2];
  58968. // calculate alpha using value
  58969. var alpha = normalize(value);
  58970. // draw with the circle brush with alpha
  58971. ctx.globalAlpha = alpha;
  58972. ctx.drawImage(brush, x - r, y - r);
  58973. }
  58974. if (!canvas.width || !canvas.height) {
  58975. // Avoid "Uncaught DOMException: Failed to execute 'getImageData' on
  58976. // 'CanvasRenderingContext2D': The source height is 0."
  58977. return canvas;
  58978. }
  58979. // colorize the canvas using alpha value and set with gradient
  58980. var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
  58981. var pixels = imageData.data;
  58982. var offset = 0;
  58983. var pixelLen = pixels.length;
  58984. var minOpacity = this.minOpacity;
  58985. var maxOpacity = this.maxOpacity;
  58986. var diffOpacity = maxOpacity - minOpacity;
  58987. while (offset < pixelLen) {
  58988. var alpha = pixels[offset + 3] / 256;
  58989. var gradientOffset = Math.floor(alpha * (GRADIENT_LEVELS - 1)) * 4;
  58990. // Simple optimize to ignore the empty data
  58991. if (alpha > 0) {
  58992. var gradient = isInRange(alpha) ? gradientInRange : gradientOutOfRange;
  58993. // Any alpha > 0 will be mapped to [minOpacity, maxOpacity]
  58994. alpha > 0 && (alpha = alpha * diffOpacity + minOpacity);
  58995. pixels[offset++] = gradient[gradientOffset];
  58996. pixels[offset++] = gradient[gradientOffset + 1];
  58997. pixels[offset++] = gradient[gradientOffset + 2];
  58998. pixels[offset++] = gradient[gradientOffset + 3] * alpha * 256;
  58999. }
  59000. else {
  59001. offset += 4;
  59002. }
  59003. }
  59004. ctx.putImageData(imageData, 0, 0);
  59005. return canvas;
  59006. },
  59007. /**
  59008. * get canvas of a black circle brush used for canvas to draw later
  59009. * @private
  59010. * @returns {Object} circle brush canvas
  59011. */
  59012. _getBrush: function () {
  59013. var brushCanvas = this._brushCanvas || (this._brushCanvas = createCanvas());
  59014. // set brush size
  59015. var r = this.pointSize + this.blurSize;
  59016. var d = r * 2;
  59017. brushCanvas.width = d;
  59018. brushCanvas.height = d;
  59019. var ctx = brushCanvas.getContext('2d');
  59020. ctx.clearRect(0, 0, d, d);
  59021. // in order to render shadow without the distinct circle,
  59022. // draw the distinct circle in an invisible place,
  59023. // and use shadowOffset to draw shadow in the center of the canvas
  59024. ctx.shadowOffsetX = d;
  59025. ctx.shadowBlur = this.blurSize;
  59026. // draw the shadow in black, and use alpha and shadow blur to generate
  59027. // color in color map
  59028. ctx.shadowColor = '#000';
  59029. // draw circle in the left to the canvas
  59030. ctx.beginPath();
  59031. ctx.arc(-r, r, this.pointSize, 0, Math.PI * 2, true);
  59032. ctx.closePath();
  59033. ctx.fill();
  59034. return brushCanvas;
  59035. },
  59036. /**
  59037. * get gradient color map
  59038. * @private
  59039. */
  59040. _getGradient: function (data, colorFunc, state) {
  59041. var gradientPixels = this._gradientPixels;
  59042. var pixelsSingleState = gradientPixels[state] || (gradientPixels[state] = new Uint8ClampedArray(256 * 4));
  59043. var color = [0, 0, 0, 0];
  59044. var off = 0;
  59045. for (var i = 0; i < 256; i++) {
  59046. colorFunc[state](i / 255, true, color);
  59047. pixelsSingleState[off++] = color[0];
  59048. pixelsSingleState[off++] = color[1];
  59049. pixelsSingleState[off++] = color[2];
  59050. pixelsSingleState[off++] = color[3];
  59051. }
  59052. return pixelsSingleState;
  59053. }
  59054. };
  59055. /*
  59056. * Licensed to the Apache Software Foundation (ASF) under one
  59057. * or more contributor license agreements. See the NOTICE file
  59058. * distributed with this work for additional information
  59059. * regarding copyright ownership. The ASF licenses this file
  59060. * to you under the Apache License, Version 2.0 (the
  59061. * "License"); you may not use this file except in compliance
  59062. * with the License. You may obtain a copy of the License at
  59063. *
  59064. * http://www.apache.org/licenses/LICENSE-2.0
  59065. *
  59066. * Unless required by applicable law or agreed to in writing,
  59067. * software distributed under the License is distributed on an
  59068. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59069. * KIND, either express or implied. See the License for the
  59070. * specific language governing permissions and limitations
  59071. * under the License.
  59072. */
  59073. function getIsInPiecewiseRange(dataExtent, pieceList, selected) {
  59074. var dataSpan = dataExtent[1] - dataExtent[0];
  59075. pieceList = map(pieceList, function (piece) {
  59076. return {
  59077. interval: [
  59078. (piece.interval[0] - dataExtent[0]) / dataSpan,
  59079. (piece.interval[1] - dataExtent[0]) / dataSpan
  59080. ]
  59081. };
  59082. });
  59083. var len = pieceList.length;
  59084. var lastIndex = 0;
  59085. return function (val) {
  59086. // Try to find in the location of the last found
  59087. for (var i = lastIndex; i < len; i++) {
  59088. var interval = pieceList[i].interval;
  59089. if (interval[0] <= val && val <= interval[1]) {
  59090. lastIndex = i;
  59091. break;
  59092. }
  59093. }
  59094. if (i === len) { // Not found, back interation
  59095. for (var i = lastIndex - 1; i >= 0; i--) {
  59096. var interval = pieceList[i].interval;
  59097. if (interval[0] <= val && val <= interval[1]) {
  59098. lastIndex = i;
  59099. break;
  59100. }
  59101. }
  59102. }
  59103. return i >= 0 && i < len && selected[i];
  59104. };
  59105. }
  59106. function getIsInContinuousRange(dataExtent, range) {
  59107. var dataSpan = dataExtent[1] - dataExtent[0];
  59108. range = [
  59109. (range[0] - dataExtent[0]) / dataSpan,
  59110. (range[1] - dataExtent[0]) / dataSpan
  59111. ];
  59112. return function (val) {
  59113. return val >= range[0] && val <= range[1];
  59114. };
  59115. }
  59116. function isGeoCoordSys(coordSys) {
  59117. var dimensions = coordSys.dimensions;
  59118. // Not use coorSys.type === 'geo' because coordSys maybe extended
  59119. return dimensions[0] === 'lng' && dimensions[1] === 'lat';
  59120. }
  59121. extendChartView({
  59122. type: 'heatmap',
  59123. render: function (seriesModel, ecModel, api) {
  59124. var visualMapOfThisSeries;
  59125. ecModel.eachComponent('visualMap', function (visualMap) {
  59126. visualMap.eachTargetSeries(function (targetSeries) {
  59127. if (targetSeries === seriesModel) {
  59128. visualMapOfThisSeries = visualMap;
  59129. }
  59130. });
  59131. });
  59132. if (__DEV__) {
  59133. if (!visualMapOfThisSeries) {
  59134. throw new Error('Heatmap must use with visualMap');
  59135. }
  59136. }
  59137. this.group.removeAll();
  59138. this._incrementalDisplayable = null;
  59139. var coordSys = seriesModel.coordinateSystem;
  59140. if (coordSys.type === 'cartesian2d' || coordSys.type === 'calendar') {
  59141. this._renderOnCartesianAndCalendar(seriesModel, api, 0, seriesModel.getData().count());
  59142. }
  59143. else if (isGeoCoordSys(coordSys)) {
  59144. this._renderOnGeo(
  59145. coordSys, seriesModel, visualMapOfThisSeries, api
  59146. );
  59147. }
  59148. },
  59149. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  59150. this.group.removeAll();
  59151. },
  59152. incrementalRender: function (params, seriesModel, ecModel, api) {
  59153. var coordSys = seriesModel.coordinateSystem;
  59154. if (coordSys) {
  59155. this._renderOnCartesianAndCalendar(seriesModel, api, params.start, params.end, true);
  59156. }
  59157. },
  59158. _renderOnCartesianAndCalendar: function (seriesModel, api, start, end, incremental) {
  59159. var coordSys = seriesModel.coordinateSystem;
  59160. var width;
  59161. var height;
  59162. if (coordSys.type === 'cartesian2d') {
  59163. var xAxis = coordSys.getAxis('x');
  59164. var yAxis = coordSys.getAxis('y');
  59165. if (__DEV__) {
  59166. if (!(xAxis.type === 'category' && yAxis.type === 'category')) {
  59167. throw new Error('Heatmap on cartesian must have two category axes');
  59168. }
  59169. if (!(xAxis.onBand && yAxis.onBand)) {
  59170. throw new Error('Heatmap on cartesian must have two axes with boundaryGap true');
  59171. }
  59172. }
  59173. width = xAxis.getBandWidth();
  59174. height = yAxis.getBandWidth();
  59175. }
  59176. var group = this.group;
  59177. var data = seriesModel.getData();
  59178. var itemStyleQuery = 'itemStyle';
  59179. var hoverItemStyleQuery = 'emphasis.itemStyle';
  59180. var labelQuery = 'label';
  59181. var hoverLabelQuery = 'emphasis.label';
  59182. var style = seriesModel.getModel(itemStyleQuery).getItemStyle(['color']);
  59183. var hoverStl = seriesModel.getModel(hoverItemStyleQuery).getItemStyle();
  59184. var labelModel = seriesModel.getModel(labelQuery);
  59185. var hoverLabelModel = seriesModel.getModel(hoverLabelQuery);
  59186. var coordSysType = coordSys.type;
  59187. var dataDims = coordSysType === 'cartesian2d'
  59188. ? [
  59189. data.mapDimension('x'),
  59190. data.mapDimension('y'),
  59191. data.mapDimension('value')
  59192. ]
  59193. : [
  59194. data.mapDimension('time'),
  59195. data.mapDimension('value')
  59196. ];
  59197. for (var idx = start; idx < end; idx++) {
  59198. var rect;
  59199. if (coordSysType === 'cartesian2d') {
  59200. // Ignore empty data
  59201. if (isNaN(data.get(dataDims[2], idx))) {
  59202. continue;
  59203. }
  59204. var point = coordSys.dataToPoint([
  59205. data.get(dataDims[0], idx),
  59206. data.get(dataDims[1], idx)
  59207. ]);
  59208. rect = new Rect({
  59209. shape: {
  59210. x: Math.floor(Math.round(point[0]) - width / 2),
  59211. y: Math.floor(Math.round(point[1]) - height / 2),
  59212. width: Math.ceil(width),
  59213. height: Math.ceil(height)
  59214. },
  59215. style: {
  59216. fill: data.getItemVisual(idx, 'color'),
  59217. opacity: data.getItemVisual(idx, 'opacity')
  59218. }
  59219. });
  59220. }
  59221. else {
  59222. // Ignore empty data
  59223. if (isNaN(data.get(dataDims[1], idx))) {
  59224. continue;
  59225. }
  59226. rect = new Rect({
  59227. z2: 1,
  59228. shape: coordSys.dataToRect([data.get(dataDims[0], idx)]).contentShape,
  59229. style: {
  59230. fill: data.getItemVisual(idx, 'color'),
  59231. opacity: data.getItemVisual(idx, 'opacity')
  59232. }
  59233. });
  59234. }
  59235. var itemModel = data.getItemModel(idx);
  59236. // Optimization for large datset
  59237. if (data.hasItemOption) {
  59238. style = itemModel.getModel(itemStyleQuery).getItemStyle(['color']);
  59239. hoverStl = itemModel.getModel(hoverItemStyleQuery).getItemStyle();
  59240. labelModel = itemModel.getModel(labelQuery);
  59241. hoverLabelModel = itemModel.getModel(hoverLabelQuery);
  59242. }
  59243. var rawValue = seriesModel.getRawValue(idx);
  59244. var defaultText = '-';
  59245. if (rawValue && rawValue[2] != null) {
  59246. defaultText = rawValue[2];
  59247. }
  59248. setLabelStyle(
  59249. style, hoverStl, labelModel, hoverLabelModel,
  59250. {
  59251. labelFetcher: seriesModel,
  59252. labelDataIndex: idx,
  59253. defaultText: defaultText,
  59254. isRectText: true
  59255. }
  59256. );
  59257. rect.setStyle(style);
  59258. setHoverStyle(rect, data.hasItemOption ? hoverStl : extend({}, hoverStl));
  59259. rect.incremental = incremental;
  59260. // PENDING
  59261. if (incremental) {
  59262. // Rect must use hover layer if it's incremental.
  59263. rect.useHoverLayer = true;
  59264. }
  59265. group.add(rect);
  59266. data.setItemGraphicEl(idx, rect);
  59267. }
  59268. },
  59269. _renderOnGeo: function (geo, seriesModel, visualMapModel, api) {
  59270. var inRangeVisuals = visualMapModel.targetVisuals.inRange;
  59271. var outOfRangeVisuals = visualMapModel.targetVisuals.outOfRange;
  59272. // if (!visualMapping) {
  59273. // throw new Error('Data range must have color visuals');
  59274. // }
  59275. var data = seriesModel.getData();
  59276. var hmLayer = this._hmLayer || (this._hmLayer || new Heatmap());
  59277. hmLayer.blurSize = seriesModel.get('blurSize');
  59278. hmLayer.pointSize = seriesModel.get('pointSize');
  59279. hmLayer.minOpacity = seriesModel.get('minOpacity');
  59280. hmLayer.maxOpacity = seriesModel.get('maxOpacity');
  59281. var rect = geo.getViewRect().clone();
  59282. var roamTransform = geo.getRoamTransform();
  59283. rect.applyTransform(roamTransform);
  59284. // Clamp on viewport
  59285. var x = Math.max(rect.x, 0);
  59286. var y = Math.max(rect.y, 0);
  59287. var x2 = Math.min(rect.width + rect.x, api.getWidth());
  59288. var y2 = Math.min(rect.height + rect.y, api.getHeight());
  59289. var width = x2 - x;
  59290. var height = y2 - y;
  59291. var dims = [
  59292. data.mapDimension('lng'),
  59293. data.mapDimension('lat'),
  59294. data.mapDimension('value')
  59295. ];
  59296. var points = data.mapArray(dims, function (lng, lat, value) {
  59297. var pt = geo.dataToPoint([lng, lat]);
  59298. pt[0] -= x;
  59299. pt[1] -= y;
  59300. pt.push(value);
  59301. return pt;
  59302. });
  59303. var dataExtent = visualMapModel.getExtent();
  59304. var isInRange = visualMapModel.type === 'visualMap.continuous'
  59305. ? getIsInContinuousRange(dataExtent, visualMapModel.option.range)
  59306. : getIsInPiecewiseRange(
  59307. dataExtent, visualMapModel.getPieceList(), visualMapModel.option.selected
  59308. );
  59309. hmLayer.update(
  59310. points, width, height,
  59311. inRangeVisuals.color.getNormalizer(),
  59312. {
  59313. inRange: inRangeVisuals.color.getColorMapper(),
  59314. outOfRange: outOfRangeVisuals.color.getColorMapper()
  59315. },
  59316. isInRange
  59317. );
  59318. var img = new ZImage({
  59319. style: {
  59320. width: width,
  59321. height: height,
  59322. x: x,
  59323. y: y,
  59324. image: hmLayer.canvas
  59325. },
  59326. silent: true
  59327. });
  59328. this.group.add(img);
  59329. },
  59330. dispose: function () {}
  59331. });
  59332. /*
  59333. * Licensed to the Apache Software Foundation (ASF) under one
  59334. * or more contributor license agreements. See the NOTICE file
  59335. * distributed with this work for additional information
  59336. * regarding copyright ownership. The ASF licenses this file
  59337. * to you under the Apache License, Version 2.0 (the
  59338. * "License"); you may not use this file except in compliance
  59339. * with the License. You may obtain a copy of the License at
  59340. *
  59341. * http://www.apache.org/licenses/LICENSE-2.0
  59342. *
  59343. * Unless required by applicable law or agreed to in writing,
  59344. * software distributed under the License is distributed on an
  59345. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59346. * KIND, either express or implied. See the License for the
  59347. * specific language governing permissions and limitations
  59348. * under the License.
  59349. */
  59350. /*
  59351. * Licensed to the Apache Software Foundation (ASF) under one
  59352. * or more contributor license agreements. See the NOTICE file
  59353. * distributed with this work for additional information
  59354. * regarding copyright ownership. The ASF licenses this file
  59355. * to you under the Apache License, Version 2.0 (the
  59356. * "License"); you may not use this file except in compliance
  59357. * with the License. You may obtain a copy of the License at
  59358. *
  59359. * http://www.apache.org/licenses/LICENSE-2.0
  59360. *
  59361. * Unless required by applicable law or agreed to in writing,
  59362. * software distributed under the License is distributed on an
  59363. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59364. * KIND, either express or implied. See the License for the
  59365. * specific language governing permissions and limitations
  59366. * under the License.
  59367. */
  59368. var PictorialBarSeries = BaseBarSeries.extend({
  59369. type: 'series.pictorialBar',
  59370. dependencies: ['grid'],
  59371. defaultOption: {
  59372. symbol: 'circle', // Customized bar shape
  59373. symbolSize: null, // Can be ['100%', '100%'], null means auto.
  59374. symbolRotate: null,
  59375. symbolPosition: null, // 'start' or 'end' or 'center', null means auto.
  59376. symbolOffset: null,
  59377. symbolMargin: null, // start margin and end margin. Can be a number or a percent string.
  59378. // Auto margin by defualt.
  59379. symbolRepeat: false, // false/null/undefined, means no repeat.
  59380. // Can be true, means auto calculate repeat times and cut by data.
  59381. // Can be a number, specifies repeat times, and do not cut by data.
  59382. // Can be 'fixed', means auto calculate repeat times but do not cut by data.
  59383. symbolRepeatDirection: 'end', // 'end' means from 'start' to 'end'.
  59384. symbolClip: false,
  59385. symbolBoundingData: null, // Can be 60 or -40 or [-40, 60]
  59386. symbolPatternSize: 400, // 400 * 400 px
  59387. barGap: '-100%', // In most case, overlap is needed.
  59388. // z can be set in data item, which is z2 actually.
  59389. // Disable progressive
  59390. progressive: 0,
  59391. hoverAnimation: false // Open only when needed.
  59392. },
  59393. getInitialData: function (option) {
  59394. // Disable stack.
  59395. option.stack = null;
  59396. return PictorialBarSeries.superApply(this, 'getInitialData', arguments);
  59397. }
  59398. });
  59399. /*
  59400. * Licensed to the Apache Software Foundation (ASF) under one
  59401. * or more contributor license agreements. See the NOTICE file
  59402. * distributed with this work for additional information
  59403. * regarding copyright ownership. The ASF licenses this file
  59404. * to you under the Apache License, Version 2.0 (the
  59405. * "License"); you may not use this file except in compliance
  59406. * with the License. You may obtain a copy of the License at
  59407. *
  59408. * http://www.apache.org/licenses/LICENSE-2.0
  59409. *
  59410. * Unless required by applicable law or agreed to in writing,
  59411. * software distributed under the License is distributed on an
  59412. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59413. * KIND, either express or implied. See the License for the
  59414. * specific language governing permissions and limitations
  59415. * under the License.
  59416. */
  59417. var BAR_BORDER_WIDTH_QUERY$1 = ['itemStyle', 'borderWidth'];
  59418. // index: +isHorizontal
  59419. var LAYOUT_ATTRS = [
  59420. {xy: 'x', wh: 'width', index: 0, posDesc: ['left', 'right']},
  59421. {xy: 'y', wh: 'height', index: 1, posDesc: ['top', 'bottom']}
  59422. ];
  59423. var pathForLineWidth = new Circle();
  59424. var BarView$1 = extendChartView({
  59425. type: 'pictorialBar',
  59426. render: function (seriesModel, ecModel, api) {
  59427. var group = this.group;
  59428. var data = seriesModel.getData();
  59429. var oldData = this._data;
  59430. var cartesian = seriesModel.coordinateSystem;
  59431. var baseAxis = cartesian.getBaseAxis();
  59432. var isHorizontal = !!baseAxis.isHorizontal();
  59433. var coordSysRect = cartesian.grid.getRect();
  59434. var opt = {
  59435. ecSize: {width: api.getWidth(), height: api.getHeight()},
  59436. seriesModel: seriesModel,
  59437. coordSys: cartesian,
  59438. coordSysExtent: [
  59439. [coordSysRect.x, coordSysRect.x + coordSysRect.width],
  59440. [coordSysRect.y, coordSysRect.y + coordSysRect.height]
  59441. ],
  59442. isHorizontal: isHorizontal,
  59443. valueDim: LAYOUT_ATTRS[+isHorizontal],
  59444. categoryDim: LAYOUT_ATTRS[1 - isHorizontal]
  59445. };
  59446. data.diff(oldData)
  59447. .add(function (dataIndex) {
  59448. if (!data.hasValue(dataIndex)) {
  59449. return;
  59450. }
  59451. var itemModel = getItemModel(data, dataIndex);
  59452. var symbolMeta = getSymbolMeta(data, dataIndex, itemModel, opt);
  59453. var bar = createBar(data, opt, symbolMeta);
  59454. data.setItemGraphicEl(dataIndex, bar);
  59455. group.add(bar);
  59456. updateCommon$1(bar, opt, symbolMeta);
  59457. })
  59458. .update(function (newIndex, oldIndex) {
  59459. var bar = oldData.getItemGraphicEl(oldIndex);
  59460. if (!data.hasValue(newIndex)) {
  59461. group.remove(bar);
  59462. return;
  59463. }
  59464. var itemModel = getItemModel(data, newIndex);
  59465. var symbolMeta = getSymbolMeta(data, newIndex, itemModel, opt);
  59466. var pictorialShapeStr = getShapeStr(data, symbolMeta);
  59467. if (bar && pictorialShapeStr !== bar.__pictorialShapeStr) {
  59468. group.remove(bar);
  59469. data.setItemGraphicEl(newIndex, null);
  59470. bar = null;
  59471. }
  59472. if (bar) {
  59473. updateBar(bar, opt, symbolMeta);
  59474. }
  59475. else {
  59476. bar = createBar(data, opt, symbolMeta, true);
  59477. }
  59478. data.setItemGraphicEl(newIndex, bar);
  59479. bar.__pictorialSymbolMeta = symbolMeta;
  59480. // Add back
  59481. group.add(bar);
  59482. updateCommon$1(bar, opt, symbolMeta);
  59483. })
  59484. .remove(function (dataIndex) {
  59485. var bar = oldData.getItemGraphicEl(dataIndex);
  59486. bar && removeBar(oldData, dataIndex, bar.__pictorialSymbolMeta.animationModel, bar);
  59487. })
  59488. .execute();
  59489. this._data = data;
  59490. return this.group;
  59491. },
  59492. dispose: noop,
  59493. remove: function (ecModel, api) {
  59494. var group = this.group;
  59495. var data = this._data;
  59496. if (ecModel.get('animation')) {
  59497. if (data) {
  59498. data.eachItemGraphicEl(function (bar) {
  59499. removeBar(data, bar.dataIndex, ecModel, bar);
  59500. });
  59501. }
  59502. }
  59503. else {
  59504. group.removeAll();
  59505. }
  59506. }
  59507. });
  59508. // Set or calculate default value about symbol, and calculate layout info.
  59509. function getSymbolMeta(data, dataIndex, itemModel, opt) {
  59510. var layout = data.getItemLayout(dataIndex);
  59511. var symbolRepeat = itemModel.get('symbolRepeat');
  59512. var symbolClip = itemModel.get('symbolClip');
  59513. var symbolPosition = itemModel.get('symbolPosition') || 'start';
  59514. var symbolRotate = itemModel.get('symbolRotate');
  59515. var rotation = (symbolRotate || 0) * Math.PI / 180 || 0;
  59516. var symbolPatternSize = itemModel.get('symbolPatternSize') || 2;
  59517. var isAnimationEnabled = itemModel.isAnimationEnabled();
  59518. var symbolMeta = {
  59519. dataIndex: dataIndex,
  59520. layout: layout,
  59521. itemModel: itemModel,
  59522. symbolType: data.getItemVisual(dataIndex, 'symbol') || 'circle',
  59523. color: data.getItemVisual(dataIndex, 'color'),
  59524. symbolClip: symbolClip,
  59525. symbolRepeat: symbolRepeat,
  59526. symbolRepeatDirection: itemModel.get('symbolRepeatDirection'),
  59527. symbolPatternSize: symbolPatternSize,
  59528. rotation: rotation,
  59529. animationModel: isAnimationEnabled ? itemModel : null,
  59530. hoverAnimation: isAnimationEnabled && itemModel.get('hoverAnimation'),
  59531. z2: itemModel.getShallow('z', true) || 0
  59532. };
  59533. prepareBarLength(itemModel, symbolRepeat, layout, opt, symbolMeta);
  59534. prepareSymbolSize(
  59535. data, dataIndex, layout, symbolRepeat, symbolClip, symbolMeta.boundingLength,
  59536. symbolMeta.pxSign, symbolPatternSize, opt, symbolMeta
  59537. );
  59538. prepareLineWidth(itemModel, symbolMeta.symbolScale, rotation, opt, symbolMeta);
  59539. var symbolSize = symbolMeta.symbolSize;
  59540. var symbolOffset = itemModel.get('symbolOffset');
  59541. if (isArray(symbolOffset)) {
  59542. symbolOffset = [
  59543. parsePercent$1(symbolOffset[0], symbolSize[0]),
  59544. parsePercent$1(symbolOffset[1], symbolSize[1])
  59545. ];
  59546. }
  59547. prepareLayoutInfo(
  59548. itemModel, symbolSize, layout, symbolRepeat, symbolClip, symbolOffset,
  59549. symbolPosition, symbolMeta.valueLineWidth, symbolMeta.boundingLength, symbolMeta.repeatCutLength,
  59550. opt, symbolMeta
  59551. );
  59552. return symbolMeta;
  59553. }
  59554. // bar length can be negative.
  59555. function prepareBarLength(itemModel, symbolRepeat, layout, opt, output) {
  59556. var valueDim = opt.valueDim;
  59557. var symbolBoundingData = itemModel.get('symbolBoundingData');
  59558. var valueAxis = opt.coordSys.getOtherAxis(opt.coordSys.getBaseAxis());
  59559. var zeroPx = valueAxis.toGlobalCoord(valueAxis.dataToCoord(0));
  59560. var pxSignIdx = 1 - +(layout[valueDim.wh] <= 0);
  59561. var boundingLength;
  59562. if (isArray(symbolBoundingData)) {
  59563. var symbolBoundingExtent = [
  59564. convertToCoordOnAxis(valueAxis, symbolBoundingData[0]) - zeroPx,
  59565. convertToCoordOnAxis(valueAxis, symbolBoundingData[1]) - zeroPx
  59566. ];
  59567. symbolBoundingExtent[1] < symbolBoundingExtent[0] && (symbolBoundingExtent.reverse());
  59568. boundingLength = symbolBoundingExtent[pxSignIdx];
  59569. }
  59570. else if (symbolBoundingData != null) {
  59571. boundingLength = convertToCoordOnAxis(valueAxis, symbolBoundingData) - zeroPx;
  59572. }
  59573. else if (symbolRepeat) {
  59574. boundingLength = opt.coordSysExtent[valueDim.index][pxSignIdx] - zeroPx;
  59575. }
  59576. else {
  59577. boundingLength = layout[valueDim.wh];
  59578. }
  59579. output.boundingLength = boundingLength;
  59580. if (symbolRepeat) {
  59581. output.repeatCutLength = layout[valueDim.wh];
  59582. }
  59583. output.pxSign = boundingLength > 0 ? 1 : boundingLength < 0 ? -1 : 0;
  59584. }
  59585. function convertToCoordOnAxis(axis, value) {
  59586. return axis.toGlobalCoord(axis.dataToCoord(axis.scale.parse(value)));
  59587. }
  59588. // Support ['100%', '100%']
  59589. function prepareSymbolSize(
  59590. data, dataIndex, layout, symbolRepeat, symbolClip, boundingLength,
  59591. pxSign, symbolPatternSize, opt, output
  59592. ) {
  59593. var valueDim = opt.valueDim;
  59594. var categoryDim = opt.categoryDim;
  59595. var categorySize = Math.abs(layout[categoryDim.wh]);
  59596. var symbolSize = data.getItemVisual(dataIndex, 'symbolSize');
  59597. if (isArray(symbolSize)) {
  59598. symbolSize = symbolSize.slice();
  59599. }
  59600. else {
  59601. if (symbolSize == null) {
  59602. symbolSize = '100%';
  59603. }
  59604. symbolSize = [symbolSize, symbolSize];
  59605. }
  59606. // Note: percentage symbolSize (like '100%') do not consider lineWidth, because it is
  59607. // to complicated to calculate real percent value if considering scaled lineWidth.
  59608. // So the actual size will bigger than layout size if lineWidth is bigger than zero,
  59609. // which can be tolerated in pictorial chart.
  59610. symbolSize[categoryDim.index] = parsePercent$1(
  59611. symbolSize[categoryDim.index],
  59612. categorySize
  59613. );
  59614. symbolSize[valueDim.index] = parsePercent$1(
  59615. symbolSize[valueDim.index],
  59616. symbolRepeat ? categorySize : Math.abs(boundingLength)
  59617. );
  59618. output.symbolSize = symbolSize;
  59619. // If x or y is less than zero, show reversed shape.
  59620. var symbolScale = output.symbolScale = [
  59621. symbolSize[0] / symbolPatternSize,
  59622. symbolSize[1] / symbolPatternSize
  59623. ];
  59624. // Follow convention, 'right' and 'top' is the normal scale.
  59625. symbolScale[valueDim.index] *= (opt.isHorizontal ? -1 : 1) * pxSign;
  59626. }
  59627. function prepareLineWidth(itemModel, symbolScale, rotation, opt, output) {
  59628. // In symbols are drawn with scale, so do not need to care about the case that width
  59629. // or height are too small. But symbol use strokeNoScale, where acture lineWidth should
  59630. // be calculated.
  59631. var valueLineWidth = itemModel.get(BAR_BORDER_WIDTH_QUERY$1) || 0;
  59632. if (valueLineWidth) {
  59633. pathForLineWidth.attr({
  59634. scale: symbolScale.slice(),
  59635. rotation: rotation
  59636. });
  59637. pathForLineWidth.updateTransform();
  59638. valueLineWidth /= pathForLineWidth.getLineScale();
  59639. valueLineWidth *= symbolScale[opt.valueDim.index];
  59640. }
  59641. output.valueLineWidth = valueLineWidth;
  59642. }
  59643. function prepareLayoutInfo(
  59644. itemModel, symbolSize, layout, symbolRepeat, symbolClip, symbolOffset,
  59645. symbolPosition, valueLineWidth, boundingLength, repeatCutLength, opt, output
  59646. ) {
  59647. var categoryDim = opt.categoryDim;
  59648. var valueDim = opt.valueDim;
  59649. var pxSign = output.pxSign;
  59650. var unitLength = Math.max(symbolSize[valueDim.index] + valueLineWidth, 0);
  59651. var pathLen = unitLength;
  59652. // Note: rotation will not effect the layout of symbols, because user may
  59653. // want symbols to rotate on its center, which should not be translated
  59654. // when rotating.
  59655. if (symbolRepeat) {
  59656. var absBoundingLength = Math.abs(boundingLength);
  59657. var symbolMargin = retrieve(itemModel.get('symbolMargin'), '15%') + '';
  59658. var hasEndGap = false;
  59659. if (symbolMargin.lastIndexOf('!') === symbolMargin.length - 1) {
  59660. hasEndGap = true;
  59661. symbolMargin = symbolMargin.slice(0, symbolMargin.length - 1);
  59662. }
  59663. symbolMargin = parsePercent$1(symbolMargin, symbolSize[valueDim.index]);
  59664. var uLenWithMargin = Math.max(unitLength + symbolMargin * 2, 0);
  59665. // When symbol margin is less than 0, margin at both ends will be subtracted
  59666. // to ensure that all of the symbols will not be overflow the given area.
  59667. var endFix = hasEndGap ? 0 : symbolMargin * 2;
  59668. // Both final repeatTimes and final symbolMargin area calculated based on
  59669. // boundingLength.
  59670. var repeatSpecified = isNumeric(symbolRepeat);
  59671. var repeatTimes = repeatSpecified
  59672. ? symbolRepeat
  59673. : toIntTimes((absBoundingLength + endFix) / uLenWithMargin);
  59674. // Adjust calculate margin, to ensure each symbol is displayed
  59675. // entirely in the given layout area.
  59676. var mDiff = absBoundingLength - repeatTimes * unitLength;
  59677. symbolMargin = mDiff / 2 / (hasEndGap ? repeatTimes : repeatTimes - 1);
  59678. uLenWithMargin = unitLength + symbolMargin * 2;
  59679. endFix = hasEndGap ? 0 : symbolMargin * 2;
  59680. // Update repeatTimes when not all symbol will be shown.
  59681. if (!repeatSpecified && symbolRepeat !== 'fixed') {
  59682. repeatTimes = repeatCutLength
  59683. ? toIntTimes((Math.abs(repeatCutLength) + endFix) / uLenWithMargin)
  59684. : 0;
  59685. }
  59686. pathLen = repeatTimes * uLenWithMargin - endFix;
  59687. output.repeatTimes = repeatTimes;
  59688. output.symbolMargin = symbolMargin;
  59689. }
  59690. var sizeFix = pxSign * (pathLen / 2);
  59691. var pathPosition = output.pathPosition = [];
  59692. pathPosition[categoryDim.index] = layout[categoryDim.wh] / 2;
  59693. pathPosition[valueDim.index] = symbolPosition === 'start'
  59694. ? sizeFix
  59695. : symbolPosition === 'end'
  59696. ? boundingLength - sizeFix
  59697. : boundingLength / 2; // 'center'
  59698. if (symbolOffset) {
  59699. pathPosition[0] += symbolOffset[0];
  59700. pathPosition[1] += symbolOffset[1];
  59701. }
  59702. var bundlePosition = output.bundlePosition = [];
  59703. bundlePosition[categoryDim.index] = layout[categoryDim.xy];
  59704. bundlePosition[valueDim.index] = layout[valueDim.xy];
  59705. var barRectShape = output.barRectShape = extend({}, layout);
  59706. barRectShape[valueDim.wh] = pxSign * Math.max(
  59707. Math.abs(layout[valueDim.wh]), Math.abs(pathPosition[valueDim.index] + sizeFix)
  59708. );
  59709. barRectShape[categoryDim.wh] = layout[categoryDim.wh];
  59710. var clipShape = output.clipShape = {};
  59711. // Consider that symbol may be overflow layout rect.
  59712. clipShape[categoryDim.xy] = -layout[categoryDim.xy];
  59713. clipShape[categoryDim.wh] = opt.ecSize[categoryDim.wh];
  59714. clipShape[valueDim.xy] = 0;
  59715. clipShape[valueDim.wh] = layout[valueDim.wh];
  59716. }
  59717. function createPath(symbolMeta) {
  59718. var symbolPatternSize = symbolMeta.symbolPatternSize;
  59719. var path = createSymbol(
  59720. // Consider texture img, make a big size.
  59721. symbolMeta.symbolType,
  59722. -symbolPatternSize / 2,
  59723. -symbolPatternSize / 2,
  59724. symbolPatternSize,
  59725. symbolPatternSize,
  59726. symbolMeta.color
  59727. );
  59728. path.attr({
  59729. culling: true
  59730. });
  59731. path.type !== 'image' && path.setStyle({
  59732. strokeNoScale: true
  59733. });
  59734. return path;
  59735. }
  59736. function createOrUpdateRepeatSymbols(bar, opt, symbolMeta, isUpdate) {
  59737. var bundle = bar.__pictorialBundle;
  59738. var symbolSize = symbolMeta.symbolSize;
  59739. var valueLineWidth = symbolMeta.valueLineWidth;
  59740. var pathPosition = symbolMeta.pathPosition;
  59741. var valueDim = opt.valueDim;
  59742. var repeatTimes = symbolMeta.repeatTimes || 0;
  59743. var index = 0;
  59744. var unit = symbolSize[opt.valueDim.index] + valueLineWidth + symbolMeta.symbolMargin * 2;
  59745. eachPath(bar, function (path) {
  59746. path.__pictorialAnimationIndex = index;
  59747. path.__pictorialRepeatTimes = repeatTimes;
  59748. if (index < repeatTimes) {
  59749. updateAttr(path, null, makeTarget(index), symbolMeta, isUpdate);
  59750. }
  59751. else {
  59752. updateAttr(path, null, {scale: [0, 0]}, symbolMeta, isUpdate, function () {
  59753. bundle.remove(path);
  59754. });
  59755. }
  59756. updateHoverAnimation(path, symbolMeta);
  59757. index++;
  59758. });
  59759. for (; index < repeatTimes; index++) {
  59760. var path = createPath(symbolMeta);
  59761. path.__pictorialAnimationIndex = index;
  59762. path.__pictorialRepeatTimes = repeatTimes;
  59763. bundle.add(path);
  59764. var target = makeTarget(index);
  59765. updateAttr(
  59766. path,
  59767. {
  59768. position: target.position,
  59769. scale: [0, 0]
  59770. },
  59771. {
  59772. scale: target.scale,
  59773. rotation: target.rotation
  59774. },
  59775. symbolMeta,
  59776. isUpdate
  59777. );
  59778. // FIXME
  59779. // If all emphasis/normal through action.
  59780. path
  59781. .on('mouseover', onMouseOver)
  59782. .on('mouseout', onMouseOut);
  59783. updateHoverAnimation(path, symbolMeta);
  59784. }
  59785. function makeTarget(index) {
  59786. var position = pathPosition.slice();
  59787. // (start && pxSign > 0) || (end && pxSign < 0): i = repeatTimes - index
  59788. // Otherwise: i = index;
  59789. var pxSign = symbolMeta.pxSign;
  59790. var i = index;
  59791. if (symbolMeta.symbolRepeatDirection === 'start' ? pxSign > 0 : pxSign < 0) {
  59792. i = repeatTimes - 1 - index;
  59793. }
  59794. position[valueDim.index] = unit * (i - repeatTimes / 2 + 0.5) + pathPosition[valueDim.index];
  59795. return {
  59796. position: position,
  59797. scale: symbolMeta.symbolScale.slice(),
  59798. rotation: symbolMeta.rotation
  59799. };
  59800. }
  59801. function onMouseOver() {
  59802. eachPath(bar, function (path) {
  59803. path.trigger('emphasis');
  59804. });
  59805. }
  59806. function onMouseOut() {
  59807. eachPath(bar, function (path) {
  59808. path.trigger('normal');
  59809. });
  59810. }
  59811. }
  59812. function createOrUpdateSingleSymbol(bar, opt, symbolMeta, isUpdate) {
  59813. var bundle = bar.__pictorialBundle;
  59814. var mainPath = bar.__pictorialMainPath;
  59815. if (!mainPath) {
  59816. mainPath = bar.__pictorialMainPath = createPath(symbolMeta);
  59817. bundle.add(mainPath);
  59818. updateAttr(
  59819. mainPath,
  59820. {
  59821. position: symbolMeta.pathPosition.slice(),
  59822. scale: [0, 0],
  59823. rotation: symbolMeta.rotation
  59824. },
  59825. {
  59826. scale: symbolMeta.symbolScale.slice()
  59827. },
  59828. symbolMeta,
  59829. isUpdate
  59830. );
  59831. mainPath
  59832. .on('mouseover', onMouseOver)
  59833. .on('mouseout', onMouseOut);
  59834. }
  59835. else {
  59836. updateAttr(
  59837. mainPath,
  59838. null,
  59839. {
  59840. position: symbolMeta.pathPosition.slice(),
  59841. scale: symbolMeta.symbolScale.slice(),
  59842. rotation: symbolMeta.rotation
  59843. },
  59844. symbolMeta,
  59845. isUpdate
  59846. );
  59847. }
  59848. updateHoverAnimation(mainPath, symbolMeta);
  59849. function onMouseOver() {
  59850. this.trigger('emphasis');
  59851. }
  59852. function onMouseOut() {
  59853. this.trigger('normal');
  59854. }
  59855. }
  59856. // bar rect is used for label.
  59857. function createOrUpdateBarRect(bar, symbolMeta, isUpdate) {
  59858. var rectShape = extend({}, symbolMeta.barRectShape);
  59859. var barRect = bar.__pictorialBarRect;
  59860. if (!barRect) {
  59861. barRect = bar.__pictorialBarRect = new Rect({
  59862. z2: 2,
  59863. shape: rectShape,
  59864. silent: true,
  59865. style: {
  59866. stroke: 'transparent',
  59867. fill: 'transparent',
  59868. lineWidth: 0
  59869. }
  59870. });
  59871. bar.add(barRect);
  59872. }
  59873. else {
  59874. updateAttr(barRect, null, {shape: rectShape}, symbolMeta, isUpdate);
  59875. }
  59876. }
  59877. function createOrUpdateClip(bar, opt, symbolMeta, isUpdate) {
  59878. // If not clip, symbol will be remove and rebuilt.
  59879. if (symbolMeta.symbolClip) {
  59880. var clipPath = bar.__pictorialClipPath;
  59881. var clipShape = extend({}, symbolMeta.clipShape);
  59882. var valueDim = opt.valueDim;
  59883. var animationModel = symbolMeta.animationModel;
  59884. var dataIndex = symbolMeta.dataIndex;
  59885. if (clipPath) {
  59886. updateProps(
  59887. clipPath, {shape: clipShape}, animationModel, dataIndex
  59888. );
  59889. }
  59890. else {
  59891. clipShape[valueDim.wh] = 0;
  59892. clipPath = new Rect({shape: clipShape});
  59893. bar.__pictorialBundle.setClipPath(clipPath);
  59894. bar.__pictorialClipPath = clipPath;
  59895. var target = {};
  59896. target[valueDim.wh] = symbolMeta.clipShape[valueDim.wh];
  59897. graphic[isUpdate ? 'updateProps' : 'initProps'](
  59898. clipPath, {shape: target}, animationModel, dataIndex
  59899. );
  59900. }
  59901. }
  59902. }
  59903. function getItemModel(data, dataIndex) {
  59904. var itemModel = data.getItemModel(dataIndex);
  59905. itemModel.getAnimationDelayParams = getAnimationDelayParams;
  59906. itemModel.isAnimationEnabled = isAnimationEnabled;
  59907. return itemModel;
  59908. }
  59909. function getAnimationDelayParams(path) {
  59910. // The order is the same as the z-order, see `symbolRepeatDiretion`.
  59911. return {
  59912. index: path.__pictorialAnimationIndex,
  59913. count: path.__pictorialRepeatTimes
  59914. };
  59915. }
  59916. function isAnimationEnabled() {
  59917. // `animation` prop can be set on itemModel in pictorial bar chart.
  59918. return this.parentModel.isAnimationEnabled() && !!this.getShallow('animation');
  59919. }
  59920. function updateHoverAnimation(path, symbolMeta) {
  59921. path.off('emphasis').off('normal');
  59922. var scale = symbolMeta.symbolScale.slice();
  59923. symbolMeta.hoverAnimation && path
  59924. .on('emphasis', function () {
  59925. this.animateTo({
  59926. scale: [scale[0] * 1.1, scale[1] * 1.1]
  59927. }, 400, 'elasticOut');
  59928. })
  59929. .on('normal', function () {
  59930. this.animateTo({
  59931. scale: scale.slice()
  59932. }, 400, 'elasticOut');
  59933. });
  59934. }
  59935. function createBar(data, opt, symbolMeta, isUpdate) {
  59936. // bar is the main element for each data.
  59937. var bar = new Group();
  59938. // bundle is used for location and clip.
  59939. var bundle = new Group();
  59940. bar.add(bundle);
  59941. bar.__pictorialBundle = bundle;
  59942. bundle.attr('position', symbolMeta.bundlePosition.slice());
  59943. if (symbolMeta.symbolRepeat) {
  59944. createOrUpdateRepeatSymbols(bar, opt, symbolMeta);
  59945. }
  59946. else {
  59947. createOrUpdateSingleSymbol(bar, opt, symbolMeta);
  59948. }
  59949. createOrUpdateBarRect(bar, symbolMeta, isUpdate);
  59950. createOrUpdateClip(bar, opt, symbolMeta, isUpdate);
  59951. bar.__pictorialShapeStr = getShapeStr(data, symbolMeta);
  59952. bar.__pictorialSymbolMeta = symbolMeta;
  59953. return bar;
  59954. }
  59955. function updateBar(bar, opt, symbolMeta) {
  59956. var animationModel = symbolMeta.animationModel;
  59957. var dataIndex = symbolMeta.dataIndex;
  59958. var bundle = bar.__pictorialBundle;
  59959. updateProps(
  59960. bundle, {position: symbolMeta.bundlePosition.slice()}, animationModel, dataIndex
  59961. );
  59962. if (symbolMeta.symbolRepeat) {
  59963. createOrUpdateRepeatSymbols(bar, opt, symbolMeta, true);
  59964. }
  59965. else {
  59966. createOrUpdateSingleSymbol(bar, opt, symbolMeta, true);
  59967. }
  59968. createOrUpdateBarRect(bar, symbolMeta, true);
  59969. createOrUpdateClip(bar, opt, symbolMeta, true);
  59970. }
  59971. function removeBar(data, dataIndex, animationModel, bar) {
  59972. // Not show text when animating
  59973. var labelRect = bar.__pictorialBarRect;
  59974. labelRect && (labelRect.style.text = null);
  59975. var pathes = [];
  59976. eachPath(bar, function (path) {
  59977. pathes.push(path);
  59978. });
  59979. bar.__pictorialMainPath && pathes.push(bar.__pictorialMainPath);
  59980. // I do not find proper remove animation for clip yet.
  59981. bar.__pictorialClipPath && (animationModel = null);
  59982. each$1(pathes, function (path) {
  59983. updateProps(
  59984. path, {scale: [0, 0]}, animationModel, dataIndex,
  59985. function () {
  59986. bar.parent && bar.parent.remove(bar);
  59987. }
  59988. );
  59989. });
  59990. data.setItemGraphicEl(dataIndex, null);
  59991. }
  59992. function getShapeStr(data, symbolMeta) {
  59993. return [
  59994. data.getItemVisual(symbolMeta.dataIndex, 'symbol') || 'none',
  59995. !!symbolMeta.symbolRepeat,
  59996. !!symbolMeta.symbolClip
  59997. ].join(':');
  59998. }
  59999. function eachPath(bar, cb, context) {
  60000. // Do not use Group#eachChild, because it do not support remove.
  60001. each$1(bar.__pictorialBundle.children(), function (el) {
  60002. el !== bar.__pictorialBarRect && cb.call(context, el);
  60003. });
  60004. }
  60005. function updateAttr(el, immediateAttrs, animationAttrs, symbolMeta, isUpdate, cb) {
  60006. immediateAttrs && el.attr(immediateAttrs);
  60007. // when symbolCip used, only clip path has init animation, otherwise it would be weird effect.
  60008. if (symbolMeta.symbolClip && !isUpdate) {
  60009. animationAttrs && el.attr(animationAttrs);
  60010. }
  60011. else {
  60012. animationAttrs && graphic[isUpdate ? 'updateProps' : 'initProps'](
  60013. el, animationAttrs, symbolMeta.animationModel, symbolMeta.dataIndex, cb
  60014. );
  60015. }
  60016. }
  60017. function updateCommon$1(bar, opt, symbolMeta) {
  60018. var color = symbolMeta.color;
  60019. var dataIndex = symbolMeta.dataIndex;
  60020. var itemModel = symbolMeta.itemModel;
  60021. // Color must be excluded.
  60022. // Because symbol provide setColor individually to set fill and stroke
  60023. var normalStyle = itemModel.getModel('itemStyle').getItemStyle(['color']);
  60024. var hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  60025. var cursorStyle = itemModel.getShallow('cursor');
  60026. eachPath(bar, function (path) {
  60027. // PENDING setColor should be before setStyle!!!
  60028. path.setColor(color);
  60029. path.setStyle(defaults(
  60030. {
  60031. fill: color,
  60032. opacity: symbolMeta.opacity
  60033. },
  60034. normalStyle
  60035. ));
  60036. setHoverStyle(path, hoverStyle);
  60037. cursorStyle && (path.cursor = cursorStyle);
  60038. path.z2 = symbolMeta.z2;
  60039. });
  60040. var barRectHoverStyle = {};
  60041. var barPositionOutside = opt.valueDim.posDesc[+(symbolMeta.boundingLength > 0)];
  60042. var barRect = bar.__pictorialBarRect;
  60043. setLabel(
  60044. barRect.style, barRectHoverStyle, itemModel,
  60045. color, opt.seriesModel, dataIndex, barPositionOutside
  60046. );
  60047. setHoverStyle(barRect, barRectHoverStyle);
  60048. }
  60049. function toIntTimes(times) {
  60050. var roundedTimes = Math.round(times);
  60051. // Escapse accurate error
  60052. return Math.abs(times - roundedTimes) < 1e-4
  60053. ? roundedTimes
  60054. : Math.ceil(times);
  60055. }
  60056. /*
  60057. * Licensed to the Apache Software Foundation (ASF) under one
  60058. * or more contributor license agreements. See the NOTICE file
  60059. * distributed with this work for additional information
  60060. * regarding copyright ownership. The ASF licenses this file
  60061. * to you under the Apache License, Version 2.0 (the
  60062. * "License"); you may not use this file except in compliance
  60063. * with the License. You may obtain a copy of the License at
  60064. *
  60065. * http://www.apache.org/licenses/LICENSE-2.0
  60066. *
  60067. * Unless required by applicable law or agreed to in writing,
  60068. * software distributed under the License is distributed on an
  60069. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60070. * KIND, either express or implied. See the License for the
  60071. * specific language governing permissions and limitations
  60072. * under the License.
  60073. */
  60074. // In case developer forget to include grid component
  60075. registerLayout(curry(
  60076. layout, 'pictorialBar'
  60077. ));
  60078. registerVisual(visualSymbol('pictorialBar', 'roundRect'));
  60079. /*
  60080. * Licensed to the Apache Software Foundation (ASF) under one
  60081. * or more contributor license agreements. See the NOTICE file
  60082. * distributed with this work for additional information
  60083. * regarding copyright ownership. The ASF licenses this file
  60084. * to you under the Apache License, Version 2.0 (the
  60085. * "License"); you may not use this file except in compliance
  60086. * with the License. You may obtain a copy of the License at
  60087. *
  60088. * http://www.apache.org/licenses/LICENSE-2.0
  60089. *
  60090. * Unless required by applicable law or agreed to in writing,
  60091. * software distributed under the License is distributed on an
  60092. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60093. * KIND, either express or implied. See the License for the
  60094. * specific language governing permissions and limitations
  60095. * under the License.
  60096. */
  60097. /**
  60098. * @constructor module:echarts/coord/single/SingleAxis
  60099. * @extends {module:echarts/coord/Axis}
  60100. * @param {string} dim
  60101. * @param {*} scale
  60102. * @param {Array.<number>} coordExtent
  60103. * @param {string} axisType
  60104. * @param {string} position
  60105. */
  60106. var SingleAxis = function (dim, scale, coordExtent, axisType, position) {
  60107. Axis.call(this, dim, scale, coordExtent);
  60108. /**
  60109. * Axis type
  60110. * - 'category'
  60111. * - 'value'
  60112. * - 'time'
  60113. * - 'log'
  60114. * @type {string}
  60115. */
  60116. this.type = axisType || 'value';
  60117. /**
  60118. * Axis position
  60119. * - 'top'
  60120. * - 'bottom'
  60121. * - 'left'
  60122. * - 'right'
  60123. * @type {string}
  60124. */
  60125. this.position = position || 'bottom';
  60126. /**
  60127. * Axis orient
  60128. * - 'horizontal'
  60129. * - 'vertical'
  60130. * @type {[type]}
  60131. */
  60132. this.orient = null;
  60133. };
  60134. SingleAxis.prototype = {
  60135. constructor: SingleAxis,
  60136. /**
  60137. * Axis model
  60138. * @type {module:echarts/coord/single/AxisModel}
  60139. */
  60140. model: null,
  60141. /**
  60142. * Judge the orient of the axis.
  60143. * @return {boolean}
  60144. */
  60145. isHorizontal: function () {
  60146. var position = this.position;
  60147. return position === 'top' || position === 'bottom';
  60148. },
  60149. /**
  60150. * @override
  60151. */
  60152. pointToData: function (point, clamp) {
  60153. return this.coordinateSystem.pointToData(point, clamp)[0];
  60154. },
  60155. /**
  60156. * Convert the local coord(processed by dataToCoord())
  60157. * to global coord(concrete pixel coord).
  60158. * designated by module:echarts/coord/single/Single.
  60159. * @type {Function}
  60160. */
  60161. toGlobalCoord: null,
  60162. /**
  60163. * Convert the global coord to local coord.
  60164. * designated by module:echarts/coord/single/Single.
  60165. * @type {Function}
  60166. */
  60167. toLocalCoord: null
  60168. };
  60169. inherits(SingleAxis, Axis);
  60170. /*
  60171. * Licensed to the Apache Software Foundation (ASF) under one
  60172. * or more contributor license agreements. See the NOTICE file
  60173. * distributed with this work for additional information
  60174. * regarding copyright ownership. The ASF licenses this file
  60175. * to you under the Apache License, Version 2.0 (the
  60176. * "License"); you may not use this file except in compliance
  60177. * with the License. You may obtain a copy of the License at
  60178. *
  60179. * http://www.apache.org/licenses/LICENSE-2.0
  60180. *
  60181. * Unless required by applicable law or agreed to in writing,
  60182. * software distributed under the License is distributed on an
  60183. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60184. * KIND, either express or implied. See the License for the
  60185. * specific language governing permissions and limitations
  60186. * under the License.
  60187. */
  60188. /**
  60189. * Single coordinates system.
  60190. */
  60191. /**
  60192. * Create a single coordinates system.
  60193. *
  60194. * @param {module:echarts/coord/single/AxisModel} axisModel
  60195. * @param {module:echarts/model/Global} ecModel
  60196. * @param {module:echarts/ExtensionAPI} api
  60197. */
  60198. function Single(axisModel, ecModel, api) {
  60199. /**
  60200. * @type {string}
  60201. * @readOnly
  60202. */
  60203. this.dimension = 'single';
  60204. /**
  60205. * Add it just for draw tooltip.
  60206. *
  60207. * @type {Array.<string>}
  60208. * @readOnly
  60209. */
  60210. this.dimensions = ['single'];
  60211. /**
  60212. * @private
  60213. * @type {module:echarts/coord/single/SingleAxis}.
  60214. */
  60215. this._axis = null;
  60216. /**
  60217. * @private
  60218. * @type {module:zrender/core/BoundingRect}
  60219. */
  60220. this._rect;
  60221. this._init(axisModel, ecModel, api);
  60222. /**
  60223. * @type {module:echarts/coord/single/AxisModel}
  60224. */
  60225. this.model = axisModel;
  60226. }
  60227. Single.prototype = {
  60228. type: 'singleAxis',
  60229. axisPointerEnabled: true,
  60230. constructor: Single,
  60231. /**
  60232. * Initialize single coordinate system.
  60233. *
  60234. * @param {module:echarts/coord/single/AxisModel} axisModel
  60235. * @param {module:echarts/model/Global} ecModel
  60236. * @param {module:echarts/ExtensionAPI} api
  60237. * @private
  60238. */
  60239. _init: function (axisModel, ecModel, api) {
  60240. var dim = this.dimension;
  60241. var axis = new SingleAxis(
  60242. dim,
  60243. createScaleByModel(axisModel),
  60244. [0, 0],
  60245. axisModel.get('type'),
  60246. axisModel.get('position')
  60247. );
  60248. var isCategory = axis.type === 'category';
  60249. axis.onBand = isCategory && axisModel.get('boundaryGap');
  60250. axis.inverse = axisModel.get('inverse');
  60251. axis.orient = axisModel.get('orient');
  60252. axisModel.axis = axis;
  60253. axis.model = axisModel;
  60254. axis.coordinateSystem = this;
  60255. this._axis = axis;
  60256. },
  60257. /**
  60258. * Update axis scale after data processed
  60259. * @param {module:echarts/model/Global} ecModel
  60260. * @param {module:echarts/ExtensionAPI} api
  60261. */
  60262. update: function (ecModel, api) {
  60263. ecModel.eachSeries(function (seriesModel) {
  60264. if (seriesModel.coordinateSystem === this) {
  60265. var data = seriesModel.getData();
  60266. each$1(data.mapDimension(this.dimension, true), function (dim) {
  60267. this._axis.scale.unionExtentFromData(data, dim);
  60268. }, this);
  60269. niceScaleExtent(this._axis.scale, this._axis.model);
  60270. }
  60271. }, this);
  60272. },
  60273. /**
  60274. * Resize the single coordinate system.
  60275. *
  60276. * @param {module:echarts/coord/single/AxisModel} axisModel
  60277. * @param {module:echarts/ExtensionAPI} api
  60278. */
  60279. resize: function (axisModel, api) {
  60280. this._rect = getLayoutRect(
  60281. {
  60282. left: axisModel.get('left'),
  60283. top: axisModel.get('top'),
  60284. right: axisModel.get('right'),
  60285. bottom: axisModel.get('bottom'),
  60286. width: axisModel.get('width'),
  60287. height: axisModel.get('height')
  60288. },
  60289. {
  60290. width: api.getWidth(),
  60291. height: api.getHeight()
  60292. }
  60293. );
  60294. this._adjustAxis();
  60295. },
  60296. /**
  60297. * @return {module:zrender/core/BoundingRect}
  60298. */
  60299. getRect: function () {
  60300. return this._rect;
  60301. },
  60302. /**
  60303. * @private
  60304. */
  60305. _adjustAxis: function () {
  60306. var rect = this._rect;
  60307. var axis = this._axis;
  60308. var isHorizontal = axis.isHorizontal();
  60309. var extent = isHorizontal ? [0, rect.width] : [0, rect.height];
  60310. var idx = axis.reverse ? 1 : 0;
  60311. axis.setExtent(extent[idx], extent[1 - idx]);
  60312. this._updateAxisTransform(axis, isHorizontal ? rect.x : rect.y);
  60313. },
  60314. /**
  60315. * @param {module:echarts/coord/single/SingleAxis} axis
  60316. * @param {number} coordBase
  60317. */
  60318. _updateAxisTransform: function (axis, coordBase) {
  60319. var axisExtent = axis.getExtent();
  60320. var extentSum = axisExtent[0] + axisExtent[1];
  60321. var isHorizontal = axis.isHorizontal();
  60322. axis.toGlobalCoord = isHorizontal
  60323. ? function (coord) {
  60324. return coord + coordBase;
  60325. }
  60326. : function (coord) {
  60327. return extentSum - coord + coordBase;
  60328. };
  60329. axis.toLocalCoord = isHorizontal
  60330. ? function (coord) {
  60331. return coord - coordBase;
  60332. }
  60333. : function (coord) {
  60334. return extentSum - coord + coordBase;
  60335. };
  60336. },
  60337. /**
  60338. * Get axis.
  60339. *
  60340. * @return {module:echarts/coord/single/SingleAxis}
  60341. */
  60342. getAxis: function () {
  60343. return this._axis;
  60344. },
  60345. /**
  60346. * Get axis, add it just for draw tooltip.
  60347. *
  60348. * @return {[type]} [description]
  60349. */
  60350. getBaseAxis: function () {
  60351. return this._axis;
  60352. },
  60353. /**
  60354. * @return {Array.<module:echarts/coord/Axis>}
  60355. */
  60356. getAxes: function () {
  60357. return [this._axis];
  60358. },
  60359. /**
  60360. * @return {Object} {baseAxes: [], otherAxes: []}
  60361. */
  60362. getTooltipAxes: function () {
  60363. return {baseAxes: [this.getAxis()]};
  60364. },
  60365. /**
  60366. * If contain point.
  60367. *
  60368. * @param {Array.<number>} point
  60369. * @return {boolean}
  60370. */
  60371. containPoint: function (point) {
  60372. var rect = this.getRect();
  60373. var axis = this.getAxis();
  60374. var orient = axis.orient;
  60375. if (orient === 'horizontal') {
  60376. return axis.contain(axis.toLocalCoord(point[0]))
  60377. && (point[1] >= rect.y && point[1] <= (rect.y + rect.height));
  60378. }
  60379. else {
  60380. return axis.contain(axis.toLocalCoord(point[1]))
  60381. && (point[0] >= rect.y && point[0] <= (rect.y + rect.height));
  60382. }
  60383. },
  60384. /**
  60385. * @param {Array.<number>} point
  60386. * @return {Array.<number>}
  60387. */
  60388. pointToData: function (point) {
  60389. var axis = this.getAxis();
  60390. return [axis.coordToData(axis.toLocalCoord(
  60391. point[axis.orient === 'horizontal' ? 0 : 1]
  60392. ))];
  60393. },
  60394. /**
  60395. * Convert the series data to concrete point.
  60396. *
  60397. * @param {number|Array.<number>} val
  60398. * @return {Array.<number>}
  60399. */
  60400. dataToPoint: function (val) {
  60401. var axis = this.getAxis();
  60402. var rect = this.getRect();
  60403. var pt = [];
  60404. var idx = axis.orient === 'horizontal' ? 0 : 1;
  60405. if (val instanceof Array) {
  60406. val = val[0];
  60407. }
  60408. pt[idx] = axis.toGlobalCoord(axis.dataToCoord(+val));
  60409. pt[1 - idx] = idx === 0 ? (rect.y + rect.height / 2) : (rect.x + rect.width / 2);
  60410. return pt;
  60411. }
  60412. };
  60413. /*
  60414. * Licensed to the Apache Software Foundation (ASF) under one
  60415. * or more contributor license agreements. See the NOTICE file
  60416. * distributed with this work for additional information
  60417. * regarding copyright ownership. The ASF licenses this file
  60418. * to you under the Apache License, Version 2.0 (the
  60419. * "License"); you may not use this file except in compliance
  60420. * with the License. You may obtain a copy of the License at
  60421. *
  60422. * http://www.apache.org/licenses/LICENSE-2.0
  60423. *
  60424. * Unless required by applicable law or agreed to in writing,
  60425. * software distributed under the License is distributed on an
  60426. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60427. * KIND, either express or implied. See the License for the
  60428. * specific language governing permissions and limitations
  60429. * under the License.
  60430. */
  60431. /**
  60432. * Single coordinate system creator.
  60433. */
  60434. /**
  60435. * Create single coordinate system and inject it into seriesModel.
  60436. *
  60437. * @param {module:echarts/model/Global} ecModel
  60438. * @param {module:echarts/ExtensionAPI} api
  60439. * @return {Array.<module:echarts/coord/single/Single>}
  60440. */
  60441. function create$3(ecModel, api) {
  60442. var singles = [];
  60443. ecModel.eachComponent('singleAxis', function (axisModel, idx) {
  60444. var single = new Single(axisModel, ecModel, api);
  60445. single.name = 'single_' + idx;
  60446. single.resize(axisModel, api);
  60447. axisModel.coordinateSystem = single;
  60448. singles.push(single);
  60449. });
  60450. ecModel.eachSeries(function (seriesModel) {
  60451. if (seriesModel.get('coordinateSystem') === 'singleAxis') {
  60452. var singleAxisModel = ecModel.queryComponents({
  60453. mainType: 'singleAxis',
  60454. index: seriesModel.get('singleAxisIndex'),
  60455. id: seriesModel.get('singleAxisId')
  60456. })[0];
  60457. seriesModel.coordinateSystem = singleAxisModel && singleAxisModel.coordinateSystem;
  60458. }
  60459. });
  60460. return singles;
  60461. }
  60462. CoordinateSystemManager.register('single', {
  60463. create: create$3,
  60464. dimensions: Single.prototype.dimensions
  60465. });
  60466. /*
  60467. * Licensed to the Apache Software Foundation (ASF) under one
  60468. * or more contributor license agreements. See the NOTICE file
  60469. * distributed with this work for additional information
  60470. * regarding copyright ownership. The ASF licenses this file
  60471. * to you under the Apache License, Version 2.0 (the
  60472. * "License"); you may not use this file except in compliance
  60473. * with the License. You may obtain a copy of the License at
  60474. *
  60475. * http://www.apache.org/licenses/LICENSE-2.0
  60476. *
  60477. * Unless required by applicable law or agreed to in writing,
  60478. * software distributed under the License is distributed on an
  60479. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60480. * KIND, either express or implied. See the License for the
  60481. * specific language governing permissions and limitations
  60482. * under the License.
  60483. */
  60484. /**
  60485. * @param {Object} opt {labelInside}
  60486. * @return {Object} {
  60487. * position, rotation, labelDirection, labelOffset,
  60488. * tickDirection, labelRotate, z2
  60489. * }
  60490. */
  60491. function layout$2(axisModel, opt) {
  60492. opt = opt || {};
  60493. var single = axisModel.coordinateSystem;
  60494. var axis = axisModel.axis;
  60495. var layout = {};
  60496. var axisPosition = axis.position;
  60497. var orient = axis.orient;
  60498. var rect = single.getRect();
  60499. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  60500. var positionMap = {
  60501. horizontal: {top: rectBound[2], bottom: rectBound[3]},
  60502. vertical: {left: rectBound[0], right: rectBound[1]}
  60503. };
  60504. layout.position = [
  60505. orient === 'vertical'
  60506. ? positionMap.vertical[axisPosition]
  60507. : rectBound[0],
  60508. orient === 'horizontal'
  60509. ? positionMap.horizontal[axisPosition]
  60510. : rectBound[3]
  60511. ];
  60512. var r = {horizontal: 0, vertical: 1};
  60513. layout.rotation = Math.PI / 2 * r[orient];
  60514. var directionMap = {top: -1, bottom: 1, right: 1, left: -1};
  60515. layout.labelDirection = layout.tickDirection =
  60516. layout.nameDirection = directionMap[axisPosition];
  60517. if (axisModel.get('axisTick.inside')) {
  60518. layout.tickDirection = -layout.tickDirection;
  60519. }
  60520. if (retrieve(opt.labelInside, axisModel.get('axisLabel.inside'))) {
  60521. layout.labelDirection = -layout.labelDirection;
  60522. }
  60523. var labelRotation = opt.rotate;
  60524. labelRotation == null && (labelRotation = axisModel.get('axisLabel.rotate'));
  60525. layout.labelRotation = axisPosition === 'top' ? -labelRotation : labelRotation;
  60526. layout.z2 = 1;
  60527. return layout;
  60528. }
  60529. /*
  60530. * Licensed to the Apache Software Foundation (ASF) under one
  60531. * or more contributor license agreements. See the NOTICE file
  60532. * distributed with this work for additional information
  60533. * regarding copyright ownership. The ASF licenses this file
  60534. * to you under the Apache License, Version 2.0 (the
  60535. * "License"); you may not use this file except in compliance
  60536. * with the License. You may obtain a copy of the License at
  60537. *
  60538. * http://www.apache.org/licenses/LICENSE-2.0
  60539. *
  60540. * Unless required by applicable law or agreed to in writing,
  60541. * software distributed under the License is distributed on an
  60542. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60543. * KIND, either express or implied. See the License for the
  60544. * specific language governing permissions and limitations
  60545. * under the License.
  60546. */
  60547. var axisBuilderAttrs$2 = [
  60548. 'axisLine', 'axisTickLabel', 'axisName'
  60549. ];
  60550. var selfBuilderAttrs$1 = ['splitArea', 'splitLine'];
  60551. var SingleAxisView = AxisView.extend({
  60552. type: 'singleAxis',
  60553. axisPointerClass: 'SingleAxisPointer',
  60554. render: function (axisModel, ecModel, api, payload) {
  60555. var group = this.group;
  60556. group.removeAll();
  60557. var oldAxisGroup = this._axisGroup;
  60558. this._axisGroup = new Group();
  60559. var layout = layout$2(axisModel);
  60560. var axisBuilder = new AxisBuilder(axisModel, layout);
  60561. each$1(axisBuilderAttrs$2, axisBuilder.add, axisBuilder);
  60562. group.add(this._axisGroup);
  60563. group.add(axisBuilder.getGroup());
  60564. each$1(selfBuilderAttrs$1, function (name) {
  60565. if (axisModel.get(name + '.show')) {
  60566. this['_' + name](axisModel);
  60567. }
  60568. }, this);
  60569. groupTransition(oldAxisGroup, this._axisGroup, axisModel);
  60570. SingleAxisView.superCall(this, 'render', axisModel, ecModel, api, payload);
  60571. },
  60572. remove: function () {
  60573. rectCoordAxisHandleRemove(this);
  60574. },
  60575. _splitLine: function (axisModel) {
  60576. var axis = axisModel.axis;
  60577. if (axis.scale.isBlank()) {
  60578. return;
  60579. }
  60580. var splitLineModel = axisModel.getModel('splitLine');
  60581. var lineStyleModel = splitLineModel.getModel('lineStyle');
  60582. var lineWidth = lineStyleModel.get('width');
  60583. var lineColors = lineStyleModel.get('color');
  60584. lineColors = lineColors instanceof Array ? lineColors : [lineColors];
  60585. var gridRect = axisModel.coordinateSystem.getRect();
  60586. var isHorizontal = axis.isHorizontal();
  60587. var splitLines = [];
  60588. var lineCount = 0;
  60589. var ticksCoords = axis.getTicksCoords({
  60590. tickModel: splitLineModel
  60591. });
  60592. var p1 = [];
  60593. var p2 = [];
  60594. for (var i = 0; i < ticksCoords.length; ++i) {
  60595. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  60596. if (isHorizontal) {
  60597. p1[0] = tickCoord;
  60598. p1[1] = gridRect.y;
  60599. p2[0] = tickCoord;
  60600. p2[1] = gridRect.y + gridRect.height;
  60601. }
  60602. else {
  60603. p1[0] = gridRect.x;
  60604. p1[1] = tickCoord;
  60605. p2[0] = gridRect.x + gridRect.width;
  60606. p2[1] = tickCoord;
  60607. }
  60608. var colorIndex = (lineCount++) % lineColors.length;
  60609. splitLines[colorIndex] = splitLines[colorIndex] || [];
  60610. splitLines[colorIndex].push(new Line({
  60611. subPixelOptimize: true,
  60612. shape: {
  60613. x1: p1[0],
  60614. y1: p1[1],
  60615. x2: p2[0],
  60616. y2: p2[1]
  60617. },
  60618. style: {
  60619. lineWidth: lineWidth
  60620. },
  60621. silent: true
  60622. }));
  60623. }
  60624. for (var i = 0; i < splitLines.length; ++i) {
  60625. this.group.add(mergePath(splitLines[i], {
  60626. style: {
  60627. stroke: lineColors[i % lineColors.length],
  60628. lineDash: lineStyleModel.getLineDash(lineWidth),
  60629. lineWidth: lineWidth
  60630. },
  60631. silent: true
  60632. }));
  60633. }
  60634. },
  60635. _splitArea: function (axisModel) {
  60636. rectCoordAxisBuildSplitArea(this, this._axisGroup, axisModel, axisModel);
  60637. }
  60638. });
  60639. /*
  60640. * Licensed to the Apache Software Foundation (ASF) under one
  60641. * or more contributor license agreements. See the NOTICE file
  60642. * distributed with this work for additional information
  60643. * regarding copyright ownership. The ASF licenses this file
  60644. * to you under the Apache License, Version 2.0 (the
  60645. * "License"); you may not use this file except in compliance
  60646. * with the License. You may obtain a copy of the License at
  60647. *
  60648. * http://www.apache.org/licenses/LICENSE-2.0
  60649. *
  60650. * Unless required by applicable law or agreed to in writing,
  60651. * software distributed under the License is distributed on an
  60652. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60653. * KIND, either express or implied. See the License for the
  60654. * specific language governing permissions and limitations
  60655. * under the License.
  60656. */
  60657. var AxisModel$4 = ComponentModel.extend({
  60658. type: 'singleAxis',
  60659. layoutMode: 'box',
  60660. /**
  60661. * @type {module:echarts/coord/single/SingleAxis}
  60662. */
  60663. axis: null,
  60664. /**
  60665. * @type {module:echarts/coord/single/Single}
  60666. */
  60667. coordinateSystem: null,
  60668. /**
  60669. * @override
  60670. */
  60671. getCoordSysModel: function () {
  60672. return this;
  60673. }
  60674. });
  60675. var defaultOption$2 = {
  60676. left: '5%',
  60677. top: '5%',
  60678. right: '5%',
  60679. bottom: '5%',
  60680. type: 'value',
  60681. position: 'bottom',
  60682. orient: 'horizontal',
  60683. axisLine: {
  60684. show: true,
  60685. lineStyle: {
  60686. width: 1,
  60687. type: 'solid'
  60688. }
  60689. },
  60690. // Single coordinate system and single axis is the,
  60691. // which is used as the parent tooltip model.
  60692. // same model, so we set default tooltip show as true.
  60693. tooltip: {
  60694. show: true
  60695. },
  60696. axisTick: {
  60697. show: true,
  60698. length: 6,
  60699. lineStyle: {
  60700. width: 1
  60701. }
  60702. },
  60703. axisLabel: {
  60704. show: true,
  60705. interval: 'auto'
  60706. },
  60707. splitLine: {
  60708. show: true,
  60709. lineStyle: {
  60710. type: 'dashed',
  60711. opacity: 0.2
  60712. }
  60713. }
  60714. };
  60715. function getAxisType$2(axisName, option) {
  60716. return option.type || (option.data ? 'category' : 'value');
  60717. }
  60718. merge(AxisModel$4.prototype, axisModelCommonMixin);
  60719. axisModelCreator('single', AxisModel$4, getAxisType$2, defaultOption$2);
  60720. /*
  60721. * Licensed to the Apache Software Foundation (ASF) under one
  60722. * or more contributor license agreements. See the NOTICE file
  60723. * distributed with this work for additional information
  60724. * regarding copyright ownership. The ASF licenses this file
  60725. * to you under the Apache License, Version 2.0 (the
  60726. * "License"); you may not use this file except in compliance
  60727. * with the License. You may obtain a copy of the License at
  60728. *
  60729. * http://www.apache.org/licenses/LICENSE-2.0
  60730. *
  60731. * Unless required by applicable law or agreed to in writing,
  60732. * software distributed under the License is distributed on an
  60733. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60734. * KIND, either express or implied. See the License for the
  60735. * specific language governing permissions and limitations
  60736. * under the License.
  60737. */
  60738. /**
  60739. * @param {Object} finder contains {seriesIndex, dataIndex, dataIndexInside}
  60740. * @param {module:echarts/model/Global} ecModel
  60741. * @return {Object} {point: [x, y], el: ...} point Will not be null.
  60742. */
  60743. var findPointFromSeries = function (finder, ecModel) {
  60744. var point = [];
  60745. var seriesIndex = finder.seriesIndex;
  60746. var seriesModel;
  60747. if (seriesIndex == null || !(
  60748. seriesModel = ecModel.getSeriesByIndex(seriesIndex)
  60749. )) {
  60750. return {point: []};
  60751. }
  60752. var data = seriesModel.getData();
  60753. var dataIndex = queryDataIndex(data, finder);
  60754. if (dataIndex == null || dataIndex < 0 || isArray(dataIndex)) {
  60755. return {point: []};
  60756. }
  60757. var el = data.getItemGraphicEl(dataIndex);
  60758. var coordSys = seriesModel.coordinateSystem;
  60759. if (seriesModel.getTooltipPosition) {
  60760. point = seriesModel.getTooltipPosition(dataIndex) || [];
  60761. }
  60762. else if (coordSys && coordSys.dataToPoint) {
  60763. point = coordSys.dataToPoint(
  60764. data.getValues(
  60765. map(coordSys.dimensions, function (dim) {
  60766. return data.mapDimension(dim);
  60767. }), dataIndex, true
  60768. )
  60769. ) || [];
  60770. }
  60771. else if (el) {
  60772. // Use graphic bounding rect
  60773. var rect = el.getBoundingRect().clone();
  60774. rect.applyTransform(el.transform);
  60775. point = [
  60776. rect.x + rect.width / 2,
  60777. rect.y + rect.height / 2
  60778. ];
  60779. }
  60780. return {point: point, el: el};
  60781. };
  60782. /*
  60783. * Licensed to the Apache Software Foundation (ASF) under one
  60784. * or more contributor license agreements. See the NOTICE file
  60785. * distributed with this work for additional information
  60786. * regarding copyright ownership. The ASF licenses this file
  60787. * to you under the Apache License, Version 2.0 (the
  60788. * "License"); you may not use this file except in compliance
  60789. * with the License. You may obtain a copy of the License at
  60790. *
  60791. * http://www.apache.org/licenses/LICENSE-2.0
  60792. *
  60793. * Unless required by applicable law or agreed to in writing,
  60794. * software distributed under the License is distributed on an
  60795. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60796. * KIND, either express or implied. See the License for the
  60797. * specific language governing permissions and limitations
  60798. * under the License.
  60799. */
  60800. var each$14 = each$1;
  60801. var curry$3 = curry;
  60802. var inner$9 = makeInner();
  60803. /**
  60804. * Basic logic: check all axis, if they do not demand show/highlight,
  60805. * then hide/downplay them.
  60806. *
  60807. * @param {Object} coordSysAxesInfo
  60808. * @param {Object} payload
  60809. * @param {string} [payload.currTrigger] 'click' | 'mousemove' | 'leave'
  60810. * @param {Array.<number>} [payload.x] x and y, which are mandatory, specify a point to
  60811. * trigger axisPointer and tooltip.
  60812. * @param {Array.<number>} [payload.y] x and y, which are mandatory, specify a point to
  60813. * trigger axisPointer and tooltip.
  60814. * @param {Object} [payload.seriesIndex] finder, optional, restrict target axes.
  60815. * @param {Object} [payload.dataIndex] finder, restrict target axes.
  60816. * @param {Object} [payload.axesInfo] finder, restrict target axes.
  60817. * [{
  60818. * axisDim: 'x'|'y'|'angle'|...,
  60819. * axisIndex: ...,
  60820. * value: ...
  60821. * }, ...]
  60822. * @param {Function} [payload.dispatchAction]
  60823. * @param {Object} [payload.tooltipOption]
  60824. * @param {Object|Array.<number>|Function} [payload.position] Tooltip position,
  60825. * which can be specified in dispatchAction
  60826. * @param {module:echarts/model/Global} ecModel
  60827. * @param {module:echarts/ExtensionAPI} api
  60828. * @return {Object} content of event obj for echarts.connect.
  60829. */
  60830. var axisTrigger = function (payload, ecModel, api) {
  60831. var currTrigger = payload.currTrigger;
  60832. var point = [payload.x, payload.y];
  60833. var finder = payload;
  60834. var dispatchAction = payload.dispatchAction || bind(api.dispatchAction, api);
  60835. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
  60836. // Pending
  60837. // See #6121. But we are not able to reproduce it yet.
  60838. if (!coordSysAxesInfo) {
  60839. return;
  60840. }
  60841. if (illegalPoint(point)) {
  60842. // Used in the default behavior of `connection`: use the sample seriesIndex
  60843. // and dataIndex. And also used in the tooltipView trigger.
  60844. point = findPointFromSeries({
  60845. seriesIndex: finder.seriesIndex,
  60846. // Do not use dataIndexInside from other ec instance.
  60847. // FIXME: auto detect it?
  60848. dataIndex: finder.dataIndex
  60849. }, ecModel).point;
  60850. }
  60851. var isIllegalPoint = illegalPoint(point);
  60852. // Axis and value can be specified when calling dispatchAction({type: 'updateAxisPointer'}).
  60853. // Notice: In this case, it is difficult to get the `point` (which is necessary to show
  60854. // tooltip, so if point is not given, we just use the point found by sample seriesIndex
  60855. // and dataIndex.
  60856. var inputAxesInfo = finder.axesInfo;
  60857. var axesInfo = coordSysAxesInfo.axesInfo;
  60858. var shouldHide = currTrigger === 'leave' || illegalPoint(point);
  60859. var outputFinder = {};
  60860. var showValueMap = {};
  60861. var dataByCoordSys = {list: [], map: {}};
  60862. var updaters = {
  60863. showPointer: curry$3(showPointer, showValueMap),
  60864. showTooltip: curry$3(showTooltip, dataByCoordSys)
  60865. };
  60866. // Process for triggered axes.
  60867. each$14(coordSysAxesInfo.coordSysMap, function (coordSys, coordSysKey) {
  60868. // If a point given, it must be contained by the coordinate system.
  60869. var coordSysContainsPoint = isIllegalPoint || coordSys.containPoint(point);
  60870. each$14(coordSysAxesInfo.coordSysAxesInfo[coordSysKey], function (axisInfo, key) {
  60871. var axis = axisInfo.axis;
  60872. var inputAxisInfo = findInputAxisInfo(inputAxesInfo, axisInfo);
  60873. // If no inputAxesInfo, no axis is restricted.
  60874. if (!shouldHide && coordSysContainsPoint && (!inputAxesInfo || inputAxisInfo)) {
  60875. var val = inputAxisInfo && inputAxisInfo.value;
  60876. if (val == null && !isIllegalPoint) {
  60877. val = axis.pointToData(point);
  60878. }
  60879. val != null && processOnAxis(axisInfo, val, updaters, false, outputFinder);
  60880. }
  60881. });
  60882. });
  60883. // Process for linked axes.
  60884. var linkTriggers = {};
  60885. each$14(axesInfo, function (tarAxisInfo, tarKey) {
  60886. var linkGroup = tarAxisInfo.linkGroup;
  60887. // If axis has been triggered in the previous stage, it should not be triggered by link.
  60888. if (linkGroup && !showValueMap[tarKey]) {
  60889. each$14(linkGroup.axesInfo, function (srcAxisInfo, srcKey) {
  60890. var srcValItem = showValueMap[srcKey];
  60891. // If srcValItem exist, source axis is triggered, so link to target axis.
  60892. if (srcAxisInfo !== tarAxisInfo && srcValItem) {
  60893. var val = srcValItem.value;
  60894. linkGroup.mapper && (val = tarAxisInfo.axis.scale.parse(linkGroup.mapper(
  60895. val, makeMapperParam(srcAxisInfo), makeMapperParam(tarAxisInfo)
  60896. )));
  60897. linkTriggers[tarAxisInfo.key] = val;
  60898. }
  60899. });
  60900. }
  60901. });
  60902. each$14(linkTriggers, function (val, tarKey) {
  60903. processOnAxis(axesInfo[tarKey], val, updaters, true, outputFinder);
  60904. });
  60905. updateModelActually(showValueMap, axesInfo, outputFinder);
  60906. dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction);
  60907. dispatchHighDownActually(axesInfo, dispatchAction, api);
  60908. return outputFinder;
  60909. };
  60910. function processOnAxis(axisInfo, newValue, updaters, dontSnap, outputFinder) {
  60911. var axis = axisInfo.axis;
  60912. if (axis.scale.isBlank() || !axis.containData(newValue)) {
  60913. return;
  60914. }
  60915. if (!axisInfo.involveSeries) {
  60916. updaters.showPointer(axisInfo, newValue);
  60917. return;
  60918. }
  60919. // Heavy calculation. So put it after axis.containData checking.
  60920. var payloadInfo = buildPayloadsBySeries(newValue, axisInfo);
  60921. var payloadBatch = payloadInfo.payloadBatch;
  60922. var snapToValue = payloadInfo.snapToValue;
  60923. // Fill content of event obj for echarts.connect.
  60924. // By defualt use the first involved series data as a sample to connect.
  60925. if (payloadBatch[0] && outputFinder.seriesIndex == null) {
  60926. extend(outputFinder, payloadBatch[0]);
  60927. }
  60928. // If no linkSource input, this process is for collecting link
  60929. // target, where snap should not be accepted.
  60930. if (!dontSnap && axisInfo.snap) {
  60931. if (axis.containData(snapToValue) && snapToValue != null) {
  60932. newValue = snapToValue;
  60933. }
  60934. }
  60935. updaters.showPointer(axisInfo, newValue, payloadBatch, outputFinder);
  60936. // Tooltip should always be snapToValue, otherwise there will be
  60937. // incorrect "axis value ~ series value" mapping displayed in tooltip.
  60938. updaters.showTooltip(axisInfo, payloadInfo, snapToValue);
  60939. }
  60940. function buildPayloadsBySeries(value, axisInfo) {
  60941. var axis = axisInfo.axis;
  60942. var dim = axis.dim;
  60943. var snapToValue = value;
  60944. var payloadBatch = [];
  60945. var minDist = Number.MAX_VALUE;
  60946. var minDiff = -1;
  60947. each$14(axisInfo.seriesModels, function (series, idx) {
  60948. var dataDim = series.getData().mapDimension(dim, true);
  60949. var seriesNestestValue;
  60950. var dataIndices;
  60951. if (series.getAxisTooltipData) {
  60952. var result = series.getAxisTooltipData(dataDim, value, axis);
  60953. dataIndices = result.dataIndices;
  60954. seriesNestestValue = result.nestestValue;
  60955. }
  60956. else {
  60957. dataIndices = series.getData().indicesOfNearest(
  60958. dataDim[0],
  60959. value,
  60960. // Add a threshold to avoid find the wrong dataIndex
  60961. // when data length is not same.
  60962. // false,
  60963. axis.type === 'category' ? 0.5 : null
  60964. );
  60965. if (!dataIndices.length) {
  60966. return;
  60967. }
  60968. seriesNestestValue = series.getData().get(dataDim[0], dataIndices[0]);
  60969. }
  60970. if (seriesNestestValue == null || !isFinite(seriesNestestValue)) {
  60971. return;
  60972. }
  60973. var diff = value - seriesNestestValue;
  60974. var dist = Math.abs(diff);
  60975. // Consider category case
  60976. if (dist <= minDist) {
  60977. if (dist < minDist || (diff >= 0 && minDiff < 0)) {
  60978. minDist = dist;
  60979. minDiff = diff;
  60980. snapToValue = seriesNestestValue;
  60981. payloadBatch.length = 0;
  60982. }
  60983. each$14(dataIndices, function (dataIndex) {
  60984. payloadBatch.push({
  60985. seriesIndex: series.seriesIndex,
  60986. dataIndexInside: dataIndex,
  60987. dataIndex: series.getData().getRawIndex(dataIndex)
  60988. });
  60989. });
  60990. }
  60991. });
  60992. return {
  60993. payloadBatch: payloadBatch,
  60994. snapToValue: snapToValue
  60995. };
  60996. }
  60997. function showPointer(showValueMap, axisInfo, value, payloadBatch) {
  60998. showValueMap[axisInfo.key] = {value: value, payloadBatch: payloadBatch};
  60999. }
  61000. function showTooltip(dataByCoordSys, axisInfo, payloadInfo, value) {
  61001. var payloadBatch = payloadInfo.payloadBatch;
  61002. var axis = axisInfo.axis;
  61003. var axisModel = axis.model;
  61004. var axisPointerModel = axisInfo.axisPointerModel;
  61005. // If no data, do not create anything in dataByCoordSys,
  61006. // whose length will be used to judge whether dispatch action.
  61007. if (!axisInfo.triggerTooltip || !payloadBatch.length) {
  61008. return;
  61009. }
  61010. var coordSysModel = axisInfo.coordSys.model;
  61011. var coordSysKey = makeKey(coordSysModel);
  61012. var coordSysItem = dataByCoordSys.map[coordSysKey];
  61013. if (!coordSysItem) {
  61014. coordSysItem = dataByCoordSys.map[coordSysKey] = {
  61015. coordSysId: coordSysModel.id,
  61016. coordSysIndex: coordSysModel.componentIndex,
  61017. coordSysType: coordSysModel.type,
  61018. coordSysMainType: coordSysModel.mainType,
  61019. dataByAxis: []
  61020. };
  61021. dataByCoordSys.list.push(coordSysItem);
  61022. }
  61023. coordSysItem.dataByAxis.push({
  61024. axisDim: axis.dim,
  61025. axisIndex: axisModel.componentIndex,
  61026. axisType: axisModel.type,
  61027. axisId: axisModel.id,
  61028. value: value,
  61029. // Caustion: viewHelper.getValueLabel is actually on "view stage", which
  61030. // depends that all models have been updated. So it should not be performed
  61031. // here. Considering axisPointerModel used here is volatile, which is hard
  61032. // to be retrieve in TooltipView, we prepare parameters here.
  61033. valueLabelOpt: {
  61034. precision: axisPointerModel.get('label.precision'),
  61035. formatter: axisPointerModel.get('label.formatter')
  61036. },
  61037. seriesDataIndices: payloadBatch.slice()
  61038. });
  61039. }
  61040. function updateModelActually(showValueMap, axesInfo, outputFinder) {
  61041. var outputAxesInfo = outputFinder.axesInfo = [];
  61042. // Basic logic: If no 'show' required, 'hide' this axisPointer.
  61043. each$14(axesInfo, function (axisInfo, key) {
  61044. var option = axisInfo.axisPointerModel.option;
  61045. var valItem = showValueMap[key];
  61046. if (valItem) {
  61047. !axisInfo.useHandle && (option.status = 'show');
  61048. option.value = valItem.value;
  61049. // For label formatter param and highlight.
  61050. option.seriesDataIndices = (valItem.payloadBatch || []).slice();
  61051. }
  61052. // When always show (e.g., handle used), remain
  61053. // original value and status.
  61054. else {
  61055. // If hide, value still need to be set, consider
  61056. // click legend to toggle axis blank.
  61057. !axisInfo.useHandle && (option.status = 'hide');
  61058. }
  61059. // If status is 'hide', should be no info in payload.
  61060. option.status === 'show' && outputAxesInfo.push({
  61061. axisDim: axisInfo.axis.dim,
  61062. axisIndex: axisInfo.axis.model.componentIndex,
  61063. value: option.value
  61064. });
  61065. });
  61066. }
  61067. function dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction) {
  61068. // Basic logic: If no showTip required, hideTip will be dispatched.
  61069. if (illegalPoint(point) || !dataByCoordSys.list.length) {
  61070. dispatchAction({type: 'hideTip'});
  61071. return;
  61072. }
  61073. // In most case only one axis (or event one series is used). It is
  61074. // convinient to fetch payload.seriesIndex and payload.dataIndex
  61075. // dirtectly. So put the first seriesIndex and dataIndex of the first
  61076. // axis on the payload.
  61077. var sampleItem = ((dataByCoordSys.list[0].dataByAxis[0] || {}).seriesDataIndices || [])[0] || {};
  61078. dispatchAction({
  61079. type: 'showTip',
  61080. escapeConnect: true,
  61081. x: point[0],
  61082. y: point[1],
  61083. tooltipOption: payload.tooltipOption,
  61084. position: payload.position,
  61085. dataIndexInside: sampleItem.dataIndexInside,
  61086. dataIndex: sampleItem.dataIndex,
  61087. seriesIndex: sampleItem.seriesIndex,
  61088. dataByCoordSys: dataByCoordSys.list
  61089. });
  61090. }
  61091. function dispatchHighDownActually(axesInfo, dispatchAction, api) {
  61092. // FIXME
  61093. // highlight status modification shoule be a stage of main process?
  61094. // (Consider confilct (e.g., legend and axisPointer) and setOption)
  61095. var zr = api.getZr();
  61096. var highDownKey = 'axisPointerLastHighlights';
  61097. var lastHighlights = inner$9(zr)[highDownKey] || {};
  61098. var newHighlights = inner$9(zr)[highDownKey] = {};
  61099. // Update highlight/downplay status according to axisPointer model.
  61100. // Build hash map and remove duplicate incidentally.
  61101. each$14(axesInfo, function (axisInfo, key) {
  61102. var option = axisInfo.axisPointerModel.option;
  61103. option.status === 'show' && each$14(option.seriesDataIndices, function (batchItem) {
  61104. var key = batchItem.seriesIndex + ' | ' + batchItem.dataIndex;
  61105. newHighlights[key] = batchItem;
  61106. });
  61107. });
  61108. // Diff.
  61109. var toHighlight = [];
  61110. var toDownplay = [];
  61111. each$1(lastHighlights, function (batchItem, key) {
  61112. !newHighlights[key] && toDownplay.push(batchItem);
  61113. });
  61114. each$1(newHighlights, function (batchItem, key) {
  61115. !lastHighlights[key] && toHighlight.push(batchItem);
  61116. });
  61117. toDownplay.length && api.dispatchAction({
  61118. type: 'downplay', escapeConnect: true, batch: toDownplay
  61119. });
  61120. toHighlight.length && api.dispatchAction({
  61121. type: 'highlight', escapeConnect: true, batch: toHighlight
  61122. });
  61123. }
  61124. function findInputAxisInfo(inputAxesInfo, axisInfo) {
  61125. for (var i = 0; i < (inputAxesInfo || []).length; i++) {
  61126. var inputAxisInfo = inputAxesInfo[i];
  61127. if (axisInfo.axis.dim === inputAxisInfo.axisDim
  61128. && axisInfo.axis.model.componentIndex === inputAxisInfo.axisIndex
  61129. ) {
  61130. return inputAxisInfo;
  61131. }
  61132. }
  61133. }
  61134. function makeMapperParam(axisInfo) {
  61135. var axisModel = axisInfo.axis.model;
  61136. var item = {};
  61137. var dim = item.axisDim = axisInfo.axis.dim;
  61138. item.axisIndex = item[dim + 'AxisIndex'] = axisModel.componentIndex;
  61139. item.axisName = item[dim + 'AxisName'] = axisModel.name;
  61140. item.axisId = item[dim + 'AxisId'] = axisModel.id;
  61141. return item;
  61142. }
  61143. function illegalPoint(point) {
  61144. return !point || point[0] == null || isNaN(point[0]) || point[1] == null || isNaN(point[1]);
  61145. }
  61146. /*
  61147. * Licensed to the Apache Software Foundation (ASF) under one
  61148. * or more contributor license agreements. See the NOTICE file
  61149. * distributed with this work for additional information
  61150. * regarding copyright ownership. The ASF licenses this file
  61151. * to you under the Apache License, Version 2.0 (the
  61152. * "License"); you may not use this file except in compliance
  61153. * with the License. You may obtain a copy of the License at
  61154. *
  61155. * http://www.apache.org/licenses/LICENSE-2.0
  61156. *
  61157. * Unless required by applicable law or agreed to in writing,
  61158. * software distributed under the License is distributed on an
  61159. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  61160. * KIND, either express or implied. See the License for the
  61161. * specific language governing permissions and limitations
  61162. * under the License.
  61163. */
  61164. var AxisPointerModel = extendComponentModel({
  61165. type: 'axisPointer',
  61166. coordSysAxesInfo: null,
  61167. defaultOption: {
  61168. // 'auto' means that show when triggered by tooltip or handle.
  61169. show: 'auto',
  61170. // 'click' | 'mousemove' | 'none'
  61171. triggerOn: null, // set default in AxisPonterView.js
  61172. zlevel: 0,
  61173. z: 50,
  61174. type: 'line', // 'line' 'shadow' 'cross' 'none'.
  61175. // axispointer triggered by tootip determine snap automatically,
  61176. // see `modelHelper`.
  61177. snap: false,
  61178. triggerTooltip: true,
  61179. value: null,
  61180. status: null, // Init value depends on whether handle is used.
  61181. // [group0, group1, ...]
  61182. // Each group can be: {
  61183. // mapper: function () {},
  61184. // singleTooltip: 'multiple', // 'multiple' or 'single'
  61185. // xAxisId: ...,
  61186. // yAxisName: ...,
  61187. // angleAxisIndex: ...
  61188. // }
  61189. // mapper: can be ignored.
  61190. // input: {axisInfo, value}
  61191. // output: {axisInfo, value}
  61192. link: [],
  61193. // Do not set 'auto' here, otherwise global animation: false
  61194. // will not effect at this axispointer.
  61195. animation: null,
  61196. animationDurationUpdate: 200,
  61197. lineStyle: {
  61198. color: '#aaa',
  61199. width: 1,
  61200. type: 'solid'
  61201. },
  61202. shadowStyle: {
  61203. color: 'rgba(150,150,150,0.3)'
  61204. },
  61205. label: {
  61206. show: true,
  61207. formatter: null, // string | Function
  61208. precision: 'auto', // Or a number like 0, 1, 2 ...
  61209. margin: 3,
  61210. color: '#fff',
  61211. padding: [5, 7, 5, 7],
  61212. backgroundColor: 'auto', // default: axis line color
  61213. borderColor: null,
  61214. borderWidth: 0,
  61215. shadowBlur: 3,
  61216. shadowColor: '#aaa'
  61217. // Considering applicability, common style should
  61218. // better not have shadowOffset.
  61219. // shadowOffsetX: 0,
  61220. // shadowOffsetY: 2
  61221. },
  61222. handle: {
  61223. show: false,
  61224. /* eslint-disable */
  61225. icon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4h1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7v-1.2h6.6z M13.3,22H6.7v-1.2h6.6z M13.3,19.6H6.7v-1.2h6.6z', // jshint ignore:line
  61226. /* eslint-enable */
  61227. size: 45,
  61228. // handle margin is from symbol center to axis, which is stable when circular move.
  61229. margin: 50,
  61230. // color: '#1b8bbd'
  61231. // color: '#2f4554'
  61232. color: '#333',
  61233. shadowBlur: 3,
  61234. shadowColor: '#aaa',
  61235. shadowOffsetX: 0,
  61236. shadowOffsetY: 2,
  61237. // For mobile performance
  61238. throttle: 40
  61239. }
  61240. }
  61241. });
  61242. /*
  61243. * Licensed to the Apache Software Foundation (ASF) under one
  61244. * or more contributor license agreements. See the NOTICE file
  61245. * distributed with this work for additional information
  61246. * regarding copyright ownership. The ASF licenses this file
  61247. * to you under the Apache License, Version 2.0 (the
  61248. * "License"); you may not use this file except in compliance
  61249. * with the License. You may obtain a copy of the License at
  61250. *
  61251. * http://www.apache.org/licenses/LICENSE-2.0
  61252. *
  61253. * Unless required by applicable law or agreed to in writing,
  61254. * software distributed under the License is distributed on an
  61255. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  61256. * KIND, either express or implied. See the License for the
  61257. * specific language governing permissions and limitations
  61258. * under the License.
  61259. */
  61260. var inner$10 = makeInner();
  61261. var each$15 = each$1;
  61262. /**
  61263. * @param {string} key
  61264. * @param {module:echarts/ExtensionAPI} api
  61265. * @param {Function} handler
  61266. * param: {string} currTrigger
  61267. * param: {Array.<number>} point
  61268. */
  61269. function register(key, api, handler) {
  61270. if (env$1.node) {
  61271. return;
  61272. }
  61273. var zr = api.getZr();
  61274. inner$10(zr).records || (inner$10(zr).records = {});
  61275. initGlobalListeners(zr, api);
  61276. var record = inner$10(zr).records[key] || (inner$10(zr).records[key] = {});
  61277. record.handler = handler;
  61278. }
  61279. function initGlobalListeners(zr, api) {
  61280. if (inner$10(zr).initialized) {
  61281. return;
  61282. }
  61283. inner$10(zr).initialized = true;
  61284. useHandler('click', curry(doEnter, 'click'));
  61285. useHandler('mousemove', curry(doEnter, 'mousemove'));
  61286. // useHandler('mouseout', onLeave);
  61287. useHandler('globalout', onLeave);
  61288. function useHandler(eventType, cb) {
  61289. zr.on(eventType, function (e) {
  61290. var dis = makeDispatchAction(api);
  61291. each$15(inner$10(zr).records, function (record) {
  61292. record && cb(record, e, dis.dispatchAction);
  61293. });
  61294. dispatchTooltipFinally(dis.pendings, api);
  61295. });
  61296. }
  61297. }
  61298. function dispatchTooltipFinally(pendings, api) {
  61299. var showLen = pendings.showTip.length;
  61300. var hideLen = pendings.hideTip.length;
  61301. var actuallyPayload;
  61302. if (showLen) {
  61303. actuallyPayload = pendings.showTip[showLen - 1];
  61304. }
  61305. else if (hideLen) {
  61306. actuallyPayload = pendings.hideTip[hideLen - 1];
  61307. }
  61308. if (actuallyPayload) {
  61309. actuallyPayload.dispatchAction = null;
  61310. api.dispatchAction(actuallyPayload);
  61311. }
  61312. }
  61313. function onLeave(record, e, dispatchAction) {
  61314. record.handler('leave', null, dispatchAction);
  61315. }
  61316. function doEnter(currTrigger, record, e, dispatchAction) {
  61317. record.handler(currTrigger, e, dispatchAction);
  61318. }
  61319. function makeDispatchAction(api) {
  61320. var pendings = {
  61321. showTip: [],
  61322. hideTip: []
  61323. };
  61324. // FIXME
  61325. // better approach?
  61326. // 'showTip' and 'hideTip' can be triggered by axisPointer and tooltip,
  61327. // which may be conflict, (axisPointer call showTip but tooltip call hideTip);
  61328. // So we have to add "final stage" to merge those dispatched actions.
  61329. var dispatchAction = function (payload) {
  61330. var pendingList = pendings[payload.type];
  61331. if (pendingList) {
  61332. pendingList.push(payload);
  61333. }
  61334. else {
  61335. payload.dispatchAction = dispatchAction;
  61336. api.dispatchAction(payload);
  61337. }
  61338. };
  61339. return {
  61340. dispatchAction: dispatchAction,
  61341. pendings: pendings
  61342. };
  61343. }
  61344. /**
  61345. * @param {string} key
  61346. * @param {module:echarts/ExtensionAPI} api
  61347. */
  61348. function unregister(key, api) {
  61349. if (env$1.node) {
  61350. return;
  61351. }
  61352. var zr = api.getZr();
  61353. var record = (inner$10(zr).records || {})[key];
  61354. if (record) {
  61355. inner$10(zr).records[key] = null;
  61356. }
  61357. }
  61358. /*
  61359. * Licensed to the Apache Software Foundation (ASF) under one
  61360. * or more contributor license agreements. See the NOTICE file
  61361. * distributed with this work for additional information
  61362. * regarding copyright ownership. The ASF licenses this file
  61363. * to you under the Apache License, Version 2.0 (the
  61364. * "License"); you may not use this file except in compliance
  61365. * with the License. You may obtain a copy of the License at
  61366. *
  61367. * http://www.apache.org/licenses/LICENSE-2.0
  61368. *
  61369. * Unless required by applicable law or agreed to in writing,
  61370. * software distributed under the License is distributed on an
  61371. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  61372. * KIND, either express or implied. See the License for the
  61373. * specific language governing permissions and limitations
  61374. * under the License.
  61375. */
  61376. var AxisPointerView = extendComponentView({
  61377. type: 'axisPointer',
  61378. render: function (globalAxisPointerModel, ecModel, api) {
  61379. var globalTooltipModel = ecModel.getComponent('tooltip');
  61380. var triggerOn = globalAxisPointerModel.get('triggerOn')
  61381. || (globalTooltipModel && globalTooltipModel.get('triggerOn') || 'mousemove|click');
  61382. // Register global listener in AxisPointerView to enable
  61383. // AxisPointerView to be independent to Tooltip.
  61384. register(
  61385. 'axisPointer',
  61386. api,
  61387. function (currTrigger, e, dispatchAction) {
  61388. // If 'none', it is not controlled by mouse totally.
  61389. if (triggerOn !== 'none'
  61390. && (currTrigger === 'leave' || triggerOn.indexOf(currTrigger) >= 0)
  61391. ) {
  61392. dispatchAction({
  61393. type: 'updateAxisPointer',
  61394. currTrigger: currTrigger,
  61395. x: e && e.offsetX,
  61396. y: e && e.offsetY
  61397. });
  61398. }
  61399. }
  61400. );
  61401. },
  61402. /**
  61403. * @override
  61404. */
  61405. remove: function (ecModel, api) {
  61406. unregister(api.getZr(), 'axisPointer');
  61407. AxisPointerView.superApply(this._model, 'remove', arguments);
  61408. },
  61409. /**
  61410. * @override
  61411. */
  61412. dispose: function (ecModel, api) {
  61413. unregister('axisPointer', api);
  61414. AxisPointerView.superApply(this._model, 'dispose', arguments);
  61415. }
  61416. });
  61417. /*
  61418. * Licensed to the Apache Software Foundation (ASF) under one
  61419. * or more contributor license agreements. See the NOTICE file
  61420. * distributed with this work for additional information
  61421. * regarding copyright ownership. The ASF licenses this file
  61422. * to you under the Apache License, Version 2.0 (the
  61423. * "License"); you may not use this file except in compliance
  61424. * with the License. You may obtain a copy of the License at
  61425. *
  61426. * http://www.apache.org/licenses/LICENSE-2.0
  61427. *
  61428. * Unless required by applicable law or agreed to in writing,
  61429. * software distributed under the License is distributed on an
  61430. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  61431. * KIND, either express or implied. See the License for the
  61432. * specific language governing permissions and limitations
  61433. * under the License.
  61434. */
  61435. var inner$11 = makeInner();
  61436. var clone$4 = clone;
  61437. var bind$2 = bind;
  61438. /**
  61439. * Base axis pointer class in 2D.
  61440. * Implemenents {module:echarts/component/axis/IAxisPointer}.
  61441. */
  61442. function BaseAxisPointer() {
  61443. }
  61444. BaseAxisPointer.prototype = {
  61445. /**
  61446. * @private
  61447. */
  61448. _group: null,
  61449. /**
  61450. * @private
  61451. */
  61452. _lastGraphicKey: null,
  61453. /**
  61454. * @private
  61455. */
  61456. _handle: null,
  61457. /**
  61458. * @private
  61459. */
  61460. _dragging: false,
  61461. /**
  61462. * @private
  61463. */
  61464. _lastValue: null,
  61465. /**
  61466. * @private
  61467. */
  61468. _lastStatus: null,
  61469. /**
  61470. * @private
  61471. */
  61472. _payloadInfo: null,
  61473. /**
  61474. * In px, arbitrary value. Do not set too small,
  61475. * no animation is ok for most cases.
  61476. * @protected
  61477. */
  61478. animationThreshold: 15,
  61479. /**
  61480. * @implement
  61481. */
  61482. render: function (axisModel, axisPointerModel, api, forceRender) {
  61483. var value = axisPointerModel.get('value');
  61484. var status = axisPointerModel.get('status');
  61485. // Bind them to `this`, not in closure, otherwise they will not
  61486. // be replaced when user calling setOption in not merge mode.
  61487. this._axisModel = axisModel;
  61488. this._axisPointerModel = axisPointerModel;
  61489. this._api = api;
  61490. // Optimize: `render` will be called repeatly during mouse move.
  61491. // So it is power consuming if performing `render` each time,
  61492. // especially on mobile device.
  61493. if (!forceRender
  61494. && this._lastValue === value
  61495. && this._lastStatus === status
  61496. ) {
  61497. return;
  61498. }
  61499. this._lastValue = value;
  61500. this._lastStatus = status;
  61501. var group = this._group;
  61502. var handle = this._handle;
  61503. if (!status || status === 'hide') {
  61504. // Do not clear here, for animation better.
  61505. group && group.hide();
  61506. handle && handle.hide();
  61507. return;
  61508. }
  61509. group && group.show();
  61510. handle && handle.show();
  61511. // Otherwise status is 'show'
  61512. var elOption = {};
  61513. this.makeElOption(elOption, value, axisModel, axisPointerModel, api);
  61514. // Enable change axis pointer type.
  61515. var graphicKey = elOption.graphicKey;
  61516. if (graphicKey !== this._lastGraphicKey) {
  61517. this.clear(api);
  61518. }
  61519. this._lastGraphicKey = graphicKey;
  61520. var moveAnimation = this._moveAnimation =
  61521. this.determineAnimation(axisModel, axisPointerModel);
  61522. if (!group) {
  61523. group = this._group = new Group();
  61524. this.createPointerEl(group, elOption, axisModel, axisPointerModel);
  61525. this.createLabelEl(group, elOption, axisModel, axisPointerModel);
  61526. api.getZr().add(group);
  61527. }
  61528. else {
  61529. var doUpdateProps = curry(updateProps$1, axisPointerModel, moveAnimation);
  61530. this.updatePointerEl(group, elOption, doUpdateProps, axisPointerModel);
  61531. this.updateLabelEl(group, elOption, doUpdateProps, axisPointerModel);
  61532. }
  61533. updateMandatoryProps(group, axisPointerModel, true);
  61534. this._renderHandle(value);
  61535. },
  61536. /**
  61537. * @implement
  61538. */
  61539. remove: function (api) {
  61540. this.clear(api);
  61541. },
  61542. /**
  61543. * @implement
  61544. */
  61545. dispose: function (api) {
  61546. this.clear(api);
  61547. },
  61548. /**
  61549. * @protected
  61550. */
  61551. determineAnimation: function (axisModel, axisPointerModel) {
  61552. var animation = axisPointerModel.get('animation');
  61553. var axis = axisModel.axis;
  61554. var isCategoryAxis = axis.type === 'category';
  61555. var useSnap = axisPointerModel.get('snap');
  61556. // Value axis without snap always do not snap.
  61557. if (!useSnap && !isCategoryAxis) {
  61558. return false;
  61559. }
  61560. if (animation === 'auto' || animation == null) {
  61561. var animationThreshold = this.animationThreshold;
  61562. if (isCategoryAxis && axis.getBandWidth() > animationThreshold) {
  61563. return true;
  61564. }
  61565. // It is important to auto animation when snap used. Consider if there is
  61566. // a dataZoom, animation will be disabled when too many points exist, while
  61567. // it will be enabled for better visual effect when little points exist.
  61568. if (useSnap) {
  61569. var seriesDataCount = getAxisInfo(axisModel).seriesDataCount;
  61570. var axisExtent = axis.getExtent();
  61571. // Approximate band width
  61572. return Math.abs(axisExtent[0] - axisExtent[1]) / seriesDataCount > animationThreshold;
  61573. }
  61574. return false;
  61575. }
  61576. return animation === true;
  61577. },
  61578. /**
  61579. * add {pointer, label, graphicKey} to elOption
  61580. * @protected
  61581. */
  61582. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  61583. // Shoule be implemenented by sub-class.
  61584. },
  61585. /**
  61586. * @protected
  61587. */
  61588. createPointerEl: function (group, elOption, axisModel, axisPointerModel) {
  61589. var pointerOption = elOption.pointer;
  61590. if (pointerOption) {
  61591. var pointerEl = inner$11(group).pointerEl = new graphic[pointerOption.type](
  61592. clone$4(elOption.pointer)
  61593. );
  61594. group.add(pointerEl);
  61595. }
  61596. },
  61597. /**
  61598. * @protected
  61599. */
  61600. createLabelEl: function (group, elOption, axisModel, axisPointerModel) {
  61601. if (elOption.label) {
  61602. var labelEl = inner$11(group).labelEl = new Rect(
  61603. clone$4(elOption.label)
  61604. );
  61605. group.add(labelEl);
  61606. updateLabelShowHide(labelEl, axisPointerModel);
  61607. }
  61608. },
  61609. /**
  61610. * @protected
  61611. */
  61612. updatePointerEl: function (group, elOption, updateProps$$1) {
  61613. var pointerEl = inner$11(group).pointerEl;
  61614. if (pointerEl && elOption.pointer) {
  61615. pointerEl.setStyle(elOption.pointer.style);
  61616. updateProps$$1(pointerEl, {shape: elOption.pointer.shape});
  61617. }
  61618. },
  61619. /**
  61620. * @protected
  61621. */
  61622. updateLabelEl: function (group, elOption, updateProps$$1, axisPointerModel) {
  61623. var labelEl = inner$11(group).labelEl;
  61624. if (labelEl) {
  61625. labelEl.setStyle(elOption.label.style);
  61626. updateProps$$1(labelEl, {
  61627. // Consider text length change in vertical axis, animation should
  61628. // be used on shape, otherwise the effect will be weird.
  61629. shape: elOption.label.shape,
  61630. position: elOption.label.position
  61631. });
  61632. updateLabelShowHide(labelEl, axisPointerModel);
  61633. }
  61634. },
  61635. /**
  61636. * @private
  61637. */
  61638. _renderHandle: function (value) {
  61639. if (this._dragging || !this.updateHandleTransform) {
  61640. return;
  61641. }
  61642. var axisPointerModel = this._axisPointerModel;
  61643. var zr = this._api.getZr();
  61644. var handle = this._handle;
  61645. var handleModel = axisPointerModel.getModel('handle');
  61646. var status = axisPointerModel.get('status');
  61647. if (!handleModel.get('show') || !status || status === 'hide') {
  61648. handle && zr.remove(handle);
  61649. this._handle = null;
  61650. return;
  61651. }
  61652. var isInit;
  61653. if (!this._handle) {
  61654. isInit = true;
  61655. handle = this._handle = createIcon(
  61656. handleModel.get('icon'),
  61657. {
  61658. cursor: 'move',
  61659. draggable: true,
  61660. onmousemove: function (e) {
  61661. // Fot mobile devicem, prevent screen slider on the button.
  61662. stop(e.event);
  61663. },
  61664. onmousedown: bind$2(this._onHandleDragMove, this, 0, 0),
  61665. drift: bind$2(this._onHandleDragMove, this),
  61666. ondragend: bind$2(this._onHandleDragEnd, this)
  61667. }
  61668. );
  61669. zr.add(handle);
  61670. }
  61671. updateMandatoryProps(handle, axisPointerModel, false);
  61672. // update style
  61673. var includeStyles = [
  61674. 'color', 'borderColor', 'borderWidth', 'opacity',
  61675. 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY'
  61676. ];
  61677. handle.setStyle(handleModel.getItemStyle(null, includeStyles));
  61678. // update position
  61679. var handleSize = handleModel.get('size');
  61680. if (!isArray(handleSize)) {
  61681. handleSize = [handleSize, handleSize];
  61682. }
  61683. handle.attr('scale', [handleSize[0] / 2, handleSize[1] / 2]);
  61684. createOrUpdate(
  61685. this,
  61686. '_doDispatchAxisPointer',
  61687. handleModel.get('throttle') || 0,
  61688. 'fixRate'
  61689. );
  61690. this._moveHandleToValue(value, isInit);
  61691. },
  61692. /**
  61693. * @private
  61694. */
  61695. _moveHandleToValue: function (value, isInit) {
  61696. updateProps$1(
  61697. this._axisPointerModel,
  61698. !isInit && this._moveAnimation,
  61699. this._handle,
  61700. getHandleTransProps(this.getHandleTransform(
  61701. value, this._axisModel, this._axisPointerModel
  61702. ))
  61703. );
  61704. },
  61705. /**
  61706. * @private
  61707. */
  61708. _onHandleDragMove: function (dx, dy) {
  61709. var handle = this._handle;
  61710. if (!handle) {
  61711. return;
  61712. }
  61713. this._dragging = true;
  61714. // Persistent for throttle.
  61715. var trans = this.updateHandleTransform(
  61716. getHandleTransProps(handle),
  61717. [dx, dy],
  61718. this._axisModel,
  61719. this._axisPointerModel
  61720. );
  61721. this._payloadInfo = trans;
  61722. handle.stopAnimation();
  61723. handle.attr(getHandleTransProps(trans));
  61724. inner$11(handle).lastProp = null;
  61725. this._doDispatchAxisPointer();
  61726. },
  61727. /**
  61728. * Throttled method.
  61729. * @private
  61730. */
  61731. _doDispatchAxisPointer: function () {
  61732. var handle = this._handle;
  61733. if (!handle) {
  61734. return;
  61735. }
  61736. var payloadInfo = this._payloadInfo;
  61737. var axisModel = this._axisModel;
  61738. this._api.dispatchAction({
  61739. type: 'updateAxisPointer',
  61740. x: payloadInfo.cursorPoint[0],
  61741. y: payloadInfo.cursorPoint[1],
  61742. tooltipOption: payloadInfo.tooltipOption,
  61743. axesInfo: [{
  61744. axisDim: axisModel.axis.dim,
  61745. axisIndex: axisModel.componentIndex
  61746. }]
  61747. });
  61748. },
  61749. /**
  61750. * @private
  61751. */
  61752. _onHandleDragEnd: function (moveAnimation) {
  61753. this._dragging = false;
  61754. var handle = this._handle;
  61755. if (!handle) {
  61756. return;
  61757. }
  61758. var value = this._axisPointerModel.get('value');
  61759. // Consider snap or categroy axis, handle may be not consistent with
  61760. // axisPointer. So move handle to align the exact value position when
  61761. // drag ended.
  61762. this._moveHandleToValue(value);
  61763. // For the effect: tooltip will be shown when finger holding on handle
  61764. // button, and will be hidden after finger left handle button.
  61765. this._api.dispatchAction({
  61766. type: 'hideTip'
  61767. });
  61768. },
  61769. /**
  61770. * Should be implemenented by sub-class if support `handle`.
  61771. * @protected
  61772. * @param {number} value
  61773. * @param {module:echarts/model/Model} axisModel
  61774. * @param {module:echarts/model/Model} axisPointerModel
  61775. * @return {Object} {position: [x, y], rotation: 0}
  61776. */
  61777. getHandleTransform: null,
  61778. /**
  61779. * * Should be implemenented by sub-class if support `handle`.
  61780. * @protected
  61781. * @param {Object} transform {position, rotation}
  61782. * @param {Array.<number>} delta [dx, dy]
  61783. * @param {module:echarts/model/Model} axisModel
  61784. * @param {module:echarts/model/Model} axisPointerModel
  61785. * @return {Object} {position: [x, y], rotation: 0, cursorPoint: [x, y]}
  61786. */
  61787. updateHandleTransform: null,
  61788. /**
  61789. * @private
  61790. */
  61791. clear: function (api) {
  61792. this._lastValue = null;
  61793. this._lastStatus = null;
  61794. var zr = api.getZr();
  61795. var group = this._group;
  61796. var handle = this._handle;
  61797. if (zr && group) {
  61798. this._lastGraphicKey = null;
  61799. group && zr.remove(group);
  61800. handle && zr.remove(handle);
  61801. this._group = null;
  61802. this._handle = null;
  61803. this._payloadInfo = null;
  61804. }
  61805. },
  61806. /**
  61807. * @protected
  61808. */
  61809. doClear: function () {
  61810. // Implemented by sub-class if necessary.
  61811. },
  61812. /**
  61813. * @protected
  61814. * @param {Array.<number>} xy
  61815. * @param {Array.<number>} wh
  61816. * @param {number} [xDimIndex=0] or 1
  61817. */
  61818. buildLabel: function (xy, wh, xDimIndex) {
  61819. xDimIndex = xDimIndex || 0;
  61820. return {
  61821. x: xy[xDimIndex],
  61822. y: xy[1 - xDimIndex],
  61823. width: wh[xDimIndex],
  61824. height: wh[1 - xDimIndex]
  61825. };
  61826. }
  61827. };
  61828. BaseAxisPointer.prototype.constructor = BaseAxisPointer;
  61829. function updateProps$1(animationModel, moveAnimation, el, props) {
  61830. // Animation optimize.
  61831. if (!propsEqual(inner$11(el).lastProp, props)) {
  61832. inner$11(el).lastProp = props;
  61833. moveAnimation
  61834. ? updateProps(el, props, animationModel)
  61835. : (el.stopAnimation(), el.attr(props));
  61836. }
  61837. }
  61838. function propsEqual(lastProps, newProps) {
  61839. if (isObject$1(lastProps) && isObject$1(newProps)) {
  61840. var equals = true;
  61841. each$1(newProps, function (item, key) {
  61842. equals = equals && propsEqual(lastProps[key], item);
  61843. });
  61844. return !!equals;
  61845. }
  61846. else {
  61847. return lastProps === newProps;
  61848. }
  61849. }
  61850. function updateLabelShowHide(labelEl, axisPointerModel) {
  61851. labelEl[axisPointerModel.get('label.show') ? 'show' : 'hide']();
  61852. }
  61853. function getHandleTransProps(trans) {
  61854. return {
  61855. position: trans.position.slice(),
  61856. rotation: trans.rotation || 0
  61857. };
  61858. }
  61859. function updateMandatoryProps(group, axisPointerModel, silent) {
  61860. var z = axisPointerModel.get('z');
  61861. var zlevel = axisPointerModel.get('zlevel');
  61862. group && group.traverse(function (el) {
  61863. if (el.type !== 'group') {
  61864. z != null && (el.z = z);
  61865. zlevel != null && (el.zlevel = zlevel);
  61866. el.silent = silent;
  61867. }
  61868. });
  61869. }
  61870. enableClassExtend(BaseAxisPointer);
  61871. /*
  61872. * Licensed to the Apache Software Foundation (ASF) under one
  61873. * or more contributor license agreements. See the NOTICE file
  61874. * distributed with this work for additional information
  61875. * regarding copyright ownership. The ASF licenses this file
  61876. * to you under the Apache License, Version 2.0 (the
  61877. * "License"); you may not use this file except in compliance
  61878. * with the License. You may obtain a copy of the License at
  61879. *
  61880. * http://www.apache.org/licenses/LICENSE-2.0
  61881. *
  61882. * Unless required by applicable law or agreed to in writing,
  61883. * software distributed under the License is distributed on an
  61884. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  61885. * KIND, either express or implied. See the License for the
  61886. * specific language governing permissions and limitations
  61887. * under the License.
  61888. */
  61889. /**
  61890. * @param {module:echarts/model/Model} axisPointerModel
  61891. */
  61892. function buildElStyle(axisPointerModel) {
  61893. var axisPointerType = axisPointerModel.get('type');
  61894. var styleModel = axisPointerModel.getModel(axisPointerType + 'Style');
  61895. var style;
  61896. if (axisPointerType === 'line') {
  61897. style = styleModel.getLineStyle();
  61898. style.fill = null;
  61899. }
  61900. else if (axisPointerType === 'shadow') {
  61901. style = styleModel.getAreaStyle();
  61902. style.stroke = null;
  61903. }
  61904. return style;
  61905. }
  61906. /**
  61907. * @param {Function} labelPos {align, verticalAlign, position}
  61908. */
  61909. function buildLabelElOption(
  61910. elOption, axisModel, axisPointerModel, api, labelPos
  61911. ) {
  61912. var value = axisPointerModel.get('value');
  61913. var text = getValueLabel(
  61914. value, axisModel.axis, axisModel.ecModel,
  61915. axisPointerModel.get('seriesDataIndices'),
  61916. {
  61917. precision: axisPointerModel.get('label.precision'),
  61918. formatter: axisPointerModel.get('label.formatter')
  61919. }
  61920. );
  61921. var labelModel = axisPointerModel.getModel('label');
  61922. var paddings = normalizeCssArray$1(labelModel.get('padding') || 0);
  61923. var font = labelModel.getFont();
  61924. var textRect = getBoundingRect(text, font);
  61925. var position = labelPos.position;
  61926. var width = textRect.width + paddings[1] + paddings[3];
  61927. var height = textRect.height + paddings[0] + paddings[2];
  61928. // Adjust by align.
  61929. var align = labelPos.align;
  61930. align === 'right' && (position[0] -= width);
  61931. align === 'center' && (position[0] -= width / 2);
  61932. var verticalAlign = labelPos.verticalAlign;
  61933. verticalAlign === 'bottom' && (position[1] -= height);
  61934. verticalAlign === 'middle' && (position[1] -= height / 2);
  61935. // Not overflow ec container
  61936. confineInContainer(position, width, height, api);
  61937. var bgColor = labelModel.get('backgroundColor');
  61938. if (!bgColor || bgColor === 'auto') {
  61939. bgColor = axisModel.get('axisLine.lineStyle.color');
  61940. }
  61941. elOption.label = {
  61942. shape: {x: 0, y: 0, width: width, height: height, r: labelModel.get('borderRadius')},
  61943. position: position.slice(),
  61944. // TODO: rich
  61945. style: {
  61946. text: text,
  61947. textFont: font,
  61948. textFill: labelModel.getTextColor(),
  61949. textPosition: 'inside',
  61950. textPadding: paddings,
  61951. fill: bgColor,
  61952. stroke: labelModel.get('borderColor') || 'transparent',
  61953. lineWidth: labelModel.get('borderWidth') || 0,
  61954. shadowBlur: labelModel.get('shadowBlur'),
  61955. shadowColor: labelModel.get('shadowColor'),
  61956. shadowOffsetX: labelModel.get('shadowOffsetX'),
  61957. shadowOffsetY: labelModel.get('shadowOffsetY')
  61958. },
  61959. // Lable should be over axisPointer.
  61960. z2: 10
  61961. };
  61962. }
  61963. // Do not overflow ec container
  61964. function confineInContainer(position, width, height, api) {
  61965. var viewWidth = api.getWidth();
  61966. var viewHeight = api.getHeight();
  61967. position[0] = Math.min(position[0] + width, viewWidth) - width;
  61968. position[1] = Math.min(position[1] + height, viewHeight) - height;
  61969. position[0] = Math.max(position[0], 0);
  61970. position[1] = Math.max(position[1], 0);
  61971. }
  61972. /**
  61973. * @param {number} value
  61974. * @param {module:echarts/coord/Axis} axis
  61975. * @param {module:echarts/model/Global} ecModel
  61976. * @param {Object} opt
  61977. * @param {Array.<Object>} seriesDataIndices
  61978. * @param {number|string} opt.precision 'auto' or a number
  61979. * @param {string|Function} opt.formatter label formatter
  61980. */
  61981. function getValueLabel(value, axis, ecModel, seriesDataIndices, opt) {
  61982. value = axis.scale.parse(value);
  61983. var text = axis.scale.getLabel(
  61984. // If `precision` is set, width can be fixed (like '12.00500'), which
  61985. // helps to debounce when when moving label.
  61986. value, {precision: opt.precision}
  61987. );
  61988. var formatter = opt.formatter;
  61989. if (formatter) {
  61990. var params = {
  61991. value: getAxisRawValue(axis, value),
  61992. axisDimension: axis.dim,
  61993. axisIndex: axis.index,
  61994. seriesData: []
  61995. };
  61996. each$1(seriesDataIndices, function (idxItem) {
  61997. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  61998. var dataIndex = idxItem.dataIndexInside;
  61999. var dataParams = series && series.getDataParams(dataIndex);
  62000. dataParams && params.seriesData.push(dataParams);
  62001. });
  62002. if (isString(formatter)) {
  62003. text = formatter.replace('{value}', text);
  62004. }
  62005. else if (isFunction$1(formatter)) {
  62006. text = formatter(params);
  62007. }
  62008. }
  62009. return text;
  62010. }
  62011. /**
  62012. * @param {module:echarts/coord/Axis} axis
  62013. * @param {number} value
  62014. * @param {Object} layoutInfo {
  62015. * rotation, position, labelOffset, labelDirection, labelMargin
  62016. * }
  62017. */
  62018. function getTransformedPosition(axis, value, layoutInfo) {
  62019. var transform = create$1();
  62020. rotate(transform, transform, layoutInfo.rotation);
  62021. translate(transform, transform, layoutInfo.position);
  62022. return applyTransform$1([
  62023. axis.dataToCoord(value),
  62024. (layoutInfo.labelOffset || 0)
  62025. + (layoutInfo.labelDirection || 1) * (layoutInfo.labelMargin || 0)
  62026. ], transform);
  62027. }
  62028. function buildCartesianSingleLabelElOption(
  62029. value, elOption, layoutInfo, axisModel, axisPointerModel, api
  62030. ) {
  62031. var textLayout = AxisBuilder.innerTextLayout(
  62032. layoutInfo.rotation, 0, layoutInfo.labelDirection
  62033. );
  62034. layoutInfo.labelMargin = axisPointerModel.get('label.margin');
  62035. buildLabelElOption(elOption, axisModel, axisPointerModel, api, {
  62036. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  62037. align: textLayout.textAlign,
  62038. verticalAlign: textLayout.textVerticalAlign
  62039. });
  62040. }
  62041. /**
  62042. * @param {Array.<number>} p1
  62043. * @param {Array.<number>} p2
  62044. * @param {number} [xDimIndex=0] or 1
  62045. */
  62046. function makeLineShape(p1, p2, xDimIndex) {
  62047. xDimIndex = xDimIndex || 0;
  62048. return {
  62049. x1: p1[xDimIndex],
  62050. y1: p1[1 - xDimIndex],
  62051. x2: p2[xDimIndex],
  62052. y2: p2[1 - xDimIndex]
  62053. };
  62054. }
  62055. /**
  62056. * @param {Array.<number>} xy
  62057. * @param {Array.<number>} wh
  62058. * @param {number} [xDimIndex=0] or 1
  62059. */
  62060. function makeRectShape(xy, wh, xDimIndex) {
  62061. xDimIndex = xDimIndex || 0;
  62062. return {
  62063. x: xy[xDimIndex],
  62064. y: xy[1 - xDimIndex],
  62065. width: wh[xDimIndex],
  62066. height: wh[1 - xDimIndex]
  62067. };
  62068. }
  62069. function makeSectorShape(cx, cy, r0, r, startAngle, endAngle) {
  62070. return {
  62071. cx: cx,
  62072. cy: cy,
  62073. r0: r0,
  62074. r: r,
  62075. startAngle: startAngle,
  62076. endAngle: endAngle,
  62077. clockwise: true
  62078. };
  62079. }
  62080. /*
  62081. * Licensed to the Apache Software Foundation (ASF) under one
  62082. * or more contributor license agreements. See the NOTICE file
  62083. * distributed with this work for additional information
  62084. * regarding copyright ownership. The ASF licenses this file
  62085. * to you under the Apache License, Version 2.0 (the
  62086. * "License"); you may not use this file except in compliance
  62087. * with the License. You may obtain a copy of the License at
  62088. *
  62089. * http://www.apache.org/licenses/LICENSE-2.0
  62090. *
  62091. * Unless required by applicable law or agreed to in writing,
  62092. * software distributed under the License is distributed on an
  62093. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62094. * KIND, either express or implied. See the License for the
  62095. * specific language governing permissions and limitations
  62096. * under the License.
  62097. */
  62098. var CartesianAxisPointer = BaseAxisPointer.extend({
  62099. /**
  62100. * @override
  62101. */
  62102. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  62103. var axis = axisModel.axis;
  62104. var grid = axis.grid;
  62105. var axisPointerType = axisPointerModel.get('type');
  62106. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  62107. var pixelValue = axis.toGlobalCoord(axis.dataToCoord(value, true));
  62108. if (axisPointerType && axisPointerType !== 'none') {
  62109. var elStyle = buildElStyle(axisPointerModel);
  62110. var pointerOption = pointerShapeBuilder[axisPointerType](
  62111. axis, pixelValue, otherExtent
  62112. );
  62113. pointerOption.style = elStyle;
  62114. elOption.graphicKey = pointerOption.type;
  62115. elOption.pointer = pointerOption;
  62116. }
  62117. var layoutInfo = layout$1(grid.model, axisModel);
  62118. buildCartesianSingleLabelElOption(
  62119. value, elOption, layoutInfo, axisModel, axisPointerModel, api
  62120. );
  62121. },
  62122. /**
  62123. * @override
  62124. */
  62125. getHandleTransform: function (value, axisModel, axisPointerModel) {
  62126. var layoutInfo = layout$1(axisModel.axis.grid.model, axisModel, {
  62127. labelInside: false
  62128. });
  62129. layoutInfo.labelMargin = axisPointerModel.get('handle.margin');
  62130. return {
  62131. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  62132. rotation: layoutInfo.rotation + (layoutInfo.labelDirection < 0 ? Math.PI : 0)
  62133. };
  62134. },
  62135. /**
  62136. * @override
  62137. */
  62138. updateHandleTransform: function (transform, delta, axisModel, axisPointerModel) {
  62139. var axis = axisModel.axis;
  62140. var grid = axis.grid;
  62141. var axisExtent = axis.getGlobalExtent(true);
  62142. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  62143. var dimIndex = axis.dim === 'x' ? 0 : 1;
  62144. var currPosition = transform.position;
  62145. currPosition[dimIndex] += delta[dimIndex];
  62146. currPosition[dimIndex] = Math.min(axisExtent[1], currPosition[dimIndex]);
  62147. currPosition[dimIndex] = Math.max(axisExtent[0], currPosition[dimIndex]);
  62148. var cursorOtherValue = (otherExtent[1] + otherExtent[0]) / 2;
  62149. var cursorPoint = [cursorOtherValue, cursorOtherValue];
  62150. cursorPoint[dimIndex] = currPosition[dimIndex];
  62151. // Make tooltip do not overlap axisPointer and in the middle of the grid.
  62152. var tooltipOptions = [{verticalAlign: 'middle'}, {align: 'center'}];
  62153. return {
  62154. position: currPosition,
  62155. rotation: transform.rotation,
  62156. cursorPoint: cursorPoint,
  62157. tooltipOption: tooltipOptions[dimIndex]
  62158. };
  62159. }
  62160. });
  62161. function getCartesian(grid, axis) {
  62162. var opt = {};
  62163. opt[axis.dim + 'AxisIndex'] = axis.index;
  62164. return grid.getCartesian(opt);
  62165. }
  62166. var pointerShapeBuilder = {
  62167. line: function (axis, pixelValue, otherExtent) {
  62168. var targetShape = makeLineShape(
  62169. [pixelValue, otherExtent[0]],
  62170. [pixelValue, otherExtent[1]],
  62171. getAxisDimIndex(axis)
  62172. );
  62173. return {
  62174. type: 'Line',
  62175. subPixelOptimize: true,
  62176. shape: targetShape
  62177. };
  62178. },
  62179. shadow: function (axis, pixelValue, otherExtent) {
  62180. var bandWidth = Math.max(1, axis.getBandWidth());
  62181. var span = otherExtent[1] - otherExtent[0];
  62182. return {
  62183. type: 'Rect',
  62184. shape: makeRectShape(
  62185. [pixelValue - bandWidth / 2, otherExtent[0]],
  62186. [bandWidth, span],
  62187. getAxisDimIndex(axis)
  62188. )
  62189. };
  62190. }
  62191. };
  62192. function getAxisDimIndex(axis) {
  62193. return axis.dim === 'x' ? 0 : 1;
  62194. }
  62195. AxisView.registerAxisPointerClass('CartesianAxisPointer', CartesianAxisPointer);
  62196. /*
  62197. * Licensed to the Apache Software Foundation (ASF) under one
  62198. * or more contributor license agreements. See the NOTICE file
  62199. * distributed with this work for additional information
  62200. * regarding copyright ownership. The ASF licenses this file
  62201. * to you under the Apache License, Version 2.0 (the
  62202. * "License"); you may not use this file except in compliance
  62203. * with the License. You may obtain a copy of the License at
  62204. *
  62205. * http://www.apache.org/licenses/LICENSE-2.0
  62206. *
  62207. * Unless required by applicable law or agreed to in writing,
  62208. * software distributed under the License is distributed on an
  62209. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62210. * KIND, either express or implied. See the License for the
  62211. * specific language governing permissions and limitations
  62212. * under the License.
  62213. */
  62214. // CartesianAxisPointer is not supposed to be required here. But consider
  62215. // echarts.simple.js and online build tooltip, which only require gridSimple,
  62216. // CartesianAxisPointer should be able to required somewhere.
  62217. registerPreprocessor(function (option) {
  62218. // Always has a global axisPointerModel for default setting.
  62219. if (option) {
  62220. (!option.axisPointer || option.axisPointer.length === 0)
  62221. && (option.axisPointer = {});
  62222. var link = option.axisPointer.link;
  62223. // Normalize to array to avoid object mergin. But if link
  62224. // is not set, remain null/undefined, otherwise it will
  62225. // override existent link setting.
  62226. if (link && !isArray(link)) {
  62227. option.axisPointer.link = [link];
  62228. }
  62229. }
  62230. });
  62231. // This process should proformed after coordinate systems created
  62232. // and series data processed. So put it on statistic processing stage.
  62233. registerProcessor(PRIORITY.PROCESSOR.STATISTIC, function (ecModel, api) {
  62234. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  62235. // allAxesInfo should be updated when setOption performed.
  62236. ecModel.getComponent('axisPointer').coordSysAxesInfo =
  62237. collect(ecModel, api);
  62238. });
  62239. // Broadcast to all views.
  62240. registerAction({
  62241. type: 'updateAxisPointer',
  62242. event: 'updateAxisPointer',
  62243. update: ':updateAxisPointer'
  62244. }, axisTrigger);
  62245. /*
  62246. * Licensed to the Apache Software Foundation (ASF) under one
  62247. * or more contributor license agreements. See the NOTICE file
  62248. * distributed with this work for additional information
  62249. * regarding copyright ownership. The ASF licenses this file
  62250. * to you under the Apache License, Version 2.0 (the
  62251. * "License"); you may not use this file except in compliance
  62252. * with the License. You may obtain a copy of the License at
  62253. *
  62254. * http://www.apache.org/licenses/LICENSE-2.0
  62255. *
  62256. * Unless required by applicable law or agreed to in writing,
  62257. * software distributed under the License is distributed on an
  62258. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62259. * KIND, either express or implied. See the License for the
  62260. * specific language governing permissions and limitations
  62261. * under the License.
  62262. */
  62263. var XY = ['x', 'y'];
  62264. var WH = ['width', 'height'];
  62265. var SingleAxisPointer = BaseAxisPointer.extend({
  62266. /**
  62267. * @override
  62268. */
  62269. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  62270. var axis = axisModel.axis;
  62271. var coordSys = axis.coordinateSystem;
  62272. var otherExtent = getGlobalExtent(coordSys, 1 - getPointDimIndex(axis));
  62273. var pixelValue = coordSys.dataToPoint(value)[0];
  62274. var axisPointerType = axisPointerModel.get('type');
  62275. if (axisPointerType && axisPointerType !== 'none') {
  62276. var elStyle = buildElStyle(axisPointerModel);
  62277. var pointerOption = pointerShapeBuilder$1[axisPointerType](
  62278. axis, pixelValue, otherExtent
  62279. );
  62280. pointerOption.style = elStyle;
  62281. elOption.graphicKey = pointerOption.type;
  62282. elOption.pointer = pointerOption;
  62283. }
  62284. var layoutInfo = layout$2(axisModel);
  62285. buildCartesianSingleLabelElOption(
  62286. value, elOption, layoutInfo, axisModel, axisPointerModel, api
  62287. );
  62288. },
  62289. /**
  62290. * @override
  62291. */
  62292. getHandleTransform: function (value, axisModel, axisPointerModel) {
  62293. var layoutInfo = layout$2(axisModel, {labelInside: false});
  62294. layoutInfo.labelMargin = axisPointerModel.get('handle.margin');
  62295. return {
  62296. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  62297. rotation: layoutInfo.rotation + (layoutInfo.labelDirection < 0 ? Math.PI : 0)
  62298. };
  62299. },
  62300. /**
  62301. * @override
  62302. */
  62303. updateHandleTransform: function (transform, delta, axisModel, axisPointerModel) {
  62304. var axis = axisModel.axis;
  62305. var coordSys = axis.coordinateSystem;
  62306. var dimIndex = getPointDimIndex(axis);
  62307. var axisExtent = getGlobalExtent(coordSys, dimIndex);
  62308. var currPosition = transform.position;
  62309. currPosition[dimIndex] += delta[dimIndex];
  62310. currPosition[dimIndex] = Math.min(axisExtent[1], currPosition[dimIndex]);
  62311. currPosition[dimIndex] = Math.max(axisExtent[0], currPosition[dimIndex]);
  62312. var otherExtent = getGlobalExtent(coordSys, 1 - dimIndex);
  62313. var cursorOtherValue = (otherExtent[1] + otherExtent[0]) / 2;
  62314. var cursorPoint = [cursorOtherValue, cursorOtherValue];
  62315. cursorPoint[dimIndex] = currPosition[dimIndex];
  62316. return {
  62317. position: currPosition,
  62318. rotation: transform.rotation,
  62319. cursorPoint: cursorPoint,
  62320. tooltipOption: {
  62321. verticalAlign: 'middle'
  62322. }
  62323. };
  62324. }
  62325. });
  62326. var pointerShapeBuilder$1 = {
  62327. line: function (axis, pixelValue, otherExtent) {
  62328. var targetShape = makeLineShape(
  62329. [pixelValue, otherExtent[0]],
  62330. [pixelValue, otherExtent[1]],
  62331. getPointDimIndex(axis)
  62332. );
  62333. return {
  62334. type: 'Line',
  62335. subPixelOptimize: true,
  62336. shape: targetShape
  62337. };
  62338. },
  62339. shadow: function (axis, pixelValue, otherExtent) {
  62340. var bandWidth = axis.getBandWidth();
  62341. var span = otherExtent[1] - otherExtent[0];
  62342. return {
  62343. type: 'Rect',
  62344. shape: makeRectShape(
  62345. [pixelValue - bandWidth / 2, otherExtent[0]],
  62346. [bandWidth, span],
  62347. getPointDimIndex(axis)
  62348. )
  62349. };
  62350. }
  62351. };
  62352. function getPointDimIndex(axis) {
  62353. return axis.isHorizontal() ? 0 : 1;
  62354. }
  62355. function getGlobalExtent(coordSys, dimIndex) {
  62356. var rect = coordSys.getRect();
  62357. return [rect[XY[dimIndex]], rect[XY[dimIndex]] + rect[WH[dimIndex]]];
  62358. }
  62359. AxisView.registerAxisPointerClass('SingleAxisPointer', SingleAxisPointer);
  62360. /*
  62361. * Licensed to the Apache Software Foundation (ASF) under one
  62362. * or more contributor license agreements. See the NOTICE file
  62363. * distributed with this work for additional information
  62364. * regarding copyright ownership. The ASF licenses this file
  62365. * to you under the Apache License, Version 2.0 (the
  62366. * "License"); you may not use this file except in compliance
  62367. * with the License. You may obtain a copy of the License at
  62368. *
  62369. * http://www.apache.org/licenses/LICENSE-2.0
  62370. *
  62371. * Unless required by applicable law or agreed to in writing,
  62372. * software distributed under the License is distributed on an
  62373. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62374. * KIND, either express or implied. See the License for the
  62375. * specific language governing permissions and limitations
  62376. * under the License.
  62377. */
  62378. extendComponentView({
  62379. type: 'single'
  62380. });
  62381. /*
  62382. * Licensed to the Apache Software Foundation (ASF) under one
  62383. * or more contributor license agreements. See the NOTICE file
  62384. * distributed with this work for additional information
  62385. * regarding copyright ownership. The ASF licenses this file
  62386. * to you under the Apache License, Version 2.0 (the
  62387. * "License"); you may not use this file except in compliance
  62388. * with the License. You may obtain a copy of the License at
  62389. *
  62390. * http://www.apache.org/licenses/LICENSE-2.0
  62391. *
  62392. * Unless required by applicable law or agreed to in writing,
  62393. * software distributed under the License is distributed on an
  62394. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62395. * KIND, either express or implied. See the License for the
  62396. * specific language governing permissions and limitations
  62397. * under the License.
  62398. */
  62399. var DATA_NAME_INDEX = 2;
  62400. var ThemeRiverSeries = SeriesModel.extend({
  62401. type: 'series.themeRiver',
  62402. dependencies: ['singleAxis'],
  62403. /**
  62404. * @readOnly
  62405. * @type {module:zrender/core/util#HashMap}
  62406. */
  62407. nameMap: null,
  62408. /**
  62409. * @override
  62410. */
  62411. init: function (option) {
  62412. // eslint-disable-next-line
  62413. ThemeRiverSeries.superApply(this, 'init', arguments);
  62414. // Put this function here is for the sake of consistency of code style.
  62415. // Enable legend selection for each data item
  62416. // Use a function instead of direct access because data reference may changed
  62417. this.legendVisualProvider = new LegendVisualProvider(
  62418. bind(this.getData, this), bind(this.getRawData, this)
  62419. );
  62420. },
  62421. /**
  62422. * If there is no value of a certain point in the time for some event,set it value to 0.
  62423. *
  62424. * @param {Array} data initial data in the option
  62425. * @return {Array}
  62426. */
  62427. fixData: function (data) {
  62428. var rawDataLength = data.length;
  62429. // grouped data by name
  62430. var groupResult = groupData(data, function (item) {
  62431. return item[2];
  62432. });
  62433. var layData = [];
  62434. groupResult.buckets.each(function (items, key) {
  62435. layData.push({name: key, dataList: items});
  62436. });
  62437. var layerNum = layData.length;
  62438. var largestLayer = -1;
  62439. var index = -1;
  62440. for (var i = 0; i < layerNum; ++i) {
  62441. var len = layData[i].dataList.length;
  62442. if (len > largestLayer) {
  62443. largestLayer = len;
  62444. index = i;
  62445. }
  62446. }
  62447. for (var k = 0; k < layerNum; ++k) {
  62448. if (k === index) {
  62449. continue;
  62450. }
  62451. var name = layData[k].name;
  62452. for (var j = 0; j < largestLayer; ++j) {
  62453. var timeValue = layData[index].dataList[j][0];
  62454. var length = layData[k].dataList.length;
  62455. var keyIndex = -1;
  62456. for (var l = 0; l < length; ++l) {
  62457. var value = layData[k].dataList[l][0];
  62458. if (value === timeValue) {
  62459. keyIndex = l;
  62460. break;
  62461. }
  62462. }
  62463. if (keyIndex === -1) {
  62464. data[rawDataLength] = [];
  62465. data[rawDataLength][0] = timeValue;
  62466. data[rawDataLength][1] = 0;
  62467. data[rawDataLength][2] = name;
  62468. rawDataLength++;
  62469. }
  62470. }
  62471. }
  62472. return data;
  62473. },
  62474. /**
  62475. * @override
  62476. * @param {Object} option the initial option that user gived
  62477. * @param {module:echarts/model/Model} ecModel the model object for themeRiver option
  62478. * @return {module:echarts/data/List}
  62479. */
  62480. getInitialData: function (option, ecModel) {
  62481. var singleAxisModel = ecModel.queryComponents({
  62482. mainType: 'singleAxis',
  62483. index: this.get('singleAxisIndex'),
  62484. id: this.get('singleAxisId')
  62485. })[0];
  62486. var axisType = singleAxisModel.get('type');
  62487. // filter the data item with the value of label is undefined
  62488. var filterData = filter(option.data, function (dataItem) {
  62489. return dataItem[2] !== undefined;
  62490. });
  62491. // ??? TODO design a stage to transfer data for themeRiver and lines?
  62492. var data = this.fixData(filterData || []);
  62493. var nameList = [];
  62494. var nameMap = this.nameMap = createHashMap();
  62495. var count = 0;
  62496. for (var i = 0; i < data.length; ++i) {
  62497. nameList.push(data[i][DATA_NAME_INDEX]);
  62498. if (!nameMap.get(data[i][DATA_NAME_INDEX])) {
  62499. nameMap.set(data[i][DATA_NAME_INDEX], count);
  62500. count++;
  62501. }
  62502. }
  62503. var dimensionsInfo = createDimensions(data, {
  62504. coordDimensions: ['single'],
  62505. dimensionsDefine: [
  62506. {
  62507. name: 'time',
  62508. type: getDimensionTypeByAxis(axisType)
  62509. },
  62510. {
  62511. name: 'value',
  62512. type: 'float'
  62513. },
  62514. {
  62515. name: 'name',
  62516. type: 'ordinal'
  62517. }
  62518. ],
  62519. encodeDefine: {
  62520. single: 0,
  62521. value: 1,
  62522. itemName: 2
  62523. }
  62524. });
  62525. var list = new List(dimensionsInfo, this);
  62526. list.initData(data);
  62527. return list;
  62528. },
  62529. /**
  62530. * The raw data is divided into multiple layers and each layer
  62531. * has same name.
  62532. *
  62533. * @return {Array.<Array.<number>>}
  62534. */
  62535. getLayerSeries: function () {
  62536. var data = this.getData();
  62537. var lenCount = data.count();
  62538. var indexArr = [];
  62539. for (var i = 0; i < lenCount; ++i) {
  62540. indexArr[i] = i;
  62541. }
  62542. var timeDim = data.mapDimension('single');
  62543. // data group by name
  62544. var groupResult = groupData(indexArr, function (index) {
  62545. return data.get('name', index);
  62546. });
  62547. var layerSeries = [];
  62548. groupResult.buckets.each(function (items, key) {
  62549. items.sort(function (index1, index2) {
  62550. return data.get(timeDim, index1) - data.get(timeDim, index2);
  62551. });
  62552. layerSeries.push({name: key, indices: items});
  62553. });
  62554. return layerSeries;
  62555. },
  62556. /**
  62557. * Get data indices for show tooltip content
  62558. * @param {Array.<string>|string} dim single coordinate dimension
  62559. * @param {number} value axis value
  62560. * @param {module:echarts/coord/single/SingleAxis} baseAxis single Axis used
  62561. * the themeRiver.
  62562. * @return {Object} {dataIndices, nestestValue}
  62563. */
  62564. getAxisTooltipData: function (dim, value, baseAxis) {
  62565. if (!isArray(dim)) {
  62566. dim = dim ? [dim] : [];
  62567. }
  62568. var data = this.getData();
  62569. var layerSeries = this.getLayerSeries();
  62570. var indices = [];
  62571. var layerNum = layerSeries.length;
  62572. var nestestValue;
  62573. for (var i = 0; i < layerNum; ++i) {
  62574. var minDist = Number.MAX_VALUE;
  62575. var nearestIdx = -1;
  62576. var pointNum = layerSeries[i].indices.length;
  62577. for (var j = 0; j < pointNum; ++j) {
  62578. var theValue = data.get(dim[0], layerSeries[i].indices[j]);
  62579. var dist = Math.abs(theValue - value);
  62580. if (dist <= minDist) {
  62581. nestestValue = theValue;
  62582. minDist = dist;
  62583. nearestIdx = layerSeries[i].indices[j];
  62584. }
  62585. }
  62586. indices.push(nearestIdx);
  62587. }
  62588. return {dataIndices: indices, nestestValue: nestestValue};
  62589. },
  62590. /**
  62591. * @override
  62592. * @param {number} dataIndex index of data
  62593. */
  62594. formatTooltip: function (dataIndex) {
  62595. var data = this.getData();
  62596. var htmlName = data.getName(dataIndex);
  62597. var htmlValue = data.get(data.mapDimension('value'), dataIndex);
  62598. if (isNaN(htmlValue) || htmlValue == null) {
  62599. htmlValue = '-';
  62600. }
  62601. return encodeHTML(htmlName + ' : ' + htmlValue);
  62602. },
  62603. defaultOption: {
  62604. zlevel: 0,
  62605. z: 2,
  62606. coordinateSystem: 'singleAxis',
  62607. // gap in axis's orthogonal orientation
  62608. boundaryGap: ['10%', '10%'],
  62609. // legendHoverLink: true,
  62610. singleAxisIndex: 0,
  62611. animationEasing: 'linear',
  62612. label: {
  62613. margin: 4,
  62614. show: true,
  62615. position: 'left',
  62616. color: '#000',
  62617. fontSize: 11
  62618. },
  62619. emphasis: {
  62620. label: {
  62621. show: true
  62622. }
  62623. }
  62624. }
  62625. });
  62626. /*
  62627. * Licensed to the Apache Software Foundation (ASF) under one
  62628. * or more contributor license agreements. See the NOTICE file
  62629. * distributed with this work for additional information
  62630. * regarding copyright ownership. The ASF licenses this file
  62631. * to you under the Apache License, Version 2.0 (the
  62632. * "License"); you may not use this file except in compliance
  62633. * with the License. You may obtain a copy of the License at
  62634. *
  62635. * http://www.apache.org/licenses/LICENSE-2.0
  62636. *
  62637. * Unless required by applicable law or agreed to in writing,
  62638. * software distributed under the License is distributed on an
  62639. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62640. * KIND, either express or implied. See the License for the
  62641. * specific language governing permissions and limitations
  62642. * under the License.
  62643. */
  62644. extendChartView({
  62645. type: 'themeRiver',
  62646. init: function () {
  62647. this._layers = [];
  62648. },
  62649. render: function (seriesModel, ecModel, api) {
  62650. var data = seriesModel.getData();
  62651. var group = this.group;
  62652. var layerSeries = seriesModel.getLayerSeries();
  62653. var layoutInfo = data.getLayout('layoutInfo');
  62654. var rect = layoutInfo.rect;
  62655. var boundaryGap = layoutInfo.boundaryGap;
  62656. group.attr('position', [0, rect.y + boundaryGap[0]]);
  62657. function keyGetter(item) {
  62658. return item.name;
  62659. }
  62660. var dataDiffer = new DataDiffer(
  62661. this._layersSeries || [], layerSeries,
  62662. keyGetter, keyGetter
  62663. );
  62664. var newLayersGroups = {};
  62665. dataDiffer
  62666. .add(bind(process, this, 'add'))
  62667. .update(bind(process, this, 'update'))
  62668. .remove(bind(process, this, 'remove'))
  62669. .execute();
  62670. function process(status, idx, oldIdx) {
  62671. var oldLayersGroups = this._layers;
  62672. if (status === 'remove') {
  62673. group.remove(oldLayersGroups[idx]);
  62674. return;
  62675. }
  62676. var points0 = [];
  62677. var points1 = [];
  62678. var color;
  62679. var indices = layerSeries[idx].indices;
  62680. for (var j = 0; j < indices.length; j++) {
  62681. var layout = data.getItemLayout(indices[j]);
  62682. var x = layout.x;
  62683. var y0 = layout.y0;
  62684. var y = layout.y;
  62685. points0.push([x, y0]);
  62686. points1.push([x, y0 + y]);
  62687. color = data.getItemVisual(indices[j], 'color');
  62688. }
  62689. var polygon;
  62690. var text;
  62691. var textLayout = data.getItemLayout(indices[0]);
  62692. var itemModel = data.getItemModel(indices[j - 1]);
  62693. var labelModel = itemModel.getModel('label');
  62694. var margin = labelModel.get('margin');
  62695. if (status === 'add') {
  62696. var layerGroup = newLayersGroups[idx] = new Group();
  62697. polygon = new Polygon$1({
  62698. shape: {
  62699. points: points0,
  62700. stackedOnPoints: points1,
  62701. smooth: 0.4,
  62702. stackedOnSmooth: 0.4,
  62703. smoothConstraint: false
  62704. },
  62705. z2: 0
  62706. });
  62707. text = new Text({
  62708. style: {
  62709. x: textLayout.x - margin,
  62710. y: textLayout.y0 + textLayout.y / 2
  62711. }
  62712. });
  62713. layerGroup.add(polygon);
  62714. layerGroup.add(text);
  62715. group.add(layerGroup);
  62716. polygon.setClipPath(createGridClipShape$2(polygon.getBoundingRect(), seriesModel, function () {
  62717. polygon.removeClipPath();
  62718. }));
  62719. }
  62720. else {
  62721. var layerGroup = oldLayersGroups[oldIdx];
  62722. polygon = layerGroup.childAt(0);
  62723. text = layerGroup.childAt(1);
  62724. group.add(layerGroup);
  62725. newLayersGroups[idx] = layerGroup;
  62726. updateProps(polygon, {
  62727. shape: {
  62728. points: points0,
  62729. stackedOnPoints: points1
  62730. }
  62731. }, seriesModel);
  62732. updateProps(text, {
  62733. style: {
  62734. x: textLayout.x - margin,
  62735. y: textLayout.y0 + textLayout.y / 2
  62736. }
  62737. }, seriesModel);
  62738. }
  62739. var hoverItemStyleModel = itemModel.getModel('emphasis.itemStyle');
  62740. var itemStyleModel = itemModel.getModel('itemStyle');
  62741. setTextStyle(text.style, labelModel, {
  62742. text: labelModel.get('show')
  62743. ? seriesModel.getFormattedLabel(indices[j - 1], 'normal')
  62744. || data.getName(indices[j - 1])
  62745. : null,
  62746. textVerticalAlign: 'middle'
  62747. });
  62748. polygon.setStyle(extend({
  62749. fill: color
  62750. }, itemStyleModel.getItemStyle(['color'])));
  62751. setHoverStyle(polygon, hoverItemStyleModel.getItemStyle());
  62752. }
  62753. this._layersSeries = layerSeries;
  62754. this._layers = newLayersGroups;
  62755. },
  62756. dispose: function () {}
  62757. });
  62758. // add animation to the view
  62759. function createGridClipShape$2(rect, seriesModel, cb) {
  62760. var rectEl = new Rect({
  62761. shape: {
  62762. x: rect.x - 10,
  62763. y: rect.y - 10,
  62764. width: 0,
  62765. height: rect.height + 20
  62766. }
  62767. });
  62768. initProps(rectEl, {
  62769. shape: {
  62770. width: rect.width + 20,
  62771. height: rect.height + 20
  62772. }
  62773. }, seriesModel, cb);
  62774. return rectEl;
  62775. }
  62776. /*
  62777. * Licensed to the Apache Software Foundation (ASF) under one
  62778. * or more contributor license agreements. See the NOTICE file
  62779. * distributed with this work for additional information
  62780. * regarding copyright ownership. The ASF licenses this file
  62781. * to you under the Apache License, Version 2.0 (the
  62782. * "License"); you may not use this file except in compliance
  62783. * with the License. You may obtain a copy of the License at
  62784. *
  62785. * http://www.apache.org/licenses/LICENSE-2.0
  62786. *
  62787. * Unless required by applicable law or agreed to in writing,
  62788. * software distributed under the License is distributed on an
  62789. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62790. * KIND, either express or implied. See the License for the
  62791. * specific language governing permissions and limitations
  62792. * under the License.
  62793. */
  62794. var themeRiverLayout = function (ecModel, api) {
  62795. ecModel.eachSeriesByType('themeRiver', function (seriesModel) {
  62796. var data = seriesModel.getData();
  62797. var single = seriesModel.coordinateSystem;
  62798. var layoutInfo = {};
  62799. // use the axis boundingRect for view
  62800. var rect = single.getRect();
  62801. layoutInfo.rect = rect;
  62802. var boundaryGap = seriesModel.get('boundaryGap');
  62803. var axis = single.getAxis();
  62804. layoutInfo.boundaryGap = boundaryGap;
  62805. if (axis.orient === 'horizontal') {
  62806. boundaryGap[0] = parsePercent$1(boundaryGap[0], rect.height);
  62807. boundaryGap[1] = parsePercent$1(boundaryGap[1], rect.height);
  62808. var height = rect.height - boundaryGap[0] - boundaryGap[1];
  62809. themeRiverLayout$1(data, seriesModel, height);
  62810. }
  62811. else {
  62812. boundaryGap[0] = parsePercent$1(boundaryGap[0], rect.width);
  62813. boundaryGap[1] = parsePercent$1(boundaryGap[1], rect.width);
  62814. var width = rect.width - boundaryGap[0] - boundaryGap[1];
  62815. themeRiverLayout$1(data, seriesModel, width);
  62816. }
  62817. data.setLayout('layoutInfo', layoutInfo);
  62818. });
  62819. };
  62820. /**
  62821. * The layout information about themeriver
  62822. *
  62823. * @param {module:echarts/data/List} data data in the series
  62824. * @param {module:echarts/model/Series} seriesModel the model object of themeRiver series
  62825. * @param {number} height value used to compute every series height
  62826. */
  62827. function themeRiverLayout$1(data, seriesModel, height) {
  62828. if (!data.count()) {
  62829. return;
  62830. }
  62831. var coordSys = seriesModel.coordinateSystem;
  62832. // the data in each layer are organized into a series.
  62833. var layerSeries = seriesModel.getLayerSeries();
  62834. // the points in each layer.
  62835. var timeDim = data.mapDimension('single');
  62836. var valueDim = data.mapDimension('value');
  62837. var layerPoints = map(layerSeries, function (singleLayer) {
  62838. return map(singleLayer.indices, function (idx) {
  62839. var pt = coordSys.dataToPoint(data.get(timeDim, idx));
  62840. pt[1] = data.get(valueDim, idx);
  62841. return pt;
  62842. });
  62843. });
  62844. var base = computeBaseline(layerPoints);
  62845. var baseLine = base.y0;
  62846. var ky = height / base.max;
  62847. // set layout information for each item.
  62848. var n = layerSeries.length;
  62849. var m = layerSeries[0].indices.length;
  62850. var baseY0;
  62851. for (var j = 0; j < m; ++j) {
  62852. baseY0 = baseLine[j] * ky;
  62853. data.setItemLayout(layerSeries[0].indices[j], {
  62854. layerIndex: 0,
  62855. x: layerPoints[0][j][0],
  62856. y0: baseY0,
  62857. y: layerPoints[0][j][1] * ky
  62858. });
  62859. for (var i = 1; i < n; ++i) {
  62860. baseY0 += layerPoints[i - 1][j][1] * ky;
  62861. data.setItemLayout(layerSeries[i].indices[j], {
  62862. layerIndex: i,
  62863. x: layerPoints[i][j][0],
  62864. y0: baseY0,
  62865. y: layerPoints[i][j][1] * ky
  62866. });
  62867. }
  62868. }
  62869. }
  62870. /**
  62871. * Compute the baseLine of the rawdata
  62872. * Inspired by Lee Byron's paper Stacked Graphs - Geometry & Aesthetics
  62873. *
  62874. * @param {Array.<Array>} data the points in each layer
  62875. * @return {Object}
  62876. */
  62877. function computeBaseline(data) {
  62878. var layerNum = data.length;
  62879. var pointNum = data[0].length;
  62880. var sums = [];
  62881. var y0 = [];
  62882. var max = 0;
  62883. var temp;
  62884. var base = {};
  62885. for (var i = 0; i < pointNum; ++i) {
  62886. for (var j = 0, temp = 0; j < layerNum; ++j) {
  62887. temp += data[j][i][1];
  62888. }
  62889. if (temp > max) {
  62890. max = temp;
  62891. }
  62892. sums.push(temp);
  62893. }
  62894. for (var k = 0; k < pointNum; ++k) {
  62895. y0[k] = (max - sums[k]) / 2;
  62896. }
  62897. max = 0;
  62898. for (var l = 0; l < pointNum; ++l) {
  62899. var sum = sums[l] + y0[l];
  62900. if (sum > max) {
  62901. max = sum;
  62902. }
  62903. }
  62904. base.y0 = y0;
  62905. base.max = max;
  62906. return base;
  62907. }
  62908. /*
  62909. * Licensed to the Apache Software Foundation (ASF) under one
  62910. * or more contributor license agreements. See the NOTICE file
  62911. * distributed with this work for additional information
  62912. * regarding copyright ownership. The ASF licenses this file
  62913. * to you under the Apache License, Version 2.0 (the
  62914. * "License"); you may not use this file except in compliance
  62915. * with the License. You may obtain a copy of the License at
  62916. *
  62917. * http://www.apache.org/licenses/LICENSE-2.0
  62918. *
  62919. * Unless required by applicable law or agreed to in writing,
  62920. * software distributed under the License is distributed on an
  62921. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62922. * KIND, either express or implied. See the License for the
  62923. * specific language governing permissions and limitations
  62924. * under the License.
  62925. */
  62926. var themeRiverVisual = function (ecModel) {
  62927. ecModel.eachSeriesByType('themeRiver', function (seriesModel) {
  62928. var data = seriesModel.getData();
  62929. var rawData = seriesModel.getRawData();
  62930. var colorList = seriesModel.get('color');
  62931. var idxMap = createHashMap();
  62932. data.each(function (idx) {
  62933. idxMap.set(data.getRawIndex(idx), idx);
  62934. });
  62935. rawData.each(function (rawIndex) {
  62936. var name = rawData.getName(rawIndex);
  62937. var color = colorList[(seriesModel.nameMap.get(name) - 1) % colorList.length];
  62938. rawData.setItemVisual(rawIndex, 'color', color);
  62939. var idx = idxMap.get(rawIndex);
  62940. if (idx != null) {
  62941. data.setItemVisual(idx, 'color', color);
  62942. }
  62943. });
  62944. });
  62945. };
  62946. /*
  62947. * Licensed to the Apache Software Foundation (ASF) under one
  62948. * or more contributor license agreements. See the NOTICE file
  62949. * distributed with this work for additional information
  62950. * regarding copyright ownership. The ASF licenses this file
  62951. * to you under the Apache License, Version 2.0 (the
  62952. * "License"); you may not use this file except in compliance
  62953. * with the License. You may obtain a copy of the License at
  62954. *
  62955. * http://www.apache.org/licenses/LICENSE-2.0
  62956. *
  62957. * Unless required by applicable law or agreed to in writing,
  62958. * software distributed under the License is distributed on an
  62959. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62960. * KIND, either express or implied. See the License for the
  62961. * specific language governing permissions and limitations
  62962. * under the License.
  62963. */
  62964. registerLayout(themeRiverLayout);
  62965. registerVisual(themeRiverVisual);
  62966. registerProcessor(dataFilter('themeRiver'));
  62967. /*
  62968. * Licensed to the Apache Software Foundation (ASF) under one
  62969. * or more contributor license agreements. See the NOTICE file
  62970. * distributed with this work for additional information
  62971. * regarding copyright ownership. The ASF licenses this file
  62972. * to you under the Apache License, Version 2.0 (the
  62973. * "License"); you may not use this file except in compliance
  62974. * with the License. You may obtain a copy of the License at
  62975. *
  62976. * http://www.apache.org/licenses/LICENSE-2.0
  62977. *
  62978. * Unless required by applicable law or agreed to in writing,
  62979. * software distributed under the License is distributed on an
  62980. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62981. * KIND, either express or implied. See the License for the
  62982. * specific language governing permissions and limitations
  62983. * under the License.
  62984. */
  62985. SeriesModel.extend({
  62986. type: 'series.sunburst',
  62987. /**
  62988. * @type {module:echarts/data/Tree~Node}
  62989. */
  62990. _viewRoot: null,
  62991. getInitialData: function (option, ecModel) {
  62992. // Create a virtual root.
  62993. var root = { name: option.name, children: option.data };
  62994. completeTreeValue$1(root);
  62995. var levels = option.levels || [];
  62996. // levels = option.levels = setDefault(levels, ecModel);
  62997. var treeOption = {};
  62998. treeOption.levels = levels;
  62999. // Make sure always a new tree is created when setOption,
  63000. // in TreemapView, we check whether oldTree === newTree
  63001. // to choose mappings approach among old shapes and new shapes.
  63002. return Tree.createTree(root, this, treeOption).data;
  63003. },
  63004. optionUpdated: function () {
  63005. this.resetViewRoot();
  63006. },
  63007. /*
  63008. * @override
  63009. */
  63010. getDataParams: function (dataIndex) {
  63011. var params = SeriesModel.prototype.getDataParams.apply(this, arguments);
  63012. var node = this.getData().tree.getNodeByDataIndex(dataIndex);
  63013. params.treePathInfo = wrapTreePathInfo(node, this);
  63014. return params;
  63015. },
  63016. defaultOption: {
  63017. zlevel: 0,
  63018. z: 2,
  63019. // 默认全局居中
  63020. center: ['50%', '50%'],
  63021. radius: [0, '75%'],
  63022. // 默认顺时针
  63023. clockwise: true,
  63024. startAngle: 90,
  63025. // 最小角度改为0
  63026. minAngle: 0,
  63027. percentPrecision: 2,
  63028. // If still show when all data zero.
  63029. stillShowZeroSum: true,
  63030. // Policy of highlighting pieces when hover on one
  63031. // Valid values: 'none' (for not downplay others), 'descendant',
  63032. // 'ancestor', 'self'
  63033. highlightPolicy: 'descendant',
  63034. // 'rootToNode', 'link', or false
  63035. nodeClick: 'rootToNode',
  63036. renderLabelForZeroData: false,
  63037. label: {
  63038. // could be: 'radial', 'tangential', or 'none'
  63039. rotate: 'radial',
  63040. show: true,
  63041. opacity: 1,
  63042. // 'left' is for inner side of inside, and 'right' is for outter
  63043. // side for inside
  63044. align: 'center',
  63045. position: 'inside',
  63046. distance: 5,
  63047. silent: true
  63048. },
  63049. itemStyle: {
  63050. borderWidth: 1,
  63051. borderColor: 'white',
  63052. borderType: 'solid',
  63053. shadowBlur: 0,
  63054. shadowColor: 'rgba(0, 0, 0, 0.2)',
  63055. shadowOffsetX: 0,
  63056. shadowOffsetY: 0,
  63057. opacity: 1
  63058. },
  63059. highlight: {
  63060. itemStyle: {
  63061. opacity: 1
  63062. }
  63063. },
  63064. downplay: {
  63065. itemStyle: {
  63066. opacity: 0.5
  63067. },
  63068. label: {
  63069. opacity: 0.6
  63070. }
  63071. },
  63072. // Animation type canbe expansion, scale
  63073. animationType: 'expansion',
  63074. animationDuration: 1000,
  63075. animationDurationUpdate: 500,
  63076. animationEasing: 'cubicOut',
  63077. data: [],
  63078. levels: [],
  63079. /**
  63080. * Sort order.
  63081. *
  63082. * Valid values: 'desc', 'asc', null, or callback function.
  63083. * 'desc' and 'asc' for descend and ascendant order;
  63084. * null for not sorting;
  63085. * example of callback function:
  63086. * function(nodeA, nodeB) {
  63087. * return nodeA.getValue() - nodeB.getValue();
  63088. * }
  63089. */
  63090. sort: 'desc'
  63091. },
  63092. getViewRoot: function () {
  63093. return this._viewRoot;
  63094. },
  63095. /**
  63096. * @param {module:echarts/data/Tree~Node} [viewRoot]
  63097. */
  63098. resetViewRoot: function (viewRoot) {
  63099. viewRoot
  63100. ? (this._viewRoot = viewRoot)
  63101. : (viewRoot = this._viewRoot);
  63102. var root = this.getRawData().tree.root;
  63103. if (!viewRoot
  63104. || (viewRoot !== root && !root.contains(viewRoot))
  63105. ) {
  63106. this._viewRoot = root;
  63107. }
  63108. }
  63109. });
  63110. /**
  63111. * @param {Object} dataNode
  63112. */
  63113. function completeTreeValue$1(dataNode) {
  63114. // Postorder travel tree.
  63115. // If value of none-leaf node is not set,
  63116. // calculate it by suming up the value of all children.
  63117. var sum = 0;
  63118. each$1(dataNode.children, function (child) {
  63119. completeTreeValue$1(child);
  63120. var childValue = child.value;
  63121. isArray(childValue) && (childValue = childValue[0]);
  63122. sum += childValue;
  63123. });
  63124. var thisValue = dataNode.value;
  63125. if (isArray(thisValue)) {
  63126. thisValue = thisValue[0];
  63127. }
  63128. if (thisValue == null || isNaN(thisValue)) {
  63129. thisValue = sum;
  63130. }
  63131. // Value should not less than 0.
  63132. if (thisValue < 0) {
  63133. thisValue = 0;
  63134. }
  63135. isArray(dataNode.value)
  63136. ? (dataNode.value[0] = thisValue)
  63137. : (dataNode.value = thisValue);
  63138. }
  63139. /*
  63140. * Licensed to the Apache Software Foundation (ASF) under one
  63141. * or more contributor license agreements. See the NOTICE file
  63142. * distributed with this work for additional information
  63143. * regarding copyright ownership. The ASF licenses this file
  63144. * to you under the Apache License, Version 2.0 (the
  63145. * "License"); you may not use this file except in compliance
  63146. * with the License. You may obtain a copy of the License at
  63147. *
  63148. * http://www.apache.org/licenses/LICENSE-2.0
  63149. *
  63150. * Unless required by applicable law or agreed to in writing,
  63151. * software distributed under the License is distributed on an
  63152. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63153. * KIND, either express or implied. See the License for the
  63154. * specific language governing permissions and limitations
  63155. * under the License.
  63156. */
  63157. var NodeHighlightPolicy = {
  63158. NONE: 'none', // not downplay others
  63159. DESCENDANT: 'descendant',
  63160. ANCESTOR: 'ancestor',
  63161. SELF: 'self'
  63162. };
  63163. var DEFAULT_SECTOR_Z = 2;
  63164. var DEFAULT_TEXT_Z = 4;
  63165. /**
  63166. * Sunburstce of Sunburst including Sector, Label, LabelLine
  63167. * @constructor
  63168. * @extends {module:zrender/graphic/Group}
  63169. */
  63170. function SunburstPiece(node, seriesModel, ecModel) {
  63171. Group.call(this);
  63172. var sector = new Sector({
  63173. z2: DEFAULT_SECTOR_Z
  63174. });
  63175. sector.seriesIndex = seriesModel.seriesIndex;
  63176. var text = new Text({
  63177. z2: DEFAULT_TEXT_Z,
  63178. silent: node.getModel('label').get('silent')
  63179. });
  63180. this.add(sector);
  63181. this.add(text);
  63182. this.updateData(true, node, 'normal', seriesModel, ecModel);
  63183. // Hover to change label and labelLine
  63184. function onEmphasis() {
  63185. text.ignore = text.hoverIgnore;
  63186. }
  63187. function onNormal() {
  63188. text.ignore = text.normalIgnore;
  63189. }
  63190. this.on('emphasis', onEmphasis)
  63191. .on('normal', onNormal)
  63192. .on('mouseover', onEmphasis)
  63193. .on('mouseout', onNormal);
  63194. }
  63195. var SunburstPieceProto = SunburstPiece.prototype;
  63196. SunburstPieceProto.updateData = function (
  63197. firstCreate,
  63198. node,
  63199. state,
  63200. seriesModel,
  63201. ecModel
  63202. ) {
  63203. this.node = node;
  63204. node.piece = this;
  63205. seriesModel = seriesModel || this._seriesModel;
  63206. ecModel = ecModel || this._ecModel;
  63207. var sector = this.childAt(0);
  63208. sector.dataIndex = node.dataIndex;
  63209. var itemModel = node.getModel();
  63210. var layout = node.getLayout();
  63211. // if (!layout) {
  63212. // console.log(node.getLayout());
  63213. // }
  63214. var sectorShape = extend({}, layout);
  63215. sectorShape.label = null;
  63216. var visualColor = getNodeColor(node, seriesModel, ecModel);
  63217. fillDefaultColor(node, seriesModel, visualColor);
  63218. var normalStyle = itemModel.getModel('itemStyle').getItemStyle();
  63219. var style;
  63220. if (state === 'normal') {
  63221. style = normalStyle;
  63222. }
  63223. else {
  63224. var stateStyle = itemModel.getModel(state + '.itemStyle')
  63225. .getItemStyle();
  63226. style = merge(stateStyle, normalStyle);
  63227. }
  63228. style = defaults(
  63229. {
  63230. lineJoin: 'bevel',
  63231. fill: style.fill || visualColor
  63232. },
  63233. style
  63234. );
  63235. if (firstCreate) {
  63236. sector.setShape(sectorShape);
  63237. sector.shape.r = layout.r0;
  63238. updateProps(
  63239. sector,
  63240. {
  63241. shape: {
  63242. r: layout.r
  63243. }
  63244. },
  63245. seriesModel,
  63246. node.dataIndex
  63247. );
  63248. sector.useStyle(style);
  63249. }
  63250. else if (typeof style.fill === 'object' && style.fill.type
  63251. || typeof sector.style.fill === 'object' && sector.style.fill.type
  63252. ) {
  63253. // Disable animation for gradient since no interpolation method
  63254. // is supported for gradient
  63255. updateProps(sector, {
  63256. shape: sectorShape
  63257. }, seriesModel);
  63258. sector.useStyle(style);
  63259. }
  63260. else {
  63261. updateProps(sector, {
  63262. shape: sectorShape,
  63263. style: style
  63264. }, seriesModel);
  63265. }
  63266. this._updateLabel(seriesModel, visualColor, state);
  63267. var cursorStyle = itemModel.getShallow('cursor');
  63268. cursorStyle && sector.attr('cursor', cursorStyle);
  63269. if (firstCreate) {
  63270. var highlightPolicy = seriesModel.getShallow('highlightPolicy');
  63271. this._initEvents(sector, node, seriesModel, highlightPolicy);
  63272. }
  63273. this._seriesModel = seriesModel || this._seriesModel;
  63274. this._ecModel = ecModel || this._ecModel;
  63275. setHoverStyle(this);
  63276. };
  63277. SunburstPieceProto.onEmphasis = function (highlightPolicy) {
  63278. var that = this;
  63279. this.node.hostTree.root.eachNode(function (n) {
  63280. if (n.piece) {
  63281. if (that.node === n) {
  63282. n.piece.updateData(false, n, 'emphasis');
  63283. }
  63284. else if (isNodeHighlighted(n, that.node, highlightPolicy)) {
  63285. n.piece.childAt(0).trigger('highlight');
  63286. }
  63287. else if (highlightPolicy !== NodeHighlightPolicy.NONE) {
  63288. n.piece.childAt(0).trigger('downplay');
  63289. }
  63290. }
  63291. });
  63292. };
  63293. SunburstPieceProto.onNormal = function () {
  63294. this.node.hostTree.root.eachNode(function (n) {
  63295. if (n.piece) {
  63296. n.piece.updateData(false, n, 'normal');
  63297. }
  63298. });
  63299. };
  63300. SunburstPieceProto.onHighlight = function () {
  63301. this.updateData(false, this.node, 'highlight');
  63302. };
  63303. SunburstPieceProto.onDownplay = function () {
  63304. this.updateData(false, this.node, 'downplay');
  63305. };
  63306. SunburstPieceProto._updateLabel = function (seriesModel, visualColor, state) {
  63307. var itemModel = this.node.getModel();
  63308. var normalModel = itemModel.getModel('label');
  63309. var labelModel = state === 'normal' || state === 'emphasis'
  63310. ? normalModel
  63311. : itemModel.getModel(state + '.label');
  63312. var labelHoverModel = itemModel.getModel('emphasis.label');
  63313. var text = retrieve(
  63314. seriesModel.getFormattedLabel(
  63315. this.node.dataIndex, state, null, null, 'label'
  63316. ),
  63317. this.node.name
  63318. );
  63319. if (getLabelAttr('show') === false) {
  63320. text = '';
  63321. }
  63322. var layout = this.node.getLayout();
  63323. var labelMinAngle = labelModel.get('minAngle');
  63324. if (labelMinAngle == null) {
  63325. labelMinAngle = normalModel.get('minAngle');
  63326. }
  63327. labelMinAngle = labelMinAngle / 180 * Math.PI;
  63328. var angle = layout.endAngle - layout.startAngle;
  63329. if (labelMinAngle != null && Math.abs(angle) < labelMinAngle) {
  63330. // Not displaying text when angle is too small
  63331. text = '';
  63332. }
  63333. var label = this.childAt(1);
  63334. setLabelStyle(
  63335. label.style, label.hoverStyle || {}, normalModel, labelHoverModel,
  63336. {
  63337. defaultText: labelModel.getShallow('show') ? text : null,
  63338. autoColor: visualColor,
  63339. useInsideStyle: true
  63340. }
  63341. );
  63342. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  63343. var dx = Math.cos(midAngle);
  63344. var dy = Math.sin(midAngle);
  63345. var r;
  63346. var labelPosition = getLabelAttr('position');
  63347. var labelPadding = getLabelAttr('distance') || 0;
  63348. var textAlign = getLabelAttr('align');
  63349. if (labelPosition === 'outside') {
  63350. r = layout.r + labelPadding;
  63351. textAlign = midAngle > Math.PI / 2 ? 'right' : 'left';
  63352. }
  63353. else {
  63354. if (!textAlign || textAlign === 'center') {
  63355. r = (layout.r + layout.r0) / 2;
  63356. textAlign = 'center';
  63357. }
  63358. else if (textAlign === 'left') {
  63359. r = layout.r0 + labelPadding;
  63360. if (midAngle > Math.PI / 2) {
  63361. textAlign = 'right';
  63362. }
  63363. }
  63364. else if (textAlign === 'right') {
  63365. r = layout.r - labelPadding;
  63366. if (midAngle > Math.PI / 2) {
  63367. textAlign = 'left';
  63368. }
  63369. }
  63370. }
  63371. label.attr('style', {
  63372. text: text,
  63373. textAlign: textAlign,
  63374. textVerticalAlign: getLabelAttr('verticalAlign') || 'middle',
  63375. opacity: getLabelAttr('opacity')
  63376. });
  63377. var textX = r * dx + layout.cx;
  63378. var textY = r * dy + layout.cy;
  63379. label.attr('position', [textX, textY]);
  63380. var rotateType = getLabelAttr('rotate');
  63381. var rotate = 0;
  63382. if (rotateType === 'radial') {
  63383. rotate = -midAngle;
  63384. if (rotate < -Math.PI / 2) {
  63385. rotate += Math.PI;
  63386. }
  63387. }
  63388. else if (rotateType === 'tangential') {
  63389. rotate = Math.PI / 2 - midAngle;
  63390. if (rotate > Math.PI / 2) {
  63391. rotate -= Math.PI;
  63392. }
  63393. else if (rotate < -Math.PI / 2) {
  63394. rotate += Math.PI;
  63395. }
  63396. }
  63397. else if (typeof rotateType === 'number') {
  63398. rotate = rotateType * Math.PI / 180;
  63399. }
  63400. label.attr('rotation', rotate);
  63401. function getLabelAttr(name) {
  63402. var stateAttr = labelModel.get(name);
  63403. if (stateAttr == null) {
  63404. return normalModel.get(name);
  63405. }
  63406. else {
  63407. return stateAttr;
  63408. }
  63409. }
  63410. };
  63411. SunburstPieceProto._initEvents = function (
  63412. sector,
  63413. node,
  63414. seriesModel,
  63415. highlightPolicy
  63416. ) {
  63417. sector.off('mouseover').off('mouseout').off('emphasis').off('normal');
  63418. var that = this;
  63419. var onEmphasis = function () {
  63420. that.onEmphasis(highlightPolicy);
  63421. };
  63422. var onNormal = function () {
  63423. that.onNormal();
  63424. };
  63425. var onDownplay = function () {
  63426. that.onDownplay();
  63427. };
  63428. var onHighlight = function () {
  63429. that.onHighlight();
  63430. };
  63431. if (seriesModel.isAnimationEnabled()) {
  63432. sector
  63433. .on('mouseover', onEmphasis)
  63434. .on('mouseout', onNormal)
  63435. .on('emphasis', onEmphasis)
  63436. .on('normal', onNormal)
  63437. .on('downplay', onDownplay)
  63438. .on('highlight', onHighlight);
  63439. }
  63440. };
  63441. inherits(SunburstPiece, Group);
  63442. /**
  63443. * Get node color
  63444. *
  63445. * @param {TreeNode} node the node to get color
  63446. * @param {module:echarts/model/Series} seriesModel series
  63447. * @param {module:echarts/model/Global} ecModel echarts defaults
  63448. */
  63449. function getNodeColor(node, seriesModel, ecModel) {
  63450. // Color from visualMap
  63451. var visualColor = node.getVisual('color');
  63452. var visualMetaList = node.getVisual('visualMeta');
  63453. if (!visualMetaList || visualMetaList.length === 0) {
  63454. // Use first-generation color if has no visualMap
  63455. visualColor = null;
  63456. }
  63457. // Self color or level color
  63458. var color = node.getModel('itemStyle').get('color');
  63459. if (color) {
  63460. return color;
  63461. }
  63462. else if (visualColor) {
  63463. // Color mapping
  63464. return visualColor;
  63465. }
  63466. else if (node.depth === 0) {
  63467. // Virtual root node
  63468. return ecModel.option.color[0];
  63469. }
  63470. else {
  63471. // First-generation color
  63472. var length = ecModel.option.color.length;
  63473. color = ecModel.option.color[getRootId(node) % length];
  63474. }
  63475. return color;
  63476. }
  63477. /**
  63478. * Get index of root in sorted order
  63479. *
  63480. * @param {TreeNode} node current node
  63481. * @return {number} index in root
  63482. */
  63483. function getRootId(node) {
  63484. var ancestor = node;
  63485. while (ancestor.depth > 1) {
  63486. ancestor = ancestor.parentNode;
  63487. }
  63488. var virtualRoot = node.getAncestors()[0];
  63489. return indexOf(virtualRoot.children, ancestor);
  63490. }
  63491. function isNodeHighlighted(node, activeNode, policy) {
  63492. if (policy === NodeHighlightPolicy.NONE) {
  63493. return false;
  63494. }
  63495. else if (policy === NodeHighlightPolicy.SELF) {
  63496. return node === activeNode;
  63497. }
  63498. else if (policy === NodeHighlightPolicy.ANCESTOR) {
  63499. return node === activeNode || node.isAncestorOf(activeNode);
  63500. }
  63501. else {
  63502. return node === activeNode || node.isDescendantOf(activeNode);
  63503. }
  63504. }
  63505. // Fix tooltip callback function params.color incorrect when pick a default color
  63506. function fillDefaultColor(node, seriesModel, color) {
  63507. var data = seriesModel.getData();
  63508. data.setItemVisual(node.dataIndex, 'color', color);
  63509. }
  63510. /*
  63511. * Licensed to the Apache Software Foundation (ASF) under one
  63512. * or more contributor license agreements. See the NOTICE file
  63513. * distributed with this work for additional information
  63514. * regarding copyright ownership. The ASF licenses this file
  63515. * to you under the Apache License, Version 2.0 (the
  63516. * "License"); you may not use this file except in compliance
  63517. * with the License. You may obtain a copy of the License at
  63518. *
  63519. * http://www.apache.org/licenses/LICENSE-2.0
  63520. *
  63521. * Unless required by applicable law or agreed to in writing,
  63522. * software distributed under the License is distributed on an
  63523. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63524. * KIND, either express or implied. See the License for the
  63525. * specific language governing permissions and limitations
  63526. * under the License.
  63527. */
  63528. var ROOT_TO_NODE_ACTION = 'sunburstRootToNode';
  63529. var SunburstView = Chart.extend({
  63530. type: 'sunburst',
  63531. init: function () {
  63532. },
  63533. render: function (seriesModel, ecModel, api, payload) {
  63534. var that = this;
  63535. this.seriesModel = seriesModel;
  63536. this.api = api;
  63537. this.ecModel = ecModel;
  63538. var data = seriesModel.getData();
  63539. var virtualRoot = data.tree.root;
  63540. var newRoot = seriesModel.getViewRoot();
  63541. var group = this.group;
  63542. var renderLabelForZeroData = seriesModel.get('renderLabelForZeroData');
  63543. var newChildren = [];
  63544. newRoot.eachNode(function (node) {
  63545. newChildren.push(node);
  63546. });
  63547. var oldChildren = this._oldChildren || [];
  63548. dualTravel(newChildren, oldChildren);
  63549. renderRollUp(virtualRoot, newRoot);
  63550. if (payload && payload.highlight && payload.highlight.piece) {
  63551. var highlightPolicy = seriesModel.getShallow('highlightPolicy');
  63552. payload.highlight.piece.onEmphasis(highlightPolicy);
  63553. }
  63554. else if (payload && payload.unhighlight) {
  63555. var piece = this.virtualPiece;
  63556. if (!piece && virtualRoot.children.length) {
  63557. piece = virtualRoot.children[0].piece;
  63558. }
  63559. if (piece) {
  63560. piece.onNormal();
  63561. }
  63562. }
  63563. this._initEvents();
  63564. this._oldChildren = newChildren;
  63565. function dualTravel(newChildren, oldChildren) {
  63566. if (newChildren.length === 0 && oldChildren.length === 0) {
  63567. return;
  63568. }
  63569. new DataDiffer(oldChildren, newChildren, getKey, getKey)
  63570. .add(processNode)
  63571. .update(processNode)
  63572. .remove(curry(processNode, null))
  63573. .execute();
  63574. function getKey(node) {
  63575. return node.getId();
  63576. }
  63577. function processNode(newId, oldId) {
  63578. var newNode = newId == null ? null : newChildren[newId];
  63579. var oldNode = oldId == null ? null : oldChildren[oldId];
  63580. doRenderNode(newNode, oldNode);
  63581. }
  63582. }
  63583. function doRenderNode(newNode, oldNode) {
  63584. if (!renderLabelForZeroData && newNode && !newNode.getValue()) {
  63585. // Not render data with value 0
  63586. newNode = null;
  63587. }
  63588. if (newNode !== virtualRoot && oldNode !== virtualRoot) {
  63589. if (oldNode && oldNode.piece) {
  63590. if (newNode) {
  63591. // Update
  63592. oldNode.piece.updateData(
  63593. false, newNode, 'normal', seriesModel, ecModel);
  63594. // For tooltip
  63595. data.setItemGraphicEl(newNode.dataIndex, oldNode.piece);
  63596. }
  63597. else {
  63598. // Remove
  63599. removeNode(oldNode);
  63600. }
  63601. }
  63602. else if (newNode) {
  63603. // Add
  63604. var piece = new SunburstPiece(
  63605. newNode,
  63606. seriesModel,
  63607. ecModel
  63608. );
  63609. group.add(piece);
  63610. // For tooltip
  63611. data.setItemGraphicEl(newNode.dataIndex, piece);
  63612. }
  63613. }
  63614. }
  63615. function removeNode(node) {
  63616. if (!node) {
  63617. return;
  63618. }
  63619. if (node.piece) {
  63620. group.remove(node.piece);
  63621. node.piece = null;
  63622. }
  63623. }
  63624. function renderRollUp(virtualRoot, viewRoot) {
  63625. if (viewRoot.depth > 0) {
  63626. // Render
  63627. if (that.virtualPiece) {
  63628. // Update
  63629. that.virtualPiece.updateData(
  63630. false, virtualRoot, 'normal', seriesModel, ecModel);
  63631. }
  63632. else {
  63633. // Add
  63634. that.virtualPiece = new SunburstPiece(
  63635. virtualRoot,
  63636. seriesModel,
  63637. ecModel
  63638. );
  63639. group.add(that.virtualPiece);
  63640. }
  63641. if (viewRoot.piece._onclickEvent) {
  63642. viewRoot.piece.off('click', viewRoot.piece._onclickEvent);
  63643. }
  63644. var event = function (e) {
  63645. that._rootToNode(viewRoot.parentNode);
  63646. };
  63647. viewRoot.piece._onclickEvent = event;
  63648. that.virtualPiece.on('click', event);
  63649. }
  63650. else if (that.virtualPiece) {
  63651. // Remove
  63652. group.remove(that.virtualPiece);
  63653. that.virtualPiece = null;
  63654. }
  63655. }
  63656. },
  63657. dispose: function () {
  63658. },
  63659. /**
  63660. * @private
  63661. */
  63662. _initEvents: function () {
  63663. var that = this;
  63664. var event = function (e) {
  63665. var targetFound = false;
  63666. var viewRoot = that.seriesModel.getViewRoot();
  63667. viewRoot.eachNode(function (node) {
  63668. if (!targetFound
  63669. && node.piece && node.piece.childAt(0) === e.target
  63670. ) {
  63671. var nodeClick = node.getModel().get('nodeClick');
  63672. if (nodeClick === 'rootToNode') {
  63673. that._rootToNode(node);
  63674. }
  63675. else if (nodeClick === 'link') {
  63676. var itemModel = node.getModel();
  63677. var link = itemModel.get('link');
  63678. if (link) {
  63679. var linkTarget = itemModel.get('target', true)
  63680. || '_blank';
  63681. windowOpen(link, linkTarget);
  63682. }
  63683. }
  63684. targetFound = true;
  63685. }
  63686. });
  63687. };
  63688. if (this.group._onclickEvent) {
  63689. this.group.off('click', this.group._onclickEvent);
  63690. }
  63691. this.group.on('click', event);
  63692. this.group._onclickEvent = event;
  63693. },
  63694. /**
  63695. * @private
  63696. */
  63697. _rootToNode: function (node) {
  63698. if (node !== this.seriesModel.getViewRoot()) {
  63699. this.api.dispatchAction({
  63700. type: ROOT_TO_NODE_ACTION,
  63701. from: this.uid,
  63702. seriesId: this.seriesModel.id,
  63703. targetNode: node
  63704. });
  63705. }
  63706. },
  63707. /**
  63708. * @implement
  63709. */
  63710. containPoint: function (point, seriesModel) {
  63711. var treeRoot = seriesModel.getData();
  63712. var itemLayout = treeRoot.getItemLayout(0);
  63713. if (itemLayout) {
  63714. var dx = point[0] - itemLayout.cx;
  63715. var dy = point[1] - itemLayout.cy;
  63716. var radius = Math.sqrt(dx * dx + dy * dy);
  63717. return radius <= itemLayout.r && radius >= itemLayout.r0;
  63718. }
  63719. }
  63720. });
  63721. /*
  63722. * Licensed to the Apache Software Foundation (ASF) under one
  63723. * or more contributor license agreements. See the NOTICE file
  63724. * distributed with this work for additional information
  63725. * regarding copyright ownership. The ASF licenses this file
  63726. * to you under the Apache License, Version 2.0 (the
  63727. * "License"); you may not use this file except in compliance
  63728. * with the License. You may obtain a copy of the License at
  63729. *
  63730. * http://www.apache.org/licenses/LICENSE-2.0
  63731. *
  63732. * Unless required by applicable law or agreed to in writing,
  63733. * software distributed under the License is distributed on an
  63734. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63735. * KIND, either express or implied. See the License for the
  63736. * specific language governing permissions and limitations
  63737. * under the License.
  63738. */
  63739. /**
  63740. * @file Sunburst action
  63741. */
  63742. var ROOT_TO_NODE_ACTION$1 = 'sunburstRootToNode';
  63743. registerAction(
  63744. {type: ROOT_TO_NODE_ACTION$1, update: 'updateView'},
  63745. function (payload, ecModel) {
  63746. ecModel.eachComponent(
  63747. {mainType: 'series', subType: 'sunburst', query: payload},
  63748. handleRootToNode
  63749. );
  63750. function handleRootToNode(model, index) {
  63751. var targetInfo = retrieveTargetInfo(payload, [ROOT_TO_NODE_ACTION$1], model);
  63752. if (targetInfo) {
  63753. var originViewRoot = model.getViewRoot();
  63754. if (originViewRoot) {
  63755. payload.direction = aboveViewRoot(originViewRoot, targetInfo.node)
  63756. ? 'rollUp' : 'drillDown';
  63757. }
  63758. model.resetViewRoot(targetInfo.node);
  63759. }
  63760. }
  63761. }
  63762. );
  63763. var HIGHLIGHT_ACTION = 'sunburstHighlight';
  63764. registerAction(
  63765. {type: HIGHLIGHT_ACTION, update: 'updateView'},
  63766. function (payload, ecModel) {
  63767. ecModel.eachComponent(
  63768. {mainType: 'series', subType: 'sunburst', query: payload},
  63769. handleHighlight
  63770. );
  63771. function handleHighlight(model, index) {
  63772. var targetInfo = retrieveTargetInfo(payload, [HIGHLIGHT_ACTION], model);
  63773. if (targetInfo) {
  63774. payload.highlight = targetInfo.node;
  63775. }
  63776. }
  63777. }
  63778. );
  63779. var UNHIGHLIGHT_ACTION = 'sunburstUnhighlight';
  63780. registerAction(
  63781. {type: UNHIGHLIGHT_ACTION, update: 'updateView'},
  63782. function (payload, ecModel) {
  63783. ecModel.eachComponent(
  63784. {mainType: 'series', subType: 'sunburst', query: payload},
  63785. handleUnhighlight
  63786. );
  63787. function handleUnhighlight(model, index) {
  63788. payload.unhighlight = true;
  63789. }
  63790. }
  63791. );
  63792. /*
  63793. * Licensed to the Apache Software Foundation (ASF) under one
  63794. * or more contributor license agreements. See the NOTICE file
  63795. * distributed with this work for additional information
  63796. * regarding copyright ownership. The ASF licenses this file
  63797. * to you under the Apache License, Version 2.0 (the
  63798. * "License"); you may not use this file except in compliance
  63799. * with the License. You may obtain a copy of the License at
  63800. *
  63801. * http://www.apache.org/licenses/LICENSE-2.0
  63802. *
  63803. * Unless required by applicable law or agreed to in writing,
  63804. * software distributed under the License is distributed on an
  63805. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63806. * KIND, either express or implied. See the License for the
  63807. * specific language governing permissions and limitations
  63808. * under the License.
  63809. */
  63810. // var PI2 = Math.PI * 2;
  63811. var RADIAN$2 = Math.PI / 180;
  63812. var sunburstLayout = function (seriesType, ecModel, api, payload) {
  63813. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  63814. var center = seriesModel.get('center');
  63815. var radius = seriesModel.get('radius');
  63816. if (!isArray(radius)) {
  63817. radius = [0, radius];
  63818. }
  63819. if (!isArray(center)) {
  63820. center = [center, center];
  63821. }
  63822. var width = api.getWidth();
  63823. var height = api.getHeight();
  63824. var size = Math.min(width, height);
  63825. var cx = parsePercent$1(center[0], width);
  63826. var cy = parsePercent$1(center[1], height);
  63827. var r0 = parsePercent$1(radius[0], size / 2);
  63828. var r = parsePercent$1(radius[1], size / 2);
  63829. var startAngle = -seriesModel.get('startAngle') * RADIAN$2;
  63830. var minAngle = seriesModel.get('minAngle') * RADIAN$2;
  63831. var virtualRoot = seriesModel.getData().tree.root;
  63832. var treeRoot = seriesModel.getViewRoot();
  63833. var rootDepth = treeRoot.depth;
  63834. var sort = seriesModel.get('sort');
  63835. if (sort != null) {
  63836. initChildren$1(treeRoot, sort);
  63837. }
  63838. var validDataCount = 0;
  63839. each$1(treeRoot.children, function (child) {
  63840. !isNaN(child.getValue()) && validDataCount++;
  63841. });
  63842. var sum = treeRoot.getValue();
  63843. // Sum may be 0
  63844. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  63845. var renderRollupNode = treeRoot.depth > 0;
  63846. var levels = treeRoot.height - (renderRollupNode ? -1 : 1);
  63847. var rPerLevel = (r - r0) / (levels || 1);
  63848. var clockwise = seriesModel.get('clockwise');
  63849. var stillShowZeroSum = seriesModel.get('stillShowZeroSum');
  63850. // In the case some sector angle is smaller than minAngle
  63851. // var restAngle = PI2;
  63852. // var valueSumLargerThanMinAngle = 0;
  63853. var dir = clockwise ? 1 : -1;
  63854. /**
  63855. * Render a tree
  63856. * @return increased angle
  63857. */
  63858. var renderNode = function (node, startAngle) {
  63859. if (!node) {
  63860. return;
  63861. }
  63862. var endAngle = startAngle;
  63863. // Render self
  63864. if (node !== virtualRoot) {
  63865. // Tree node is virtual, so it doesn't need to be drawn
  63866. var value = node.getValue();
  63867. var angle = (sum === 0 && stillShowZeroSum)
  63868. ? unitRadian : (value * unitRadian);
  63869. if (angle < minAngle) {
  63870. angle = minAngle;
  63871. // restAngle -= minAngle;
  63872. }
  63873. // else {
  63874. // valueSumLargerThanMinAngle += value;
  63875. // }
  63876. endAngle = startAngle + dir * angle;
  63877. var depth = node.depth - rootDepth
  63878. - (renderRollupNode ? -1 : 1);
  63879. var rStart = r0 + rPerLevel * depth;
  63880. var rEnd = r0 + rPerLevel * (depth + 1);
  63881. var itemModel = node.getModel();
  63882. if (itemModel.get('r0') != null) {
  63883. rStart = parsePercent$1(itemModel.get('r0'), size / 2);
  63884. }
  63885. if (itemModel.get('r') != null) {
  63886. rEnd = parsePercent$1(itemModel.get('r'), size / 2);
  63887. }
  63888. node.setLayout({
  63889. angle: angle,
  63890. startAngle: startAngle,
  63891. endAngle: endAngle,
  63892. clockwise: clockwise,
  63893. cx: cx,
  63894. cy: cy,
  63895. r0: rStart,
  63896. r: rEnd
  63897. });
  63898. }
  63899. // Render children
  63900. if (node.children && node.children.length) {
  63901. // currentAngle = startAngle;
  63902. var siblingAngle = 0;
  63903. each$1(node.children, function (node) {
  63904. siblingAngle += renderNode(node, startAngle + siblingAngle);
  63905. });
  63906. }
  63907. return endAngle - startAngle;
  63908. };
  63909. // Virtual root node for roll up
  63910. if (renderRollupNode) {
  63911. var rStart = r0;
  63912. var rEnd = r0 + rPerLevel;
  63913. var angle = Math.PI * 2;
  63914. virtualRoot.setLayout({
  63915. angle: angle,
  63916. startAngle: startAngle,
  63917. endAngle: startAngle + angle,
  63918. clockwise: clockwise,
  63919. cx: cx,
  63920. cy: cy,
  63921. r0: rStart,
  63922. r: rEnd
  63923. });
  63924. }
  63925. renderNode(treeRoot, startAngle);
  63926. });
  63927. };
  63928. /**
  63929. * Init node children by order and update visual
  63930. *
  63931. * @param {TreeNode} node root node
  63932. * @param {boolean} isAsc if is in ascendant order
  63933. */
  63934. function initChildren$1(node, isAsc) {
  63935. var children = node.children || [];
  63936. node.children = sort$2(children, isAsc);
  63937. // Init children recursively
  63938. if (children.length) {
  63939. each$1(node.children, function (child) {
  63940. initChildren$1(child, isAsc);
  63941. });
  63942. }
  63943. }
  63944. /**
  63945. * Sort children nodes
  63946. *
  63947. * @param {TreeNode[]} children children of node to be sorted
  63948. * @param {string | function | null} sort sort method
  63949. * See SunburstSeries.js for details.
  63950. */
  63951. function sort$2(children, sortOrder) {
  63952. if (typeof sortOrder === 'function') {
  63953. return children.sort(sortOrder);
  63954. }
  63955. else {
  63956. var isAsc = sortOrder === 'asc';
  63957. return children.sort(function (a, b) {
  63958. var diff = (a.getValue() - b.getValue()) * (isAsc ? 1 : -1);
  63959. return diff === 0
  63960. ? (a.dataIndex - b.dataIndex) * (isAsc ? -1 : 1)
  63961. : diff;
  63962. });
  63963. }
  63964. }
  63965. /*
  63966. * Licensed to the Apache Software Foundation (ASF) under one
  63967. * or more contributor license agreements. See the NOTICE file
  63968. * distributed with this work for additional information
  63969. * regarding copyright ownership. The ASF licenses this file
  63970. * to you under the Apache License, Version 2.0 (the
  63971. * "License"); you may not use this file except in compliance
  63972. * with the License. You may obtain a copy of the License at
  63973. *
  63974. * http://www.apache.org/licenses/LICENSE-2.0
  63975. *
  63976. * Unless required by applicable law or agreed to in writing,
  63977. * software distributed under the License is distributed on an
  63978. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63979. * KIND, either express or implied. See the License for the
  63980. * specific language governing permissions and limitations
  63981. * under the License.
  63982. */
  63983. registerVisual(curry(dataColor, 'sunburst'));
  63984. registerLayout(curry(sunburstLayout, 'sunburst'));
  63985. registerProcessor(curry(dataFilter, 'sunburst'));
  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. function dataToCoordSize(dataSize, dataItem) {
  64005. // dataItem is necessary in log axis.
  64006. dataItem = dataItem || [0, 0];
  64007. return map(['x', 'y'], function (dim, dimIdx) {
  64008. var axis = this.getAxis(dim);
  64009. var val = dataItem[dimIdx];
  64010. var halfSize = dataSize[dimIdx] / 2;
  64011. return axis.type === 'category'
  64012. ? axis.getBandWidth()
  64013. : Math.abs(axis.dataToCoord(val - halfSize) - axis.dataToCoord(val + halfSize));
  64014. }, this);
  64015. }
  64016. var prepareCartesian2d = function (coordSys) {
  64017. var rect = coordSys.grid.getRect();
  64018. return {
  64019. coordSys: {
  64020. // The name exposed to user is always 'cartesian2d' but not 'grid'.
  64021. type: 'cartesian2d',
  64022. x: rect.x,
  64023. y: rect.y,
  64024. width: rect.width,
  64025. height: rect.height
  64026. },
  64027. api: {
  64028. coord: function (data) {
  64029. // do not provide "out" param
  64030. return coordSys.dataToPoint(data);
  64031. },
  64032. size: bind(dataToCoordSize, coordSys)
  64033. }
  64034. };
  64035. };
  64036. /*
  64037. * Licensed to the Apache Software Foundation (ASF) under one
  64038. * or more contributor license agreements. See the NOTICE file
  64039. * distributed with this work for additional information
  64040. * regarding copyright ownership. The ASF licenses this file
  64041. * to you under the Apache License, Version 2.0 (the
  64042. * "License"); you may not use this file except in compliance
  64043. * with the License. You may obtain a copy of the License at
  64044. *
  64045. * http://www.apache.org/licenses/LICENSE-2.0
  64046. *
  64047. * Unless required by applicable law or agreed to in writing,
  64048. * software distributed under the License is distributed on an
  64049. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  64050. * KIND, either express or implied. See the License for the
  64051. * specific language governing permissions and limitations
  64052. * under the License.
  64053. */
  64054. function dataToCoordSize$1(dataSize, dataItem) {
  64055. dataItem = dataItem || [0, 0];
  64056. return map([0, 1], function (dimIdx) {
  64057. var val = dataItem[dimIdx];
  64058. var halfSize = dataSize[dimIdx] / 2;
  64059. var p1 = [];
  64060. var p2 = [];
  64061. p1[dimIdx] = val - halfSize;
  64062. p2[dimIdx] = val + halfSize;
  64063. p1[1 - dimIdx] = p2[1 - dimIdx] = dataItem[1 - dimIdx];
  64064. return Math.abs(this.dataToPoint(p1)[dimIdx] - this.dataToPoint(p2)[dimIdx]);
  64065. }, this);
  64066. }
  64067. var prepareGeo = function (coordSys) {
  64068. var rect = coordSys.getBoundingRect();
  64069. return {
  64070. coordSys: {
  64071. type: 'geo',
  64072. x: rect.x,
  64073. y: rect.y,
  64074. width: rect.width,
  64075. height: rect.height,
  64076. zoom: coordSys.getZoom()
  64077. },
  64078. api: {
  64079. coord: function (data) {
  64080. // do not provide "out" and noRoam param,
  64081. // Compatible with this usage:
  64082. // echarts.util.map(item.points, api.coord)
  64083. return coordSys.dataToPoint(data);
  64084. },
  64085. size: bind(dataToCoordSize$1, coordSys)
  64086. }
  64087. };
  64088. };
  64089. /*
  64090. * Licensed to the Apache Software Foundation (ASF) under one
  64091. * or more contributor license agreements. See the NOTICE file
  64092. * distributed with this work for additional information
  64093. * regarding copyright ownership. The ASF licenses this file
  64094. * to you under the Apache License, Version 2.0 (the
  64095. * "License"); you may not use this file except in compliance
  64096. * with the License. You may obtain a copy of the License at
  64097. *
  64098. * http://www.apache.org/licenses/LICENSE-2.0
  64099. *
  64100. * Unless required by applicable law or agreed to in writing,
  64101. * software distributed under the License is distributed on an
  64102. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  64103. * KIND, either express or implied. See the License for the
  64104. * specific language governing permissions and limitations
  64105. * under the License.
  64106. */
  64107. function dataToCoordSize$2(dataSize, dataItem) {
  64108. // dataItem is necessary in log axis.
  64109. var axis = this.getAxis();
  64110. var val = dataItem instanceof Array ? dataItem[0] : dataItem;
  64111. var halfSize = (dataSize instanceof Array ? dataSize[0] : dataSize) / 2;
  64112. return axis.type === 'category'
  64113. ? axis.getBandWidth()
  64114. : Math.abs(axis.dataToCoord(val - halfSize) - axis.dataToCoord(val + halfSize));
  64115. }
  64116. var prepareSingleAxis = function (coordSys) {
  64117. var rect = coordSys.getRect();
  64118. return {
  64119. coordSys: {
  64120. type: 'singleAxis',
  64121. x: rect.x,
  64122. y: rect.y,
  64123. width: rect.width,
  64124. height: rect.height
  64125. },
  64126. api: {
  64127. coord: function (val) {
  64128. // do not provide "out" param
  64129. return coordSys.dataToPoint(val);
  64130. },
  64131. size: bind(dataToCoordSize$2, coordSys)
  64132. }
  64133. };
  64134. };
  64135. /*
  64136. * Licensed to the Apache Software Foundation (ASF) under one
  64137. * or more contributor license agreements. See the NOTICE file
  64138. * distributed with this work for additional information
  64139. * regarding copyright ownership. The ASF licenses this file
  64140. * to you under the Apache License, Version 2.0 (the
  64141. * "License"); you may not use this file except in compliance
  64142. * with the License. You may obtain a copy of the License at
  64143. *
  64144. * http://www.apache.org/licenses/LICENSE-2.0
  64145. *
  64146. * Unless required by applicable law or agreed to in writing,
  64147. * software distributed under the License is distributed on an
  64148. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  64149. * KIND, either express or implied. See the License for the
  64150. * specific language governing permissions and limitations
  64151. * under the License.
  64152. */
  64153. function dataToCoordSize$3(dataSize, dataItem) {
  64154. // dataItem is necessary in log axis.
  64155. return map(['Radius', 'Angle'], function (dim, dimIdx) {
  64156. var axis = this['get' + dim + 'Axis']();
  64157. var val = dataItem[dimIdx];
  64158. var halfSize = dataSize[dimIdx] / 2;
  64159. var method = 'dataTo' + dim;
  64160. var result = axis.type === 'category'
  64161. ? axis.getBandWidth()
  64162. : Math.abs(axis[method](val - halfSize) - axis[method](val + halfSize));
  64163. if (dim === 'Angle') {
  64164. result = result * Math.PI / 180;
  64165. }
  64166. return result;
  64167. }, this);
  64168. }
  64169. var preparePolar = function (coordSys) {
  64170. var radiusAxis = coordSys.getRadiusAxis();
  64171. var angleAxis = coordSys.getAngleAxis();
  64172. var radius = radiusAxis.getExtent();
  64173. radius[0] > radius[1] && radius.reverse();
  64174. return {
  64175. coordSys: {
  64176. type: 'polar',
  64177. cx: coordSys.cx,
  64178. cy: coordSys.cy,
  64179. r: radius[1],
  64180. r0: radius[0]
  64181. },
  64182. api: {
  64183. coord: bind(function (data) {
  64184. var radius = radiusAxis.dataToRadius(data[0]);
  64185. var angle = angleAxis.dataToAngle(data[1]);
  64186. var coord = coordSys.coordToPoint([radius, angle]);
  64187. coord.push(radius, angle * Math.PI / 180);
  64188. return coord;
  64189. }),
  64190. size: bind(dataToCoordSize$3, coordSys)
  64191. }
  64192. };
  64193. };
  64194. /*
  64195. * Licensed to the Apache Software Foundation (ASF) under one
  64196. * or more contributor license agreements. See the NOTICE file
  64197. * distributed with this work for additional information
  64198. * regarding copyright ownership. The ASF licenses this file
  64199. * to you under the Apache License, Version 2.0 (the
  64200. * "License"); you may not use this file except in compliance
  64201. * with the License. You may obtain a copy of the License at
  64202. *
  64203. * http://www.apache.org/licenses/LICENSE-2.0
  64204. *
  64205. * Unless required by applicable law or agreed to in writing,
  64206. * software distributed under the License is distributed on an
  64207. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  64208. * KIND, either express or implied. See the License for the
  64209. * specific language governing permissions and limitations
  64210. * under the License.
  64211. */
  64212. var prepareCalendar = function (coordSys) {
  64213. var rect = coordSys.getRect();
  64214. var rangeInfo = coordSys.getRangeInfo();
  64215. return {
  64216. coordSys: {
  64217. type: 'calendar',
  64218. x: rect.x,
  64219. y: rect.y,
  64220. width: rect.width,
  64221. height: rect.height,
  64222. cellWidth: coordSys.getCellWidth(),
  64223. cellHeight: coordSys.getCellHeight(),
  64224. rangeInfo: {
  64225. start: rangeInfo.start,
  64226. end: rangeInfo.end,
  64227. weeks: rangeInfo.weeks,
  64228. dayCount: rangeInfo.allDay
  64229. }
  64230. },
  64231. api: {
  64232. coord: function (data, clamp) {
  64233. return coordSys.dataToPoint(data, clamp);
  64234. }
  64235. }
  64236. };
  64237. };
  64238. /*
  64239. * Licensed to the Apache Software Foundation (ASF) under one
  64240. * or more contributor license agreements. See the NOTICE file
  64241. * distributed with this work for additional information
  64242. * regarding copyright ownership. The ASF licenses this file
  64243. * to you under the Apache License, Version 2.0 (the
  64244. * "License"); you may not use this file except in compliance
  64245. * with the License. You may obtain a copy of the License at
  64246. *
  64247. * http://www.apache.org/licenses/LICENSE-2.0
  64248. *
  64249. * Unless required by applicable law or agreed to in writing,
  64250. * software distributed under the License is distributed on an
  64251. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  64252. * KIND, either express or implied. See the License for the
  64253. * specific language governing permissions and limitations
  64254. * under the License.
  64255. */
  64256. var CACHED_LABEL_STYLE_PROPERTIES$1 = CACHED_LABEL_STYLE_PROPERTIES;
  64257. var ITEM_STYLE_NORMAL_PATH = ['itemStyle'];
  64258. var ITEM_STYLE_EMPHASIS_PATH = ['emphasis', 'itemStyle'];
  64259. var LABEL_NORMAL = ['label'];
  64260. var LABEL_EMPHASIS = ['emphasis', 'label'];
  64261. // Use prefix to avoid index to be the same as el.name,
  64262. // which will cause weird udpate animation.
  64263. var GROUP_DIFF_PREFIX = 'e\0\0';
  64264. /**
  64265. * To reduce total package size of each coordinate systems, the modules `prepareCustom`
  64266. * of each coordinate systems are not required by each coordinate systems directly, but
  64267. * required by the module `custom`.
  64268. *
  64269. * prepareInfoForCustomSeries {Function}: optional
  64270. * @return {Object} {coordSys: {...}, api: {
  64271. * coord: function (data, clamp) {}, // return point in global.
  64272. * size: function (dataSize, dataItem) {} // return size of each axis in coordSys.
  64273. * }}
  64274. */
  64275. var prepareCustoms = {
  64276. cartesian2d: prepareCartesian2d,
  64277. geo: prepareGeo,
  64278. singleAxis: prepareSingleAxis,
  64279. polar: preparePolar,
  64280. calendar: prepareCalendar
  64281. };
  64282. // ------
  64283. // Model
  64284. // ------
  64285. SeriesModel.extend({
  64286. type: 'series.custom',
  64287. dependencies: ['grid', 'polar', 'geo', 'singleAxis', 'calendar'],
  64288. defaultOption: {
  64289. coordinateSystem: 'cartesian2d', // Can be set as 'none'
  64290. zlevel: 0,
  64291. z: 2,
  64292. legendHoverLink: true,
  64293. useTransform: true,
  64294. // Custom series will not clip by default.
  64295. // Some case will use custom series to draw label
  64296. // For example https://echarts.apache.org/examples/en/editor.html?c=custom-gantt-flight
  64297. // Only works on polar and cartesian2d coordinate system.
  64298. clip: false
  64299. // Cartesian coordinate system
  64300. // xAxisIndex: 0,
  64301. // yAxisIndex: 0,
  64302. // Polar coordinate system
  64303. // polarIndex: 0,
  64304. // Geo coordinate system
  64305. // geoIndex: 0,
  64306. // label: {}
  64307. // itemStyle: {}
  64308. },
  64309. /**
  64310. * @override
  64311. */
  64312. getInitialData: function (option, ecModel) {
  64313. return createListFromArray(this.getSource(), this);
  64314. },
  64315. /**
  64316. * @override
  64317. */
  64318. getDataParams: function (dataIndex, dataType, el) {
  64319. var params = SeriesModel.prototype.getDataParams.apply(this, arguments);
  64320. el && (params.info = el.info);
  64321. return params;
  64322. }
  64323. });
  64324. // -----
  64325. // View
  64326. // -----
  64327. Chart.extend({
  64328. type: 'custom',
  64329. /**
  64330. * @private
  64331. * @type {module:echarts/data/List}
  64332. */
  64333. _data: null,
  64334. /**
  64335. * @override
  64336. */
  64337. render: function (customSeries, ecModel, api, payload) {
  64338. var oldData = this._data;
  64339. var data = customSeries.getData();
  64340. var group = this.group;
  64341. var renderItem = makeRenderItem(customSeries, data, ecModel, api);
  64342. // By default, merge mode is applied. In most cases, custom series is
  64343. // used in the scenario that data amount is not large but graphic elements
  64344. // is complicated, where merge mode is probably necessary for optimization.
  64345. // For example, reuse graphic elements and only update the transform when
  64346. // roam or data zoom according to `actionType`.
  64347. data.diff(oldData)
  64348. .add(function (newIdx) {
  64349. createOrUpdate$1(
  64350. null, newIdx, renderItem(newIdx, payload), customSeries, group, data
  64351. );
  64352. })
  64353. .update(function (newIdx, oldIdx) {
  64354. var el = oldData.getItemGraphicEl(oldIdx);
  64355. createOrUpdate$1(
  64356. el, newIdx, renderItem(newIdx, payload), customSeries, group, data
  64357. );
  64358. })
  64359. .remove(function (oldIdx) {
  64360. var el = oldData.getItemGraphicEl(oldIdx);
  64361. el && group.remove(el);
  64362. })
  64363. .execute();
  64364. // Do clipping
  64365. var clipPath = customSeries.get('clip', true)
  64366. ? createClipPath(customSeries.coordinateSystem, false, customSeries)
  64367. : null;
  64368. if (clipPath) {
  64369. group.setClipPath(clipPath);
  64370. }
  64371. else {
  64372. group.removeClipPath();
  64373. }
  64374. this._data = data;
  64375. },
  64376. incrementalPrepareRender: function (customSeries, ecModel, api) {
  64377. this.group.removeAll();
  64378. this._data = null;
  64379. },
  64380. incrementalRender: function (params, customSeries, ecModel, api, payload) {
  64381. var data = customSeries.getData();
  64382. var renderItem = makeRenderItem(customSeries, data, ecModel, api);
  64383. function setIncrementalAndHoverLayer(el) {
  64384. if (!el.isGroup) {
  64385. el.incremental = true;
  64386. el.useHoverLayer = true;
  64387. }
  64388. }
  64389. for (var idx = params.start; idx < params.end; idx++) {
  64390. var el = createOrUpdate$1(null, idx, renderItem(idx, payload), customSeries, this.group, data);
  64391. el.traverse(setIncrementalAndHoverLayer);
  64392. }
  64393. },
  64394. /**
  64395. * @override
  64396. */
  64397. dispose: noop,
  64398. /**
  64399. * @override
  64400. */
  64401. filterForExposedEvent: function (eventType, query, targetEl, packedEvent) {
  64402. var elementName = query.element;
  64403. if (elementName == null || targetEl.name === elementName) {
  64404. return true;
  64405. }
  64406. // Enable to give a name on a group made by `renderItem`, and listen
  64407. // events that triggerd by its descendents.
  64408. while ((targetEl = targetEl.parent) && targetEl !== this.group) {
  64409. if (targetEl.name === elementName) {
  64410. return true;
  64411. }
  64412. }
  64413. return false;
  64414. }
  64415. });
  64416. function createEl(elOption) {
  64417. var graphicType = elOption.type;
  64418. var el;
  64419. // Those graphic elements are not shapes. They should not be
  64420. // overwritten by users, so do them first.
  64421. if (graphicType === 'path') {
  64422. var shape = elOption.shape;
  64423. // Using pathRect brings convenience to users sacle svg path.
  64424. var pathRect = (shape.width != null && shape.height != null)
  64425. ? {
  64426. x: shape.x || 0,
  64427. y: shape.y || 0,
  64428. width: shape.width,
  64429. height: shape.height
  64430. }
  64431. : null;
  64432. var pathData = getPathData(shape);
  64433. // Path is also used for icon, so layout 'center' by default.
  64434. el = makePath(pathData, null, pathRect, shape.layout || 'center');
  64435. el.__customPathData = pathData;
  64436. }
  64437. else if (graphicType === 'image') {
  64438. el = new ZImage({});
  64439. el.__customImagePath = elOption.style.image;
  64440. }
  64441. else if (graphicType === 'text') {
  64442. el = new Text({});
  64443. el.__customText = elOption.style.text;
  64444. }
  64445. else if (graphicType === 'group') {
  64446. el = new Group();
  64447. }
  64448. else if (graphicType === 'compoundPath') {
  64449. throw new Error('"compoundPath" is not supported yet.');
  64450. }
  64451. else {
  64452. var Clz = getShapeClass(graphicType);
  64453. if (__DEV__) {
  64454. assert$1(Clz, 'graphic type "' + graphicType + '" can not be found.');
  64455. }
  64456. el = new Clz();
  64457. }
  64458. el.__customGraphicType = graphicType;
  64459. el.name = elOption.name;
  64460. return el;
  64461. }
  64462. function updateEl(el, dataIndex, elOption, animatableModel, data, isInit, isRoot) {
  64463. var transitionProps = {};
  64464. var elOptionStyle = elOption.style || {};
  64465. elOption.shape && (transitionProps.shape = clone(elOption.shape));
  64466. elOption.position && (transitionProps.position = elOption.position.slice());
  64467. elOption.scale && (transitionProps.scale = elOption.scale.slice());
  64468. elOption.origin && (transitionProps.origin = elOption.origin.slice());
  64469. elOption.rotation && (transitionProps.rotation = elOption.rotation);
  64470. if (el.type === 'image' && elOption.style) {
  64471. var targetStyle = transitionProps.style = {};
  64472. each$1(['x', 'y', 'width', 'height'], function (prop) {
  64473. prepareStyleTransition(prop, targetStyle, elOptionStyle, el.style, isInit);
  64474. });
  64475. }
  64476. if (el.type === 'text' && elOption.style) {
  64477. var targetStyle = transitionProps.style = {};
  64478. each$1(['x', 'y'], function (prop) {
  64479. prepareStyleTransition(prop, targetStyle, elOptionStyle, el.style, isInit);
  64480. });
  64481. // Compatible with previous: both support
  64482. // textFill and fill, textStroke and stroke in 'text' element.
  64483. !elOptionStyle.hasOwnProperty('textFill') && elOptionStyle.fill && (
  64484. elOptionStyle.textFill = elOptionStyle.fill
  64485. );
  64486. !elOptionStyle.hasOwnProperty('textStroke') && elOptionStyle.stroke && (
  64487. elOptionStyle.textStroke = elOptionStyle.stroke
  64488. );
  64489. }
  64490. if (el.type !== 'group') {
  64491. el.useStyle(elOptionStyle);
  64492. // Init animation.
  64493. if (isInit) {
  64494. el.style.opacity = 0;
  64495. var targetOpacity = elOptionStyle.opacity;
  64496. targetOpacity == null && (targetOpacity = 1);
  64497. initProps(el, {style: {opacity: targetOpacity}}, animatableModel, dataIndex);
  64498. }
  64499. }
  64500. if (isInit) {
  64501. el.attr(transitionProps);
  64502. }
  64503. else {
  64504. updateProps(el, transitionProps, animatableModel, dataIndex);
  64505. }
  64506. // Merge by default.
  64507. // z2 must not be null/undefined, otherwise sort error may occur.
  64508. elOption.hasOwnProperty('z2') && el.attr('z2', elOption.z2 || 0);
  64509. elOption.hasOwnProperty('silent') && el.attr('silent', elOption.silent);
  64510. elOption.hasOwnProperty('invisible') && el.attr('invisible', elOption.invisible);
  64511. elOption.hasOwnProperty('ignore') && el.attr('ignore', elOption.ignore);
  64512. // `elOption.info` enables user to mount some info on
  64513. // elements and use them in event handlers.
  64514. // Update them only when user specified, otherwise, remain.
  64515. elOption.hasOwnProperty('info') && el.attr('info', elOption.info);
  64516. // If `elOption.styleEmphasis` is `false`, remove hover style. The
  64517. // logic is ensured by `graphicUtil.setElementHoverStyle`.
  64518. var styleEmphasis = elOption.styleEmphasis;
  64519. // hoverStyle should always be set here, because if the hover style
  64520. // may already be changed, where the inner cache should be reset.
  64521. setElementHoverStyle(el, styleEmphasis);
  64522. if (isRoot) {
  64523. setAsHighDownDispatcher(el, styleEmphasis !== false);
  64524. }
  64525. }
  64526. function prepareStyleTransition(prop, targetStyle, elOptionStyle, oldElStyle, isInit) {
  64527. if (elOptionStyle[prop] != null && !isInit) {
  64528. targetStyle[prop] = elOptionStyle[prop];
  64529. elOptionStyle[prop] = oldElStyle[prop];
  64530. }
  64531. }
  64532. function makeRenderItem(customSeries, data, ecModel, api) {
  64533. var renderItem = customSeries.get('renderItem');
  64534. var coordSys = customSeries.coordinateSystem;
  64535. var prepareResult = {};
  64536. if (coordSys) {
  64537. if (__DEV__) {
  64538. assert$1(renderItem, 'series.render is required.');
  64539. assert$1(
  64540. coordSys.prepareCustoms || prepareCustoms[coordSys.type],
  64541. 'This coordSys does not support custom series.'
  64542. );
  64543. }
  64544. prepareResult = coordSys.prepareCustoms
  64545. ? coordSys.prepareCustoms()
  64546. : prepareCustoms[coordSys.type](coordSys);
  64547. }
  64548. var userAPI = defaults({
  64549. getWidth: api.getWidth,
  64550. getHeight: api.getHeight,
  64551. getZr: api.getZr,
  64552. getDevicePixelRatio: api.getDevicePixelRatio,
  64553. value: value,
  64554. style: style,
  64555. styleEmphasis: styleEmphasis,
  64556. visual: visual,
  64557. barLayout: barLayout,
  64558. currentSeriesIndices: currentSeriesIndices,
  64559. font: font
  64560. }, prepareResult.api || {});
  64561. var userParams = {
  64562. // The life cycle of context: current round of rendering.
  64563. // The global life cycle is probably not necessary, because
  64564. // user can store global status by themselves.
  64565. context: {},
  64566. seriesId: customSeries.id,
  64567. seriesName: customSeries.name,
  64568. seriesIndex: customSeries.seriesIndex,
  64569. coordSys: prepareResult.coordSys,
  64570. dataInsideLength: data.count(),
  64571. encode: wrapEncodeDef(customSeries.getData())
  64572. };
  64573. // Do not support call `api` asynchronously without dataIndexInside input.
  64574. var currDataIndexInside;
  64575. var currDirty = true;
  64576. var currItemModel;
  64577. var currLabelNormalModel;
  64578. var currLabelEmphasisModel;
  64579. var currVisualColor;
  64580. return function (dataIndexInside, payload) {
  64581. currDataIndexInside = dataIndexInside;
  64582. currDirty = true;
  64583. return renderItem && renderItem(
  64584. defaults({
  64585. dataIndexInside: dataIndexInside,
  64586. dataIndex: data.getRawIndex(dataIndexInside),
  64587. // Can be used for optimization when zoom or roam.
  64588. actionType: payload ? payload.type : null
  64589. }, userParams),
  64590. userAPI
  64591. );
  64592. };
  64593. // Do not update cache until api called.
  64594. function updateCache(dataIndexInside) {
  64595. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  64596. if (currDirty) {
  64597. currItemModel = data.getItemModel(dataIndexInside);
  64598. currLabelNormalModel = currItemModel.getModel(LABEL_NORMAL);
  64599. currLabelEmphasisModel = currItemModel.getModel(LABEL_EMPHASIS);
  64600. currVisualColor = data.getItemVisual(dataIndexInside, 'color');
  64601. currDirty = false;
  64602. }
  64603. }
  64604. /**
  64605. * @public
  64606. * @param {number|string} dim
  64607. * @param {number} [dataIndexInside=currDataIndexInside]
  64608. * @return {number|string} value
  64609. */
  64610. function value(dim, dataIndexInside) {
  64611. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  64612. return data.get(data.getDimension(dim || 0), dataIndexInside);
  64613. }
  64614. /**
  64615. * By default, `visual` is applied to style (to support visualMap).
  64616. * `visual.color` is applied at `fill`. If user want apply visual.color on `stroke`,
  64617. * it can be implemented as:
  64618. * `api.style({stroke: api.visual('color'), fill: null})`;
  64619. * @public
  64620. * @param {Object} [extra]
  64621. * @param {number} [dataIndexInside=currDataIndexInside]
  64622. */
  64623. function style(extra, dataIndexInside) {
  64624. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  64625. updateCache(dataIndexInside);
  64626. var itemStyle = currItemModel.getModel(ITEM_STYLE_NORMAL_PATH).getItemStyle();
  64627. currVisualColor != null && (itemStyle.fill = currVisualColor);
  64628. var opacity = data.getItemVisual(dataIndexInside, 'opacity');
  64629. opacity != null && (itemStyle.opacity = opacity);
  64630. var labelModel = extra
  64631. ? applyExtraBefore(extra, currLabelNormalModel)
  64632. : currLabelNormalModel;
  64633. setTextStyle(itemStyle, labelModel, null, {
  64634. autoColor: currVisualColor,
  64635. isRectText: true
  64636. });
  64637. itemStyle.text = labelModel.getShallow('show')
  64638. ? retrieve2(
  64639. customSeries.getFormattedLabel(dataIndexInside, 'normal'),
  64640. getDefaultLabel(data, dataIndexInside)
  64641. )
  64642. : null;
  64643. extra && applyExtraAfter(itemStyle, extra);
  64644. return itemStyle;
  64645. }
  64646. /**
  64647. * @public
  64648. * @param {Object} [extra]
  64649. * @param {number} [dataIndexInside=currDataIndexInside]
  64650. */
  64651. function styleEmphasis(extra, dataIndexInside) {
  64652. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  64653. updateCache(dataIndexInside);
  64654. var itemStyle = currItemModel.getModel(ITEM_STYLE_EMPHASIS_PATH).getItemStyle();
  64655. var labelModel = extra
  64656. ? applyExtraBefore(extra, currLabelEmphasisModel)
  64657. : currLabelEmphasisModel;
  64658. setTextStyle(itemStyle, labelModel, null, {
  64659. isRectText: true
  64660. }, true);
  64661. itemStyle.text = labelModel.getShallow('show')
  64662. ? retrieve3(
  64663. customSeries.getFormattedLabel(dataIndexInside, 'emphasis'),
  64664. customSeries.getFormattedLabel(dataIndexInside, 'normal'),
  64665. getDefaultLabel(data, dataIndexInside)
  64666. )
  64667. : null;
  64668. extra && applyExtraAfter(itemStyle, extra);
  64669. return itemStyle;
  64670. }
  64671. /**
  64672. * @public
  64673. * @param {string} visualType
  64674. * @param {number} [dataIndexInside=currDataIndexInside]
  64675. */
  64676. function visual(visualType, dataIndexInside) {
  64677. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  64678. return data.getItemVisual(dataIndexInside, visualType);
  64679. }
  64680. /**
  64681. * @public
  64682. * @param {number} opt.count Positive interger.
  64683. * @param {number} [opt.barWidth]
  64684. * @param {number} [opt.barMaxWidth]
  64685. * @param {number} [opt.barMinWidth]
  64686. * @param {number} [opt.barGap]
  64687. * @param {number} [opt.barCategoryGap]
  64688. * @return {Object} {width, offset, offsetCenter} is not support, return undefined.
  64689. */
  64690. function barLayout(opt) {
  64691. if (coordSys.getBaseAxis) {
  64692. var baseAxis = coordSys.getBaseAxis();
  64693. return getLayoutOnAxis(defaults({axis: baseAxis}, opt), api);
  64694. }
  64695. }
  64696. /**
  64697. * @public
  64698. * @return {Array.<number>}
  64699. */
  64700. function currentSeriesIndices() {
  64701. return ecModel.getCurrentSeriesIndices();
  64702. }
  64703. /**
  64704. * @public
  64705. * @param {Object} opt
  64706. * @param {string} [opt.fontStyle]
  64707. * @param {number} [opt.fontWeight]
  64708. * @param {number} [opt.fontSize]
  64709. * @param {string} [opt.fontFamily]
  64710. * @return {string} font string
  64711. */
  64712. function font(opt) {
  64713. return getFont(opt, ecModel);
  64714. }
  64715. }
  64716. function wrapEncodeDef(data) {
  64717. var encodeDef = {};
  64718. each$1(data.dimensions, function (dimName, dataDimIndex) {
  64719. var dimInfo = data.getDimensionInfo(dimName);
  64720. if (!dimInfo.isExtraCoord) {
  64721. var coordDim = dimInfo.coordDim;
  64722. var dataDims = encodeDef[coordDim] = encodeDef[coordDim] || [];
  64723. dataDims[dimInfo.coordDimIndex] = dataDimIndex;
  64724. }
  64725. });
  64726. return encodeDef;
  64727. }
  64728. function createOrUpdate$1(el, dataIndex, elOption, animatableModel, group, data) {
  64729. el = doCreateOrUpdate(el, dataIndex, elOption, animatableModel, group, data, true);
  64730. el && data.setItemGraphicEl(dataIndex, el);
  64731. return el;
  64732. }
  64733. function doCreateOrUpdate(el, dataIndex, elOption, animatableModel, group, data, isRoot) {
  64734. // [Rule]
  64735. // By default, follow merge mode.
  64736. // (It probably brings benifit for performance in some cases of large data, where
  64737. // user program can be optimized to that only updated props needed to be re-calculated,
  64738. // or according to `actionType` some calculation can be skipped.)
  64739. // If `renderItem` returns `null`/`undefined`/`false`, remove the previous el if existing.
  64740. // (It seems that violate the "merge" principle, but most of users probably intuitively
  64741. // regard "return;" as "show nothing element whatever", so make a exception to meet the
  64742. // most cases.)
  64743. var simplyRemove = !elOption; // `null`/`undefined`/`false`
  64744. elOption = elOption || {};
  64745. var elOptionType = elOption.type;
  64746. var elOptionShape = elOption.shape;
  64747. var elOptionStyle = elOption.style;
  64748. if (el && (
  64749. simplyRemove
  64750. // || elOption.$merge === false
  64751. // If `elOptionType` is `null`, follow the merge principle.
  64752. || (elOptionType != null
  64753. && elOptionType !== el.__customGraphicType
  64754. )
  64755. || (elOptionType === 'path'
  64756. && hasOwnPathData(elOptionShape) && getPathData(elOptionShape) !== el.__customPathData
  64757. )
  64758. || (elOptionType === 'image'
  64759. && hasOwn(elOptionStyle, 'image') && elOptionStyle.image !== el.__customImagePath
  64760. )
  64761. // FIXME test and remove this restriction?
  64762. || (elOptionType === 'text'
  64763. && hasOwn(elOptionShape, 'text') && elOptionStyle.text !== el.__customText
  64764. )
  64765. )) {
  64766. group.remove(el);
  64767. el = null;
  64768. }
  64769. // `elOption.type` is undefined when `renderItem` returns nothing.
  64770. if (simplyRemove) {
  64771. return;
  64772. }
  64773. var isInit = !el;
  64774. !el && (el = createEl(elOption));
  64775. updateEl(el, dataIndex, elOption, animatableModel, data, isInit, isRoot);
  64776. if (elOptionType === 'group') {
  64777. mergeChildren(el, dataIndex, elOption, animatableModel, data);
  64778. }
  64779. // Always add whatever already added to ensure sequence.
  64780. group.add(el);
  64781. return el;
  64782. }
  64783. // Usage:
  64784. // (1) By default, `elOption.$mergeChildren` is `'byIndex'`, which indicates that
  64785. // the existing children will not be removed, and enables the feature that
  64786. // update some of the props of some of the children simply by construct
  64787. // the returned children of `renderItem` like:
  64788. // `var children = group.children = []; children[3] = {opacity: 0.5};`
  64789. // (2) If `elOption.$mergeChildren` is `'byName'`, add/update/remove children
  64790. // by child.name. But that might be lower performance.
  64791. // (3) If `elOption.$mergeChildren` is `false`, the existing children will be
  64792. // replaced totally.
  64793. // (4) If `!elOption.children`, following the "merge" principle, nothing will happen.
  64794. //
  64795. // For implementation simpleness, do not provide a direct way to remove sinlge
  64796. // child (otherwise the total indicies of the children array have to be modified).
  64797. // User can remove a single child by set its `ignore` as `true` or replace
  64798. // it by another element, where its `$merge` can be set as `true` if necessary.
  64799. function mergeChildren(el, dataIndex, elOption, animatableModel, data) {
  64800. var newChildren = elOption.children;
  64801. var newLen = newChildren ? newChildren.length : 0;
  64802. var mergeChildren = elOption.$mergeChildren;
  64803. // `diffChildrenByName` has been deprecated.
  64804. var byName = mergeChildren === 'byName' || elOption.diffChildrenByName;
  64805. var notMerge = mergeChildren === false;
  64806. // For better performance on roam update, only enter if necessary.
  64807. if (!newLen && !byName && !notMerge) {
  64808. return;
  64809. }
  64810. if (byName) {
  64811. diffGroupChildren({
  64812. oldChildren: el.children() || [],
  64813. newChildren: newChildren || [],
  64814. dataIndex: dataIndex,
  64815. animatableModel: animatableModel,
  64816. group: el,
  64817. data: data
  64818. });
  64819. return;
  64820. }
  64821. notMerge && el.removeAll();
  64822. // Mapping children of a group simply by index, which
  64823. // might be better performance.
  64824. var index = 0;
  64825. for (; index < newLen; index++) {
  64826. newChildren[index] && doCreateOrUpdate(
  64827. el.childAt(index),
  64828. dataIndex,
  64829. newChildren[index],
  64830. animatableModel,
  64831. el,
  64832. data
  64833. );
  64834. }
  64835. if (__DEV__) {
  64836. assert$1(
  64837. !notMerge || el.childCount() === index,
  64838. 'MUST NOT contain empty item in children array when `group.$mergeChildren` is `false`.'
  64839. );
  64840. }
  64841. }
  64842. function diffGroupChildren(context) {
  64843. (new DataDiffer(
  64844. context.oldChildren,
  64845. context.newChildren,
  64846. getKey,
  64847. getKey,
  64848. context
  64849. ))
  64850. .add(processAddUpdate)
  64851. .update(processAddUpdate)
  64852. .remove(processRemove)
  64853. .execute();
  64854. }
  64855. function getKey(item, idx) {
  64856. var name = item && item.name;
  64857. return name != null ? name : GROUP_DIFF_PREFIX + idx;
  64858. }
  64859. function processAddUpdate(newIndex, oldIndex) {
  64860. var context = this.context;
  64861. var childOption = newIndex != null ? context.newChildren[newIndex] : null;
  64862. var child = oldIndex != null ? context.oldChildren[oldIndex] : null;
  64863. doCreateOrUpdate(
  64864. child,
  64865. context.dataIndex,
  64866. childOption,
  64867. context.animatableModel,
  64868. context.group,
  64869. context.data
  64870. );
  64871. }
  64872. // `graphic#applyDefaultTextStyle` will cache
  64873. // textFill, textStroke, textStrokeWidth.
  64874. // We have to do this trick.
  64875. function applyExtraBefore(extra, model) {
  64876. var dummyModel = new Model({}, model);
  64877. each$1(CACHED_LABEL_STYLE_PROPERTIES$1, function (stylePropName, modelPropName) {
  64878. if (extra.hasOwnProperty(stylePropName)) {
  64879. dummyModel.option[modelPropName] = extra[stylePropName];
  64880. }
  64881. });
  64882. return dummyModel;
  64883. }
  64884. function applyExtraAfter(itemStyle, extra) {
  64885. for (var key in extra) {
  64886. if (extra.hasOwnProperty(key)
  64887. || !CACHED_LABEL_STYLE_PROPERTIES$1.hasOwnProperty(key)
  64888. ) {
  64889. itemStyle[key] = extra[key];
  64890. }
  64891. }
  64892. }
  64893. function processRemove(oldIndex) {
  64894. var context = this.context;
  64895. var child = context.oldChildren[oldIndex];
  64896. child && context.group.remove(child);
  64897. }
  64898. function getPathData(shape) {
  64899. // "d" follows the SVG convention.
  64900. return shape && (shape.pathData || shape.d);
  64901. }
  64902. function hasOwnPathData(shape) {
  64903. return shape && (shape.hasOwnProperty('pathData') || shape.hasOwnProperty('d'));
  64904. }
  64905. function hasOwn(host, prop) {
  64906. return host && host.hasOwnProperty(prop);
  64907. }
  64908. /*
  64909. * Licensed to the Apache Software Foundation (ASF) under one
  64910. * or more contributor license agreements. See the NOTICE file
  64911. * distributed with this work for additional information
  64912. * regarding copyright ownership. The ASF licenses this file
  64913. * to you under the Apache License, Version 2.0 (the
  64914. * "License"); you may not use this file except in compliance
  64915. * with the License. You may obtain a copy of the License at
  64916. *
  64917. * http://www.apache.org/licenses/LICENSE-2.0
  64918. *
  64919. * Unless required by applicable law or agreed to in writing,
  64920. * software distributed under the License is distributed on an
  64921. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  64922. * KIND, either express or implied. See the License for the
  64923. * specific language governing permissions and limitations
  64924. * under the License.
  64925. */
  64926. /*
  64927. * Licensed to the Apache Software Foundation (ASF) under one
  64928. * or more contributor license agreements. See the NOTICE file
  64929. * distributed with this work for additional information
  64930. * regarding copyright ownership. The ASF licenses this file
  64931. * to you under the Apache License, Version 2.0 (the
  64932. * "License"); you may not use this file except in compliance
  64933. * with the License. You may obtain a copy of the License at
  64934. *
  64935. * http://www.apache.org/licenses/LICENSE-2.0
  64936. *
  64937. * Unless required by applicable law or agreed to in writing,
  64938. * software distributed under the License is distributed on an
  64939. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  64940. * KIND, either express or implied. See the License for the
  64941. * specific language governing permissions and limitations
  64942. * under the License.
  64943. */
  64944. function getSeriesStackId$1(seriesModel) {
  64945. return seriesModel.get('stack')
  64946. || '__ec_stack_' + seriesModel.seriesIndex;
  64947. }
  64948. function getAxisKey$1(polar, axis) {
  64949. return axis.dim + polar.model.componentIndex;
  64950. }
  64951. /**
  64952. * @param {string} seriesType
  64953. * @param {module:echarts/model/Global} ecModel
  64954. * @param {module:echarts/ExtensionAPI} api
  64955. */
  64956. function barLayoutPolar(seriesType, ecModel, api) {
  64957. var lastStackCoords = {};
  64958. var barWidthAndOffset = calRadialBar(
  64959. filter(
  64960. ecModel.getSeriesByType(seriesType),
  64961. function (seriesModel) {
  64962. return !ecModel.isSeriesFiltered(seriesModel)
  64963. && seriesModel.coordinateSystem
  64964. && seriesModel.coordinateSystem.type === 'polar';
  64965. }
  64966. )
  64967. );
  64968. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  64969. // Check series coordinate, do layout for polar only
  64970. if (seriesModel.coordinateSystem.type !== 'polar') {
  64971. return;
  64972. }
  64973. var data = seriesModel.getData();
  64974. var polar = seriesModel.coordinateSystem;
  64975. var baseAxis = polar.getBaseAxis();
  64976. var axisKey = getAxisKey$1(polar, baseAxis);
  64977. var stackId = getSeriesStackId$1(seriesModel);
  64978. var columnLayoutInfo = barWidthAndOffset[axisKey][stackId];
  64979. var columnOffset = columnLayoutInfo.offset;
  64980. var columnWidth = columnLayoutInfo.width;
  64981. var valueAxis = polar.getOtherAxis(baseAxis);
  64982. var cx = seriesModel.coordinateSystem.cx;
  64983. var cy = seriesModel.coordinateSystem.cy;
  64984. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  64985. var barMinAngle = seriesModel.get('barMinAngle') || 0;
  64986. lastStackCoords[stackId] = lastStackCoords[stackId] || [];
  64987. var valueDim = data.mapDimension(valueAxis.dim);
  64988. var baseDim = data.mapDimension(baseAxis.dim);
  64989. var stacked = isDimensionStacked(data, valueDim /*, baseDim*/);
  64990. var clampLayout = baseAxis.dim !== 'radius'
  64991. || !seriesModel.get('roundCap', true);
  64992. var valueAxisStart = valueAxis.getExtent()[0];
  64993. for (var idx = 0, len = data.count(); idx < len; idx++) {
  64994. var value = data.get(valueDim, idx);
  64995. var baseValue = data.get(baseDim, idx);
  64996. var sign = value >= 0 ? 'p' : 'n';
  64997. var baseCoord = valueAxisStart;
  64998. // Because of the barMinHeight, we can not use the value in
  64999. // stackResultDimension directly.
  65000. // Only ordinal axis can be stacked.
  65001. if (stacked) {
  65002. if (!lastStackCoords[stackId][baseValue]) {
  65003. lastStackCoords[stackId][baseValue] = {
  65004. p: valueAxisStart, // Positive stack
  65005. n: valueAxisStart // Negative stack
  65006. };
  65007. }
  65008. // Should also consider #4243
  65009. baseCoord = lastStackCoords[stackId][baseValue][sign];
  65010. }
  65011. var r0;
  65012. var r;
  65013. var startAngle;
  65014. var endAngle;
  65015. // radial sector
  65016. if (valueAxis.dim === 'radius') {
  65017. var radiusSpan = valueAxis.dataToRadius(value) - valueAxisStart;
  65018. var angle = baseAxis.dataToAngle(baseValue);
  65019. if (Math.abs(radiusSpan) < barMinHeight) {
  65020. radiusSpan = (radiusSpan < 0 ? -1 : 1) * barMinHeight;
  65021. }
  65022. r0 = baseCoord;
  65023. r = baseCoord + radiusSpan;
  65024. startAngle = angle - columnOffset;
  65025. endAngle = startAngle - columnWidth;
  65026. stacked && (lastStackCoords[stackId][baseValue][sign] = r);
  65027. }
  65028. // tangential sector
  65029. else {
  65030. var angleSpan = valueAxis.dataToAngle(value, clampLayout) - valueAxisStart;
  65031. var radius = baseAxis.dataToRadius(baseValue);
  65032. if (Math.abs(angleSpan) < barMinAngle) {
  65033. angleSpan = (angleSpan < 0 ? -1 : 1) * barMinAngle;
  65034. }
  65035. r0 = radius + columnOffset;
  65036. r = r0 + columnWidth;
  65037. startAngle = baseCoord;
  65038. endAngle = baseCoord + angleSpan;
  65039. // if the previous stack is at the end of the ring,
  65040. // add a round to differentiate it from origin
  65041. // var extent = angleAxis.getExtent();
  65042. // var stackCoord = angle;
  65043. // if (stackCoord === extent[0] && value > 0) {
  65044. // stackCoord = extent[1];
  65045. // }
  65046. // else if (stackCoord === extent[1] && value < 0) {
  65047. // stackCoord = extent[0];
  65048. // }
  65049. stacked && (lastStackCoords[stackId][baseValue][sign] = endAngle);
  65050. }
  65051. data.setItemLayout(idx, {
  65052. cx: cx,
  65053. cy: cy,
  65054. r0: r0,
  65055. r: r,
  65056. // Consider that positive angle is anti-clockwise,
  65057. // while positive radian of sector is clockwise
  65058. startAngle: -startAngle * Math.PI / 180,
  65059. endAngle: -endAngle * Math.PI / 180
  65060. });
  65061. }
  65062. }, this);
  65063. }
  65064. /**
  65065. * Calculate bar width and offset for radial bar charts
  65066. */
  65067. function calRadialBar(barSeries, api) {
  65068. // Columns info on each category axis. Key is polar name
  65069. var columnsMap = {};
  65070. each$1(barSeries, function (seriesModel, idx) {
  65071. var data = seriesModel.getData();
  65072. var polar = seriesModel.coordinateSystem;
  65073. var baseAxis = polar.getBaseAxis();
  65074. var axisKey = getAxisKey$1(polar, baseAxis);
  65075. var axisExtent = baseAxis.getExtent();
  65076. var bandWidth = baseAxis.type === 'category'
  65077. ? baseAxis.getBandWidth()
  65078. : (Math.abs(axisExtent[1] - axisExtent[0]) / data.count());
  65079. var columnsOnAxis = columnsMap[axisKey] || {
  65080. bandWidth: bandWidth,
  65081. remainedWidth: bandWidth,
  65082. autoWidthCount: 0,
  65083. categoryGap: '20%',
  65084. gap: '30%',
  65085. stacks: {}
  65086. };
  65087. var stacks = columnsOnAxis.stacks;
  65088. columnsMap[axisKey] = columnsOnAxis;
  65089. var stackId = getSeriesStackId$1(seriesModel);
  65090. if (!stacks[stackId]) {
  65091. columnsOnAxis.autoWidthCount++;
  65092. }
  65093. stacks[stackId] = stacks[stackId] || {
  65094. width: 0,
  65095. maxWidth: 0
  65096. };
  65097. var barWidth = parsePercent$1(
  65098. seriesModel.get('barWidth'),
  65099. bandWidth
  65100. );
  65101. var barMaxWidth = parsePercent$1(
  65102. seriesModel.get('barMaxWidth'),
  65103. bandWidth
  65104. );
  65105. var barGap = seriesModel.get('barGap');
  65106. var barCategoryGap = seriesModel.get('barCategoryGap');
  65107. if (barWidth && !stacks[stackId].width) {
  65108. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  65109. stacks[stackId].width = barWidth;
  65110. columnsOnAxis.remainedWidth -= barWidth;
  65111. }
  65112. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  65113. (barGap != null) && (columnsOnAxis.gap = barGap);
  65114. (barCategoryGap != null) && (columnsOnAxis.categoryGap = barCategoryGap);
  65115. });
  65116. var result = {};
  65117. each$1(columnsMap, function (columnsOnAxis, coordSysName) {
  65118. result[coordSysName] = {};
  65119. var stacks = columnsOnAxis.stacks;
  65120. var bandWidth = columnsOnAxis.bandWidth;
  65121. var categoryGap = parsePercent$1(columnsOnAxis.categoryGap, bandWidth);
  65122. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  65123. var remainedWidth = columnsOnAxis.remainedWidth;
  65124. var autoWidthCount = columnsOnAxis.autoWidthCount;
  65125. var autoWidth = (remainedWidth - categoryGap)
  65126. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  65127. autoWidth = Math.max(autoWidth, 0);
  65128. // Find if any auto calculated bar exceeded maxBarWidth
  65129. each$1(stacks, function (column, stack) {
  65130. var maxWidth = column.maxWidth;
  65131. if (maxWidth && maxWidth < autoWidth) {
  65132. maxWidth = Math.min(maxWidth, remainedWidth);
  65133. if (column.width) {
  65134. maxWidth = Math.min(maxWidth, column.width);
  65135. }
  65136. remainedWidth -= maxWidth;
  65137. column.width = maxWidth;
  65138. autoWidthCount--;
  65139. }
  65140. });
  65141. // Recalculate width again
  65142. autoWidth = (remainedWidth - categoryGap)
  65143. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  65144. autoWidth = Math.max(autoWidth, 0);
  65145. var widthSum = 0;
  65146. var lastColumn;
  65147. each$1(stacks, function (column, idx) {
  65148. if (!column.width) {
  65149. column.width = autoWidth;
  65150. }
  65151. lastColumn = column;
  65152. widthSum += column.width * (1 + barGapPercent);
  65153. });
  65154. if (lastColumn) {
  65155. widthSum -= lastColumn.width * barGapPercent;
  65156. }
  65157. var offset = -widthSum / 2;
  65158. each$1(stacks, function (column, stackId) {
  65159. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  65160. offset: offset,
  65161. width: column.width
  65162. };
  65163. offset += column.width * (1 + barGapPercent);
  65164. });
  65165. });
  65166. return result;
  65167. }
  65168. /*
  65169. * Licensed to the Apache Software Foundation (ASF) under one
  65170. * or more contributor license agreements. See the NOTICE file
  65171. * distributed with this work for additional information
  65172. * regarding copyright ownership. The ASF licenses this file
  65173. * to you under the Apache License, Version 2.0 (the
  65174. * "License"); you may not use this file except in compliance
  65175. * with the License. You may obtain a copy of the License at
  65176. *
  65177. * http://www.apache.org/licenses/LICENSE-2.0
  65178. *
  65179. * Unless required by applicable law or agreed to in writing,
  65180. * software distributed under the License is distributed on an
  65181. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65182. * KIND, either express or implied. See the License for the
  65183. * specific language governing permissions and limitations
  65184. * under the License.
  65185. */
  65186. function RadiusAxis(scale, radiusExtent) {
  65187. Axis.call(this, 'radius', scale, radiusExtent);
  65188. /**
  65189. * Axis type
  65190. * - 'category'
  65191. * - 'value'
  65192. * - 'time'
  65193. * - 'log'
  65194. * @type {string}
  65195. */
  65196. this.type = 'category';
  65197. }
  65198. RadiusAxis.prototype = {
  65199. constructor: RadiusAxis,
  65200. /**
  65201. * @override
  65202. */
  65203. pointToData: function (point, clamp) {
  65204. return this.polar.pointToData(point, clamp)[this.dim === 'radius' ? 0 : 1];
  65205. },
  65206. dataToRadius: Axis.prototype.dataToCoord,
  65207. radiusToData: Axis.prototype.coordToData
  65208. };
  65209. inherits(RadiusAxis, Axis);
  65210. /*
  65211. * Licensed to the Apache Software Foundation (ASF) under one
  65212. * or more contributor license agreements. See the NOTICE file
  65213. * distributed with this work for additional information
  65214. * regarding copyright ownership. The ASF licenses this file
  65215. * to you under the Apache License, Version 2.0 (the
  65216. * "License"); you may not use this file except in compliance
  65217. * with the License. You may obtain a copy of the License at
  65218. *
  65219. * http://www.apache.org/licenses/LICENSE-2.0
  65220. *
  65221. * Unless required by applicable law or agreed to in writing,
  65222. * software distributed under the License is distributed on an
  65223. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65224. * KIND, either express or implied. See the License for the
  65225. * specific language governing permissions and limitations
  65226. * under the License.
  65227. */
  65228. var inner$12 = makeInner();
  65229. function AngleAxis(scale, angleExtent) {
  65230. angleExtent = angleExtent || [0, 360];
  65231. Axis.call(this, 'angle', scale, angleExtent);
  65232. /**
  65233. * Axis type
  65234. * - 'category'
  65235. * - 'value'
  65236. * - 'time'
  65237. * - 'log'
  65238. * @type {string}
  65239. */
  65240. this.type = 'category';
  65241. }
  65242. AngleAxis.prototype = {
  65243. constructor: AngleAxis,
  65244. /**
  65245. * @override
  65246. */
  65247. pointToData: function (point, clamp) {
  65248. return this.polar.pointToData(point, clamp)[this.dim === 'radius' ? 0 : 1];
  65249. },
  65250. dataToAngle: Axis.prototype.dataToCoord,
  65251. angleToData: Axis.prototype.coordToData,
  65252. /**
  65253. * Only be called in category axis.
  65254. * Angle axis uses text height to decide interval
  65255. *
  65256. * @override
  65257. * @return {number} Auto interval for cateogry axis tick and label
  65258. */
  65259. calculateCategoryInterval: function () {
  65260. var axis = this;
  65261. var labelModel = axis.getLabelModel();
  65262. var ordinalScale = axis.scale;
  65263. var ordinalExtent = ordinalScale.getExtent();
  65264. // Providing this method is for optimization:
  65265. // avoid generating a long array by `getTicks`
  65266. // in large category data case.
  65267. var tickCount = ordinalScale.count();
  65268. if (ordinalExtent[1] - ordinalExtent[0] < 1) {
  65269. return 0;
  65270. }
  65271. var tickValue = ordinalExtent[0];
  65272. var unitSpan = axis.dataToCoord(tickValue + 1) - axis.dataToCoord(tickValue);
  65273. var unitH = Math.abs(unitSpan);
  65274. // Not precise, just use height as text width
  65275. // and each distance from axis line yet.
  65276. var rect = getBoundingRect(
  65277. tickValue, labelModel.getFont(), 'center', 'top'
  65278. );
  65279. var maxH = Math.max(rect.height, 7);
  65280. var dh = maxH / unitH;
  65281. // 0/0 is NaN, 1/0 is Infinity.
  65282. isNaN(dh) && (dh = Infinity);
  65283. var interval = Math.max(0, Math.floor(dh));
  65284. var cache = inner$12(axis.model);
  65285. var lastAutoInterval = cache.lastAutoInterval;
  65286. var lastTickCount = cache.lastTickCount;
  65287. // Use cache to keep interval stable while moving zoom window,
  65288. // otherwise the calculated interval might jitter when the zoom
  65289. // window size is close to the interval-changing size.
  65290. if (lastAutoInterval != null
  65291. && lastTickCount != null
  65292. && Math.abs(lastAutoInterval - interval) <= 1
  65293. && Math.abs(lastTickCount - tickCount) <= 1
  65294. // Always choose the bigger one, otherwise the critical
  65295. // point is not the same when zooming in or zooming out.
  65296. && lastAutoInterval > interval
  65297. ) {
  65298. interval = lastAutoInterval;
  65299. }
  65300. // Only update cache if cache not used, otherwise the
  65301. // changing of interval is too insensitive.
  65302. else {
  65303. cache.lastTickCount = tickCount;
  65304. cache.lastAutoInterval = interval;
  65305. }
  65306. return interval;
  65307. }
  65308. };
  65309. inherits(AngleAxis, Axis);
  65310. /*
  65311. * Licensed to the Apache Software Foundation (ASF) under one
  65312. * or more contributor license agreements. See the NOTICE file
  65313. * distributed with this work for additional information
  65314. * regarding copyright ownership. The ASF licenses this file
  65315. * to you under the Apache License, Version 2.0 (the
  65316. * "License"); you may not use this file except in compliance
  65317. * with the License. You may obtain a copy of the License at
  65318. *
  65319. * http://www.apache.org/licenses/LICENSE-2.0
  65320. *
  65321. * Unless required by applicable law or agreed to in writing,
  65322. * software distributed under the License is distributed on an
  65323. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65324. * KIND, either express or implied. See the License for the
  65325. * specific language governing permissions and limitations
  65326. * under the License.
  65327. */
  65328. /**
  65329. * @module echarts/coord/polar/Polar
  65330. */
  65331. /**
  65332. * @alias {module:echarts/coord/polar/Polar}
  65333. * @constructor
  65334. * @param {string} name
  65335. */
  65336. var Polar = function (name) {
  65337. /**
  65338. * @type {string}
  65339. */
  65340. this.name = name || '';
  65341. /**
  65342. * x of polar center
  65343. * @type {number}
  65344. */
  65345. this.cx = 0;
  65346. /**
  65347. * y of polar center
  65348. * @type {number}
  65349. */
  65350. this.cy = 0;
  65351. /**
  65352. * @type {module:echarts/coord/polar/RadiusAxis}
  65353. * @private
  65354. */
  65355. this._radiusAxis = new RadiusAxis();
  65356. /**
  65357. * @type {module:echarts/coord/polar/AngleAxis}
  65358. * @private
  65359. */
  65360. this._angleAxis = new AngleAxis();
  65361. this._radiusAxis.polar = this._angleAxis.polar = this;
  65362. };
  65363. Polar.prototype = {
  65364. type: 'polar',
  65365. axisPointerEnabled: true,
  65366. constructor: Polar,
  65367. /**
  65368. * @param {Array.<string>}
  65369. * @readOnly
  65370. */
  65371. dimensions: ['radius', 'angle'],
  65372. /**
  65373. * @type {module:echarts/coord/PolarModel}
  65374. */
  65375. model: null,
  65376. /**
  65377. * If contain coord
  65378. * @param {Array.<number>} point
  65379. * @return {boolean}
  65380. */
  65381. containPoint: function (point) {
  65382. var coord = this.pointToCoord(point);
  65383. return this._radiusAxis.contain(coord[0])
  65384. && this._angleAxis.contain(coord[1]);
  65385. },
  65386. /**
  65387. * If contain data
  65388. * @param {Array.<number>} data
  65389. * @return {boolean}
  65390. */
  65391. containData: function (data) {
  65392. return this._radiusAxis.containData(data[0])
  65393. && this._angleAxis.containData(data[1]);
  65394. },
  65395. /**
  65396. * @param {string} dim
  65397. * @return {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis}
  65398. */
  65399. getAxis: function (dim) {
  65400. return this['_' + dim + 'Axis'];
  65401. },
  65402. /**
  65403. * @return {Array.<module:echarts/coord/Axis>}
  65404. */
  65405. getAxes: function () {
  65406. return [this._radiusAxis, this._angleAxis];
  65407. },
  65408. /**
  65409. * Get axes by type of scale
  65410. * @param {string} scaleType
  65411. * @return {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis}
  65412. */
  65413. getAxesByScale: function (scaleType) {
  65414. var axes = [];
  65415. var angleAxis = this._angleAxis;
  65416. var radiusAxis = this._radiusAxis;
  65417. angleAxis.scale.type === scaleType && axes.push(angleAxis);
  65418. radiusAxis.scale.type === scaleType && axes.push(radiusAxis);
  65419. return axes;
  65420. },
  65421. /**
  65422. * @return {module:echarts/coord/polar/AngleAxis}
  65423. */
  65424. getAngleAxis: function () {
  65425. return this._angleAxis;
  65426. },
  65427. /**
  65428. * @return {module:echarts/coord/polar/RadiusAxis}
  65429. */
  65430. getRadiusAxis: function () {
  65431. return this._radiusAxis;
  65432. },
  65433. /**
  65434. * @param {module:echarts/coord/polar/Axis}
  65435. * @return {module:echarts/coord/polar/Axis}
  65436. */
  65437. getOtherAxis: function (axis) {
  65438. var angleAxis = this._angleAxis;
  65439. return axis === angleAxis ? this._radiusAxis : angleAxis;
  65440. },
  65441. /**
  65442. * Base axis will be used on stacking.
  65443. *
  65444. * @return {module:echarts/coord/polar/Axis}
  65445. */
  65446. getBaseAxis: function () {
  65447. return this.getAxesByScale('ordinal')[0]
  65448. || this.getAxesByScale('time')[0]
  65449. || this.getAngleAxis();
  65450. },
  65451. /**
  65452. * @param {string} [dim] 'radius' or 'angle' or 'auto' or null/undefined
  65453. * @return {Object} {baseAxes: [], otherAxes: []}
  65454. */
  65455. getTooltipAxes: function (dim) {
  65456. var baseAxis = (dim != null && dim !== 'auto')
  65457. ? this.getAxis(dim) : this.getBaseAxis();
  65458. return {
  65459. baseAxes: [baseAxis],
  65460. otherAxes: [this.getOtherAxis(baseAxis)]
  65461. };
  65462. },
  65463. /**
  65464. * Convert a single data item to (x, y) point.
  65465. * Parameter data is an array which the first element is radius and the second is angle
  65466. * @param {Array.<number>} data
  65467. * @param {boolean} [clamp=false]
  65468. * @return {Array.<number>}
  65469. */
  65470. dataToPoint: function (data, clamp) {
  65471. return this.coordToPoint([
  65472. this._radiusAxis.dataToRadius(data[0], clamp),
  65473. this._angleAxis.dataToAngle(data[1], clamp)
  65474. ]);
  65475. },
  65476. /**
  65477. * Convert a (x, y) point to data
  65478. * @param {Array.<number>} point
  65479. * @param {boolean} [clamp=false]
  65480. * @return {Array.<number>}
  65481. */
  65482. pointToData: function (point, clamp) {
  65483. var coord = this.pointToCoord(point);
  65484. return [
  65485. this._radiusAxis.radiusToData(coord[0], clamp),
  65486. this._angleAxis.angleToData(coord[1], clamp)
  65487. ];
  65488. },
  65489. /**
  65490. * Convert a (x, y) point to (radius, angle) coord
  65491. * @param {Array.<number>} point
  65492. * @return {Array.<number>}
  65493. */
  65494. pointToCoord: function (point) {
  65495. var dx = point[0] - this.cx;
  65496. var dy = point[1] - this.cy;
  65497. var angleAxis = this.getAngleAxis();
  65498. var extent = angleAxis.getExtent();
  65499. var minAngle = Math.min(extent[0], extent[1]);
  65500. var maxAngle = Math.max(extent[0], extent[1]);
  65501. // Fix fixed extent in polarCreator
  65502. // FIXME
  65503. angleAxis.inverse
  65504. ? (minAngle = maxAngle - 360)
  65505. : (maxAngle = minAngle + 360);
  65506. var radius = Math.sqrt(dx * dx + dy * dy);
  65507. dx /= radius;
  65508. dy /= radius;
  65509. var radian = Math.atan2(-dy, dx) / Math.PI * 180;
  65510. // move to angleExtent
  65511. var dir = radian < minAngle ? 1 : -1;
  65512. while (radian < minAngle || radian > maxAngle) {
  65513. radian += dir * 360;
  65514. }
  65515. return [radius, radian];
  65516. },
  65517. /**
  65518. * Convert a (radius, angle) coord to (x, y) point
  65519. * @param {Array.<number>} coord
  65520. * @return {Array.<number>}
  65521. */
  65522. coordToPoint: function (coord) {
  65523. var radius = coord[0];
  65524. var radian = coord[1] / 180 * Math.PI;
  65525. var x = Math.cos(radian) * radius + this.cx;
  65526. // Inverse the y
  65527. var y = -Math.sin(radian) * radius + this.cy;
  65528. return [x, y];
  65529. },
  65530. /**
  65531. * Get ring area of cartesian.
  65532. * Area will have a contain function to determine if a point is in the coordinate system.
  65533. * @return {Ring}
  65534. */
  65535. getArea: function () {
  65536. var angleAxis = this.getAngleAxis();
  65537. var radiusAxis = this.getRadiusAxis();
  65538. var radiusExtent = radiusAxis.getExtent().slice();
  65539. radiusExtent[0] > radiusExtent[1] && radiusExtent.reverse();
  65540. var angleExtent = angleAxis.getExtent();
  65541. var RADIAN = Math.PI / 180;
  65542. return {
  65543. cx: this.cx,
  65544. cy: this.cy,
  65545. r0: radiusExtent[0],
  65546. r: radiusExtent[1],
  65547. startAngle: -angleExtent[0] * RADIAN,
  65548. endAngle: -angleExtent[1] * RADIAN,
  65549. clockwise: angleAxis.inverse,
  65550. contain: function (x, y) {
  65551. // It's a ring shape.
  65552. // Start angle and end angle don't matter
  65553. var dx = x - this.cx;
  65554. var dy = y - this.cy;
  65555. var d2 = dx * dx + dy * dy;
  65556. var r = this.r;
  65557. var r0 = this.r0;
  65558. return d2 <= r * r && d2 >= r0 * r0;
  65559. }
  65560. };
  65561. }
  65562. };
  65563. /*
  65564. * Licensed to the Apache Software Foundation (ASF) under one
  65565. * or more contributor license agreements. See the NOTICE file
  65566. * distributed with this work for additional information
  65567. * regarding copyright ownership. The ASF licenses this file
  65568. * to you under the Apache License, Version 2.0 (the
  65569. * "License"); you may not use this file except in compliance
  65570. * with the License. You may obtain a copy of the License at
  65571. *
  65572. * http://www.apache.org/licenses/LICENSE-2.0
  65573. *
  65574. * Unless required by applicable law or agreed to in writing,
  65575. * software distributed under the License is distributed on an
  65576. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65577. * KIND, either express or implied. See the License for the
  65578. * specific language governing permissions and limitations
  65579. * under the License.
  65580. */
  65581. var PolarAxisModel = ComponentModel.extend({
  65582. type: 'polarAxis',
  65583. /**
  65584. * @type {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis}
  65585. */
  65586. axis: null,
  65587. /**
  65588. * @override
  65589. */
  65590. getCoordSysModel: function () {
  65591. return this.ecModel.queryComponents({
  65592. mainType: 'polar',
  65593. index: this.option.polarIndex,
  65594. id: this.option.polarId
  65595. })[0];
  65596. }
  65597. });
  65598. merge(PolarAxisModel.prototype, axisModelCommonMixin);
  65599. var polarAxisDefaultExtendedOption = {
  65600. angle: {
  65601. // polarIndex: 0,
  65602. // polarId: '',
  65603. startAngle: 90,
  65604. clockwise: true,
  65605. splitNumber: 12,
  65606. axisLabel: {
  65607. rotate: false
  65608. }
  65609. },
  65610. radius: {
  65611. // polarIndex: 0,
  65612. // polarId: '',
  65613. splitNumber: 5
  65614. }
  65615. };
  65616. function getAxisType$3(axisDim, option) {
  65617. // Default axis with data is category axis
  65618. return option.type || (option.data ? 'category' : 'value');
  65619. }
  65620. axisModelCreator('angle', PolarAxisModel, getAxisType$3, polarAxisDefaultExtendedOption.angle);
  65621. axisModelCreator('radius', PolarAxisModel, getAxisType$3, polarAxisDefaultExtendedOption.radius);
  65622. /*
  65623. * Licensed to the Apache Software Foundation (ASF) under one
  65624. * or more contributor license agreements. See the NOTICE file
  65625. * distributed with this work for additional information
  65626. * regarding copyright ownership. The ASF licenses this file
  65627. * to you under the Apache License, Version 2.0 (the
  65628. * "License"); you may not use this file except in compliance
  65629. * with the License. You may obtain a copy of the License at
  65630. *
  65631. * http://www.apache.org/licenses/LICENSE-2.0
  65632. *
  65633. * Unless required by applicable law or agreed to in writing,
  65634. * software distributed under the License is distributed on an
  65635. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65636. * KIND, either express or implied. See the License for the
  65637. * specific language governing permissions and limitations
  65638. * under the License.
  65639. */
  65640. extendComponentModel({
  65641. type: 'polar',
  65642. dependencies: ['polarAxis', 'angleAxis'],
  65643. /**
  65644. * @type {module:echarts/coord/polar/Polar}
  65645. */
  65646. coordinateSystem: null,
  65647. /**
  65648. * @param {string} axisType
  65649. * @return {module:echarts/coord/polar/AxisModel}
  65650. */
  65651. findAxisModel: function (axisType) {
  65652. var foundAxisModel;
  65653. var ecModel = this.ecModel;
  65654. ecModel.eachComponent(axisType, function (axisModel) {
  65655. if (axisModel.getCoordSysModel() === this) {
  65656. foundAxisModel = axisModel;
  65657. }
  65658. }, this);
  65659. return foundAxisModel;
  65660. },
  65661. defaultOption: {
  65662. zlevel: 0,
  65663. z: 0,
  65664. center: ['50%', '50%'],
  65665. radius: '80%'
  65666. }
  65667. });
  65668. /*
  65669. * Licensed to the Apache Software Foundation (ASF) under one
  65670. * or more contributor license agreements. See the NOTICE file
  65671. * distributed with this work for additional information
  65672. * regarding copyright ownership. The ASF licenses this file
  65673. * to you under the Apache License, Version 2.0 (the
  65674. * "License"); you may not use this file except in compliance
  65675. * with the License. You may obtain a copy of the License at
  65676. *
  65677. * http://www.apache.org/licenses/LICENSE-2.0
  65678. *
  65679. * Unless required by applicable law or agreed to in writing,
  65680. * software distributed under the License is distributed on an
  65681. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65682. * KIND, either express or implied. See the License for the
  65683. * specific language governing permissions and limitations
  65684. * under the License.
  65685. */
  65686. // TODO Axis scale
  65687. /**
  65688. * Resize method bound to the polar
  65689. * @param {module:echarts/coord/polar/PolarModel} polarModel
  65690. * @param {module:echarts/ExtensionAPI} api
  65691. */
  65692. function resizePolar(polar, polarModel, api) {
  65693. var center = polarModel.get('center');
  65694. var width = api.getWidth();
  65695. var height = api.getHeight();
  65696. polar.cx = parsePercent$1(center[0], width);
  65697. polar.cy = parsePercent$1(center[1], height);
  65698. var radiusAxis = polar.getRadiusAxis();
  65699. var size = Math.min(width, height) / 2;
  65700. var radius = polarModel.get('radius');
  65701. if (radius == null) {
  65702. radius = [0, '100%'];
  65703. }
  65704. else if (!isArray(radius)) {
  65705. // r0 = 0
  65706. radius = [0, radius];
  65707. }
  65708. radius = [
  65709. parsePercent$1(radius[0], size),
  65710. parsePercent$1(radius[1], size)
  65711. ];
  65712. radiusAxis.inverse
  65713. ? radiusAxis.setExtent(radius[1], radius[0])
  65714. : radiusAxis.setExtent(radius[0], radius[1]);
  65715. }
  65716. /**
  65717. * Update polar
  65718. */
  65719. function updatePolarScale(ecModel, api) {
  65720. var polar = this;
  65721. var angleAxis = polar.getAngleAxis();
  65722. var radiusAxis = polar.getRadiusAxis();
  65723. // Reset scale
  65724. angleAxis.scale.setExtent(Infinity, -Infinity);
  65725. radiusAxis.scale.setExtent(Infinity, -Infinity);
  65726. ecModel.eachSeries(function (seriesModel) {
  65727. if (seriesModel.coordinateSystem === polar) {
  65728. var data = seriesModel.getData();
  65729. each$1(data.mapDimension('radius', true), function (dim) {
  65730. radiusAxis.scale.unionExtentFromData(
  65731. data, getStackedDimension(data, dim)
  65732. );
  65733. });
  65734. each$1(data.mapDimension('angle', true), function (dim) {
  65735. angleAxis.scale.unionExtentFromData(
  65736. data, getStackedDimension(data, dim)
  65737. );
  65738. });
  65739. }
  65740. });
  65741. niceScaleExtent(angleAxis.scale, angleAxis.model);
  65742. niceScaleExtent(radiusAxis.scale, radiusAxis.model);
  65743. // Fix extent of category angle axis
  65744. if (angleAxis.type === 'category' && !angleAxis.onBand) {
  65745. var extent = angleAxis.getExtent();
  65746. var diff = 360 / angleAxis.scale.count();
  65747. angleAxis.inverse ? (extent[1] += diff) : (extent[1] -= diff);
  65748. angleAxis.setExtent(extent[0], extent[1]);
  65749. }
  65750. }
  65751. /**
  65752. * Set common axis properties
  65753. * @param {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis}
  65754. * @param {module:echarts/coord/polar/AxisModel}
  65755. * @inner
  65756. */
  65757. function setAxis(axis, axisModel) {
  65758. axis.type = axisModel.get('type');
  65759. axis.scale = createScaleByModel(axisModel);
  65760. axis.onBand = axisModel.get('boundaryGap') && axis.type === 'category';
  65761. axis.inverse = axisModel.get('inverse');
  65762. if (axisModel.mainType === 'angleAxis') {
  65763. axis.inverse ^= axisModel.get('clockwise');
  65764. var startAngle = axisModel.get('startAngle');
  65765. axis.setExtent(startAngle, startAngle + (axis.inverse ? -360 : 360));
  65766. }
  65767. // Inject axis instance
  65768. axisModel.axis = axis;
  65769. axis.model = axisModel;
  65770. }
  65771. var polarCreator = {
  65772. dimensions: Polar.prototype.dimensions,
  65773. create: function (ecModel, api) {
  65774. var polarList = [];
  65775. ecModel.eachComponent('polar', function (polarModel, idx) {
  65776. var polar = new Polar(idx);
  65777. // Inject resize and update method
  65778. polar.update = updatePolarScale;
  65779. var radiusAxis = polar.getRadiusAxis();
  65780. var angleAxis = polar.getAngleAxis();
  65781. var radiusAxisModel = polarModel.findAxisModel('radiusAxis');
  65782. var angleAxisModel = polarModel.findAxisModel('angleAxis');
  65783. setAxis(radiusAxis, radiusAxisModel);
  65784. setAxis(angleAxis, angleAxisModel);
  65785. resizePolar(polar, polarModel, api);
  65786. polarList.push(polar);
  65787. polarModel.coordinateSystem = polar;
  65788. polar.model = polarModel;
  65789. });
  65790. // Inject coordinateSystem to series
  65791. ecModel.eachSeries(function (seriesModel) {
  65792. if (seriesModel.get('coordinateSystem') === 'polar') {
  65793. var polarModel = ecModel.queryComponents({
  65794. mainType: 'polar',
  65795. index: seriesModel.get('polarIndex'),
  65796. id: seriesModel.get('polarId')
  65797. })[0];
  65798. if (__DEV__) {
  65799. if (!polarModel) {
  65800. throw new Error(
  65801. 'Polar "' + retrieve(
  65802. seriesModel.get('polarIndex'),
  65803. seriesModel.get('polarId'),
  65804. 0
  65805. ) + '" not found'
  65806. );
  65807. }
  65808. }
  65809. seriesModel.coordinateSystem = polarModel.coordinateSystem;
  65810. }
  65811. });
  65812. return polarList;
  65813. }
  65814. };
  65815. CoordinateSystemManager.register('polar', polarCreator);
  65816. /*
  65817. * Licensed to the Apache Software Foundation (ASF) under one
  65818. * or more contributor license agreements. See the NOTICE file
  65819. * distributed with this work for additional information
  65820. * regarding copyright ownership. The ASF licenses this file
  65821. * to you under the Apache License, Version 2.0 (the
  65822. * "License"); you may not use this file except in compliance
  65823. * with the License. You may obtain a copy of the License at
  65824. *
  65825. * http://www.apache.org/licenses/LICENSE-2.0
  65826. *
  65827. * Unless required by applicable law or agreed to in writing,
  65828. * software distributed under the License is distributed on an
  65829. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65830. * KIND, either express or implied. See the License for the
  65831. * specific language governing permissions and limitations
  65832. * under the License.
  65833. */
  65834. var elementList$1 = ['axisLine', 'axisLabel', 'axisTick', 'minorTick', 'splitLine', 'minorSplitLine', 'splitArea'];
  65835. function getAxisLineShape(polar, rExtent, angle) {
  65836. rExtent[1] > rExtent[0] && (rExtent = rExtent.slice().reverse());
  65837. var start = polar.coordToPoint([rExtent[0], angle]);
  65838. var end = polar.coordToPoint([rExtent[1], angle]);
  65839. return {
  65840. x1: start[0],
  65841. y1: start[1],
  65842. x2: end[0],
  65843. y2: end[1]
  65844. };
  65845. }
  65846. function getRadiusIdx(polar) {
  65847. var radiusAxis = polar.getRadiusAxis();
  65848. return radiusAxis.inverse ? 0 : 1;
  65849. }
  65850. // Remove the last tick which will overlap the first tick
  65851. function fixAngleOverlap(list) {
  65852. var firstItem = list[0];
  65853. var lastItem = list[list.length - 1];
  65854. if (firstItem
  65855. && lastItem
  65856. && Math.abs(Math.abs(firstItem.coord - lastItem.coord) - 360) < 1e-4
  65857. ) {
  65858. list.pop();
  65859. }
  65860. }
  65861. AxisView.extend({
  65862. type: 'angleAxis',
  65863. axisPointerClass: 'PolarAxisPointer',
  65864. render: function (angleAxisModel, ecModel) {
  65865. this.group.removeAll();
  65866. if (!angleAxisModel.get('show')) {
  65867. return;
  65868. }
  65869. var angleAxis = angleAxisModel.axis;
  65870. var polar = angleAxis.polar;
  65871. var radiusExtent = polar.getRadiusAxis().getExtent();
  65872. var ticksAngles = angleAxis.getTicksCoords();
  65873. var minorTickAngles = angleAxis.getMinorTicksCoords();
  65874. var labels = map(angleAxis.getViewLabels(), function (labelItem) {
  65875. var labelItem = clone(labelItem);
  65876. labelItem.coord = angleAxis.dataToCoord(labelItem.tickValue);
  65877. return labelItem;
  65878. });
  65879. fixAngleOverlap(labels);
  65880. fixAngleOverlap(ticksAngles);
  65881. each$1(elementList$1, function (name) {
  65882. if (angleAxisModel.get(name + '.show')
  65883. && (!angleAxis.scale.isBlank() || name === 'axisLine')
  65884. ) {
  65885. this['_' + name](angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent, labels);
  65886. }
  65887. }, this);
  65888. },
  65889. /**
  65890. * @private
  65891. */
  65892. _axisLine: function (angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent) {
  65893. var lineStyleModel = angleAxisModel.getModel('axisLine.lineStyle');
  65894. // extent id of the axis radius (r0 and r)
  65895. var rId = getRadiusIdx(polar);
  65896. var r0Id = rId ? 0 : 1;
  65897. var shape;
  65898. if (radiusExtent[r0Id] === 0) {
  65899. shape = new Circle({
  65900. shape: {
  65901. cx: polar.cx,
  65902. cy: polar.cy,
  65903. r: radiusExtent[rId]
  65904. },
  65905. style: lineStyleModel.getLineStyle(),
  65906. z2: 1,
  65907. silent: true
  65908. });
  65909. }
  65910. else {
  65911. shape = new Ring({
  65912. shape: {
  65913. cx: polar.cx,
  65914. cy: polar.cy,
  65915. r: radiusExtent[rId],
  65916. r0: radiusExtent[r0Id]
  65917. },
  65918. style: lineStyleModel.getLineStyle(),
  65919. z2: 1,
  65920. silent: true
  65921. });
  65922. }
  65923. shape.style.fill = null;
  65924. this.group.add(shape);
  65925. },
  65926. /**
  65927. * @private
  65928. */
  65929. _axisTick: function (angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent) {
  65930. var tickModel = angleAxisModel.getModel('axisTick');
  65931. var tickLen = (tickModel.get('inside') ? -1 : 1) * tickModel.get('length');
  65932. var radius = radiusExtent[getRadiusIdx(polar)];
  65933. var lines = map(ticksAngles, function (tickAngleItem) {
  65934. return new Line({
  65935. shape: getAxisLineShape(polar, [radius, radius + tickLen], tickAngleItem.coord)
  65936. });
  65937. });
  65938. this.group.add(mergePath(
  65939. lines, {
  65940. style: defaults(
  65941. tickModel.getModel('lineStyle').getLineStyle(),
  65942. {
  65943. stroke: angleAxisModel.get('axisLine.lineStyle.color')
  65944. }
  65945. )
  65946. }
  65947. ));
  65948. },
  65949. /**
  65950. * @private
  65951. */
  65952. _minorTick: function (angleAxisModel, polar, tickAngles, minorTickAngles, radiusExtent) {
  65953. if (!minorTickAngles.length) {
  65954. return;
  65955. }
  65956. var tickModel = angleAxisModel.getModel('axisTick');
  65957. var minorTickModel = angleAxisModel.getModel('minorTick');
  65958. var tickLen = (tickModel.get('inside') ? -1 : 1) * minorTickModel.get('length');
  65959. var radius = radiusExtent[getRadiusIdx(polar)];
  65960. var lines = [];
  65961. for (var i = 0; i < minorTickAngles.length; i++) {
  65962. for (var k = 0; k < minorTickAngles[i].length; k++) {
  65963. lines.push(new Line({
  65964. shape: getAxisLineShape(polar, [radius, radius + tickLen], minorTickAngles[i][k].coord)
  65965. }));
  65966. }
  65967. }
  65968. this.group.add(mergePath(
  65969. lines, {
  65970. style: defaults(
  65971. minorTickModel.getModel('lineStyle').getLineStyle(),
  65972. defaults(
  65973. tickModel.getLineStyle(), {
  65974. stroke: angleAxisModel.get('axisLine.lineStyle.color')
  65975. }
  65976. )
  65977. )
  65978. }
  65979. ));
  65980. },
  65981. /**
  65982. * @private
  65983. */
  65984. _axisLabel: function (angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent, labels) {
  65985. var rawCategoryData = angleAxisModel.getCategories(true);
  65986. var commonLabelModel = angleAxisModel.getModel('axisLabel');
  65987. var labelMargin = commonLabelModel.get('margin');
  65988. var triggerEvent = angleAxisModel.get('triggerEvent');
  65989. // Use length of ticksAngles because it may remove the last tick to avoid overlapping
  65990. each$1(labels, function (labelItem, idx) {
  65991. var labelModel = commonLabelModel;
  65992. var tickValue = labelItem.tickValue;
  65993. var r = radiusExtent[getRadiusIdx(polar)];
  65994. var p = polar.coordToPoint([r + labelMargin, labelItem.coord]);
  65995. var cx = polar.cx;
  65996. var cy = polar.cy;
  65997. var labelTextAlign = Math.abs(p[0] - cx) / r < 0.3
  65998. ? 'center' : (p[0] > cx ? 'left' : 'right');
  65999. var labelTextVerticalAlign = Math.abs(p[1] - cy) / r < 0.3
  66000. ? 'middle' : (p[1] > cy ? 'top' : 'bottom');
  66001. if (rawCategoryData && rawCategoryData[tickValue] && rawCategoryData[tickValue].textStyle) {
  66002. labelModel = new Model(
  66003. rawCategoryData[tickValue].textStyle, commonLabelModel, commonLabelModel.ecModel
  66004. );
  66005. }
  66006. var textEl = new Text({
  66007. silent: AxisBuilder.isLabelSilent(angleAxisModel)
  66008. });
  66009. this.group.add(textEl);
  66010. setTextStyle(textEl.style, labelModel, {
  66011. x: p[0],
  66012. y: p[1],
  66013. textFill: labelModel.getTextColor() || angleAxisModel.get('axisLine.lineStyle.color'),
  66014. text: labelItem.formattedLabel,
  66015. textAlign: labelTextAlign,
  66016. textVerticalAlign: labelTextVerticalAlign
  66017. });
  66018. // Pack data for mouse event
  66019. if (triggerEvent) {
  66020. textEl.eventData = AxisBuilder.makeAxisEventDataBase(angleAxisModel);
  66021. textEl.eventData.targetType = 'axisLabel';
  66022. textEl.eventData.value = labelItem.rawLabel;
  66023. }
  66024. }, this);
  66025. },
  66026. /**
  66027. * @private
  66028. */
  66029. _splitLine: function (angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent) {
  66030. var splitLineModel = angleAxisModel.getModel('splitLine');
  66031. var lineStyleModel = splitLineModel.getModel('lineStyle');
  66032. var lineColors = lineStyleModel.get('color');
  66033. var lineCount = 0;
  66034. lineColors = lineColors instanceof Array ? lineColors : [lineColors];
  66035. var splitLines = [];
  66036. for (var i = 0; i < ticksAngles.length; i++) {
  66037. var colorIndex = (lineCount++) % lineColors.length;
  66038. splitLines[colorIndex] = splitLines[colorIndex] || [];
  66039. splitLines[colorIndex].push(new Line({
  66040. shape: getAxisLineShape(polar, radiusExtent, ticksAngles[i].coord)
  66041. }));
  66042. }
  66043. // Simple optimization
  66044. // Batching the lines if color are the same
  66045. for (var i = 0; i < splitLines.length; i++) {
  66046. this.group.add(mergePath(splitLines[i], {
  66047. style: defaults({
  66048. stroke: lineColors[i % lineColors.length]
  66049. }, lineStyleModel.getLineStyle()),
  66050. silent: true,
  66051. z: angleAxisModel.get('z')
  66052. }));
  66053. }
  66054. },
  66055. /**
  66056. * @private
  66057. */
  66058. _minorSplitLine: function (angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent) {
  66059. if (!minorTickAngles.length) {
  66060. return;
  66061. }
  66062. var minorSplitLineModel = angleAxisModel.getModel('minorSplitLine');
  66063. var lineStyleModel = minorSplitLineModel.getModel('lineStyle');
  66064. var lines = [];
  66065. for (var i = 0; i < minorTickAngles.length; i++) {
  66066. for (var k = 0; k < minorTickAngles[i].length; k++) {
  66067. lines.push(new Line({
  66068. shape: getAxisLineShape(polar, radiusExtent, minorTickAngles[i][k].coord)
  66069. }));
  66070. }
  66071. }
  66072. this.group.add(mergePath(lines, {
  66073. style: lineStyleModel.getLineStyle(),
  66074. silent: true,
  66075. z: angleAxisModel.get('z')
  66076. }));
  66077. },
  66078. /**
  66079. * @private
  66080. */
  66081. _splitArea: function (angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent) {
  66082. if (!ticksAngles.length) {
  66083. return;
  66084. }
  66085. var splitAreaModel = angleAxisModel.getModel('splitArea');
  66086. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  66087. var areaColors = areaStyleModel.get('color');
  66088. var lineCount = 0;
  66089. areaColors = areaColors instanceof Array ? areaColors : [areaColors];
  66090. var splitAreas = [];
  66091. var RADIAN = Math.PI / 180;
  66092. var prevAngle = -ticksAngles[0].coord * RADIAN;
  66093. var r0 = Math.min(radiusExtent[0], radiusExtent[1]);
  66094. var r1 = Math.max(radiusExtent[0], radiusExtent[1]);
  66095. var clockwise = angleAxisModel.get('clockwise');
  66096. for (var i = 1; i < ticksAngles.length; i++) {
  66097. var colorIndex = (lineCount++) % areaColors.length;
  66098. splitAreas[colorIndex] = splitAreas[colorIndex] || [];
  66099. splitAreas[colorIndex].push(new Sector({
  66100. shape: {
  66101. cx: polar.cx,
  66102. cy: polar.cy,
  66103. r0: r0,
  66104. r: r1,
  66105. startAngle: prevAngle,
  66106. endAngle: -ticksAngles[i].coord * RADIAN,
  66107. clockwise: clockwise
  66108. },
  66109. silent: true
  66110. }));
  66111. prevAngle = -ticksAngles[i].coord * RADIAN;
  66112. }
  66113. // Simple optimization
  66114. // Batching the lines if color are the same
  66115. for (var i = 0; i < splitAreas.length; i++) {
  66116. this.group.add(mergePath(splitAreas[i], {
  66117. style: defaults({
  66118. fill: areaColors[i % areaColors.length]
  66119. }, areaStyleModel.getAreaStyle()),
  66120. silent: true
  66121. }));
  66122. }
  66123. }
  66124. });
  66125. /*
  66126. * Licensed to the Apache Software Foundation (ASF) under one
  66127. * or more contributor license agreements. See the NOTICE file
  66128. * distributed with this work for additional information
  66129. * regarding copyright ownership. The ASF licenses this file
  66130. * to you under the Apache License, Version 2.0 (the
  66131. * "License"); you may not use this file except in compliance
  66132. * with the License. You may obtain a copy of the License at
  66133. *
  66134. * http://www.apache.org/licenses/LICENSE-2.0
  66135. *
  66136. * Unless required by applicable law or agreed to in writing,
  66137. * software distributed under the License is distributed on an
  66138. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66139. * KIND, either express or implied. See the License for the
  66140. * specific language governing permissions and limitations
  66141. * under the License.
  66142. */
  66143. /*
  66144. * Licensed to the Apache Software Foundation (ASF) under one
  66145. * or more contributor license agreements. See the NOTICE file
  66146. * distributed with this work for additional information
  66147. * regarding copyright ownership. The ASF licenses this file
  66148. * to you under the Apache License, Version 2.0 (the
  66149. * "License"); you may not use this file except in compliance
  66150. * with the License. You may obtain a copy of the License at
  66151. *
  66152. * http://www.apache.org/licenses/LICENSE-2.0
  66153. *
  66154. * Unless required by applicable law or agreed to in writing,
  66155. * software distributed under the License is distributed on an
  66156. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66157. * KIND, either express or implied. See the License for the
  66158. * specific language governing permissions and limitations
  66159. * under the License.
  66160. */
  66161. var axisBuilderAttrs$3 = [
  66162. 'axisLine', 'axisTickLabel', 'axisName'
  66163. ];
  66164. var selfBuilderAttrs$2 = [
  66165. 'splitLine', 'splitArea', 'minorSplitLine'
  66166. ];
  66167. AxisView.extend({
  66168. type: 'radiusAxis',
  66169. axisPointerClass: 'PolarAxisPointer',
  66170. render: function (radiusAxisModel, ecModel) {
  66171. this.group.removeAll();
  66172. if (!radiusAxisModel.get('show')) {
  66173. return;
  66174. }
  66175. var radiusAxis = radiusAxisModel.axis;
  66176. var polar = radiusAxis.polar;
  66177. var angleAxis = polar.getAngleAxis();
  66178. var ticksCoords = radiusAxis.getTicksCoords();
  66179. var minorTicksCoords = radiusAxis.getMinorTicksCoords();
  66180. var axisAngle = angleAxis.getExtent()[0];
  66181. var radiusExtent = radiusAxis.getExtent();
  66182. var layout = layoutAxis(polar, radiusAxisModel, axisAngle);
  66183. var axisBuilder = new AxisBuilder(radiusAxisModel, layout);
  66184. each$1(axisBuilderAttrs$3, axisBuilder.add, axisBuilder);
  66185. this.group.add(axisBuilder.getGroup());
  66186. each$1(selfBuilderAttrs$2, function (name) {
  66187. if (radiusAxisModel.get(name + '.show') && !radiusAxis.scale.isBlank()) {
  66188. this['_' + name](radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords, minorTicksCoords);
  66189. }
  66190. }, this);
  66191. },
  66192. /**
  66193. * @private
  66194. */
  66195. _splitLine: function (radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords) {
  66196. var splitLineModel = radiusAxisModel.getModel('splitLine');
  66197. var lineStyleModel = splitLineModel.getModel('lineStyle');
  66198. var lineColors = lineStyleModel.get('color');
  66199. var lineCount = 0;
  66200. lineColors = lineColors instanceof Array ? lineColors : [lineColors];
  66201. var splitLines = [];
  66202. for (var i = 0; i < ticksCoords.length; i++) {
  66203. var colorIndex = (lineCount++) % lineColors.length;
  66204. splitLines[colorIndex] = splitLines[colorIndex] || [];
  66205. splitLines[colorIndex].push(new Circle({
  66206. shape: {
  66207. cx: polar.cx,
  66208. cy: polar.cy,
  66209. r: ticksCoords[i].coord
  66210. }
  66211. }));
  66212. }
  66213. // Simple optimization
  66214. // Batching the lines if color are the same
  66215. for (var i = 0; i < splitLines.length; i++) {
  66216. this.group.add(mergePath(splitLines[i], {
  66217. style: defaults({
  66218. stroke: lineColors[i % lineColors.length],
  66219. fill: null
  66220. }, lineStyleModel.getLineStyle()),
  66221. silent: true
  66222. }));
  66223. }
  66224. },
  66225. /**
  66226. * @private
  66227. */
  66228. _minorSplitLine: function (radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords, minorTicksCoords) {
  66229. if (!minorTicksCoords.length) {
  66230. return;
  66231. }
  66232. var minorSplitLineModel = radiusAxisModel.getModel('minorSplitLine');
  66233. var lineStyleModel = minorSplitLineModel.getModel('lineStyle');
  66234. var lines = [];
  66235. for (var i = 0; i < minorTicksCoords.length; i++) {
  66236. for (var k = 0; k < minorTicksCoords[i].length; k++) {
  66237. lines.push(new Circle({
  66238. shape: {
  66239. cx: polar.cx,
  66240. cy: polar.cy,
  66241. r: minorTicksCoords[i][k].coord
  66242. }
  66243. }));
  66244. }
  66245. }
  66246. this.group.add(mergePath(lines, {
  66247. style: defaults({
  66248. fill: null
  66249. }, lineStyleModel.getLineStyle()),
  66250. silent: true
  66251. }));
  66252. },
  66253. /**
  66254. * @private
  66255. */
  66256. _splitArea: function (radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords) {
  66257. if (!ticksCoords.length) {
  66258. return;
  66259. }
  66260. var splitAreaModel = radiusAxisModel.getModel('splitArea');
  66261. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  66262. var areaColors = areaStyleModel.get('color');
  66263. var lineCount = 0;
  66264. areaColors = areaColors instanceof Array ? areaColors : [areaColors];
  66265. var splitAreas = [];
  66266. var prevRadius = ticksCoords[0].coord;
  66267. for (var i = 1; i < ticksCoords.length; i++) {
  66268. var colorIndex = (lineCount++) % areaColors.length;
  66269. splitAreas[colorIndex] = splitAreas[colorIndex] || [];
  66270. splitAreas[colorIndex].push(new Sector({
  66271. shape: {
  66272. cx: polar.cx,
  66273. cy: polar.cy,
  66274. r0: prevRadius,
  66275. r: ticksCoords[i].coord,
  66276. startAngle: 0,
  66277. endAngle: Math.PI * 2
  66278. },
  66279. silent: true
  66280. }));
  66281. prevRadius = ticksCoords[i].coord;
  66282. }
  66283. // Simple optimization
  66284. // Batching the lines if color are the same
  66285. for (var i = 0; i < splitAreas.length; i++) {
  66286. this.group.add(mergePath(splitAreas[i], {
  66287. style: defaults({
  66288. fill: areaColors[i % areaColors.length]
  66289. }, areaStyleModel.getAreaStyle()),
  66290. silent: true
  66291. }));
  66292. }
  66293. }
  66294. });
  66295. /**
  66296. * @inner
  66297. */
  66298. function layoutAxis(polar, radiusAxisModel, axisAngle) {
  66299. return {
  66300. position: [polar.cx, polar.cy],
  66301. rotation: axisAngle / 180 * Math.PI,
  66302. labelDirection: -1,
  66303. tickDirection: -1,
  66304. nameDirection: 1,
  66305. labelRotate: radiusAxisModel.getModel('axisLabel').get('rotate'),
  66306. // Over splitLine and splitArea
  66307. z2: 1
  66308. };
  66309. }
  66310. /*
  66311. * Licensed to the Apache Software Foundation (ASF) under one
  66312. * or more contributor license agreements. See the NOTICE file
  66313. * distributed with this work for additional information
  66314. * regarding copyright ownership. The ASF licenses this file
  66315. * to you under the Apache License, Version 2.0 (the
  66316. * "License"); you may not use this file except in compliance
  66317. * with the License. You may obtain a copy of the License at
  66318. *
  66319. * http://www.apache.org/licenses/LICENSE-2.0
  66320. *
  66321. * Unless required by applicable law or agreed to in writing,
  66322. * software distributed under the License is distributed on an
  66323. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66324. * KIND, either express or implied. See the License for the
  66325. * specific language governing permissions and limitations
  66326. * under the License.
  66327. */
  66328. /*
  66329. * Licensed to the Apache Software Foundation (ASF) under one
  66330. * or more contributor license agreements. See the NOTICE file
  66331. * distributed with this work for additional information
  66332. * regarding copyright ownership. The ASF licenses this file
  66333. * to you under the Apache License, Version 2.0 (the
  66334. * "License"); you may not use this file except in compliance
  66335. * with the License. You may obtain a copy of the License at
  66336. *
  66337. * http://www.apache.org/licenses/LICENSE-2.0
  66338. *
  66339. * Unless required by applicable law or agreed to in writing,
  66340. * software distributed under the License is distributed on an
  66341. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66342. * KIND, either express or implied. See the License for the
  66343. * specific language governing permissions and limitations
  66344. * under the License.
  66345. */
  66346. var PolarAxisPointer = BaseAxisPointer.extend({
  66347. /**
  66348. * @override
  66349. */
  66350. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  66351. var axis = axisModel.axis;
  66352. if (axis.dim === 'angle') {
  66353. this.animationThreshold = Math.PI / 18;
  66354. }
  66355. var polar = axis.polar;
  66356. var otherAxis = polar.getOtherAxis(axis);
  66357. var otherExtent = otherAxis.getExtent();
  66358. var coordValue;
  66359. coordValue = axis['dataTo' + capitalFirst(axis.dim)](value);
  66360. var axisPointerType = axisPointerModel.get('type');
  66361. if (axisPointerType && axisPointerType !== 'none') {
  66362. var elStyle = buildElStyle(axisPointerModel);
  66363. var pointerOption = pointerShapeBuilder$2[axisPointerType](
  66364. axis, polar, coordValue, otherExtent, elStyle
  66365. );
  66366. pointerOption.style = elStyle;
  66367. elOption.graphicKey = pointerOption.type;
  66368. elOption.pointer = pointerOption;
  66369. }
  66370. var labelMargin = axisPointerModel.get('label.margin');
  66371. var labelPos = getLabelPosition(value, axisModel, axisPointerModel, polar, labelMargin);
  66372. buildLabelElOption(elOption, axisModel, axisPointerModel, api, labelPos);
  66373. }
  66374. // Do not support handle, utill any user requires it.
  66375. });
  66376. function getLabelPosition(value, axisModel, axisPointerModel, polar, labelMargin) {
  66377. var axis = axisModel.axis;
  66378. var coord = axis.dataToCoord(value);
  66379. var axisAngle = polar.getAngleAxis().getExtent()[0];
  66380. axisAngle = axisAngle / 180 * Math.PI;
  66381. var radiusExtent = polar.getRadiusAxis().getExtent();
  66382. var position;
  66383. var align;
  66384. var verticalAlign;
  66385. if (axis.dim === 'radius') {
  66386. var transform = create$1();
  66387. rotate(transform, transform, axisAngle);
  66388. translate(transform, transform, [polar.cx, polar.cy]);
  66389. position = applyTransform$1([coord, -labelMargin], transform);
  66390. var labelRotation = axisModel.getModel('axisLabel').get('rotate') || 0;
  66391. var labelLayout = AxisBuilder.innerTextLayout(
  66392. axisAngle, labelRotation * Math.PI / 180, -1
  66393. );
  66394. align = labelLayout.textAlign;
  66395. verticalAlign = labelLayout.textVerticalAlign;
  66396. }
  66397. else { // angle axis
  66398. var r = radiusExtent[1];
  66399. position = polar.coordToPoint([r + labelMargin, coord]);
  66400. var cx = polar.cx;
  66401. var cy = polar.cy;
  66402. align = Math.abs(position[0] - cx) / r < 0.3
  66403. ? 'center' : (position[0] > cx ? 'left' : 'right');
  66404. verticalAlign = Math.abs(position[1] - cy) / r < 0.3
  66405. ? 'middle' : (position[1] > cy ? 'top' : 'bottom');
  66406. }
  66407. return {
  66408. position: position,
  66409. align: align,
  66410. verticalAlign: verticalAlign
  66411. };
  66412. }
  66413. var pointerShapeBuilder$2 = {
  66414. line: function (axis, polar, coordValue, otherExtent, elStyle) {
  66415. return axis.dim === 'angle'
  66416. ? {
  66417. type: 'Line',
  66418. shape: makeLineShape(
  66419. polar.coordToPoint([otherExtent[0], coordValue]),
  66420. polar.coordToPoint([otherExtent[1], coordValue])
  66421. )
  66422. }
  66423. : {
  66424. type: 'Circle',
  66425. shape: {
  66426. cx: polar.cx,
  66427. cy: polar.cy,
  66428. r: coordValue
  66429. }
  66430. };
  66431. },
  66432. shadow: function (axis, polar, coordValue, otherExtent, elStyle) {
  66433. var bandWidth = Math.max(1, axis.getBandWidth());
  66434. var radian = Math.PI / 180;
  66435. return axis.dim === 'angle'
  66436. ? {
  66437. type: 'Sector',
  66438. shape: makeSectorShape(
  66439. polar.cx, polar.cy,
  66440. otherExtent[0], otherExtent[1],
  66441. // In ECharts y is negative if angle is positive
  66442. (-coordValue - bandWidth / 2) * radian,
  66443. (-coordValue + bandWidth / 2) * radian
  66444. )
  66445. }
  66446. : {
  66447. type: 'Sector',
  66448. shape: makeSectorShape(
  66449. polar.cx, polar.cy,
  66450. coordValue - bandWidth / 2,
  66451. coordValue + bandWidth / 2,
  66452. 0, Math.PI * 2
  66453. )
  66454. };
  66455. }
  66456. };
  66457. AxisView.registerAxisPointerClass('PolarAxisPointer', PolarAxisPointer);
  66458. /*
  66459. * Licensed to the Apache Software Foundation (ASF) under one
  66460. * or more contributor license agreements. See the NOTICE file
  66461. * distributed with this work for additional information
  66462. * regarding copyright ownership. The ASF licenses this file
  66463. * to you under the Apache License, Version 2.0 (the
  66464. * "License"); you may not use this file except in compliance
  66465. * with the License. You may obtain a copy of the License at
  66466. *
  66467. * http://www.apache.org/licenses/LICENSE-2.0
  66468. *
  66469. * Unless required by applicable law or agreed to in writing,
  66470. * software distributed under the License is distributed on an
  66471. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66472. * KIND, either express or implied. See the License for the
  66473. * specific language governing permissions and limitations
  66474. * under the License.
  66475. */
  66476. // For reducing size of echarts.min, barLayoutPolar is required by polar.
  66477. registerLayout(curry(barLayoutPolar, 'bar'));
  66478. // Polar view
  66479. extendComponentView({
  66480. type: 'polar'
  66481. });
  66482. /*
  66483. * Licensed to the Apache Software Foundation (ASF) under one
  66484. * or more contributor license agreements. See the NOTICE file
  66485. * distributed with this work for additional information
  66486. * regarding copyright ownership. The ASF licenses this file
  66487. * to you under the Apache License, Version 2.0 (the
  66488. * "License"); you may not use this file except in compliance
  66489. * with the License. You may obtain a copy of the License at
  66490. *
  66491. * http://www.apache.org/licenses/LICENSE-2.0
  66492. *
  66493. * Unless required by applicable law or agreed to in writing,
  66494. * software distributed under the License is distributed on an
  66495. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66496. * KIND, either express or implied. See the License for the
  66497. * specific language governing permissions and limitations
  66498. * under the License.
  66499. */
  66500. var GeoModel = ComponentModel.extend({
  66501. type: 'geo',
  66502. /**
  66503. * @type {module:echarts/coord/geo/Geo}
  66504. */
  66505. coordinateSystem: null,
  66506. layoutMode: 'box',
  66507. init: function (option) {
  66508. ComponentModel.prototype.init.apply(this, arguments);
  66509. // Default label emphasis `show`
  66510. defaultEmphasis(option, 'label', ['show']);
  66511. },
  66512. optionUpdated: function () {
  66513. var option = this.option;
  66514. var self = this;
  66515. option.regions = geoCreator.getFilledRegions(option.regions, option.map, option.nameMap);
  66516. this._optionModelMap = reduce(option.regions || [], function (optionModelMap, regionOpt) {
  66517. if (regionOpt.name) {
  66518. optionModelMap.set(regionOpt.name, new Model(regionOpt, self));
  66519. }
  66520. return optionModelMap;
  66521. }, createHashMap());
  66522. this.updateSelectedMap(option.regions);
  66523. },
  66524. defaultOption: {
  66525. zlevel: 0,
  66526. z: 0,
  66527. show: true,
  66528. left: 'center',
  66529. top: 'center',
  66530. // width:,
  66531. // height:,
  66532. // right
  66533. // bottom
  66534. // Aspect is width / height. Inited to be geoJson bbox aspect
  66535. // This parameter is used for scale this aspect
  66536. // If svg used, aspectScale is 1 by default.
  66537. // aspectScale: 0.75,
  66538. aspectScale: null,
  66539. ///// Layout with center and size
  66540. // If you wan't to put map in a fixed size box with right aspect ratio
  66541. // This two properties may more conveninet
  66542. // layoutCenter: [50%, 50%]
  66543. // layoutSize: 100
  66544. silent: false,
  66545. // Map type
  66546. map: '',
  66547. // Define left-top, right-bottom coords to control view
  66548. // For example, [ [180, 90], [-180, -90] ]
  66549. boundingCoords: null,
  66550. // Default on center of map
  66551. center: null,
  66552. zoom: 1,
  66553. scaleLimit: null,
  66554. // selectedMode: false
  66555. label: {
  66556. show: false,
  66557. color: '#000'
  66558. },
  66559. itemStyle: {
  66560. // color: 各异,
  66561. borderWidth: 0.5,
  66562. borderColor: '#444',
  66563. color: '#eee'
  66564. },
  66565. emphasis: {
  66566. label: {
  66567. show: true,
  66568. color: 'rgb(100,0,0)'
  66569. },
  66570. itemStyle: {
  66571. color: 'rgba(255,215,0,0.8)'
  66572. }
  66573. },
  66574. regions: []
  66575. },
  66576. /**
  66577. * Get model of region
  66578. * @param {string} name
  66579. * @return {module:echarts/model/Model}
  66580. */
  66581. getRegionModel: function (name) {
  66582. return this._optionModelMap.get(name) || new Model(null, this, this.ecModel);
  66583. },
  66584. /**
  66585. * Format label
  66586. * @param {string} name Region name
  66587. * @param {string} [status='normal'] 'normal' or 'emphasis'
  66588. * @return {string}
  66589. */
  66590. getFormattedLabel: function (name, status) {
  66591. var regionModel = this.getRegionModel(name);
  66592. var formatter = regionModel.get(
  66593. 'label'
  66594. + (status === 'normal' ? '.' : status + '.')
  66595. + 'formatter'
  66596. );
  66597. var params = {
  66598. name: name
  66599. };
  66600. if (typeof formatter === 'function') {
  66601. params.status = status;
  66602. return formatter(params);
  66603. }
  66604. else if (typeof formatter === 'string') {
  66605. return formatter.replace('{a}', name != null ? name : '');
  66606. }
  66607. },
  66608. setZoom: function (zoom) {
  66609. this.option.zoom = zoom;
  66610. },
  66611. setCenter: function (center) {
  66612. this.option.center = center;
  66613. }
  66614. });
  66615. mixin(GeoModel, selectableMixin);
  66616. /*
  66617. * Licensed to the Apache Software Foundation (ASF) under one
  66618. * or more contributor license agreements. See the NOTICE file
  66619. * distributed with this work for additional information
  66620. * regarding copyright ownership. The ASF licenses this file
  66621. * to you under the Apache License, Version 2.0 (the
  66622. * "License"); you may not use this file except in compliance
  66623. * with the License. You may obtain a copy of the License at
  66624. *
  66625. * http://www.apache.org/licenses/LICENSE-2.0
  66626. *
  66627. * Unless required by applicable law or agreed to in writing,
  66628. * software distributed under the License is distributed on an
  66629. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66630. * KIND, either express or implied. See the License for the
  66631. * specific language governing permissions and limitations
  66632. * under the License.
  66633. */
  66634. extendComponentView({
  66635. type: 'geo',
  66636. init: function (ecModel, api) {
  66637. var mapDraw = new MapDraw(api, true);
  66638. this._mapDraw = mapDraw;
  66639. this.group.add(mapDraw.group);
  66640. },
  66641. render: function (geoModel, ecModel, api, payload) {
  66642. // Not render if it is an toggleSelect action from self
  66643. if (payload && payload.type === 'geoToggleSelect'
  66644. && payload.from === this.uid
  66645. ) {
  66646. return;
  66647. }
  66648. var mapDraw = this._mapDraw;
  66649. if (geoModel.get('show')) {
  66650. mapDraw.draw(geoModel, ecModel, api, this, payload);
  66651. }
  66652. else {
  66653. this._mapDraw.group.removeAll();
  66654. }
  66655. this.group.silent = geoModel.get('silent');
  66656. },
  66657. dispose: function () {
  66658. this._mapDraw && this._mapDraw.remove();
  66659. }
  66660. });
  66661. /*
  66662. * Licensed to the Apache Software Foundation (ASF) under one
  66663. * or more contributor license agreements. See the NOTICE file
  66664. * distributed with this work for additional information
  66665. * regarding copyright ownership. The ASF licenses this file
  66666. * to you under the Apache License, Version 2.0 (the
  66667. * "License"); you may not use this file except in compliance
  66668. * with the License. You may obtain a copy of the License at
  66669. *
  66670. * http://www.apache.org/licenses/LICENSE-2.0
  66671. *
  66672. * Unless required by applicable law or agreed to in writing,
  66673. * software distributed under the License is distributed on an
  66674. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66675. * KIND, either express or implied. See the License for the
  66676. * specific language governing permissions and limitations
  66677. * under the License.
  66678. */
  66679. function makeAction(method, actionInfo) {
  66680. actionInfo.update = 'updateView';
  66681. registerAction(actionInfo, function (payload, ecModel) {
  66682. var selected = {};
  66683. ecModel.eachComponent(
  66684. { mainType: 'geo', query: payload},
  66685. function (geoModel) {
  66686. geoModel[method](payload.name);
  66687. var geo = geoModel.coordinateSystem;
  66688. each$1(geo.regions, function (region) {
  66689. selected[region.name] = geoModel.isSelected(region.name) || false;
  66690. });
  66691. }
  66692. );
  66693. return {
  66694. selected: selected,
  66695. name: payload.name
  66696. };
  66697. });
  66698. }
  66699. makeAction('toggleSelected', {
  66700. type: 'geoToggleSelect',
  66701. event: 'geoselectchanged'
  66702. });
  66703. makeAction('select', {
  66704. type: 'geoSelect',
  66705. event: 'geoselected'
  66706. });
  66707. makeAction('unSelect', {
  66708. type: 'geoUnSelect',
  66709. event: 'geounselected'
  66710. });
  66711. /*
  66712. * Licensed to the Apache Software Foundation (ASF) under one
  66713. * or more contributor license agreements. See the NOTICE file
  66714. * distributed with this work for additional information
  66715. * regarding copyright ownership. The ASF licenses this file
  66716. * to you under the Apache License, Version 2.0 (the
  66717. * "License"); you may not use this file except in compliance
  66718. * with the License. You may obtain a copy of the License at
  66719. *
  66720. * http://www.apache.org/licenses/LICENSE-2.0
  66721. *
  66722. * Unless required by applicable law or agreed to in writing,
  66723. * software distributed under the License is distributed on an
  66724. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66725. * KIND, either express or implied. See the License for the
  66726. * specific language governing permissions and limitations
  66727. * under the License.
  66728. */
  66729. // (24*60*60*1000)
  66730. var PROXIMATE_ONE_DAY = 86400000;
  66731. /**
  66732. * Calendar
  66733. *
  66734. * @constructor
  66735. *
  66736. * @param {Object} calendarModel calendarModel
  66737. * @param {Object} ecModel ecModel
  66738. * @param {Object} api api
  66739. */
  66740. function Calendar(calendarModel, ecModel, api) {
  66741. this._model = calendarModel;
  66742. }
  66743. Calendar.prototype = {
  66744. constructor: Calendar,
  66745. type: 'calendar',
  66746. dimensions: ['time', 'value'],
  66747. // Required in createListFromData
  66748. getDimensionsInfo: function () {
  66749. return [{name: 'time', type: 'time'}, 'value'];
  66750. },
  66751. getRangeInfo: function () {
  66752. return this._rangeInfo;
  66753. },
  66754. getModel: function () {
  66755. return this._model;
  66756. },
  66757. getRect: function () {
  66758. return this._rect;
  66759. },
  66760. getCellWidth: function () {
  66761. return this._sw;
  66762. },
  66763. getCellHeight: function () {
  66764. return this._sh;
  66765. },
  66766. getOrient: function () {
  66767. return this._orient;
  66768. },
  66769. /**
  66770. * getFirstDayOfWeek
  66771. *
  66772. * @example
  66773. * 0 : start at Sunday
  66774. * 1 : start at Monday
  66775. *
  66776. * @return {number}
  66777. */
  66778. getFirstDayOfWeek: function () {
  66779. return this._firstDayOfWeek;
  66780. },
  66781. /**
  66782. * get date info
  66783. *
  66784. * @param {string|number} date date
  66785. * @return {Object}
  66786. * {
  66787. * y: string, local full year, eg., '1940',
  66788. * m: string, local month, from '01' ot '12',
  66789. * d: string, local date, from '01' to '31' (if exists),
  66790. * day: It is not date.getDay(). It is the location of the cell in a week, from 0 to 6,
  66791. * time: timestamp,
  66792. * formatedDate: string, yyyy-MM-dd,
  66793. * date: original date object.
  66794. * }
  66795. */
  66796. getDateInfo: function (date) {
  66797. date = parseDate(date);
  66798. var y = date.getFullYear();
  66799. var m = date.getMonth() + 1;
  66800. m = m < 10 ? '0' + m : m;
  66801. var d = date.getDate();
  66802. d = d < 10 ? '0' + d : d;
  66803. var day = date.getDay();
  66804. day = Math.abs((day + 7 - this.getFirstDayOfWeek()) % 7);
  66805. return {
  66806. y: y,
  66807. m: m,
  66808. d: d,
  66809. day: day,
  66810. time: date.getTime(),
  66811. formatedDate: y + '-' + m + '-' + d,
  66812. date: date
  66813. };
  66814. },
  66815. getNextNDay: function (date, n) {
  66816. n = n || 0;
  66817. if (n === 0) {
  66818. return this.getDateInfo(date);
  66819. }
  66820. date = new Date(this.getDateInfo(date).time);
  66821. date.setDate(date.getDate() + n);
  66822. return this.getDateInfo(date);
  66823. },
  66824. update: function (ecModel, api) {
  66825. this._firstDayOfWeek = +this._model.getModel('dayLabel').get('firstDay');
  66826. this._orient = this._model.get('orient');
  66827. this._lineWidth = this._model.getModel('itemStyle').getItemStyle().lineWidth || 0;
  66828. this._rangeInfo = this._getRangeInfo(this._initRangeOption());
  66829. var weeks = this._rangeInfo.weeks || 1;
  66830. var whNames = ['width', 'height'];
  66831. var cellSize = this._model.get('cellSize').slice();
  66832. var layoutParams = this._model.getBoxLayoutParams();
  66833. var cellNumbers = this._orient === 'horizontal' ? [weeks, 7] : [7, weeks];
  66834. each$1([0, 1], function (idx) {
  66835. if (cellSizeSpecified(cellSize, idx)) {
  66836. layoutParams[whNames[idx]] = cellSize[idx] * cellNumbers[idx];
  66837. }
  66838. });
  66839. var whGlobal = {
  66840. width: api.getWidth(),
  66841. height: api.getHeight()
  66842. };
  66843. var calendarRect = this._rect = getLayoutRect(layoutParams, whGlobal);
  66844. each$1([0, 1], function (idx) {
  66845. if (!cellSizeSpecified(cellSize, idx)) {
  66846. cellSize[idx] = calendarRect[whNames[idx]] / cellNumbers[idx];
  66847. }
  66848. });
  66849. function cellSizeSpecified(cellSize, idx) {
  66850. return cellSize[idx] != null && cellSize[idx] !== 'auto';
  66851. }
  66852. this._sw = cellSize[0];
  66853. this._sh = cellSize[1];
  66854. },
  66855. /**
  66856. * Convert a time data(time, value) item to (x, y) point.
  66857. *
  66858. * @override
  66859. * @param {Array|number} data data
  66860. * @param {boolean} [clamp=true] out of range
  66861. * @return {Array} point
  66862. */
  66863. dataToPoint: function (data, clamp) {
  66864. isArray(data) && (data = data[0]);
  66865. clamp == null && (clamp = true);
  66866. var dayInfo = this.getDateInfo(data);
  66867. var range = this._rangeInfo;
  66868. var date = dayInfo.formatedDate;
  66869. // if not in range return [NaN, NaN]
  66870. if (clamp && !(
  66871. dayInfo.time >= range.start.time
  66872. && dayInfo.time < range.end.time + PROXIMATE_ONE_DAY
  66873. )) {
  66874. return [NaN, NaN];
  66875. }
  66876. var week = dayInfo.day;
  66877. var nthWeek = this._getRangeInfo([range.start.time, date]).nthWeek;
  66878. if (this._orient === 'vertical') {
  66879. return [
  66880. this._rect.x + week * this._sw + this._sw / 2,
  66881. this._rect.y + nthWeek * this._sh + this._sh / 2
  66882. ];
  66883. }
  66884. return [
  66885. this._rect.x + nthWeek * this._sw + this._sw / 2,
  66886. this._rect.y + week * this._sh + this._sh / 2
  66887. ];
  66888. },
  66889. /**
  66890. * Convert a (x, y) point to time data
  66891. *
  66892. * @override
  66893. * @param {string} point point
  66894. * @return {string} data
  66895. */
  66896. pointToData: function (point) {
  66897. var date = this.pointToDate(point);
  66898. return date && date.time;
  66899. },
  66900. /**
  66901. * Convert a time date item to (x, y) four point.
  66902. *
  66903. * @param {Array} data date[0] is date
  66904. * @param {boolean} [clamp=true] out of range
  66905. * @return {Object} point
  66906. */
  66907. dataToRect: function (data, clamp) {
  66908. var point = this.dataToPoint(data, clamp);
  66909. return {
  66910. contentShape: {
  66911. x: point[0] - (this._sw - this._lineWidth) / 2,
  66912. y: point[1] - (this._sh - this._lineWidth) / 2,
  66913. width: this._sw - this._lineWidth,
  66914. height: this._sh - this._lineWidth
  66915. },
  66916. center: point,
  66917. tl: [
  66918. point[0] - this._sw / 2,
  66919. point[1] - this._sh / 2
  66920. ],
  66921. tr: [
  66922. point[0] + this._sw / 2,
  66923. point[1] - this._sh / 2
  66924. ],
  66925. br: [
  66926. point[0] + this._sw / 2,
  66927. point[1] + this._sh / 2
  66928. ],
  66929. bl: [
  66930. point[0] - this._sw / 2,
  66931. point[1] + this._sh / 2
  66932. ]
  66933. };
  66934. },
  66935. /**
  66936. * Convert a (x, y) point to time date
  66937. *
  66938. * @param {Array} point point
  66939. * @return {Object} date
  66940. */
  66941. pointToDate: function (point) {
  66942. var nthX = Math.floor((point[0] - this._rect.x) / this._sw) + 1;
  66943. var nthY = Math.floor((point[1] - this._rect.y) / this._sh) + 1;
  66944. var range = this._rangeInfo.range;
  66945. if (this._orient === 'vertical') {
  66946. return this._getDateByWeeksAndDay(nthY, nthX - 1, range);
  66947. }
  66948. return this._getDateByWeeksAndDay(nthX, nthY - 1, range);
  66949. },
  66950. /**
  66951. * @inheritDoc
  66952. */
  66953. convertToPixel: curry(doConvert$2, 'dataToPoint'),
  66954. /**
  66955. * @inheritDoc
  66956. */
  66957. convertFromPixel: curry(doConvert$2, 'pointToData'),
  66958. /**
  66959. * initRange
  66960. *
  66961. * @private
  66962. * @return {Array} [start, end]
  66963. */
  66964. _initRangeOption: function () {
  66965. var range = this._model.get('range');
  66966. var rg = range;
  66967. if (isArray(rg) && rg.length === 1) {
  66968. rg = rg[0];
  66969. }
  66970. if (/^\d{4}$/.test(rg)) {
  66971. range = [rg + '-01-01', rg + '-12-31'];
  66972. }
  66973. if (/^\d{4}[\/|-]\d{1,2}$/.test(rg)) {
  66974. var start = this.getDateInfo(rg);
  66975. var firstDay = start.date;
  66976. firstDay.setMonth(firstDay.getMonth() + 1);
  66977. var end = this.getNextNDay(firstDay, -1);
  66978. range = [start.formatedDate, end.formatedDate];
  66979. }
  66980. if (/^\d{4}[\/|-]\d{1,2}[\/|-]\d{1,2}$/.test(rg)) {
  66981. range = [rg, rg];
  66982. }
  66983. var tmp = this._getRangeInfo(range);
  66984. if (tmp.start.time > tmp.end.time) {
  66985. range.reverse();
  66986. }
  66987. return range;
  66988. },
  66989. /**
  66990. * range info
  66991. *
  66992. * @private
  66993. * @param {Array} range range ['2017-01-01', '2017-07-08']
  66994. * If range[0] > range[1], they will not be reversed.
  66995. * @return {Object} obj
  66996. */
  66997. _getRangeInfo: function (range) {
  66998. range = [
  66999. this.getDateInfo(range[0]),
  67000. this.getDateInfo(range[1])
  67001. ];
  67002. var reversed;
  67003. if (range[0].time > range[1].time) {
  67004. reversed = true;
  67005. range.reverse();
  67006. }
  67007. var allDay = Math.floor(range[1].time / PROXIMATE_ONE_DAY)
  67008. - Math.floor(range[0].time / PROXIMATE_ONE_DAY) + 1;
  67009. // Consider case1 (#11677 #10430):
  67010. // Set the system timezone as "UK", set the range to `['2016-07-01', '2016-12-31']`
  67011. // Consider case2:
  67012. // Firstly set system timezone as "Time Zone: America/Toronto",
  67013. // ```
  67014. // var first = new Date(1478412000000 - 3600 * 1000 * 2.5);
  67015. // var second = new Date(1478412000000);
  67016. // var allDays = Math.floor(second / ONE_DAY) - Math.floor(first / ONE_DAY) + 1;
  67017. // ```
  67018. // will get wrong result because of DST. So we should fix it.
  67019. var date = new Date(range[0].time);
  67020. var startDateNum = date.getDate();
  67021. var endDateNum = range[1].date.getDate();
  67022. date.setDate(startDateNum + allDay - 1);
  67023. // The bias can not over a month, so just compare date.
  67024. var dateNum = date.getDate();
  67025. if (dateNum !== endDateNum) {
  67026. var sign = date.getTime() - range[1].time > 0 ? 1 : -1;
  67027. while (
  67028. (dateNum = date.getDate()) !== endDateNum
  67029. && (date.getTime() - range[1].time) * sign > 0
  67030. ) {
  67031. allDay -= sign;
  67032. date.setDate(dateNum - sign);
  67033. }
  67034. }
  67035. var weeks = Math.floor((allDay + range[0].day + 6) / 7);
  67036. var nthWeek = reversed ? -weeks + 1 : weeks - 1;
  67037. reversed && range.reverse();
  67038. return {
  67039. range: [range[0].formatedDate, range[1].formatedDate],
  67040. start: range[0],
  67041. end: range[1],
  67042. allDay: allDay,
  67043. weeks: weeks,
  67044. // From 0.
  67045. nthWeek: nthWeek,
  67046. fweek: range[0].day,
  67047. lweek: range[1].day
  67048. };
  67049. },
  67050. /**
  67051. * get date by nthWeeks and week day in range
  67052. *
  67053. * @private
  67054. * @param {number} nthWeek the week
  67055. * @param {number} day the week day
  67056. * @param {Array} range [d1, d2]
  67057. * @return {Object}
  67058. */
  67059. _getDateByWeeksAndDay: function (nthWeek, day, range) {
  67060. var rangeInfo = this._getRangeInfo(range);
  67061. if (nthWeek > rangeInfo.weeks
  67062. || (nthWeek === 0 && day < rangeInfo.fweek)
  67063. || (nthWeek === rangeInfo.weeks && day > rangeInfo.lweek)
  67064. ) {
  67065. return false;
  67066. }
  67067. var nthDay = (nthWeek - 1) * 7 - rangeInfo.fweek + day;
  67068. var date = new Date(rangeInfo.start.time);
  67069. date.setDate(rangeInfo.start.d + nthDay);
  67070. return this.getDateInfo(date);
  67071. }
  67072. };
  67073. Calendar.dimensions = Calendar.prototype.dimensions;
  67074. Calendar.getDimensionsInfo = Calendar.prototype.getDimensionsInfo;
  67075. Calendar.create = function (ecModel, api) {
  67076. var calendarList = [];
  67077. ecModel.eachComponent('calendar', function (calendarModel) {
  67078. var calendar = new Calendar(calendarModel, ecModel, api);
  67079. calendarList.push(calendar);
  67080. calendarModel.coordinateSystem = calendar;
  67081. });
  67082. ecModel.eachSeries(function (calendarSeries) {
  67083. if (calendarSeries.get('coordinateSystem') === 'calendar') {
  67084. // Inject coordinate system
  67085. calendarSeries.coordinateSystem = calendarList[calendarSeries.get('calendarIndex') || 0];
  67086. }
  67087. });
  67088. return calendarList;
  67089. };
  67090. function doConvert$2(methodName, ecModel, finder, value) {
  67091. var calendarModel = finder.calendarModel;
  67092. var seriesModel = finder.seriesModel;
  67093. var coordSys = calendarModel
  67094. ? calendarModel.coordinateSystem
  67095. : seriesModel
  67096. ? seriesModel.coordinateSystem
  67097. : null;
  67098. return coordSys === this ? coordSys[methodName](value) : null;
  67099. }
  67100. CoordinateSystemManager.register('calendar', Calendar);
  67101. /*
  67102. * Licensed to the Apache Software Foundation (ASF) under one
  67103. * or more contributor license agreements. See the NOTICE file
  67104. * distributed with this work for additional information
  67105. * regarding copyright ownership. The ASF licenses this file
  67106. * to you under the Apache License, Version 2.0 (the
  67107. * "License"); you may not use this file except in compliance
  67108. * with the License. You may obtain a copy of the License at
  67109. *
  67110. * http://www.apache.org/licenses/LICENSE-2.0
  67111. *
  67112. * Unless required by applicable law or agreed to in writing,
  67113. * software distributed under the License is distributed on an
  67114. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  67115. * KIND, either express or implied. See the License for the
  67116. * specific language governing permissions and limitations
  67117. * under the License.
  67118. */
  67119. var CalendarModel = ComponentModel.extend({
  67120. type: 'calendar',
  67121. /**
  67122. * @type {module:echarts/coord/calendar/Calendar}
  67123. */
  67124. coordinateSystem: null,
  67125. defaultOption: {
  67126. zlevel: 0,
  67127. z: 2,
  67128. left: 80,
  67129. top: 60,
  67130. cellSize: 20,
  67131. // horizontal vertical
  67132. orient: 'horizontal',
  67133. // month separate line style
  67134. splitLine: {
  67135. show: true,
  67136. lineStyle: {
  67137. color: '#000',
  67138. width: 1,
  67139. type: 'solid'
  67140. }
  67141. },
  67142. // rect style temporarily unused emphasis
  67143. itemStyle: {
  67144. color: '#fff',
  67145. borderWidth: 1,
  67146. borderColor: '#ccc'
  67147. },
  67148. // week text style
  67149. dayLabel: {
  67150. show: true,
  67151. // a week first day
  67152. firstDay: 0,
  67153. // start end
  67154. position: 'start',
  67155. margin: '50%', // 50% of cellSize
  67156. nameMap: 'en',
  67157. color: '#000'
  67158. },
  67159. // month text style
  67160. monthLabel: {
  67161. show: true,
  67162. // start end
  67163. position: 'start',
  67164. margin: 5,
  67165. // center or left
  67166. align: 'center',
  67167. // cn en []
  67168. nameMap: 'en',
  67169. formatter: null,
  67170. color: '#000'
  67171. },
  67172. // year text style
  67173. yearLabel: {
  67174. show: true,
  67175. // top bottom left right
  67176. position: null,
  67177. margin: 30,
  67178. formatter: null,
  67179. color: '#ccc',
  67180. fontFamily: 'sans-serif',
  67181. fontWeight: 'bolder',
  67182. fontSize: 20
  67183. }
  67184. },
  67185. /**
  67186. * @override
  67187. */
  67188. init: function (option, parentModel, ecModel, extraOpt) {
  67189. var inputPositionParams = getLayoutParams(option);
  67190. CalendarModel.superApply(this, 'init', arguments);
  67191. mergeAndNormalizeLayoutParams(option, inputPositionParams);
  67192. },
  67193. /**
  67194. * @override
  67195. */
  67196. mergeOption: function (option, extraOpt) {
  67197. CalendarModel.superApply(this, 'mergeOption', arguments);
  67198. mergeAndNormalizeLayoutParams(this.option, option);
  67199. }
  67200. });
  67201. function mergeAndNormalizeLayoutParams(target, raw) {
  67202. // Normalize cellSize
  67203. var cellSize = target.cellSize;
  67204. if (!isArray(cellSize)) {
  67205. cellSize = target.cellSize = [cellSize, cellSize];
  67206. }
  67207. else if (cellSize.length === 1) {
  67208. cellSize[1] = cellSize[0];
  67209. }
  67210. var ignoreSize = map([0, 1], function (hvIdx) {
  67211. // If user have set `width` or both `left` and `right`, cellSize
  67212. // will be automatically set to 'auto', otherwise the default
  67213. // setting of cellSize will make `width` setting not work.
  67214. if (sizeCalculable(raw, hvIdx)) {
  67215. cellSize[hvIdx] = 'auto';
  67216. }
  67217. return cellSize[hvIdx] != null && cellSize[hvIdx] !== 'auto';
  67218. });
  67219. mergeLayoutParam(target, raw, {
  67220. type: 'box', ignoreSize: ignoreSize
  67221. });
  67222. }
  67223. /*
  67224. * Licensed to the Apache Software Foundation (ASF) under one
  67225. * or more contributor license agreements. See the NOTICE file
  67226. * distributed with this work for additional information
  67227. * regarding copyright ownership. The ASF licenses this file
  67228. * to you under the Apache License, Version 2.0 (the
  67229. * "License"); you may not use this file except in compliance
  67230. * with the License. You may obtain a copy of the License at
  67231. *
  67232. * http://www.apache.org/licenses/LICENSE-2.0
  67233. *
  67234. * Unless required by applicable law or agreed to in writing,
  67235. * software distributed under the License is distributed on an
  67236. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  67237. * KIND, either express or implied. See the License for the
  67238. * specific language governing permissions and limitations
  67239. * under the License.
  67240. */
  67241. var MONTH_TEXT = {
  67242. EN: [
  67243. 'Jan', 'Feb', 'Mar',
  67244. 'Apr', 'May', 'Jun',
  67245. 'Jul', 'Aug', 'Sep',
  67246. 'Oct', 'Nov', 'Dec'
  67247. ],
  67248. CN: [
  67249. '一月', '二月', '三月',
  67250. '四月', '五月', '六月',
  67251. '七月', '八月', '九月',
  67252. '十月', '十一月', '十二月'
  67253. ]
  67254. };
  67255. var WEEK_TEXT = {
  67256. EN: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
  67257. CN: ['日', '一', '二', '三', '四', '五', '六']
  67258. };
  67259. extendComponentView({
  67260. type: 'calendar',
  67261. /**
  67262. * top/left line points
  67263. * @private
  67264. */
  67265. _tlpoints: null,
  67266. /**
  67267. * bottom/right line points
  67268. * @private
  67269. */
  67270. _blpoints: null,
  67271. /**
  67272. * first day of month
  67273. * @private
  67274. */
  67275. _firstDayOfMonth: null,
  67276. /**
  67277. * first day point of month
  67278. * @private
  67279. */
  67280. _firstDayPoints: null,
  67281. render: function (calendarModel, ecModel, api) {
  67282. var group = this.group;
  67283. group.removeAll();
  67284. var coordSys = calendarModel.coordinateSystem;
  67285. // range info
  67286. var rangeData = coordSys.getRangeInfo();
  67287. var orient = coordSys.getOrient();
  67288. this._renderDayRect(calendarModel, rangeData, group);
  67289. // _renderLines must be called prior to following function
  67290. this._renderLines(calendarModel, rangeData, orient, group);
  67291. this._renderYearText(calendarModel, rangeData, orient, group);
  67292. this._renderMonthText(calendarModel, orient, group);
  67293. this._renderWeekText(calendarModel, rangeData, orient, group);
  67294. },
  67295. // render day rect
  67296. _renderDayRect: function (calendarModel, rangeData, group) {
  67297. var coordSys = calendarModel.coordinateSystem;
  67298. var itemRectStyleModel = calendarModel.getModel('itemStyle').getItemStyle();
  67299. var sw = coordSys.getCellWidth();
  67300. var sh = coordSys.getCellHeight();
  67301. for (var i = rangeData.start.time;
  67302. i <= rangeData.end.time;
  67303. i = coordSys.getNextNDay(i, 1).time
  67304. ) {
  67305. var point = coordSys.dataToRect([i], false).tl;
  67306. // every rect
  67307. var rect = new Rect({
  67308. shape: {
  67309. x: point[0],
  67310. y: point[1],
  67311. width: sw,
  67312. height: sh
  67313. },
  67314. cursor: 'default',
  67315. style: itemRectStyleModel
  67316. });
  67317. group.add(rect);
  67318. }
  67319. },
  67320. // render separate line
  67321. _renderLines: function (calendarModel, rangeData, orient, group) {
  67322. var self = this;
  67323. var coordSys = calendarModel.coordinateSystem;
  67324. var lineStyleModel = calendarModel.getModel('splitLine.lineStyle').getLineStyle();
  67325. var show = calendarModel.get('splitLine.show');
  67326. var lineWidth = lineStyleModel.lineWidth;
  67327. this._tlpoints = [];
  67328. this._blpoints = [];
  67329. this._firstDayOfMonth = [];
  67330. this._firstDayPoints = [];
  67331. var firstDay = rangeData.start;
  67332. for (var i = 0; firstDay.time <= rangeData.end.time; i++) {
  67333. addPoints(firstDay.formatedDate);
  67334. if (i === 0) {
  67335. firstDay = coordSys.getDateInfo(rangeData.start.y + '-' + rangeData.start.m);
  67336. }
  67337. var date = firstDay.date;
  67338. date.setMonth(date.getMonth() + 1);
  67339. firstDay = coordSys.getDateInfo(date);
  67340. }
  67341. addPoints(coordSys.getNextNDay(rangeData.end.time, 1).formatedDate);
  67342. function addPoints(date) {
  67343. self._firstDayOfMonth.push(coordSys.getDateInfo(date));
  67344. self._firstDayPoints.push(coordSys.dataToRect([date], false).tl);
  67345. var points = self._getLinePointsOfOneWeek(calendarModel, date, orient);
  67346. self._tlpoints.push(points[0]);
  67347. self._blpoints.push(points[points.length - 1]);
  67348. show && self._drawSplitline(points, lineStyleModel, group);
  67349. }
  67350. // render top/left line
  67351. show && this._drawSplitline(self._getEdgesPoints(self._tlpoints, lineWidth, orient), lineStyleModel, group);
  67352. // render bottom/right line
  67353. show && this._drawSplitline(self._getEdgesPoints(self._blpoints, lineWidth, orient), lineStyleModel, group);
  67354. },
  67355. // get points at both ends
  67356. _getEdgesPoints: function (points, lineWidth, orient) {
  67357. var rs = [points[0].slice(), points[points.length - 1].slice()];
  67358. var idx = orient === 'horizontal' ? 0 : 1;
  67359. // both ends of the line are extend half lineWidth
  67360. rs[0][idx] = rs[0][idx] - lineWidth / 2;
  67361. rs[1][idx] = rs[1][idx] + lineWidth / 2;
  67362. return rs;
  67363. },
  67364. // render split line
  67365. _drawSplitline: function (points, lineStyleModel, group) {
  67366. var poyline = new Polyline({
  67367. z2: 20,
  67368. shape: {
  67369. points: points
  67370. },
  67371. style: lineStyleModel
  67372. });
  67373. group.add(poyline);
  67374. },
  67375. // render month line of one week points
  67376. _getLinePointsOfOneWeek: function (calendarModel, date, orient) {
  67377. var coordSys = calendarModel.coordinateSystem;
  67378. date = coordSys.getDateInfo(date);
  67379. var points = [];
  67380. for (var i = 0; i < 7; i++) {
  67381. var tmpD = coordSys.getNextNDay(date.time, i);
  67382. var point = coordSys.dataToRect([tmpD.time], false);
  67383. points[2 * tmpD.day] = point.tl;
  67384. points[2 * tmpD.day + 1] = point[orient === 'horizontal' ? 'bl' : 'tr'];
  67385. }
  67386. return points;
  67387. },
  67388. _formatterLabel: function (formatter, params) {
  67389. if (typeof formatter === 'string' && formatter) {
  67390. return formatTplSimple(formatter, params);
  67391. }
  67392. if (typeof formatter === 'function') {
  67393. return formatter(params);
  67394. }
  67395. return params.nameMap;
  67396. },
  67397. _yearTextPositionControl: function (textEl, point, orient, position, margin) {
  67398. point = point.slice();
  67399. var aligns = ['center', 'bottom'];
  67400. if (position === 'bottom') {
  67401. point[1] += margin;
  67402. aligns = ['center', 'top'];
  67403. }
  67404. else if (position === 'left') {
  67405. point[0] -= margin;
  67406. }
  67407. else if (position === 'right') {
  67408. point[0] += margin;
  67409. aligns = ['center', 'top'];
  67410. }
  67411. else { // top
  67412. point[1] -= margin;
  67413. }
  67414. var rotate = 0;
  67415. if (position === 'left' || position === 'right') {
  67416. rotate = Math.PI / 2;
  67417. }
  67418. return {
  67419. rotation: rotate,
  67420. position: point,
  67421. style: {
  67422. textAlign: aligns[0],
  67423. textVerticalAlign: aligns[1]
  67424. }
  67425. };
  67426. },
  67427. // render year
  67428. _renderYearText: function (calendarModel, rangeData, orient, group) {
  67429. var yearLabel = calendarModel.getModel('yearLabel');
  67430. if (!yearLabel.get('show')) {
  67431. return;
  67432. }
  67433. var margin = yearLabel.get('margin');
  67434. var pos = yearLabel.get('position');
  67435. if (!pos) {
  67436. pos = orient !== 'horizontal' ? 'top' : 'left';
  67437. }
  67438. var points = [this._tlpoints[this._tlpoints.length - 1], this._blpoints[0]];
  67439. var xc = (points[0][0] + points[1][0]) / 2;
  67440. var yc = (points[0][1] + points[1][1]) / 2;
  67441. var idx = orient === 'horizontal' ? 0 : 1;
  67442. var posPoints = {
  67443. top: [xc, points[idx][1]],
  67444. bottom: [xc, points[1 - idx][1]],
  67445. left: [points[1 - idx][0], yc],
  67446. right: [points[idx][0], yc]
  67447. };
  67448. var name = rangeData.start.y;
  67449. if (+rangeData.end.y > +rangeData.start.y) {
  67450. name = name + '-' + rangeData.end.y;
  67451. }
  67452. var formatter = yearLabel.get('formatter');
  67453. var params = {
  67454. start: rangeData.start.y,
  67455. end: rangeData.end.y,
  67456. nameMap: name
  67457. };
  67458. var content = this._formatterLabel(formatter, params);
  67459. var yearText = new Text({z2: 30});
  67460. setTextStyle(yearText.style, yearLabel, {text: content}),
  67461. yearText.attr(this._yearTextPositionControl(yearText, posPoints[pos], orient, pos, margin));
  67462. group.add(yearText);
  67463. },
  67464. _monthTextPositionControl: function (point, isCenter, orient, position, margin) {
  67465. var align = 'left';
  67466. var vAlign = 'top';
  67467. var x = point[0];
  67468. var y = point[1];
  67469. if (orient === 'horizontal') {
  67470. y = y + margin;
  67471. if (isCenter) {
  67472. align = 'center';
  67473. }
  67474. if (position === 'start') {
  67475. vAlign = 'bottom';
  67476. }
  67477. }
  67478. else {
  67479. x = x + margin;
  67480. if (isCenter) {
  67481. vAlign = 'middle';
  67482. }
  67483. if (position === 'start') {
  67484. align = 'right';
  67485. }
  67486. }
  67487. return {
  67488. x: x,
  67489. y: y,
  67490. textAlign: align,
  67491. textVerticalAlign: vAlign
  67492. };
  67493. },
  67494. // render month and year text
  67495. _renderMonthText: function (calendarModel, orient, group) {
  67496. var monthLabel = calendarModel.getModel('monthLabel');
  67497. if (!monthLabel.get('show')) {
  67498. return;
  67499. }
  67500. var nameMap = monthLabel.get('nameMap');
  67501. var margin = monthLabel.get('margin');
  67502. var pos = monthLabel.get('position');
  67503. var align = monthLabel.get('align');
  67504. var termPoints = [this._tlpoints, this._blpoints];
  67505. if (isString(nameMap)) {
  67506. nameMap = MONTH_TEXT[nameMap.toUpperCase()] || [];
  67507. }
  67508. var idx = pos === 'start' ? 0 : 1;
  67509. var axis = orient === 'horizontal' ? 0 : 1;
  67510. margin = pos === 'start' ? -margin : margin;
  67511. var isCenter = (align === 'center');
  67512. for (var i = 0; i < termPoints[idx].length - 1; i++) {
  67513. var tmp = termPoints[idx][i].slice();
  67514. var firstDay = this._firstDayOfMonth[i];
  67515. if (isCenter) {
  67516. var firstDayPoints = this._firstDayPoints[i];
  67517. tmp[axis] = (firstDayPoints[axis] + termPoints[0][i + 1][axis]) / 2;
  67518. }
  67519. var formatter = monthLabel.get('formatter');
  67520. var name = nameMap[+firstDay.m - 1];
  67521. var params = {
  67522. yyyy: firstDay.y,
  67523. yy: (firstDay.y + '').slice(2),
  67524. MM: firstDay.m,
  67525. M: +firstDay.m,
  67526. nameMap: name
  67527. };
  67528. var content = this._formatterLabel(formatter, params);
  67529. var monthText = new Text({z2: 30});
  67530. extend(
  67531. setTextStyle(monthText.style, monthLabel, {text: content}),
  67532. this._monthTextPositionControl(tmp, isCenter, orient, pos, margin)
  67533. );
  67534. group.add(monthText);
  67535. }
  67536. },
  67537. _weekTextPositionControl: function (point, orient, position, margin, cellSize) {
  67538. var align = 'center';
  67539. var vAlign = 'middle';
  67540. var x = point[0];
  67541. var y = point[1];
  67542. var isStart = position === 'start';
  67543. if (orient === 'horizontal') {
  67544. x = x + margin + (isStart ? 1 : -1) * cellSize[0] / 2;
  67545. align = isStart ? 'right' : 'left';
  67546. }
  67547. else {
  67548. y = y + margin + (isStart ? 1 : -1) * cellSize[1] / 2;
  67549. vAlign = isStart ? 'bottom' : 'top';
  67550. }
  67551. return {
  67552. x: x,
  67553. y: y,
  67554. textAlign: align,
  67555. textVerticalAlign: vAlign
  67556. };
  67557. },
  67558. // render weeks
  67559. _renderWeekText: function (calendarModel, rangeData, orient, group) {
  67560. var dayLabel = calendarModel.getModel('dayLabel');
  67561. if (!dayLabel.get('show')) {
  67562. return;
  67563. }
  67564. var coordSys = calendarModel.coordinateSystem;
  67565. var pos = dayLabel.get('position');
  67566. var nameMap = dayLabel.get('nameMap');
  67567. var margin = dayLabel.get('margin');
  67568. var firstDayOfWeek = coordSys.getFirstDayOfWeek();
  67569. if (isString(nameMap)) {
  67570. nameMap = WEEK_TEXT[nameMap.toUpperCase()] || [];
  67571. }
  67572. var start = coordSys.getNextNDay(
  67573. rangeData.end.time, (7 - rangeData.lweek)
  67574. ).time;
  67575. var cellSize = [coordSys.getCellWidth(), coordSys.getCellHeight()];
  67576. margin = parsePercent$1(margin, cellSize[orient === 'horizontal' ? 0 : 1]);
  67577. if (pos === 'start') {
  67578. start = coordSys.getNextNDay(
  67579. rangeData.start.time, -(7 + rangeData.fweek)
  67580. ).time;
  67581. margin = -margin;
  67582. }
  67583. for (var i = 0; i < 7; i++) {
  67584. var tmpD = coordSys.getNextNDay(start, i);
  67585. var point = coordSys.dataToRect([tmpD.time], false).center;
  67586. var day = i;
  67587. day = Math.abs((i + firstDayOfWeek) % 7);
  67588. var weekText = new Text({z2: 30});
  67589. extend(
  67590. setTextStyle(weekText.style, dayLabel, {text: nameMap[day]}),
  67591. this._weekTextPositionControl(point, orient, pos, margin, cellSize)
  67592. );
  67593. group.add(weekText);
  67594. }
  67595. }
  67596. });
  67597. /*
  67598. * Licensed to the Apache Software Foundation (ASF) under one
  67599. * or more contributor license agreements. See the NOTICE file
  67600. * distributed with this work for additional information
  67601. * regarding copyright ownership. The ASF licenses this file
  67602. * to you under the Apache License, Version 2.0 (the
  67603. * "License"); you may not use this file except in compliance
  67604. * with the License. You may obtain a copy of the License at
  67605. *
  67606. * http://www.apache.org/licenses/LICENSE-2.0
  67607. *
  67608. * Unless required by applicable law or agreed to in writing,
  67609. * software distributed under the License is distributed on an
  67610. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  67611. * KIND, either express or implied. See the License for the
  67612. * specific language governing permissions and limitations
  67613. * under the License.
  67614. */
  67615. /*
  67616. * Licensed to the Apache Software Foundation (ASF) under one
  67617. * or more contributor license agreements. See the NOTICE file
  67618. * distributed with this work for additional information
  67619. * regarding copyright ownership. The ASF licenses this file
  67620. * to you under the Apache License, Version 2.0 (the
  67621. * "License"); you may not use this file except in compliance
  67622. * with the License. You may obtain a copy of the License at
  67623. *
  67624. * http://www.apache.org/licenses/LICENSE-2.0
  67625. *
  67626. * Unless required by applicable law or agreed to in writing,
  67627. * software distributed under the License is distributed on an
  67628. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  67629. * KIND, either express or implied. See the License for the
  67630. * specific language governing permissions and limitations
  67631. * under the License.
  67632. */
  67633. var _nonShapeGraphicElements = {
  67634. // Reserved but not supported in graphic component.
  67635. path: null,
  67636. compoundPath: null,
  67637. // Supported in graphic component.
  67638. group: Group,
  67639. image: ZImage,
  67640. text: Text
  67641. };
  67642. // -------------
  67643. // Preprocessor
  67644. // -------------
  67645. registerPreprocessor(function (option) {
  67646. var graphicOption = option.graphic;
  67647. // Convert
  67648. // {graphic: [{left: 10, type: 'circle'}, ...]}
  67649. // or
  67650. // {graphic: {left: 10, type: 'circle'}}
  67651. // to
  67652. // {graphic: [{elements: [{left: 10, type: 'circle'}, ...]}]}
  67653. if (isArray(graphicOption)) {
  67654. if (!graphicOption[0] || !graphicOption[0].elements) {
  67655. option.graphic = [{elements: graphicOption}];
  67656. }
  67657. else {
  67658. // Only one graphic instance can be instantiated. (We dont
  67659. // want that too many views are created in echarts._viewMap)
  67660. option.graphic = [option.graphic[0]];
  67661. }
  67662. }
  67663. else if (graphicOption && !graphicOption.elements) {
  67664. option.graphic = [{elements: [graphicOption]}];
  67665. }
  67666. });
  67667. // ------
  67668. // Model
  67669. // ------
  67670. var GraphicModel = extendComponentModel({
  67671. type: 'graphic',
  67672. defaultOption: {
  67673. // Extra properties for each elements:
  67674. //
  67675. // left/right/top/bottom: (like 12, '22%', 'center', default undefined)
  67676. // If left/rigth is set, shape.x/shape.cx/position will not be used.
  67677. // If top/bottom is set, shape.y/shape.cy/position will not be used.
  67678. // This mechanism is useful when you want to position a group/element
  67679. // against the right side or the center of this container.
  67680. //
  67681. // width/height: (can only be pixel value, default 0)
  67682. // Only be used to specify contianer(group) size, if needed. And
  67683. // can not be percentage value (like '33%'). See the reason in the
  67684. // layout algorithm below.
  67685. //
  67686. // bounding: (enum: 'all' (default) | 'raw')
  67687. // Specify how to calculate boundingRect when locating.
  67688. // 'all': Get uioned and transformed boundingRect
  67689. // from both itself and its descendants.
  67690. // This mode simplies confining a group of elements in the bounding
  67691. // of their ancester container (e.g., using 'right: 0').
  67692. // 'raw': Only use the boundingRect of itself and before transformed.
  67693. // This mode is similar to css behavior, which is useful when you
  67694. // want an element to be able to overflow its container. (Consider
  67695. // a rotated circle needs to be located in a corner.)
  67696. // info: custom info. enables user to mount some info on elements and use them
  67697. // in event handlers. Update them only when user specified, otherwise, remain.
  67698. // Note: elements is always behind its ancestors in this elements array.
  67699. elements: [],
  67700. parentId: null
  67701. },
  67702. /**
  67703. * Save el options for the sake of the performance (only update modified graphics).
  67704. * The order is the same as those in option. (ancesters -> descendants)
  67705. *
  67706. * @private
  67707. * @type {Array.<Object>}
  67708. */
  67709. _elOptionsToUpdate: null,
  67710. /**
  67711. * @override
  67712. */
  67713. mergeOption: function (option) {
  67714. // Prevent default merge to elements
  67715. var elements = this.option.elements;
  67716. this.option.elements = null;
  67717. GraphicModel.superApply(this, 'mergeOption', arguments);
  67718. this.option.elements = elements;
  67719. },
  67720. /**
  67721. * @override
  67722. */
  67723. optionUpdated: function (newOption, isInit) {
  67724. var thisOption = this.option;
  67725. var newList = (isInit ? thisOption : newOption).elements;
  67726. var existList = thisOption.elements = isInit ? [] : thisOption.elements;
  67727. var flattenedList = [];
  67728. this._flatten(newList, flattenedList);
  67729. var mappingResult = mappingToExists(existList, flattenedList);
  67730. makeIdAndName(mappingResult);
  67731. // Clear elOptionsToUpdate
  67732. var elOptionsToUpdate = this._elOptionsToUpdate = [];
  67733. each$1(mappingResult, function (resultItem, index) {
  67734. var newElOption = resultItem.option;
  67735. if (__DEV__) {
  67736. assert$1(
  67737. isObject$1(newElOption) || resultItem.exist,
  67738. 'Empty graphic option definition'
  67739. );
  67740. }
  67741. if (!newElOption) {
  67742. return;
  67743. }
  67744. elOptionsToUpdate.push(newElOption);
  67745. setKeyInfoToNewElOption(resultItem, newElOption);
  67746. mergeNewElOptionToExist(existList, index, newElOption);
  67747. setLayoutInfoToExist(existList[index], newElOption);
  67748. }, this);
  67749. // Clean
  67750. for (var i = existList.length - 1; i >= 0; i--) {
  67751. if (existList[i] == null) {
  67752. existList.splice(i, 1);
  67753. }
  67754. else {
  67755. // $action should be volatile, otherwise option gotten from
  67756. // `getOption` will contain unexpected $action.
  67757. delete existList[i].$action;
  67758. }
  67759. }
  67760. },
  67761. /**
  67762. * Convert
  67763. * [{
  67764. * type: 'group',
  67765. * id: 'xx',
  67766. * children: [{type: 'circle'}, {type: 'polygon'}]
  67767. * }]
  67768. * to
  67769. * [
  67770. * {type: 'group', id: 'xx'},
  67771. * {type: 'circle', parentId: 'xx'},
  67772. * {type: 'polygon', parentId: 'xx'}
  67773. * ]
  67774. *
  67775. * @private
  67776. * @param {Array.<Object>} optionList option list
  67777. * @param {Array.<Object>} result result of flatten
  67778. * @param {Object} parentOption parent option
  67779. */
  67780. _flatten: function (optionList, result, parentOption) {
  67781. each$1(optionList, function (option) {
  67782. if (!option) {
  67783. return;
  67784. }
  67785. if (parentOption) {
  67786. option.parentOption = parentOption;
  67787. }
  67788. result.push(option);
  67789. var children = option.children;
  67790. if (option.type === 'group' && children) {
  67791. this._flatten(children, result, option);
  67792. }
  67793. // Deleting for JSON output, and for not affecting group creation.
  67794. delete option.children;
  67795. }, this);
  67796. },
  67797. // FIXME
  67798. // Pass to view using payload? setOption has a payload?
  67799. useElOptionsToUpdate: function () {
  67800. var els = this._elOptionsToUpdate;
  67801. // Clear to avoid render duplicately when zooming.
  67802. this._elOptionsToUpdate = null;
  67803. return els;
  67804. }
  67805. });
  67806. // -----
  67807. // View
  67808. // -----
  67809. extendComponentView({
  67810. type: 'graphic',
  67811. /**
  67812. * @override
  67813. */
  67814. init: function (ecModel, api) {
  67815. /**
  67816. * @private
  67817. * @type {module:zrender/core/util.HashMap}
  67818. */
  67819. this._elMap = createHashMap();
  67820. /**
  67821. * @private
  67822. * @type {module:echarts/graphic/GraphicModel}
  67823. */
  67824. this._lastGraphicModel;
  67825. },
  67826. /**
  67827. * @override
  67828. */
  67829. render: function (graphicModel, ecModel, api) {
  67830. // Having leveraged between use cases and algorithm complexity, a very
  67831. // simple layout mechanism is used:
  67832. // The size(width/height) can be determined by itself or its parent (not
  67833. // implemented yet), but can not by its children. (Top-down travel)
  67834. // The location(x/y) can be determined by the bounding rect of itself
  67835. // (can including its descendants or not) and the size of its parent.
  67836. // (Bottom-up travel)
  67837. // When `chart.clear()` or `chart.setOption({...}, true)` with the same id,
  67838. // view will be reused.
  67839. if (graphicModel !== this._lastGraphicModel) {
  67840. this._clear();
  67841. }
  67842. this._lastGraphicModel = graphicModel;
  67843. this._updateElements(graphicModel);
  67844. this._relocate(graphicModel, api);
  67845. },
  67846. /**
  67847. * Update graphic elements.
  67848. *
  67849. * @private
  67850. * @param {Object} graphicModel graphic model
  67851. */
  67852. _updateElements: function (graphicModel) {
  67853. var elOptionsToUpdate = graphicModel.useElOptionsToUpdate();
  67854. if (!elOptionsToUpdate) {
  67855. return;
  67856. }
  67857. var elMap = this._elMap;
  67858. var rootGroup = this.group;
  67859. // Top-down tranverse to assign graphic settings to each elements.
  67860. each$1(elOptionsToUpdate, function (elOption) {
  67861. var $action = elOption.$action;
  67862. var id = elOption.id;
  67863. var existEl = elMap.get(id);
  67864. var parentId = elOption.parentId;
  67865. var targetElParent = parentId != null ? elMap.get(parentId) : rootGroup;
  67866. var elOptionStyle = elOption.style;
  67867. if (elOption.type === 'text' && elOptionStyle) {
  67868. // In top/bottom mode, textVerticalAlign should not be used, which cause
  67869. // inaccurately locating.
  67870. if (elOption.hv && elOption.hv[1]) {
  67871. elOptionStyle.textVerticalAlign = elOptionStyle.textBaseline = null;
  67872. }
  67873. // Compatible with previous setting: both support fill and textFill,
  67874. // stroke and textStroke.
  67875. !elOptionStyle.hasOwnProperty('textFill') && elOptionStyle.fill && (
  67876. elOptionStyle.textFill = elOptionStyle.fill
  67877. );
  67878. !elOptionStyle.hasOwnProperty('textStroke') && elOptionStyle.stroke && (
  67879. elOptionStyle.textStroke = elOptionStyle.stroke
  67880. );
  67881. }
  67882. // Remove unnecessary props to avoid potential problems.
  67883. var elOptionCleaned = getCleanedElOption(elOption);
  67884. // For simple, do not support parent change, otherwise reorder is needed.
  67885. if (__DEV__) {
  67886. existEl && assert$1(
  67887. targetElParent === existEl.parent,
  67888. 'Changing parent is not supported.'
  67889. );
  67890. }
  67891. if (!$action || $action === 'merge') {
  67892. existEl
  67893. ? existEl.attr(elOptionCleaned)
  67894. : createEl$1(id, targetElParent, elOptionCleaned, elMap);
  67895. }
  67896. else if ($action === 'replace') {
  67897. removeEl(existEl, elMap);
  67898. createEl$1(id, targetElParent, elOptionCleaned, elMap);
  67899. }
  67900. else if ($action === 'remove') {
  67901. removeEl(existEl, elMap);
  67902. }
  67903. var el = elMap.get(id);
  67904. if (el) {
  67905. el.__ecGraphicWidthOption = elOption.width;
  67906. el.__ecGraphicHeightOption = elOption.height;
  67907. setEventData(el, graphicModel, elOption);
  67908. }
  67909. });
  67910. },
  67911. /**
  67912. * Locate graphic elements.
  67913. *
  67914. * @private
  67915. * @param {Object} graphicModel graphic model
  67916. * @param {module:echarts/ExtensionAPI} api extension API
  67917. */
  67918. _relocate: function (graphicModel, api) {
  67919. var elOptions = graphicModel.option.elements;
  67920. var rootGroup = this.group;
  67921. var elMap = this._elMap;
  67922. var apiWidth = api.getWidth();
  67923. var apiHeight = api.getHeight();
  67924. // Top-down to calculate percentage width/height of group
  67925. for (var i = 0; i < elOptions.length; i++) {
  67926. var elOption = elOptions[i];
  67927. var el = elMap.get(elOption.id);
  67928. if (!el || !el.isGroup) {
  67929. continue;
  67930. }
  67931. var parentEl = el.parent;
  67932. var isParentRoot = parentEl === rootGroup;
  67933. // Like 'position:absolut' in css, default 0.
  67934. el.__ecGraphicWidth = parsePercent$1(
  67935. el.__ecGraphicWidthOption,
  67936. isParentRoot ? apiWidth : parentEl.__ecGraphicWidth
  67937. ) || 0;
  67938. el.__ecGraphicHeight = parsePercent$1(
  67939. el.__ecGraphicHeightOption,
  67940. isParentRoot ? apiHeight : parentEl.__ecGraphicHeight
  67941. ) || 0;
  67942. }
  67943. // Bottom-up tranvese all elements (consider ec resize) to locate elements.
  67944. for (var i = elOptions.length - 1; i >= 0; i--) {
  67945. var elOption = elOptions[i];
  67946. var el = elMap.get(elOption.id);
  67947. if (!el) {
  67948. continue;
  67949. }
  67950. var parentEl = el.parent;
  67951. var containerInfo = parentEl === rootGroup
  67952. ? {
  67953. width: apiWidth,
  67954. height: apiHeight
  67955. }
  67956. : {
  67957. width: parentEl.__ecGraphicWidth,
  67958. height: parentEl.__ecGraphicHeight
  67959. };
  67960. // PENDING
  67961. // Currently, when `bounding: 'all'`, the union bounding rect of the group
  67962. // does not include the rect of [0, 0, group.width, group.height], which
  67963. // is probably weird for users. Should we make a break change for it?
  67964. positionElement(
  67965. el, elOption, containerInfo, null,
  67966. {hv: elOption.hv, boundingMode: elOption.bounding}
  67967. );
  67968. }
  67969. },
  67970. /**
  67971. * Clear all elements.
  67972. *
  67973. * @private
  67974. */
  67975. _clear: function () {
  67976. var elMap = this._elMap;
  67977. elMap.each(function (el) {
  67978. removeEl(el, elMap);
  67979. });
  67980. this._elMap = createHashMap();
  67981. },
  67982. /**
  67983. * @override
  67984. */
  67985. dispose: function () {
  67986. this._clear();
  67987. }
  67988. });
  67989. function createEl$1(id, targetElParent, elOption, elMap) {
  67990. var graphicType = elOption.type;
  67991. if (__DEV__) {
  67992. assert$1(graphicType, 'graphic type MUST be set');
  67993. }
  67994. var Clz = _nonShapeGraphicElements.hasOwnProperty(graphicType)
  67995. // Those graphic elements are not shapes. They should not be
  67996. // overwritten by users, so do them first.
  67997. ? _nonShapeGraphicElements[graphicType]
  67998. : getShapeClass(graphicType);
  67999. if (__DEV__) {
  68000. assert$1(Clz, 'graphic type can not be found');
  68001. }
  68002. var el = new Clz(elOption);
  68003. targetElParent.add(el);
  68004. elMap.set(id, el);
  68005. el.__ecGraphicId = id;
  68006. }
  68007. function removeEl(existEl, elMap) {
  68008. var existElParent = existEl && existEl.parent;
  68009. if (existElParent) {
  68010. existEl.type === 'group' && existEl.traverse(function (el) {
  68011. removeEl(el, elMap);
  68012. });
  68013. elMap.removeKey(existEl.__ecGraphicId);
  68014. existElParent.remove(existEl);
  68015. }
  68016. }
  68017. // Remove unnecessary props to avoid potential problems.
  68018. function getCleanedElOption(elOption) {
  68019. elOption = extend({}, elOption);
  68020. each$1(
  68021. ['id', 'parentId', '$action', 'hv', 'bounding'].concat(LOCATION_PARAMS),
  68022. function (name) {
  68023. delete elOption[name];
  68024. }
  68025. );
  68026. return elOption;
  68027. }
  68028. function isSetLoc(obj, props) {
  68029. var isSet;
  68030. each$1(props, function (prop) {
  68031. obj[prop] != null && obj[prop] !== 'auto' && (isSet = true);
  68032. });
  68033. return isSet;
  68034. }
  68035. function setKeyInfoToNewElOption(resultItem, newElOption) {
  68036. var existElOption = resultItem.exist;
  68037. // Set id and type after id assigned.
  68038. newElOption.id = resultItem.keyInfo.id;
  68039. !newElOption.type && existElOption && (newElOption.type = existElOption.type);
  68040. // Set parent id if not specified
  68041. if (newElOption.parentId == null) {
  68042. var newElParentOption = newElOption.parentOption;
  68043. if (newElParentOption) {
  68044. newElOption.parentId = newElParentOption.id;
  68045. }
  68046. else if (existElOption) {
  68047. newElOption.parentId = existElOption.parentId;
  68048. }
  68049. }
  68050. // Clear
  68051. newElOption.parentOption = null;
  68052. }
  68053. function mergeNewElOptionToExist(existList, index, newElOption) {
  68054. // Update existing options, for `getOption` feature.
  68055. var newElOptCopy = extend({}, newElOption);
  68056. var existElOption = existList[index];
  68057. var $action = newElOption.$action || 'merge';
  68058. if ($action === 'merge') {
  68059. if (existElOption) {
  68060. if (__DEV__) {
  68061. var newType = newElOption.type;
  68062. assert$1(
  68063. !newType || existElOption.type === newType,
  68064. 'Please set $action: "replace" to change `type`'
  68065. );
  68066. }
  68067. // We can ensure that newElOptCopy and existElOption are not
  68068. // the same object, so `merge` will not change newElOptCopy.
  68069. merge(existElOption, newElOptCopy, true);
  68070. // Rigid body, use ignoreSize.
  68071. mergeLayoutParam(existElOption, newElOptCopy, {ignoreSize: true});
  68072. // Will be used in render.
  68073. copyLayoutParams(newElOption, existElOption);
  68074. }
  68075. else {
  68076. existList[index] = newElOptCopy;
  68077. }
  68078. }
  68079. else if ($action === 'replace') {
  68080. existList[index] = newElOptCopy;
  68081. }
  68082. else if ($action === 'remove') {
  68083. // null will be cleaned later.
  68084. existElOption && (existList[index] = null);
  68085. }
  68086. }
  68087. function setLayoutInfoToExist(existItem, newElOption) {
  68088. if (!existItem) {
  68089. return;
  68090. }
  68091. existItem.hv = newElOption.hv = [
  68092. // Rigid body, dont care `width`.
  68093. isSetLoc(newElOption, ['left', 'right']),
  68094. // Rigid body, dont care `height`.
  68095. isSetLoc(newElOption, ['top', 'bottom'])
  68096. ];
  68097. // Give default group size. Otherwise layout error may occur.
  68098. if (existItem.type === 'group') {
  68099. existItem.width == null && (existItem.width = newElOption.width = 0);
  68100. existItem.height == null && (existItem.height = newElOption.height = 0);
  68101. }
  68102. }
  68103. function setEventData(el, graphicModel, elOption) {
  68104. var eventData = el.eventData;
  68105. // Simple optimize for large amount of elements that no need event.
  68106. if (!el.silent && !el.ignore && !eventData) {
  68107. eventData = el.eventData = {
  68108. componentType: 'graphic',
  68109. componentIndex: graphicModel.componentIndex,
  68110. name: el.name
  68111. };
  68112. }
  68113. // `elOption.info` enables user to mount some info on
  68114. // elements and use them in event handlers.
  68115. if (eventData) {
  68116. eventData.info = el.info;
  68117. }
  68118. }
  68119. /*
  68120. * Licensed to the Apache Software Foundation (ASF) under one
  68121. * or more contributor license agreements. See the NOTICE file
  68122. * distributed with this work for additional information
  68123. * regarding copyright ownership. The ASF licenses this file
  68124. * to you under the Apache License, Version 2.0 (the
  68125. * "License"); you may not use this file except in compliance
  68126. * with the License. You may obtain a copy of the License at
  68127. *
  68128. * http://www.apache.org/licenses/LICENSE-2.0
  68129. *
  68130. * Unless required by applicable law or agreed to in writing,
  68131. * software distributed under the License is distributed on an
  68132. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68133. * KIND, either express or implied. See the License for the
  68134. * specific language governing permissions and limitations
  68135. * under the License.
  68136. */
  68137. var features = {};
  68138. function register$1(name, ctor) {
  68139. features[name] = ctor;
  68140. }
  68141. function get$1(name) {
  68142. return features[name];
  68143. }
  68144. /*
  68145. * Licensed to the Apache Software Foundation (ASF) under one
  68146. * or more contributor license agreements. See the NOTICE file
  68147. * distributed with this work for additional information
  68148. * regarding copyright ownership. The ASF licenses this file
  68149. * to you under the Apache License, Version 2.0 (the
  68150. * "License"); you may not use this file except in compliance
  68151. * with the License. You may obtain a copy of the License at
  68152. *
  68153. * http://www.apache.org/licenses/LICENSE-2.0
  68154. *
  68155. * Unless required by applicable law or agreed to in writing,
  68156. * software distributed under the License is distributed on an
  68157. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68158. * KIND, either express or implied. See the License for the
  68159. * specific language governing permissions and limitations
  68160. * under the License.
  68161. */
  68162. var ToolboxModel = extendComponentModel({
  68163. type: 'toolbox',
  68164. layoutMode: {
  68165. type: 'box',
  68166. ignoreSize: true
  68167. },
  68168. optionUpdated: function () {
  68169. ToolboxModel.superApply(this, 'optionUpdated', arguments);
  68170. each$1(this.option.feature, function (featureOpt, featureName) {
  68171. var Feature = get$1(featureName);
  68172. Feature && merge(featureOpt, Feature.defaultOption);
  68173. });
  68174. },
  68175. defaultOption: {
  68176. show: true,
  68177. z: 6,
  68178. zlevel: 0,
  68179. orient: 'horizontal',
  68180. left: 'right',
  68181. top: 'top',
  68182. // right
  68183. // bottom
  68184. backgroundColor: 'transparent',
  68185. borderColor: '#ccc',
  68186. borderRadius: 0,
  68187. borderWidth: 0,
  68188. padding: 5,
  68189. itemSize: 15,
  68190. itemGap: 8,
  68191. showTitle: true,
  68192. iconStyle: {
  68193. borderColor: '#666',
  68194. color: 'none'
  68195. },
  68196. emphasis: {
  68197. iconStyle: {
  68198. borderColor: '#3E98C5'
  68199. }
  68200. },
  68201. // textStyle: {},
  68202. // feature
  68203. tooltip: {
  68204. show: false
  68205. }
  68206. }
  68207. });
  68208. /*
  68209. * Licensed to the Apache Software Foundation (ASF) under one
  68210. * or more contributor license agreements. See the NOTICE file
  68211. * distributed with this work for additional information
  68212. * regarding copyright ownership. The ASF licenses this file
  68213. * to you under the Apache License, Version 2.0 (the
  68214. * "License"); you may not use this file except in compliance
  68215. * with the License. You may obtain a copy of the License at
  68216. *
  68217. * http://www.apache.org/licenses/LICENSE-2.0
  68218. *
  68219. * Unless required by applicable law or agreed to in writing,
  68220. * software distributed under the License is distributed on an
  68221. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68222. * KIND, either express or implied. See the License for the
  68223. * specific language governing permissions and limitations
  68224. * under the License.
  68225. */
  68226. /**
  68227. * Layout list like component.
  68228. * It will box layout each items in group of component and then position the whole group in the viewport
  68229. * @param {module:zrender/group/Group} group
  68230. * @param {module:echarts/model/Component} componentModel
  68231. * @param {module:echarts/ExtensionAPI}
  68232. */
  68233. function layout$3(group, componentModel, api) {
  68234. var boxLayoutParams = componentModel.getBoxLayoutParams();
  68235. var padding = componentModel.get('padding');
  68236. var viewportSize = {width: api.getWidth(), height: api.getHeight()};
  68237. var rect = getLayoutRect(
  68238. boxLayoutParams,
  68239. viewportSize,
  68240. padding
  68241. );
  68242. box(
  68243. componentModel.get('orient'),
  68244. group,
  68245. componentModel.get('itemGap'),
  68246. rect.width,
  68247. rect.height
  68248. );
  68249. positionElement(
  68250. group,
  68251. boxLayoutParams,
  68252. viewportSize,
  68253. padding
  68254. );
  68255. }
  68256. function makeBackground(rect, componentModel) {
  68257. var padding = normalizeCssArray$1(
  68258. componentModel.get('padding')
  68259. );
  68260. var style = componentModel.getItemStyle(['color', 'opacity']);
  68261. style.fill = componentModel.get('backgroundColor');
  68262. var rect = new Rect({
  68263. shape: {
  68264. x: rect.x - padding[3],
  68265. y: rect.y - padding[0],
  68266. width: rect.width + padding[1] + padding[3],
  68267. height: rect.height + padding[0] + padding[2],
  68268. r: componentModel.get('borderRadius')
  68269. },
  68270. style: style,
  68271. silent: true,
  68272. z2: -1
  68273. });
  68274. // FIXME
  68275. // `subPixelOptimizeRect` may bring some gap between edge of viewpart
  68276. // and background rect when setting like `left: 0`, `top: 0`.
  68277. // graphic.subPixelOptimizeRect(rect);
  68278. return rect;
  68279. }
  68280. /*
  68281. * Licensed to the Apache Software Foundation (ASF) under one
  68282. * or more contributor license agreements. See the NOTICE file
  68283. * distributed with this work for additional information
  68284. * regarding copyright ownership. The ASF licenses this file
  68285. * to you under the Apache License, Version 2.0 (the
  68286. * "License"); you may not use this file except in compliance
  68287. * with the License. You may obtain a copy of the License at
  68288. *
  68289. * http://www.apache.org/licenses/LICENSE-2.0
  68290. *
  68291. * Unless required by applicable law or agreed to in writing,
  68292. * software distributed under the License is distributed on an
  68293. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68294. * KIND, either express or implied. See the License for the
  68295. * specific language governing permissions and limitations
  68296. * under the License.
  68297. */
  68298. extendComponentView({
  68299. type: 'toolbox',
  68300. render: function (toolboxModel, ecModel, api, payload) {
  68301. var group = this.group;
  68302. group.removeAll();
  68303. if (!toolboxModel.get('show')) {
  68304. return;
  68305. }
  68306. var itemSize = +toolboxModel.get('itemSize');
  68307. var featureOpts = toolboxModel.get('feature') || {};
  68308. var features = this._features || (this._features = {});
  68309. var featureNames = [];
  68310. each$1(featureOpts, function (opt, name) {
  68311. featureNames.push(name);
  68312. });
  68313. (new DataDiffer(this._featureNames || [], featureNames))
  68314. .add(processFeature)
  68315. .update(processFeature)
  68316. .remove(curry(processFeature, null))
  68317. .execute();
  68318. // Keep for diff.
  68319. this._featureNames = featureNames;
  68320. function processFeature(newIndex, oldIndex) {
  68321. var featureName = featureNames[newIndex];
  68322. var oldName = featureNames[oldIndex];
  68323. var featureOpt = featureOpts[featureName];
  68324. var featureModel = new Model(featureOpt, toolboxModel, toolboxModel.ecModel);
  68325. var feature;
  68326. // FIX#11236, merge feature title from MagicType newOption. TODO: consider seriesIndex ?
  68327. if (payload && payload.newTitle != null && payload.featureName === featureName) {
  68328. featureOpt.title = payload.newTitle;
  68329. }
  68330. if (featureName && !oldName) { // Create
  68331. if (isUserFeatureName(featureName)) {
  68332. feature = {
  68333. model: featureModel,
  68334. onclick: featureModel.option.onclick,
  68335. featureName: featureName
  68336. };
  68337. }
  68338. else {
  68339. var Feature = get$1(featureName);
  68340. if (!Feature) {
  68341. return;
  68342. }
  68343. feature = new Feature(featureModel, ecModel, api);
  68344. }
  68345. features[featureName] = feature;
  68346. }
  68347. else {
  68348. feature = features[oldName];
  68349. // If feature does not exsit.
  68350. if (!feature) {
  68351. return;
  68352. }
  68353. feature.model = featureModel;
  68354. feature.ecModel = ecModel;
  68355. feature.api = api;
  68356. }
  68357. if (!featureName && oldName) {
  68358. feature.dispose && feature.dispose(ecModel, api);
  68359. return;
  68360. }
  68361. if (!featureModel.get('show') || feature.unusable) {
  68362. feature.remove && feature.remove(ecModel, api);
  68363. return;
  68364. }
  68365. createIconPaths(featureModel, feature, featureName);
  68366. featureModel.setIconStatus = function (iconName, status) {
  68367. var option = this.option;
  68368. var iconPaths = this.iconPaths;
  68369. option.iconStatus = option.iconStatus || {};
  68370. option.iconStatus[iconName] = status;
  68371. // FIXME
  68372. iconPaths[iconName] && iconPaths[iconName].trigger(status);
  68373. };
  68374. if (feature.render) {
  68375. feature.render(featureModel, ecModel, api, payload);
  68376. }
  68377. }
  68378. function createIconPaths(featureModel, feature, featureName) {
  68379. var iconStyleModel = featureModel.getModel('iconStyle');
  68380. var iconStyleEmphasisModel = featureModel.getModel('emphasis.iconStyle');
  68381. // If one feature has mutiple icon. they are orginaized as
  68382. // {
  68383. // icon: {
  68384. // foo: '',
  68385. // bar: ''
  68386. // },
  68387. // title: {
  68388. // foo: '',
  68389. // bar: ''
  68390. // }
  68391. // }
  68392. var icons = feature.getIcons ? feature.getIcons() : featureModel.get('icon');
  68393. var titles = featureModel.get('title') || {};
  68394. if (typeof icons === 'string') {
  68395. var icon = icons;
  68396. var title = titles;
  68397. icons = {};
  68398. titles = {};
  68399. icons[featureName] = icon;
  68400. titles[featureName] = title;
  68401. }
  68402. var iconPaths = featureModel.iconPaths = {};
  68403. each$1(icons, function (iconStr, iconName) {
  68404. var path = createIcon(
  68405. iconStr,
  68406. {},
  68407. {
  68408. x: -itemSize / 2,
  68409. y: -itemSize / 2,
  68410. width: itemSize,
  68411. height: itemSize
  68412. }
  68413. );
  68414. path.setStyle(iconStyleModel.getItemStyle());
  68415. path.hoverStyle = iconStyleEmphasisModel.getItemStyle();
  68416. // Text position calculation
  68417. path.setStyle({
  68418. text: titles[iconName],
  68419. textAlign: iconStyleEmphasisModel.get('textAlign'),
  68420. textBorderRadius: iconStyleEmphasisModel.get('textBorderRadius'),
  68421. textPadding: iconStyleEmphasisModel.get('textPadding'),
  68422. textFill: null
  68423. });
  68424. var tooltipModel = toolboxModel.getModel('tooltip');
  68425. if (tooltipModel && tooltipModel.get('show')) {
  68426. path.attr('tooltip', extend({
  68427. content: titles[iconName],
  68428. formatter: tooltipModel.get('formatter', true)
  68429. || function () {
  68430. return titles[iconName];
  68431. },
  68432. formatterParams: {
  68433. componentType: 'toolbox',
  68434. name: iconName,
  68435. title: titles[iconName],
  68436. $vars: ['name', 'title']
  68437. },
  68438. position: tooltipModel.get('position', true) || 'bottom'
  68439. }, tooltipModel.option));
  68440. }
  68441. setHoverStyle(path);
  68442. if (toolboxModel.get('showTitle')) {
  68443. path.__title = titles[iconName];
  68444. path.on('mouseover', function () {
  68445. // Should not reuse above hoverStyle, which might be modified.
  68446. var hoverStyle = iconStyleEmphasisModel.getItemStyle();
  68447. var defaultTextPosition = toolboxModel.get('orient') === 'vertical'
  68448. ? (toolboxModel.get('right') == null ? 'right' : 'left')
  68449. : (toolboxModel.get('bottom') == null ? 'bottom' : 'top');
  68450. path.setStyle({
  68451. textFill: iconStyleEmphasisModel.get('textFill')
  68452. || hoverStyle.fill || hoverStyle.stroke || '#000',
  68453. textBackgroundColor: iconStyleEmphasisModel.get('textBackgroundColor'),
  68454. textPosition: iconStyleEmphasisModel.get('textPosition') || defaultTextPosition
  68455. });
  68456. })
  68457. .on('mouseout', function () {
  68458. path.setStyle({
  68459. textFill: null,
  68460. textBackgroundColor: null
  68461. });
  68462. });
  68463. }
  68464. path.trigger(featureModel.get('iconStatus.' + iconName) || 'normal');
  68465. group.add(path);
  68466. path.on('click', bind(
  68467. feature.onclick, feature, ecModel, api, iconName
  68468. ));
  68469. iconPaths[iconName] = path;
  68470. });
  68471. }
  68472. layout$3(group, toolboxModel, api);
  68473. // Render background after group is layout
  68474. // FIXME
  68475. group.add(makeBackground(group.getBoundingRect(), toolboxModel));
  68476. // Adjust icon title positions to avoid them out of screen
  68477. group.eachChild(function (icon) {
  68478. var titleText = icon.__title;
  68479. var hoverStyle = icon.hoverStyle;
  68480. // May be background element
  68481. if (hoverStyle && titleText) {
  68482. var rect = getBoundingRect(
  68483. titleText, makeFont(hoverStyle)
  68484. );
  68485. var offsetX = icon.position[0] + group.position[0];
  68486. var offsetY = icon.position[1] + group.position[1] + itemSize;
  68487. var needPutOnTop = false;
  68488. if (offsetY + rect.height > api.getHeight()) {
  68489. hoverStyle.textPosition = 'top';
  68490. needPutOnTop = true;
  68491. }
  68492. var topOffset = needPutOnTop ? (-5 - rect.height) : (itemSize + 8);
  68493. if (offsetX + rect.width / 2 > api.getWidth()) {
  68494. hoverStyle.textPosition = ['100%', topOffset];
  68495. hoverStyle.textAlign = 'right';
  68496. }
  68497. else if (offsetX - rect.width / 2 < 0) {
  68498. hoverStyle.textPosition = [0, topOffset];
  68499. hoverStyle.textAlign = 'left';
  68500. }
  68501. }
  68502. });
  68503. },
  68504. updateView: function (toolboxModel, ecModel, api, payload) {
  68505. each$1(this._features, function (feature) {
  68506. feature.updateView && feature.updateView(feature.model, ecModel, api, payload);
  68507. });
  68508. },
  68509. // updateLayout: function (toolboxModel, ecModel, api, payload) {
  68510. // zrUtil.each(this._features, function (feature) {
  68511. // feature.updateLayout && feature.updateLayout(feature.model, ecModel, api, payload);
  68512. // });
  68513. // },
  68514. remove: function (ecModel, api) {
  68515. each$1(this._features, function (feature) {
  68516. feature.remove && feature.remove(ecModel, api);
  68517. });
  68518. this.group.removeAll();
  68519. },
  68520. dispose: function (ecModel, api) {
  68521. each$1(this._features, function (feature) {
  68522. feature.dispose && feature.dispose(ecModel, api);
  68523. });
  68524. }
  68525. });
  68526. function isUserFeatureName(featureName) {
  68527. return featureName.indexOf('my') === 0;
  68528. }
  68529. /*
  68530. * Licensed to the Apache Software Foundation (ASF) under one
  68531. * or more contributor license agreements. See the NOTICE file
  68532. * distributed with this work for additional information
  68533. * regarding copyright ownership. The ASF licenses this file
  68534. * to you under the Apache License, Version 2.0 (the
  68535. * "License"); you may not use this file except in compliance
  68536. * with the License. You may obtain a copy of the License at
  68537. *
  68538. * http://www.apache.org/licenses/LICENSE-2.0
  68539. *
  68540. * Unless required by applicable law or agreed to in writing,
  68541. * software distributed under the License is distributed on an
  68542. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68543. * KIND, either express or implied. See the License for the
  68544. * specific language governing permissions and limitations
  68545. * under the License.
  68546. */
  68547. /* global Uint8Array */
  68548. var saveAsImageLang = lang.toolbox.saveAsImage;
  68549. function SaveAsImage(model) {
  68550. this.model = model;
  68551. }
  68552. SaveAsImage.defaultOption = {
  68553. show: true,
  68554. 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',
  68555. title: saveAsImageLang.title,
  68556. type: 'png',
  68557. // Default use option.backgroundColor
  68558. // backgroundColor: '#fff',
  68559. connectedBackgroundColor: '#fff',
  68560. name: '',
  68561. excludeComponents: ['toolbox'],
  68562. pixelRatio: 1,
  68563. lang: saveAsImageLang.lang.slice()
  68564. };
  68565. SaveAsImage.prototype.unusable = !env$1.canvasSupported;
  68566. var proto$2 = SaveAsImage.prototype;
  68567. proto$2.onclick = function (ecModel, api) {
  68568. var model = this.model;
  68569. var title = model.get('name') || ecModel.get('title.0.text') || 'echarts';
  68570. var isSvg = api.getZr().painter.getType() === 'svg';
  68571. var type = isSvg ? 'svg' : model.get('type', true) || 'png';
  68572. var url = api.getConnectedDataURL({
  68573. type: type,
  68574. backgroundColor: model.get('backgroundColor', true)
  68575. || ecModel.get('backgroundColor') || '#fff',
  68576. connectedBackgroundColor: model.get('connectedBackgroundColor'),
  68577. excludeComponents: model.get('excludeComponents'),
  68578. pixelRatio: model.get('pixelRatio')
  68579. });
  68580. // Chrome and Firefox
  68581. if (typeof MouseEvent === 'function' && !env$1.browser.ie && !env$1.browser.edge) {
  68582. var $a = document.createElement('a');
  68583. $a.download = title + '.' + type;
  68584. $a.target = '_blank';
  68585. $a.href = url;
  68586. var evt = new MouseEvent('click', {
  68587. view: window,
  68588. bubbles: true,
  68589. cancelable: false
  68590. });
  68591. $a.dispatchEvent(evt);
  68592. }
  68593. // IE
  68594. else {
  68595. if (window.navigator.msSaveOrOpenBlob) {
  68596. var bstr = atob(url.split(',')[1]);
  68597. var n = bstr.length;
  68598. var u8arr = new Uint8Array(n);
  68599. while (n--) {
  68600. u8arr[n] = bstr.charCodeAt(n);
  68601. }
  68602. var blob = new Blob([u8arr]);
  68603. window.navigator.msSaveOrOpenBlob(blob, title + '.' + type);
  68604. }
  68605. else {
  68606. var lang$$1 = model.get('lang');
  68607. var html = ''
  68608. + '<body style="margin:0;">'
  68609. + '<img src="' + url + '" style="max-width:100%;" title="' + ((lang$$1 && lang$$1[0]) || '') + '" />'
  68610. + '</body>';
  68611. var tab = window.open();
  68612. tab.document.write(html);
  68613. }
  68614. }
  68615. };
  68616. register$1(
  68617. 'saveAsImage', SaveAsImage
  68618. );
  68619. /*
  68620. * Licensed to the Apache Software Foundation (ASF) under one
  68621. * or more contributor license agreements. See the NOTICE file
  68622. * distributed with this work for additional information
  68623. * regarding copyright ownership. The ASF licenses this file
  68624. * to you under the Apache License, Version 2.0 (the
  68625. * "License"); you may not use this file except in compliance
  68626. * with the License. You may obtain a copy of the License at
  68627. *
  68628. * http://www.apache.org/licenses/LICENSE-2.0
  68629. *
  68630. * Unless required by applicable law or agreed to in writing,
  68631. * software distributed under the License is distributed on an
  68632. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68633. * KIND, either express or implied. See the License for the
  68634. * specific language governing permissions and limitations
  68635. * under the License.
  68636. */
  68637. var magicTypeLang = lang.toolbox.magicType;
  68638. var INNER_STACK_KEYWORD = '__ec_magicType_stack__';
  68639. function MagicType(model) {
  68640. this.model = model;
  68641. }
  68642. MagicType.defaultOption = {
  68643. show: true,
  68644. type: [],
  68645. // Icon group
  68646. icon: {
  68647. /* eslint-disable */
  68648. line: 'M4.1,28.9h7.1l9.3-22l7.4,38l9.7-19.7l3,12.8h14.9M4.1,58h51.4',
  68649. bar: 'M6.7,22.9h10V48h-10V22.9zM24.9,13h10v35h-10V13zM43.2,2h10v46h-10V2zM3.1,58h53.7',
  68650. 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
  68651. /* eslint-enable */
  68652. },
  68653. // `line`, `bar`, `stack`, `tiled`
  68654. title: clone(magicTypeLang.title),
  68655. option: {},
  68656. seriesIndex: {}
  68657. };
  68658. var proto$3 = MagicType.prototype;
  68659. proto$3.getIcons = function () {
  68660. var model = this.model;
  68661. var availableIcons = model.get('icon');
  68662. var icons = {};
  68663. each$1(model.get('type'), function (type) {
  68664. if (availableIcons[type]) {
  68665. icons[type] = availableIcons[type];
  68666. }
  68667. });
  68668. return icons;
  68669. };
  68670. var seriesOptGenreator = {
  68671. 'line': function (seriesType, seriesId, seriesModel, model) {
  68672. if (seriesType === 'bar') {
  68673. return merge({
  68674. id: seriesId,
  68675. type: 'line',
  68676. // Preserve data related option
  68677. data: seriesModel.get('data'),
  68678. stack: seriesModel.get('stack'),
  68679. markPoint: seriesModel.get('markPoint'),
  68680. markLine: seriesModel.get('markLine')
  68681. }, model.get('option.line') || {}, true);
  68682. }
  68683. },
  68684. 'bar': function (seriesType, seriesId, seriesModel, model) {
  68685. if (seriesType === 'line') {
  68686. return merge({
  68687. id: seriesId,
  68688. type: 'bar',
  68689. // Preserve data related option
  68690. data: seriesModel.get('data'),
  68691. stack: seriesModel.get('stack'),
  68692. markPoint: seriesModel.get('markPoint'),
  68693. markLine: seriesModel.get('markLine')
  68694. }, model.get('option.bar') || {}, true);
  68695. }
  68696. },
  68697. 'stack': function (seriesType, seriesId, seriesModel, model) {
  68698. var isStack = seriesModel.get('stack') === INNER_STACK_KEYWORD;
  68699. if (seriesType === 'line' || seriesType === 'bar') {
  68700. model.setIconStatus('stack', isStack ? 'normal' : 'emphasis');
  68701. return merge({
  68702. id: seriesId,
  68703. stack: isStack ? '' : INNER_STACK_KEYWORD
  68704. }, model.get('option.stack') || {}, true);
  68705. }
  68706. }
  68707. };
  68708. var radioTypes = [
  68709. ['line', 'bar'],
  68710. ['stack']
  68711. ];
  68712. proto$3.onclick = function (ecModel, api, type) {
  68713. var model = this.model;
  68714. var seriesIndex = model.get('seriesIndex.' + type);
  68715. // Not supported magicType
  68716. if (!seriesOptGenreator[type]) {
  68717. return;
  68718. }
  68719. var newOption = {
  68720. series: []
  68721. };
  68722. var generateNewSeriesTypes = function (seriesModel) {
  68723. var seriesType = seriesModel.subType;
  68724. var seriesId = seriesModel.id;
  68725. var newSeriesOpt = seriesOptGenreator[type](
  68726. seriesType, seriesId, seriesModel, model
  68727. );
  68728. if (newSeriesOpt) {
  68729. // PENDING If merge original option?
  68730. defaults(newSeriesOpt, seriesModel.option);
  68731. newOption.series.push(newSeriesOpt);
  68732. }
  68733. // Modify boundaryGap
  68734. var coordSys = seriesModel.coordinateSystem;
  68735. if (coordSys && coordSys.type === 'cartesian2d' && (type === 'line' || type === 'bar')) {
  68736. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  68737. if (categoryAxis) {
  68738. var axisDim = categoryAxis.dim;
  68739. var axisType = axisDim + 'Axis';
  68740. var axisModel = ecModel.queryComponents({
  68741. mainType: axisType,
  68742. index: seriesModel.get(name + 'Index'),
  68743. id: seriesModel.get(name + 'Id')
  68744. })[0];
  68745. var axisIndex = axisModel.componentIndex;
  68746. newOption[axisType] = newOption[axisType] || [];
  68747. for (var i = 0; i <= axisIndex; i++) {
  68748. newOption[axisType][axisIndex] = newOption[axisType][axisIndex] || {};
  68749. }
  68750. newOption[axisType][axisIndex].boundaryGap = type === 'bar';
  68751. }
  68752. }
  68753. };
  68754. each$1(radioTypes, function (radio) {
  68755. if (indexOf(radio, type) >= 0) {
  68756. each$1(radio, function (item) {
  68757. model.setIconStatus(item, 'normal');
  68758. });
  68759. }
  68760. });
  68761. model.setIconStatus(type, 'emphasis');
  68762. ecModel.eachComponent(
  68763. {
  68764. mainType: 'series',
  68765. query: seriesIndex == null ? null : {
  68766. seriesIndex: seriesIndex
  68767. }
  68768. }, generateNewSeriesTypes
  68769. );
  68770. var newTitle;
  68771. // Change title of stack
  68772. if (type === 'stack') {
  68773. var isStack = newOption.series && newOption.series[0] && newOption.series[0].stack === INNER_STACK_KEYWORD;
  68774. newTitle = isStack
  68775. ? merge({ stack: magicTypeLang.title.tiled }, magicTypeLang.title)
  68776. : clone(magicTypeLang.title);
  68777. }
  68778. api.dispatchAction({
  68779. type: 'changeMagicType',
  68780. currentType: type,
  68781. newOption: newOption,
  68782. newTitle: newTitle,
  68783. featureName: 'magicType'
  68784. });
  68785. };
  68786. registerAction({
  68787. type: 'changeMagicType',
  68788. event: 'magicTypeChanged',
  68789. update: 'prepareAndUpdate'
  68790. }, function (payload, ecModel) {
  68791. ecModel.mergeOption(payload.newOption);
  68792. });
  68793. register$1('magicType', MagicType);
  68794. /*
  68795. * Licensed to the Apache Software Foundation (ASF) under one
  68796. * or more contributor license agreements. See the NOTICE file
  68797. * distributed with this work for additional information
  68798. * regarding copyright ownership. The ASF licenses this file
  68799. * to you under the Apache License, Version 2.0 (the
  68800. * "License"); you may not use this file except in compliance
  68801. * with the License. You may obtain a copy of the License at
  68802. *
  68803. * http://www.apache.org/licenses/LICENSE-2.0
  68804. *
  68805. * Unless required by applicable law or agreed to in writing,
  68806. * software distributed under the License is distributed on an
  68807. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68808. * KIND, either express or implied. See the License for the
  68809. * specific language governing permissions and limitations
  68810. * under the License.
  68811. */
  68812. var dataViewLang = lang.toolbox.dataView;
  68813. var BLOCK_SPLITER = new Array(60).join('-');
  68814. var ITEM_SPLITER = '\t';
  68815. /**
  68816. * Group series into two types
  68817. * 1. on category axis, like line, bar
  68818. * 2. others, like scatter, pie
  68819. * @param {module:echarts/model/Global} ecModel
  68820. * @return {Object}
  68821. * @inner
  68822. */
  68823. function groupSeries(ecModel) {
  68824. var seriesGroupByCategoryAxis = {};
  68825. var otherSeries = [];
  68826. var meta = [];
  68827. ecModel.eachRawSeries(function (seriesModel) {
  68828. var coordSys = seriesModel.coordinateSystem;
  68829. if (coordSys && (coordSys.type === 'cartesian2d' || coordSys.type === 'polar')) {
  68830. var baseAxis = coordSys.getBaseAxis();
  68831. if (baseAxis.type === 'category') {
  68832. var key = baseAxis.dim + '_' + baseAxis.index;
  68833. if (!seriesGroupByCategoryAxis[key]) {
  68834. seriesGroupByCategoryAxis[key] = {
  68835. categoryAxis: baseAxis,
  68836. valueAxis: coordSys.getOtherAxis(baseAxis),
  68837. series: []
  68838. };
  68839. meta.push({
  68840. axisDim: baseAxis.dim,
  68841. axisIndex: baseAxis.index
  68842. });
  68843. }
  68844. seriesGroupByCategoryAxis[key].series.push(seriesModel);
  68845. }
  68846. else {
  68847. otherSeries.push(seriesModel);
  68848. }
  68849. }
  68850. else {
  68851. otherSeries.push(seriesModel);
  68852. }
  68853. });
  68854. return {
  68855. seriesGroupByCategoryAxis: seriesGroupByCategoryAxis,
  68856. other: otherSeries,
  68857. meta: meta
  68858. };
  68859. }
  68860. /**
  68861. * Assemble content of series on cateogory axis
  68862. * @param {Array.<module:echarts/model/Series>} series
  68863. * @return {string}
  68864. * @inner
  68865. */
  68866. function assembleSeriesWithCategoryAxis(series) {
  68867. var tables = [];
  68868. each$1(series, function (group, key) {
  68869. var categoryAxis = group.categoryAxis;
  68870. var valueAxis = group.valueAxis;
  68871. var valueAxisDim = valueAxis.dim;
  68872. var headers = [' '].concat(map(group.series, function (series) {
  68873. return series.name;
  68874. }));
  68875. var columns = [categoryAxis.model.getCategories()];
  68876. each$1(group.series, function (series) {
  68877. columns.push(series.getRawData().mapArray(valueAxisDim, function (val) {
  68878. return val;
  68879. }));
  68880. });
  68881. // Assemble table content
  68882. var lines = [headers.join(ITEM_SPLITER)];
  68883. for (var i = 0; i < columns[0].length; i++) {
  68884. var items = [];
  68885. for (var j = 0; j < columns.length; j++) {
  68886. items.push(columns[j][i]);
  68887. }
  68888. lines.push(items.join(ITEM_SPLITER));
  68889. }
  68890. tables.push(lines.join('\n'));
  68891. });
  68892. return tables.join('\n\n' + BLOCK_SPLITER + '\n\n');
  68893. }
  68894. /**
  68895. * Assemble content of other series
  68896. * @param {Array.<module:echarts/model/Series>} series
  68897. * @return {string}
  68898. * @inner
  68899. */
  68900. function assembleOtherSeries(series) {
  68901. return map(series, function (series) {
  68902. var data = series.getRawData();
  68903. var lines = [series.name];
  68904. var vals = [];
  68905. data.each(data.dimensions, function () {
  68906. var argLen = arguments.length;
  68907. var dataIndex = arguments[argLen - 1];
  68908. var name = data.getName(dataIndex);
  68909. for (var i = 0; i < argLen - 1; i++) {
  68910. vals[i] = arguments[i];
  68911. }
  68912. lines.push((name ? (name + ITEM_SPLITER) : '') + vals.join(ITEM_SPLITER));
  68913. });
  68914. return lines.join('\n');
  68915. }).join('\n\n' + BLOCK_SPLITER + '\n\n');
  68916. }
  68917. /**
  68918. * @param {module:echarts/model/Global}
  68919. * @return {Object}
  68920. * @inner
  68921. */
  68922. function getContentFromModel(ecModel) {
  68923. var result = groupSeries(ecModel);
  68924. return {
  68925. value: filter([
  68926. assembleSeriesWithCategoryAxis(result.seriesGroupByCategoryAxis),
  68927. assembleOtherSeries(result.other)
  68928. ], function (str) {
  68929. return str.replace(/[\n\t\s]/g, '');
  68930. }).join('\n\n' + BLOCK_SPLITER + '\n\n'),
  68931. meta: result.meta
  68932. };
  68933. }
  68934. function trim$1(str) {
  68935. return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  68936. }
  68937. /**
  68938. * If a block is tsv format
  68939. */
  68940. function isTSVFormat(block) {
  68941. // Simple method to find out if a block is tsv format
  68942. var firstLine = block.slice(0, block.indexOf('\n'));
  68943. if (firstLine.indexOf(ITEM_SPLITER) >= 0) {
  68944. return true;
  68945. }
  68946. }
  68947. var itemSplitRegex = new RegExp('[' + ITEM_SPLITER + ']+', 'g');
  68948. /**
  68949. * @param {string} tsv
  68950. * @return {Object}
  68951. */
  68952. function parseTSVContents(tsv) {
  68953. var tsvLines = tsv.split(/\n+/g);
  68954. var headers = trim$1(tsvLines.shift()).split(itemSplitRegex);
  68955. var categories = [];
  68956. var series = map(headers, function (header) {
  68957. return {
  68958. name: header,
  68959. data: []
  68960. };
  68961. });
  68962. for (var i = 0; i < tsvLines.length; i++) {
  68963. var items = trim$1(tsvLines[i]).split(itemSplitRegex);
  68964. categories.push(items.shift());
  68965. for (var j = 0; j < items.length; j++) {
  68966. series[j] && (series[j].data[i] = items[j]);
  68967. }
  68968. }
  68969. return {
  68970. series: series,
  68971. categories: categories
  68972. };
  68973. }
  68974. /**
  68975. * @param {string} str
  68976. * @return {Array.<Object>}
  68977. * @inner
  68978. */
  68979. function parseListContents(str) {
  68980. var lines = str.split(/\n+/g);
  68981. var seriesName = trim$1(lines.shift());
  68982. var data = [];
  68983. for (var i = 0; i < lines.length; i++) {
  68984. var items = trim$1(lines[i]).split(itemSplitRegex);
  68985. var name = '';
  68986. var value;
  68987. var hasName = false;
  68988. if (isNaN(items[0])) { // First item is name
  68989. hasName = true;
  68990. name = items[0];
  68991. items = items.slice(1);
  68992. data[i] = {
  68993. name: name,
  68994. value: []
  68995. };
  68996. value = data[i].value;
  68997. }
  68998. else {
  68999. value = data[i] = [];
  69000. }
  69001. for (var j = 0; j < items.length; j++) {
  69002. value.push(+items[j]);
  69003. }
  69004. if (value.length === 1) {
  69005. hasName ? (data[i].value = value[0]) : (data[i] = value[0]);
  69006. }
  69007. }
  69008. return {
  69009. name: seriesName,
  69010. data: data
  69011. };
  69012. }
  69013. /**
  69014. * @param {string} str
  69015. * @param {Array.<Object>} blockMetaList
  69016. * @return {Object}
  69017. * @inner
  69018. */
  69019. function parseContents(str, blockMetaList) {
  69020. var blocks = str.split(new RegExp('\n*' + BLOCK_SPLITER + '\n*', 'g'));
  69021. var newOption = {
  69022. series: []
  69023. };
  69024. each$1(blocks, function (block, idx) {
  69025. if (isTSVFormat(block)) {
  69026. var result = parseTSVContents(block);
  69027. var blockMeta = blockMetaList[idx];
  69028. var axisKey = blockMeta.axisDim + 'Axis';
  69029. if (blockMeta) {
  69030. newOption[axisKey] = newOption[axisKey] || [];
  69031. newOption[axisKey][blockMeta.axisIndex] = {
  69032. data: result.categories
  69033. };
  69034. newOption.series = newOption.series.concat(result.series);
  69035. }
  69036. }
  69037. else {
  69038. var result = parseListContents(block);
  69039. newOption.series.push(result);
  69040. }
  69041. });
  69042. return newOption;
  69043. }
  69044. /**
  69045. * @alias {module:echarts/component/toolbox/feature/DataView}
  69046. * @constructor
  69047. * @param {module:echarts/model/Model} model
  69048. */
  69049. function DataView(model) {
  69050. this._dom = null;
  69051. this.model = model;
  69052. }
  69053. DataView.defaultOption = {
  69054. show: true,
  69055. readOnly: false,
  69056. optionToContent: null,
  69057. contentToOption: null,
  69058. 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',
  69059. title: clone(dataViewLang.title),
  69060. lang: clone(dataViewLang.lang),
  69061. backgroundColor: '#fff',
  69062. textColor: '#000',
  69063. textareaColor: '#fff',
  69064. textareaBorderColor: '#333',
  69065. buttonColor: '#c23531',
  69066. buttonTextColor: '#fff'
  69067. };
  69068. DataView.prototype.onclick = function (ecModel, api) {
  69069. var container = api.getDom();
  69070. var model = this.model;
  69071. if (this._dom) {
  69072. container.removeChild(this._dom);
  69073. }
  69074. var root = document.createElement('div');
  69075. root.style.cssText = 'position:absolute;left:5px;top:5px;bottom:5px;right:5px;';
  69076. root.style.backgroundColor = model.get('backgroundColor') || '#fff';
  69077. // Create elements
  69078. var header = document.createElement('h4');
  69079. var lang$$1 = model.get('lang') || [];
  69080. header.innerHTML = lang$$1[0] || model.get('title');
  69081. header.style.cssText = 'margin: 10px 20px;';
  69082. header.style.color = model.get('textColor');
  69083. var viewMain = document.createElement('div');
  69084. var textarea = document.createElement('textarea');
  69085. viewMain.style.cssText = 'display:block;width:100%;overflow:auto;';
  69086. var optionToContent = model.get('optionToContent');
  69087. var contentToOption = model.get('contentToOption');
  69088. var result = getContentFromModel(ecModel);
  69089. if (typeof optionToContent === 'function') {
  69090. var htmlOrDom = optionToContent(api.getOption());
  69091. if (typeof htmlOrDom === 'string') {
  69092. viewMain.innerHTML = htmlOrDom;
  69093. }
  69094. else if (isDom(htmlOrDom)) {
  69095. viewMain.appendChild(htmlOrDom);
  69096. }
  69097. }
  69098. else {
  69099. // Use default textarea
  69100. viewMain.appendChild(textarea);
  69101. textarea.readOnly = model.get('readOnly');
  69102. textarea.style.cssText = 'width:100%;height:100%;font-family:monospace;font-size:14px;line-height:1.6rem;';
  69103. textarea.style.color = model.get('textColor');
  69104. textarea.style.borderColor = model.get('textareaBorderColor');
  69105. textarea.style.backgroundColor = model.get('textareaColor');
  69106. textarea.value = result.value;
  69107. }
  69108. var blockMetaList = result.meta;
  69109. var buttonContainer = document.createElement('div');
  69110. buttonContainer.style.cssText = 'position:absolute;bottom:0;left:0;right:0;';
  69111. var buttonStyle = 'float:right;margin-right:20px;border:none;'
  69112. + 'cursor:pointer;padding:2px 5px;font-size:12px;border-radius:3px';
  69113. var closeButton = document.createElement('div');
  69114. var refreshButton = document.createElement('div');
  69115. buttonStyle += ';background-color:' + model.get('buttonColor');
  69116. buttonStyle += ';color:' + model.get('buttonTextColor');
  69117. var self = this;
  69118. function close() {
  69119. container.removeChild(root);
  69120. self._dom = null;
  69121. }
  69122. addEventListener(closeButton, 'click', close);
  69123. addEventListener(refreshButton, 'click', function () {
  69124. var newOption;
  69125. try {
  69126. if (typeof contentToOption === 'function') {
  69127. newOption = contentToOption(viewMain, api.getOption());
  69128. }
  69129. else {
  69130. newOption = parseContents(textarea.value, blockMetaList);
  69131. }
  69132. }
  69133. catch (e) {
  69134. close();
  69135. throw new Error('Data view format error ' + e);
  69136. }
  69137. if (newOption) {
  69138. api.dispatchAction({
  69139. type: 'changeDataView',
  69140. newOption: newOption
  69141. });
  69142. }
  69143. close();
  69144. });
  69145. closeButton.innerHTML = lang$$1[1];
  69146. refreshButton.innerHTML = lang$$1[2];
  69147. refreshButton.style.cssText = buttonStyle;
  69148. closeButton.style.cssText = buttonStyle;
  69149. !model.get('readOnly') && buttonContainer.appendChild(refreshButton);
  69150. buttonContainer.appendChild(closeButton);
  69151. root.appendChild(header);
  69152. root.appendChild(viewMain);
  69153. root.appendChild(buttonContainer);
  69154. viewMain.style.height = (container.clientHeight - 80) + 'px';
  69155. container.appendChild(root);
  69156. this._dom = root;
  69157. };
  69158. DataView.prototype.remove = function (ecModel, api) {
  69159. this._dom && api.getDom().removeChild(this._dom);
  69160. };
  69161. DataView.prototype.dispose = function (ecModel, api) {
  69162. this.remove(ecModel, api);
  69163. };
  69164. /**
  69165. * @inner
  69166. */
  69167. function tryMergeDataOption(newData, originalData) {
  69168. return map(newData, function (newVal, idx) {
  69169. var original = originalData && originalData[idx];
  69170. if (isObject$1(original) && !isArray(original)) {
  69171. if (isObject$1(newVal) && !isArray(newVal)) {
  69172. newVal = newVal.value;
  69173. }
  69174. // Original data has option
  69175. return defaults({
  69176. value: newVal
  69177. }, original);
  69178. }
  69179. else {
  69180. return newVal;
  69181. }
  69182. });
  69183. }
  69184. register$1('dataView', DataView);
  69185. registerAction({
  69186. type: 'changeDataView',
  69187. event: 'dataViewChanged',
  69188. update: 'prepareAndUpdate'
  69189. }, function (payload, ecModel) {
  69190. var newSeriesOptList = [];
  69191. each$1(payload.newOption.series, function (seriesOpt) {
  69192. var seriesModel = ecModel.getSeriesByName(seriesOpt.name)[0];
  69193. if (!seriesModel) {
  69194. // New created series
  69195. // Geuss the series type
  69196. newSeriesOptList.push(extend({
  69197. // Default is scatter
  69198. type: 'scatter'
  69199. }, seriesOpt));
  69200. }
  69201. else {
  69202. var originalData = seriesModel.get('data');
  69203. newSeriesOptList.push({
  69204. name: seriesOpt.name,
  69205. data: tryMergeDataOption(seriesOpt.data, originalData)
  69206. });
  69207. }
  69208. });
  69209. ecModel.mergeOption(defaults({
  69210. series: newSeriesOptList
  69211. }, payload.newOption));
  69212. });
  69213. /*
  69214. * Licensed to the Apache Software Foundation (ASF) under one
  69215. * or more contributor license agreements. See the NOTICE file
  69216. * distributed with this work for additional information
  69217. * regarding copyright ownership. The ASF licenses this file
  69218. * to you under the Apache License, Version 2.0 (the
  69219. * "License"); you may not use this file except in compliance
  69220. * with the License. You may obtain a copy of the License at
  69221. *
  69222. * http://www.apache.org/licenses/LICENSE-2.0
  69223. *
  69224. * Unless required by applicable law or agreed to in writing,
  69225. * software distributed under the License is distributed on an
  69226. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  69227. * KIND, either express or implied. See the License for the
  69228. * specific language governing permissions and limitations
  69229. * under the License.
  69230. */
  69231. var each$17 = each$1;
  69232. var indexOf$1 = indexOf;
  69233. var curry$4 = curry;
  69234. var COORD_CONVERTS = ['dataToPoint', 'pointToData'];
  69235. // FIXME
  69236. // how to genarialize to more coordinate systems.
  69237. var INCLUDE_FINDER_MAIN_TYPES = [
  69238. 'grid', 'xAxis', 'yAxis', 'geo', 'graph',
  69239. 'polar', 'radiusAxis', 'angleAxis', 'bmap'
  69240. ];
  69241. /**
  69242. * [option in constructor]:
  69243. * {
  69244. * Index/Id/Name of geo, xAxis, yAxis, grid: See util/model#parseFinder.
  69245. * }
  69246. *
  69247. *
  69248. * [targetInfo]:
  69249. *
  69250. * There can be multiple axes in a single targetInfo. Consider the case
  69251. * of `grid` component, a targetInfo represents a grid which contains one or more
  69252. * cartesian and one or more axes. And consider the case of parallel system,
  69253. * which has multiple axes in a coordinate system.
  69254. * Can be {
  69255. * panelId: ...,
  69256. * coordSys: <a representitive cartesian in grid (first cartesian by default)>,
  69257. * coordSyses: all cartesians.
  69258. * gridModel: <grid component>
  69259. * xAxes: correspond to coordSyses on index
  69260. * yAxes: correspond to coordSyses on index
  69261. * }
  69262. * or {
  69263. * panelId: ...,
  69264. * coordSys: <geo coord sys>
  69265. * coordSyses: [<geo coord sys>]
  69266. * geoModel: <geo component>
  69267. * }
  69268. *
  69269. *
  69270. * [panelOpt]:
  69271. *
  69272. * Make from targetInfo. Input to BrushController.
  69273. * {
  69274. * panelId: ...,
  69275. * rect: ...
  69276. * }
  69277. *
  69278. *
  69279. * [area]:
  69280. *
  69281. * Generated by BrushController or user input.
  69282. * {
  69283. * panelId: Used to locate coordInfo directly. If user inpput, no panelId.
  69284. * brushType: determine how to convert to/from coord('rect' or 'polygon' or 'lineX/Y').
  69285. * Index/Id/Name of geo, xAxis, yAxis, grid: See util/model#parseFinder.
  69286. * range: pixel range.
  69287. * coordRange: representitive coord range (the first one of coordRanges).
  69288. * coordRanges: <Array> coord ranges, used in multiple cartesian in one grid.
  69289. * }
  69290. */
  69291. /**
  69292. * @param {Object} option contains Index/Id/Name of xAxis/yAxis/geo/grid
  69293. * Each can be {number|Array.<number>}. like: {xAxisIndex: [3, 4]}
  69294. * @param {module:echarts/model/Global} ecModel
  69295. * @param {Object} [opt]
  69296. * @param {Array.<string>} [opt.include] include coordinate system types.
  69297. */
  69298. function BrushTargetManager(option, ecModel, opt) {
  69299. /**
  69300. * @private
  69301. * @type {Array.<Object>}
  69302. */
  69303. var targetInfoList = this._targetInfoList = [];
  69304. var info = {};
  69305. var foundCpts = parseFinder$1(ecModel, option);
  69306. each$17(targetInfoBuilders, function (builder, type) {
  69307. if (!opt || !opt.include || indexOf$1(opt.include, type) >= 0) {
  69308. builder(foundCpts, targetInfoList, info);
  69309. }
  69310. });
  69311. }
  69312. var proto$5 = BrushTargetManager.prototype;
  69313. proto$5.setOutputRanges = function (areas, ecModel) {
  69314. this.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  69315. (area.coordRanges || (area.coordRanges = [])).push(coordRange);
  69316. // area.coordRange is the first of area.coordRanges
  69317. if (!area.coordRange) {
  69318. area.coordRange = coordRange;
  69319. // In 'category' axis, coord to pixel is not reversible, so we can not
  69320. // rebuild range by coordRange accrately, which may bring trouble when
  69321. // brushing only one item. So we use __rangeOffset to rebuilding range
  69322. // by coordRange. And this it only used in brush component so it is no
  69323. // need to be adapted to coordRanges.
  69324. var result = coordConvert[area.brushType](0, coordSys, coordRange);
  69325. area.__rangeOffset = {
  69326. offset: diffProcessor[area.brushType](result.values, area.range, [1, 1]),
  69327. xyMinMax: result.xyMinMax
  69328. };
  69329. }
  69330. });
  69331. };
  69332. proto$5.matchOutputRanges = function (areas, ecModel, cb) {
  69333. each$17(areas, function (area) {
  69334. var targetInfo = this.findTargetInfo(area, ecModel);
  69335. if (targetInfo && targetInfo !== true) {
  69336. each$1(
  69337. targetInfo.coordSyses,
  69338. function (coordSys) {
  69339. var result = coordConvert[area.brushType](1, coordSys, area.range);
  69340. cb(area, result.values, coordSys, ecModel);
  69341. }
  69342. );
  69343. }
  69344. }, this);
  69345. };
  69346. proto$5.setInputRanges = function (areas, ecModel) {
  69347. each$17(areas, function (area) {
  69348. var targetInfo = this.findTargetInfo(area, ecModel);
  69349. if (__DEV__) {
  69350. assert$1(
  69351. !targetInfo || targetInfo === true || area.coordRange,
  69352. 'coordRange must be specified when coord index specified.'
  69353. );
  69354. assert$1(
  69355. !targetInfo || targetInfo !== true || area.range,
  69356. 'range must be specified in global brush.'
  69357. );
  69358. }
  69359. area.range = area.range || [];
  69360. // convert coordRange to global range and set panelId.
  69361. if (targetInfo && targetInfo !== true) {
  69362. area.panelId = targetInfo.panelId;
  69363. // (1) area.range shoule always be calculate from coordRange but does
  69364. // not keep its original value, for the sake of the dataZoom scenario,
  69365. // where area.coordRange remains unchanged but area.range may be changed.
  69366. // (2) Only support converting one coordRange to pixel range in brush
  69367. // component. So do not consider `coordRanges`.
  69368. // (3) About __rangeOffset, see comment above.
  69369. var result = coordConvert[area.brushType](0, targetInfo.coordSys, area.coordRange);
  69370. var rangeOffset = area.__rangeOffset;
  69371. area.range = rangeOffset
  69372. ? diffProcessor[area.brushType](
  69373. result.values,
  69374. rangeOffset.offset,
  69375. getScales(result.xyMinMax, rangeOffset.xyMinMax)
  69376. )
  69377. : result.values;
  69378. }
  69379. }, this);
  69380. };
  69381. proto$5.makePanelOpts = function (api, getDefaultBrushType) {
  69382. return map(this._targetInfoList, function (targetInfo) {
  69383. var rect = targetInfo.getPanelRect();
  69384. return {
  69385. panelId: targetInfo.panelId,
  69386. defaultBrushType: getDefaultBrushType && getDefaultBrushType(targetInfo),
  69387. clipPath: makeRectPanelClipPath(rect),
  69388. isTargetByCursor: makeRectIsTargetByCursor(
  69389. rect, api, targetInfo.coordSysModel
  69390. ),
  69391. getLinearBrushOtherExtent: makeLinearBrushOtherExtent(rect)
  69392. };
  69393. });
  69394. };
  69395. proto$5.controlSeries = function (area, seriesModel, ecModel) {
  69396. // Check whether area is bound in coord, and series do not belong to that coord.
  69397. // If do not do this check, some brush (like lineX) will controll all axes.
  69398. var targetInfo = this.findTargetInfo(area, ecModel);
  69399. return targetInfo === true || (
  69400. targetInfo && indexOf$1(targetInfo.coordSyses, seriesModel.coordinateSystem) >= 0
  69401. );
  69402. };
  69403. /**
  69404. * If return Object, a coord found.
  69405. * If reutrn true, global found.
  69406. * Otherwise nothing found.
  69407. *
  69408. * @param {Object} area
  69409. * @param {Array} targetInfoList
  69410. * @return {Object|boolean}
  69411. */
  69412. proto$5.findTargetInfo = function (area, ecModel) {
  69413. var targetInfoList = this._targetInfoList;
  69414. var foundCpts = parseFinder$1(ecModel, area);
  69415. for (var i = 0; i < targetInfoList.length; i++) {
  69416. var targetInfo = targetInfoList[i];
  69417. var areaPanelId = area.panelId;
  69418. if (areaPanelId) {
  69419. if (targetInfo.panelId === areaPanelId) {
  69420. return targetInfo;
  69421. }
  69422. }
  69423. else {
  69424. for (var i = 0; i < targetInfoMatchers.length; i++) {
  69425. if (targetInfoMatchers[i](foundCpts, targetInfo)) {
  69426. return targetInfo;
  69427. }
  69428. }
  69429. }
  69430. }
  69431. return true;
  69432. };
  69433. function formatMinMax(minMax) {
  69434. minMax[0] > minMax[1] && minMax.reverse();
  69435. return minMax;
  69436. }
  69437. function parseFinder$1(ecModel, option) {
  69438. return parseFinder(
  69439. ecModel, option, {includeMainTypes: INCLUDE_FINDER_MAIN_TYPES}
  69440. );
  69441. }
  69442. var targetInfoBuilders = {
  69443. grid: function (foundCpts, targetInfoList) {
  69444. var xAxisModels = foundCpts.xAxisModels;
  69445. var yAxisModels = foundCpts.yAxisModels;
  69446. var gridModels = foundCpts.gridModels;
  69447. // Remove duplicated.
  69448. var gridModelMap = createHashMap();
  69449. var xAxesHas = {};
  69450. var yAxesHas = {};
  69451. if (!xAxisModels && !yAxisModels && !gridModels) {
  69452. return;
  69453. }
  69454. each$17(xAxisModels, function (axisModel) {
  69455. var gridModel = axisModel.axis.grid.model;
  69456. gridModelMap.set(gridModel.id, gridModel);
  69457. xAxesHas[gridModel.id] = true;
  69458. });
  69459. each$17(yAxisModels, function (axisModel) {
  69460. var gridModel = axisModel.axis.grid.model;
  69461. gridModelMap.set(gridModel.id, gridModel);
  69462. yAxesHas[gridModel.id] = true;
  69463. });
  69464. each$17(gridModels, function (gridModel) {
  69465. gridModelMap.set(gridModel.id, gridModel);
  69466. xAxesHas[gridModel.id] = true;
  69467. yAxesHas[gridModel.id] = true;
  69468. });
  69469. gridModelMap.each(function (gridModel) {
  69470. var grid = gridModel.coordinateSystem;
  69471. var cartesians = [];
  69472. each$17(grid.getCartesians(), function (cartesian, index) {
  69473. if (indexOf$1(xAxisModels, cartesian.getAxis('x').model) >= 0
  69474. || indexOf$1(yAxisModels, cartesian.getAxis('y').model) >= 0
  69475. ) {
  69476. cartesians.push(cartesian);
  69477. }
  69478. });
  69479. targetInfoList.push({
  69480. panelId: 'grid--' + gridModel.id,
  69481. gridModel: gridModel,
  69482. coordSysModel: gridModel,
  69483. // Use the first one as the representitive coordSys.
  69484. coordSys: cartesians[0],
  69485. coordSyses: cartesians,
  69486. getPanelRect: panelRectBuilder.grid,
  69487. xAxisDeclared: xAxesHas[gridModel.id],
  69488. yAxisDeclared: yAxesHas[gridModel.id]
  69489. });
  69490. });
  69491. },
  69492. geo: function (foundCpts, targetInfoList) {
  69493. each$17(foundCpts.geoModels, function (geoModel) {
  69494. var coordSys = geoModel.coordinateSystem;
  69495. targetInfoList.push({
  69496. panelId: 'geo--' + geoModel.id,
  69497. geoModel: geoModel,
  69498. coordSysModel: geoModel,
  69499. coordSys: coordSys,
  69500. coordSyses: [coordSys],
  69501. getPanelRect: panelRectBuilder.geo
  69502. });
  69503. });
  69504. }
  69505. };
  69506. var targetInfoMatchers = [
  69507. // grid
  69508. function (foundCpts, targetInfo) {
  69509. var xAxisModel = foundCpts.xAxisModel;
  69510. var yAxisModel = foundCpts.yAxisModel;
  69511. var gridModel = foundCpts.gridModel;
  69512. !gridModel && xAxisModel && (gridModel = xAxisModel.axis.grid.model);
  69513. !gridModel && yAxisModel && (gridModel = yAxisModel.axis.grid.model);
  69514. return gridModel && gridModel === targetInfo.gridModel;
  69515. },
  69516. // geo
  69517. function (foundCpts, targetInfo) {
  69518. var geoModel = foundCpts.geoModel;
  69519. return geoModel && geoModel === targetInfo.geoModel;
  69520. }
  69521. ];
  69522. var panelRectBuilder = {
  69523. grid: function () {
  69524. // grid is not Transformable.
  69525. return this.coordSys.grid.getRect().clone();
  69526. },
  69527. geo: function () {
  69528. var coordSys = this.coordSys;
  69529. var rect = coordSys.getBoundingRect().clone();
  69530. // geo roam and zoom transform
  69531. rect.applyTransform(getTransform(coordSys));
  69532. return rect;
  69533. }
  69534. };
  69535. var coordConvert = {
  69536. lineX: curry$4(axisConvert, 0),
  69537. lineY: curry$4(axisConvert, 1),
  69538. rect: function (to, coordSys, rangeOrCoordRange) {
  69539. var xminymin = coordSys[COORD_CONVERTS[to]]([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]]);
  69540. var xmaxymax = coordSys[COORD_CONVERTS[to]]([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]]);
  69541. var values = [
  69542. formatMinMax([xminymin[0], xmaxymax[0]]),
  69543. formatMinMax([xminymin[1], xmaxymax[1]])
  69544. ];
  69545. return {values: values, xyMinMax: values};
  69546. },
  69547. polygon: function (to, coordSys, rangeOrCoordRange) {
  69548. var xyMinMax = [[Infinity, -Infinity], [Infinity, -Infinity]];
  69549. var values = map(rangeOrCoordRange, function (item) {
  69550. var p = coordSys[COORD_CONVERTS[to]](item);
  69551. xyMinMax[0][0] = Math.min(xyMinMax[0][0], p[0]);
  69552. xyMinMax[1][0] = Math.min(xyMinMax[1][0], p[1]);
  69553. xyMinMax[0][1] = Math.max(xyMinMax[0][1], p[0]);
  69554. xyMinMax[1][1] = Math.max(xyMinMax[1][1], p[1]);
  69555. return p;
  69556. });
  69557. return {values: values, xyMinMax: xyMinMax};
  69558. }
  69559. };
  69560. function axisConvert(axisNameIndex, to, coordSys, rangeOrCoordRange) {
  69561. if (__DEV__) {
  69562. assert$1(
  69563. coordSys.type === 'cartesian2d',
  69564. 'lineX/lineY brush is available only in cartesian2d.'
  69565. );
  69566. }
  69567. var axis = coordSys.getAxis(['x', 'y'][axisNameIndex]);
  69568. var values = formatMinMax(map([0, 1], function (i) {
  69569. return to
  69570. ? axis.coordToData(axis.toLocalCoord(rangeOrCoordRange[i]))
  69571. : axis.toGlobalCoord(axis.dataToCoord(rangeOrCoordRange[i]));
  69572. }));
  69573. var xyMinMax = [];
  69574. xyMinMax[axisNameIndex] = values;
  69575. xyMinMax[1 - axisNameIndex] = [NaN, NaN];
  69576. return {values: values, xyMinMax: xyMinMax};
  69577. }
  69578. var diffProcessor = {
  69579. lineX: curry$4(axisDiffProcessor, 0),
  69580. lineY: curry$4(axisDiffProcessor, 1),
  69581. rect: function (values, refer, scales) {
  69582. return [
  69583. [values[0][0] - scales[0] * refer[0][0], values[0][1] - scales[0] * refer[0][1]],
  69584. [values[1][0] - scales[1] * refer[1][0], values[1][1] - scales[1] * refer[1][1]]
  69585. ];
  69586. },
  69587. polygon: function (values, refer, scales) {
  69588. return map(values, function (item, idx) {
  69589. return [item[0] - scales[0] * refer[idx][0], item[1] - scales[1] * refer[idx][1]];
  69590. });
  69591. }
  69592. };
  69593. function axisDiffProcessor(axisNameIndex, values, refer, scales) {
  69594. return [
  69595. values[0] - scales[axisNameIndex] * refer[0],
  69596. values[1] - scales[axisNameIndex] * refer[1]
  69597. ];
  69598. }
  69599. // We have to process scale caused by dataZoom manually,
  69600. // although it might be not accurate.
  69601. function getScales(xyMinMaxCurr, xyMinMaxOrigin) {
  69602. var sizeCurr = getSize(xyMinMaxCurr);
  69603. var sizeOrigin = getSize(xyMinMaxOrigin);
  69604. var scales = [sizeCurr[0] / sizeOrigin[0], sizeCurr[1] / sizeOrigin[1]];
  69605. isNaN(scales[0]) && (scales[0] = 1);
  69606. isNaN(scales[1]) && (scales[1] = 1);
  69607. return scales;
  69608. }
  69609. function getSize(xyMinMax) {
  69610. return xyMinMax
  69611. ? [xyMinMax[0][1] - xyMinMax[0][0], xyMinMax[1][1] - xyMinMax[1][0]]
  69612. : [NaN, NaN];
  69613. }
  69614. /*
  69615. * Licensed to the Apache Software Foundation (ASF) under one
  69616. * or more contributor license agreements. See the NOTICE file
  69617. * distributed with this work for additional information
  69618. * regarding copyright ownership. The ASF licenses this file
  69619. * to you under the Apache License, Version 2.0 (the
  69620. * "License"); you may not use this file except in compliance
  69621. * with the License. You may obtain a copy of the License at
  69622. *
  69623. * http://www.apache.org/licenses/LICENSE-2.0
  69624. *
  69625. * Unless required by applicable law or agreed to in writing,
  69626. * software distributed under the License is distributed on an
  69627. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  69628. * KIND, either express or implied. See the License for the
  69629. * specific language governing permissions and limitations
  69630. * under the License.
  69631. */
  69632. var each$18 = each$1;
  69633. var ATTR$1 = '\0_ec_hist_store';
  69634. /**
  69635. * @param {module:echarts/model/Global} ecModel
  69636. * @param {Object} newSnapshot {dataZoomId, batch: [payloadInfo, ...]}
  69637. */
  69638. function push(ecModel, newSnapshot) {
  69639. var store = giveStore(ecModel);
  69640. // If previous dataZoom can not be found,
  69641. // complete an range with current range.
  69642. each$18(newSnapshot, function (batchItem, dataZoomId) {
  69643. var i = store.length - 1;
  69644. for (; i >= 0; i--) {
  69645. var snapshot = store[i];
  69646. if (snapshot[dataZoomId]) {
  69647. break;
  69648. }
  69649. }
  69650. if (i < 0) {
  69651. // No origin range set, create one by current range.
  69652. var dataZoomModel = ecModel.queryComponents(
  69653. {mainType: 'dataZoom', subType: 'select', id: dataZoomId}
  69654. )[0];
  69655. if (dataZoomModel) {
  69656. var percentRange = dataZoomModel.getPercentRange();
  69657. store[0][dataZoomId] = {
  69658. dataZoomId: dataZoomId,
  69659. start: percentRange[0],
  69660. end: percentRange[1]
  69661. };
  69662. }
  69663. }
  69664. });
  69665. store.push(newSnapshot);
  69666. }
  69667. /**
  69668. * @param {module:echarts/model/Global} ecModel
  69669. * @return {Object} snapshot
  69670. */
  69671. function pop(ecModel) {
  69672. var store = giveStore(ecModel);
  69673. var head = store[store.length - 1];
  69674. store.length > 1 && store.pop();
  69675. // Find top for all dataZoom.
  69676. var snapshot = {};
  69677. each$18(head, function (batchItem, dataZoomId) {
  69678. for (var i = store.length - 1; i >= 0; i--) {
  69679. var batchItem = store[i][dataZoomId];
  69680. if (batchItem) {
  69681. snapshot[dataZoomId] = batchItem;
  69682. break;
  69683. }
  69684. }
  69685. });
  69686. return snapshot;
  69687. }
  69688. /**
  69689. * @param {module:echarts/model/Global} ecModel
  69690. */
  69691. function clear$1(ecModel) {
  69692. ecModel[ATTR$1] = null;
  69693. }
  69694. /**
  69695. * @param {module:echarts/model/Global} ecModel
  69696. * @return {number} records. always >= 1.
  69697. */
  69698. function count(ecModel) {
  69699. return giveStore(ecModel).length;
  69700. }
  69701. /**
  69702. * [{key: dataZoomId, value: {dataZoomId, range}}, ...]
  69703. * History length of each dataZoom may be different.
  69704. * this._history[0] is used to store origin range.
  69705. * @type {Array.<Object>}
  69706. */
  69707. function giveStore(ecModel) {
  69708. var store = ecModel[ATTR$1];
  69709. if (!store) {
  69710. store = ecModel[ATTR$1] = [{}];
  69711. }
  69712. return store;
  69713. }
  69714. /*
  69715. * Licensed to the Apache Software Foundation (ASF) under one
  69716. * or more contributor license agreements. See the NOTICE file
  69717. * distributed with this work for additional information
  69718. * regarding copyright ownership. The ASF licenses this file
  69719. * to you under the Apache License, Version 2.0 (the
  69720. * "License"); you may not use this file except in compliance
  69721. * with the License. You may obtain a copy of the License at
  69722. *
  69723. * http://www.apache.org/licenses/LICENSE-2.0
  69724. *
  69725. * Unless required by applicable law or agreed to in writing,
  69726. * software distributed under the License is distributed on an
  69727. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  69728. * KIND, either express or implied. See the License for the
  69729. * specific language governing permissions and limitations
  69730. * under the License.
  69731. */
  69732. ComponentModel.registerSubTypeDefaulter('dataZoom', function () {
  69733. // Default 'slider' when no type specified.
  69734. return 'slider';
  69735. });
  69736. /*
  69737. * Licensed to the Apache Software Foundation (ASF) under one
  69738. * or more contributor license agreements. See the NOTICE file
  69739. * distributed with this work for additional information
  69740. * regarding copyright ownership. The ASF licenses this file
  69741. * to you under the Apache License, Version 2.0 (the
  69742. * "License"); you may not use this file except in compliance
  69743. * with the License. You may obtain a copy of the License at
  69744. *
  69745. * http://www.apache.org/licenses/LICENSE-2.0
  69746. *
  69747. * Unless required by applicable law or agreed to in writing,
  69748. * software distributed under the License is distributed on an
  69749. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  69750. * KIND, either express or implied. See the License for the
  69751. * specific language governing permissions and limitations
  69752. * under the License.
  69753. */
  69754. var AXIS_DIMS = ['x', 'y', 'z', 'radius', 'angle', 'single'];
  69755. // Supported coords.
  69756. var COORDS = ['cartesian2d', 'polar', 'singleAxis'];
  69757. /**
  69758. * @param {string} coordType
  69759. * @return {boolean}
  69760. */
  69761. function isCoordSupported(coordType) {
  69762. return indexOf(COORDS, coordType) >= 0;
  69763. }
  69764. /**
  69765. * Create "each" method to iterate names.
  69766. *
  69767. * @pubilc
  69768. * @param {Array.<string>} names
  69769. * @param {Array.<string>=} attrs
  69770. * @return {Function}
  69771. */
  69772. function createNameEach(names, attrs) {
  69773. names = names.slice();
  69774. var capitalNames = map(names, capitalFirst);
  69775. attrs = (attrs || []).slice();
  69776. var capitalAttrs = map(attrs, capitalFirst);
  69777. return function (callback, context) {
  69778. each$1(names, function (name, index) {
  69779. var nameObj = {name: name, capital: capitalNames[index]};
  69780. for (var j = 0; j < attrs.length; j++) {
  69781. nameObj[attrs[j]] = name + capitalAttrs[j];
  69782. }
  69783. callback.call(context, nameObj);
  69784. });
  69785. };
  69786. }
  69787. /**
  69788. * Iterate each dimension name.
  69789. *
  69790. * @public
  69791. * @param {Function} callback The parameter is like:
  69792. * {
  69793. * name: 'angle',
  69794. * capital: 'Angle',
  69795. * axis: 'angleAxis',
  69796. * axisIndex: 'angleAixs',
  69797. * index: 'angleIndex'
  69798. * }
  69799. * @param {Object} context
  69800. */
  69801. var eachAxisDim$1 = createNameEach(AXIS_DIMS, ['axisIndex', 'axis', 'index', 'id']);
  69802. /**
  69803. * If tow dataZoomModels has the same axis controlled, we say that they are 'linked'.
  69804. * dataZoomModels and 'links' make up one or more graphics.
  69805. * This function finds the graphic where the source dataZoomModel is in.
  69806. *
  69807. * @public
  69808. * @param {Function} forEachNode Node iterator.
  69809. * @param {Function} forEachEdgeType edgeType iterator
  69810. * @param {Function} edgeIdGetter Giving node and edgeType, return an array of edge id.
  69811. * @return {Function} Input: sourceNode, Output: Like {nodes: [], dims: {}}
  69812. */
  69813. function createLinkedNodesFinder(forEachNode, forEachEdgeType, edgeIdGetter) {
  69814. return function (sourceNode) {
  69815. var result = {
  69816. nodes: [],
  69817. records: {} // key: edgeType.name, value: Object (key: edge id, value: boolean).
  69818. };
  69819. forEachEdgeType(function (edgeType) {
  69820. result.records[edgeType.name] = {};
  69821. });
  69822. if (!sourceNode) {
  69823. return result;
  69824. }
  69825. absorb(sourceNode, result);
  69826. var existsLink;
  69827. do {
  69828. existsLink = false;
  69829. forEachNode(processSingleNode);
  69830. }
  69831. while (existsLink);
  69832. function processSingleNode(node) {
  69833. if (!isNodeAbsorded(node, result) && isLinked(node, result)) {
  69834. absorb(node, result);
  69835. existsLink = true;
  69836. }
  69837. }
  69838. return result;
  69839. };
  69840. function isNodeAbsorded(node, result) {
  69841. return indexOf(result.nodes, node) >= 0;
  69842. }
  69843. function isLinked(node, result) {
  69844. var hasLink = false;
  69845. forEachEdgeType(function (edgeType) {
  69846. each$1(edgeIdGetter(node, edgeType) || [], function (edgeId) {
  69847. result.records[edgeType.name][edgeId] && (hasLink = true);
  69848. });
  69849. });
  69850. return hasLink;
  69851. }
  69852. function absorb(node, result) {
  69853. result.nodes.push(node);
  69854. forEachEdgeType(function (edgeType) {
  69855. each$1(edgeIdGetter(node, edgeType) || [], function (edgeId) {
  69856. result.records[edgeType.name][edgeId] = true;
  69857. });
  69858. });
  69859. }
  69860. }
  69861. /*
  69862. * Licensed to the Apache Software Foundation (ASF) under one
  69863. * or more contributor license agreements. See the NOTICE file
  69864. * distributed with this work for additional information
  69865. * regarding copyright ownership. The ASF licenses this file
  69866. * to you under the Apache License, Version 2.0 (the
  69867. * "License"); you may not use this file except in compliance
  69868. * with the License. You may obtain a copy of the License at
  69869. *
  69870. * http://www.apache.org/licenses/LICENSE-2.0
  69871. *
  69872. * Unless required by applicable law or agreed to in writing,
  69873. * software distributed under the License is distributed on an
  69874. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  69875. * KIND, either express or implied. See the License for the
  69876. * specific language governing permissions and limitations
  69877. * under the License.
  69878. */
  69879. var each$20 = each$1;
  69880. var asc$1 = asc;
  69881. /**
  69882. * Operate single axis.
  69883. * One axis can only operated by one axis operator.
  69884. * Different dataZoomModels may be defined to operate the same axis.
  69885. * (i.e. 'inside' data zoom and 'slider' data zoom components)
  69886. * So dataZoomModels share one axisProxy in that case.
  69887. *
  69888. * @class
  69889. */
  69890. var AxisProxy = function (dimName, axisIndex, dataZoomModel, ecModel) {
  69891. /**
  69892. * @private
  69893. * @type {string}
  69894. */
  69895. this._dimName = dimName;
  69896. /**
  69897. * @private
  69898. */
  69899. this._axisIndex = axisIndex;
  69900. /**
  69901. * @private
  69902. * @type {Array.<number>}
  69903. */
  69904. this._valueWindow;
  69905. /**
  69906. * @private
  69907. * @type {Array.<number>}
  69908. */
  69909. this._percentWindow;
  69910. /**
  69911. * @private
  69912. * @type {Array.<number>}
  69913. */
  69914. this._dataExtent;
  69915. /**
  69916. * {minSpan, maxSpan, minValueSpan, maxValueSpan}
  69917. * @private
  69918. * @type {Object}
  69919. */
  69920. this._minMaxSpan;
  69921. /**
  69922. * @readOnly
  69923. * @type {module: echarts/model/Global}
  69924. */
  69925. this.ecModel = ecModel;
  69926. /**
  69927. * @private
  69928. * @type {module: echarts/component/dataZoom/DataZoomModel}
  69929. */
  69930. this._dataZoomModel = dataZoomModel;
  69931. // /**
  69932. // * @readOnly
  69933. // * @private
  69934. // */
  69935. // this.hasSeriesStacked;
  69936. };
  69937. AxisProxy.prototype = {
  69938. constructor: AxisProxy,
  69939. /**
  69940. * Whether the axisProxy is hosted by dataZoomModel.
  69941. *
  69942. * @public
  69943. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  69944. * @return {boolean}
  69945. */
  69946. hostedBy: function (dataZoomModel) {
  69947. return this._dataZoomModel === dataZoomModel;
  69948. },
  69949. /**
  69950. * @return {Array.<number>} Value can only be NaN or finite value.
  69951. */
  69952. getDataValueWindow: function () {
  69953. return this._valueWindow.slice();
  69954. },
  69955. /**
  69956. * @return {Array.<number>}
  69957. */
  69958. getDataPercentWindow: function () {
  69959. return this._percentWindow.slice();
  69960. },
  69961. /**
  69962. * @public
  69963. * @param {number} axisIndex
  69964. * @return {Array} seriesModels
  69965. */
  69966. getTargetSeriesModels: function () {
  69967. var seriesModels = [];
  69968. var ecModel = this.ecModel;
  69969. ecModel.eachSeries(function (seriesModel) {
  69970. if (isCoordSupported(seriesModel.get('coordinateSystem'))) {
  69971. var dimName = this._dimName;
  69972. var axisModel = ecModel.queryComponents({
  69973. mainType: dimName + 'Axis',
  69974. index: seriesModel.get(dimName + 'AxisIndex'),
  69975. id: seriesModel.get(dimName + 'AxisId')
  69976. })[0];
  69977. if (this._axisIndex === (axisModel && axisModel.componentIndex)) {
  69978. seriesModels.push(seriesModel);
  69979. }
  69980. }
  69981. }, this);
  69982. return seriesModels;
  69983. },
  69984. getAxisModel: function () {
  69985. return this.ecModel.getComponent(this._dimName + 'Axis', this._axisIndex);
  69986. },
  69987. getOtherAxisModel: function () {
  69988. var axisDim = this._dimName;
  69989. var ecModel = this.ecModel;
  69990. var axisModel = this.getAxisModel();
  69991. var isCartesian = axisDim === 'x' || axisDim === 'y';
  69992. var otherAxisDim;
  69993. var coordSysIndexName;
  69994. if (isCartesian) {
  69995. coordSysIndexName = 'gridIndex';
  69996. otherAxisDim = axisDim === 'x' ? 'y' : 'x';
  69997. }
  69998. else {
  69999. coordSysIndexName = 'polarIndex';
  70000. otherAxisDim = axisDim === 'angle' ? 'radius' : 'angle';
  70001. }
  70002. var foundOtherAxisModel;
  70003. ecModel.eachComponent(otherAxisDim + 'Axis', function (otherAxisModel) {
  70004. if ((otherAxisModel.get(coordSysIndexName) || 0)
  70005. === (axisModel.get(coordSysIndexName) || 0)
  70006. ) {
  70007. foundOtherAxisModel = otherAxisModel;
  70008. }
  70009. });
  70010. return foundOtherAxisModel;
  70011. },
  70012. getMinMaxSpan: function () {
  70013. return clone(this._minMaxSpan);
  70014. },
  70015. /**
  70016. * Only calculate by given range and this._dataExtent, do not change anything.
  70017. *
  70018. * @param {Object} opt
  70019. * @param {number} [opt.start]
  70020. * @param {number} [opt.end]
  70021. * @param {number} [opt.startValue]
  70022. * @param {number} [opt.endValue]
  70023. */
  70024. calculateDataWindow: function (opt) {
  70025. var dataExtent = this._dataExtent;
  70026. var axisModel = this.getAxisModel();
  70027. var scale = axisModel.axis.scale;
  70028. var rangePropMode = this._dataZoomModel.getRangePropMode();
  70029. var percentExtent = [0, 100];
  70030. var percentWindow = [];
  70031. var valueWindow = [];
  70032. var hasPropModeValue;
  70033. each$20(['start', 'end'], function (prop, idx) {
  70034. var boundPercent = opt[prop];
  70035. var boundValue = opt[prop + 'Value'];
  70036. // Notice: dataZoom is based either on `percentProp` ('start', 'end') or
  70037. // on `valueProp` ('startValue', 'endValue'). (They are based on the data extent
  70038. // but not min/max of axis, which will be calculated by data window then).
  70039. // The former one is suitable for cases that a dataZoom component controls multiple
  70040. // axes with different unit or extent, and the latter one is suitable for accurate
  70041. // zoom by pixel (e.g., in dataZoomSelect).
  70042. // we use `getRangePropMode()` to mark which prop is used. `rangePropMode` is updated
  70043. // only when setOption or dispatchAction, otherwise it remains its original value.
  70044. // (Why not only record `percentProp` and always map to `valueProp`? Because
  70045. // the map `valueProp` -> `percentProp` -> `valueProp` probably not the original
  70046. // `valueProp`. consider two axes constrolled by one dataZoom. They have different
  70047. // data extent. All of values that are overflow the `dataExtent` will be calculated
  70048. // to percent '100%').
  70049. if (rangePropMode[idx] === 'percent') {
  70050. boundPercent == null && (boundPercent = percentExtent[idx]);
  70051. // Use scale.parse to math round for category or time axis.
  70052. boundValue = scale.parse(linearMap(
  70053. boundPercent, percentExtent, dataExtent
  70054. ));
  70055. }
  70056. else {
  70057. hasPropModeValue = true;
  70058. boundValue = boundValue == null ? dataExtent[idx] : scale.parse(boundValue);
  70059. // Calculating `percent` from `value` may be not accurate, because
  70060. // This calculation can not be inversed, because all of values that
  70061. // are overflow the `dataExtent` will be calculated to percent '100%'
  70062. boundPercent = linearMap(
  70063. boundValue, dataExtent, percentExtent
  70064. );
  70065. }
  70066. // valueWindow[idx] = round(boundValue);
  70067. // percentWindow[idx] = round(boundPercent);
  70068. valueWindow[idx] = boundValue;
  70069. percentWindow[idx] = boundPercent;
  70070. });
  70071. asc$1(valueWindow);
  70072. asc$1(percentWindow);
  70073. // The windows from user calling of `dispatchAction` might be out of the extent,
  70074. // or do not obey the `min/maxSpan`, `min/maxValueSpan`. But we dont restrict window
  70075. // by `zoomLock` here, because we see `zoomLock` just as a interaction constraint,
  70076. // where API is able to initialize/modify the window size even though `zoomLock`
  70077. // specified.
  70078. var spans = this._minMaxSpan;
  70079. hasPropModeValue
  70080. ? restrictSet(valueWindow, percentWindow, dataExtent, percentExtent, false)
  70081. : restrictSet(percentWindow, valueWindow, percentExtent, dataExtent, true);
  70082. function restrictSet(fromWindow, toWindow, fromExtent, toExtent, toValue) {
  70083. var suffix = toValue ? 'Span' : 'ValueSpan';
  70084. sliderMove(0, fromWindow, fromExtent, 'all', spans['min' + suffix], spans['max' + suffix]);
  70085. for (var i = 0; i < 2; i++) {
  70086. toWindow[i] = linearMap(fromWindow[i], fromExtent, toExtent, true);
  70087. toValue && (toWindow[i] = scale.parse(toWindow[i]));
  70088. }
  70089. }
  70090. return {
  70091. valueWindow: valueWindow,
  70092. percentWindow: percentWindow
  70093. };
  70094. },
  70095. /**
  70096. * Notice: reset should not be called before series.restoreData() called,
  70097. * so it is recommanded to be called in "process stage" but not "model init
  70098. * stage".
  70099. *
  70100. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  70101. */
  70102. reset: function (dataZoomModel) {
  70103. if (dataZoomModel !== this._dataZoomModel) {
  70104. return;
  70105. }
  70106. var targetSeries = this.getTargetSeriesModels();
  70107. // Culculate data window and data extent, and record them.
  70108. this._dataExtent = calculateDataExtent(this, this._dimName, targetSeries);
  70109. // this.hasSeriesStacked = false;
  70110. // each(targetSeries, function (series) {
  70111. // var data = series.getData();
  70112. // var dataDim = data.mapDimension(this._dimName);
  70113. // var stackedDimension = data.getCalculationInfo('stackedDimension');
  70114. // if (stackedDimension && stackedDimension === dataDim) {
  70115. // this.hasSeriesStacked = true;
  70116. // }
  70117. // }, this);
  70118. // `calculateDataWindow` uses min/maxSpan.
  70119. setMinMaxSpan(this);
  70120. var dataWindow = this.calculateDataWindow(dataZoomModel.settledOption);
  70121. this._valueWindow = dataWindow.valueWindow;
  70122. this._percentWindow = dataWindow.percentWindow;
  70123. // Update axis setting then.
  70124. setAxisModel(this);
  70125. },
  70126. /**
  70127. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  70128. */
  70129. restore: function (dataZoomModel) {
  70130. if (dataZoomModel !== this._dataZoomModel) {
  70131. return;
  70132. }
  70133. this._valueWindow = this._percentWindow = null;
  70134. setAxisModel(this, true);
  70135. },
  70136. /**
  70137. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  70138. */
  70139. filterData: function (dataZoomModel, api) {
  70140. if (dataZoomModel !== this._dataZoomModel) {
  70141. return;
  70142. }
  70143. var axisDim = this._dimName;
  70144. var seriesModels = this.getTargetSeriesModels();
  70145. var filterMode = dataZoomModel.get('filterMode');
  70146. var valueWindow = this._valueWindow;
  70147. if (filterMode === 'none') {
  70148. return;
  70149. }
  70150. // FIXME
  70151. // Toolbox may has dataZoom injected. And if there are stacked bar chart
  70152. // with NaN data, NaN will be filtered and stack will be wrong.
  70153. // So we need to force the mode to be set empty.
  70154. // In fect, it is not a big deal that do not support filterMode-'filter'
  70155. // when using toolbox#dataZoom, utill tooltip#dataZoom support "single axis
  70156. // selection" some day, which might need "adapt to data extent on the
  70157. // otherAxis", which is disabled by filterMode-'empty'.
  70158. // But currently, stack has been fixed to based on value but not index,
  70159. // so this is not an issue any more.
  70160. // var otherAxisModel = this.getOtherAxisModel();
  70161. // if (dataZoomModel.get('$fromToolbox')
  70162. // && otherAxisModel
  70163. // && otherAxisModel.hasSeriesStacked
  70164. // ) {
  70165. // filterMode = 'empty';
  70166. // }
  70167. // TODO
  70168. // filterMode 'weakFilter' and 'empty' is not optimized for huge data yet.
  70169. each$20(seriesModels, function (seriesModel) {
  70170. var seriesData = seriesModel.getData();
  70171. var dataDims = seriesData.mapDimension(axisDim, true);
  70172. if (!dataDims.length) {
  70173. return;
  70174. }
  70175. if (filterMode === 'weakFilter') {
  70176. seriesData.filterSelf(function (dataIndex) {
  70177. var leftOut;
  70178. var rightOut;
  70179. var hasValue;
  70180. for (var i = 0; i < dataDims.length; i++) {
  70181. var value = seriesData.get(dataDims[i], dataIndex);
  70182. var thisHasValue = !isNaN(value);
  70183. var thisLeftOut = value < valueWindow[0];
  70184. var thisRightOut = value > valueWindow[1];
  70185. if (thisHasValue && !thisLeftOut && !thisRightOut) {
  70186. return true;
  70187. }
  70188. thisHasValue && (hasValue = true);
  70189. thisLeftOut && (leftOut = true);
  70190. thisRightOut && (rightOut = true);
  70191. }
  70192. // If both left out and right out, do not filter.
  70193. return hasValue && leftOut && rightOut;
  70194. });
  70195. }
  70196. else {
  70197. each$20(dataDims, function (dim) {
  70198. if (filterMode === 'empty') {
  70199. seriesModel.setData(
  70200. seriesData = seriesData.map(dim, function (value) {
  70201. return !isInWindow(value) ? NaN : value;
  70202. })
  70203. );
  70204. }
  70205. else {
  70206. var range = {};
  70207. range[dim] = valueWindow;
  70208. // console.time('select');
  70209. seriesData.selectRange(range);
  70210. // console.timeEnd('select');
  70211. }
  70212. });
  70213. }
  70214. each$20(dataDims, function (dim) {
  70215. seriesData.setApproximateExtent(valueWindow, dim);
  70216. });
  70217. });
  70218. function isInWindow(value) {
  70219. return value >= valueWindow[0] && value <= valueWindow[1];
  70220. }
  70221. }
  70222. };
  70223. function calculateDataExtent(axisProxy, axisDim, seriesModels) {
  70224. var dataExtent = [Infinity, -Infinity];
  70225. each$20(seriesModels, function (seriesModel) {
  70226. var seriesData = seriesModel.getData();
  70227. if (seriesData) {
  70228. each$20(seriesData.mapDimension(axisDim, true), function (dim) {
  70229. var seriesExtent = seriesData.getApproximateExtent(dim);
  70230. seriesExtent[0] < dataExtent[0] && (dataExtent[0] = seriesExtent[0]);
  70231. seriesExtent[1] > dataExtent[1] && (dataExtent[1] = seriesExtent[1]);
  70232. });
  70233. }
  70234. });
  70235. if (dataExtent[1] < dataExtent[0]) {
  70236. dataExtent = [NaN, NaN];
  70237. }
  70238. // It is important to get "consistent" extent when more then one axes is
  70239. // controlled by a `dataZoom`, otherwise those axes will not be synchronized
  70240. // when zooming. But it is difficult to know what is "consistent", considering
  70241. // axes have different type or even different meanings (For example, two
  70242. // time axes are used to compare data of the same date in different years).
  70243. // So basically dataZoom just obtains extent by series.data (in category axis
  70244. // extent can be obtained from axis.data).
  70245. // Nevertheless, user can set min/max/scale on axes to make extent of axes
  70246. // consistent.
  70247. fixExtentByAxis(axisProxy, dataExtent);
  70248. return dataExtent;
  70249. }
  70250. function fixExtentByAxis(axisProxy, dataExtent) {
  70251. var axisModel = axisProxy.getAxisModel();
  70252. var min = axisModel.getMin(true);
  70253. // For category axis, if min/max/scale are not set, extent is determined
  70254. // by axis.data by default.
  70255. var isCategoryAxis = axisModel.get('type') === 'category';
  70256. var axisDataLen = isCategoryAxis && axisModel.getCategories().length;
  70257. if (min != null && min !== 'dataMin' && typeof min !== 'function') {
  70258. dataExtent[0] = min;
  70259. }
  70260. else if (isCategoryAxis) {
  70261. dataExtent[0] = axisDataLen > 0 ? 0 : NaN;
  70262. }
  70263. var max = axisModel.getMax(true);
  70264. if (max != null && max !== 'dataMax' && typeof max !== 'function') {
  70265. dataExtent[1] = max;
  70266. }
  70267. else if (isCategoryAxis) {
  70268. dataExtent[1] = axisDataLen > 0 ? axisDataLen - 1 : NaN;
  70269. }
  70270. if (!axisModel.get('scale', true)) {
  70271. dataExtent[0] > 0 && (dataExtent[0] = 0);
  70272. dataExtent[1] < 0 && (dataExtent[1] = 0);
  70273. }
  70274. // For value axis, if min/max/scale are not set, we just use the extent obtained
  70275. // by series data, which may be a little different from the extent calculated by
  70276. // `axisHelper.getScaleExtent`. But the different just affects the experience a
  70277. // little when zooming. So it will not be fixed until some users require it strongly.
  70278. return dataExtent;
  70279. }
  70280. function setAxisModel(axisProxy, isRestore) {
  70281. var axisModel = axisProxy.getAxisModel();
  70282. var percentWindow = axisProxy._percentWindow;
  70283. var valueWindow = axisProxy._valueWindow;
  70284. if (!percentWindow) {
  70285. return;
  70286. }
  70287. // [0, 500]: arbitrary value, guess axis extent.
  70288. var precision = getPixelPrecision(valueWindow, [0, 500]);
  70289. precision = Math.min(precision, 20);
  70290. // isRestore or isFull
  70291. var useOrigin = isRestore || (percentWindow[0] === 0 && percentWindow[1] === 100);
  70292. axisModel.setRange(
  70293. useOrigin ? null : +valueWindow[0].toFixed(precision),
  70294. useOrigin ? null : +valueWindow[1].toFixed(precision)
  70295. );
  70296. }
  70297. function setMinMaxSpan(axisProxy) {
  70298. var minMaxSpan = axisProxy._minMaxSpan = {};
  70299. var dataZoomModel = axisProxy._dataZoomModel;
  70300. var dataExtent = axisProxy._dataExtent;
  70301. each$20(['min', 'max'], function (minMax) {
  70302. var percentSpan = dataZoomModel.get(minMax + 'Span');
  70303. var valueSpan = dataZoomModel.get(minMax + 'ValueSpan');
  70304. valueSpan != null && (valueSpan = axisProxy.getAxisModel().axis.scale.parse(valueSpan));
  70305. // minValueSpan and maxValueSpan has higher priority than minSpan and maxSpan
  70306. if (valueSpan != null) {
  70307. percentSpan = linearMap(
  70308. dataExtent[0] + valueSpan, dataExtent, [0, 100], true
  70309. );
  70310. }
  70311. else if (percentSpan != null) {
  70312. valueSpan = linearMap(
  70313. percentSpan, [0, 100], dataExtent, true
  70314. ) - dataExtent[0];
  70315. }
  70316. minMaxSpan[minMax + 'Span'] = percentSpan;
  70317. minMaxSpan[minMax + 'ValueSpan'] = valueSpan;
  70318. });
  70319. }
  70320. /*
  70321. * Licensed to the Apache Software Foundation (ASF) under one
  70322. * or more contributor license agreements. See the NOTICE file
  70323. * distributed with this work for additional information
  70324. * regarding copyright ownership. The ASF licenses this file
  70325. * to you under the Apache License, Version 2.0 (the
  70326. * "License"); you may not use this file except in compliance
  70327. * with the License. You may obtain a copy of the License at
  70328. *
  70329. * http://www.apache.org/licenses/LICENSE-2.0
  70330. *
  70331. * Unless required by applicable law or agreed to in writing,
  70332. * software distributed under the License is distributed on an
  70333. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  70334. * KIND, either express or implied. See the License for the
  70335. * specific language governing permissions and limitations
  70336. * under the License.
  70337. */
  70338. var each$19 = each$1;
  70339. var eachAxisDim = eachAxisDim$1;
  70340. var DataZoomModel = extendComponentModel({
  70341. type: 'dataZoom',
  70342. dependencies: [
  70343. 'xAxis', 'yAxis', 'zAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'series'
  70344. ],
  70345. /**
  70346. * @protected
  70347. */
  70348. defaultOption: {
  70349. zlevel: 0,
  70350. z: 4, // Higher than normal component (z: 2).
  70351. orient: null, // Default auto by axisIndex. Possible value: 'horizontal', 'vertical'.
  70352. xAxisIndex: null, // Default the first horizontal category axis.
  70353. yAxisIndex: null, // Default the first vertical category axis.
  70354. filterMode: 'filter', // Possible values: 'filter' or 'empty' or 'weakFilter'.
  70355. // 'filter': data items which are out of window will be removed. This option is
  70356. // applicable when filtering outliers. For each data item, it will be
  70357. // filtered if one of the relevant dimensions is out of the window.
  70358. // 'weakFilter': data items which are out of window will be removed. This option
  70359. // is applicable when filtering outliers. For each data item, it will be
  70360. // filtered only if all of the relevant dimensions are out of the same
  70361. // side of the window.
  70362. // 'empty': data items which are out of window will be set to empty.
  70363. // This option is applicable when user should not neglect
  70364. // that there are some data items out of window.
  70365. // 'none': Do not filter.
  70366. // Taking line chart as an example, line will be broken in
  70367. // the filtered points when filterModel is set to 'empty', but
  70368. // be connected when set to 'filter'.
  70369. throttle: null, // Dispatch action by the fixed rate, avoid frequency.
  70370. // default 100. Do not throttle when use null/undefined.
  70371. // If animation === true and animationDurationUpdate > 0,
  70372. // default value is 100, otherwise 20.
  70373. start: 0, // Start percent. 0 ~ 100
  70374. end: 100, // End percent. 0 ~ 100
  70375. startValue: null, // Start value. If startValue specified, start is ignored.
  70376. endValue: null, // End value. If endValue specified, end is ignored.
  70377. minSpan: null, // 0 ~ 100
  70378. maxSpan: null, // 0 ~ 100
  70379. minValueSpan: null, // The range of dataZoom can not be smaller than that.
  70380. maxValueSpan: null, // The range of dataZoom can not be larger than that.
  70381. rangeMode: null // Array, can be 'value' or 'percent'.
  70382. },
  70383. /**
  70384. * @override
  70385. */
  70386. init: function (option, parentModel, ecModel) {
  70387. /**
  70388. * key like x_0, y_1
  70389. * @private
  70390. * @type {Object}
  70391. */
  70392. this._dataIntervalByAxis = {};
  70393. /**
  70394. * @private
  70395. */
  70396. this._dataInfo = {};
  70397. /**
  70398. * key like x_0, y_1
  70399. * @private
  70400. */
  70401. this._axisProxies = {};
  70402. /**
  70403. * @readOnly
  70404. */
  70405. this.textStyleModel;
  70406. /**
  70407. * @private
  70408. */
  70409. this._autoThrottle = true;
  70410. /**
  70411. * It is `[rangeModeForMin, rangeModeForMax]`.
  70412. * The optional values for `rangeMode`:
  70413. * + `'value'` mode: the axis extent will always be determined by
  70414. * `dataZoom.startValue` and `dataZoom.endValue`, despite
  70415. * how data like and how `axis.min` and `axis.max` are.
  70416. * + `'percent'` mode: `100` represents 100% of the `[dMin, dMax]`,
  70417. * where `dMin` is `axis.min` if `axis.min` specified, otherwise `data.extent[0]`,
  70418. * and `dMax` is `axis.max` if `axis.max` specified, otherwise `data.extent[1]`.
  70419. * Axis extent will be determined by the result of the percent of `[dMin, dMax]`.
  70420. *
  70421. * For example, when users are using dynamic data (update data periodically via `setOption`),
  70422. * if in `'value`' mode, the window will be kept in a fixed value range despite how
  70423. * data are appended, while if in `'percent'` mode, whe window range will be changed alone with
  70424. * the appended data (suppose `axis.min` and `axis.max` are not specified).
  70425. *
  70426. * @private
  70427. */
  70428. this._rangePropMode = ['percent', 'percent'];
  70429. var inputRawOption = retrieveRawOption(option);
  70430. /**
  70431. * Suppose a "main process" start at the point that model prepared (that is,
  70432. * model initialized or merged or method called in `action`).
  70433. * We should keep the `main process` idempotent, that is, given a set of values
  70434. * on `option`, we get the same result.
  70435. *
  70436. * But sometimes, values on `option` will be updated for providing users
  70437. * a "final calculated value" (`dataZoomProcessor` will do that). Those value
  70438. * should not be the base/input of the `main process`.
  70439. *
  70440. * So in that case we should save and keep the input of the `main process`
  70441. * separately, called `settledOption`.
  70442. *
  70443. * For example, consider the case:
  70444. * (Step_1) brush zoom the grid by `toolbox.dataZoom`,
  70445. * where the original input `option.startValue`, `option.endValue` are earsed by
  70446. * calculated value.
  70447. * (Step)2) click the legend to hide and show a series,
  70448. * where the new range is calculated by the earsed `startValue` and `endValue`,
  70449. * which brings incorrect result.
  70450. *
  70451. * @readOnly
  70452. */
  70453. this.settledOption = inputRawOption;
  70454. this.mergeDefaultAndTheme(option, ecModel);
  70455. this.doInit(inputRawOption);
  70456. },
  70457. /**
  70458. * @override
  70459. */
  70460. mergeOption: function (newOption) {
  70461. var inputRawOption = retrieveRawOption(newOption);
  70462. //FIX #2591
  70463. merge(this.option, newOption, true);
  70464. merge(this.settledOption, inputRawOption, true);
  70465. this.doInit(inputRawOption);
  70466. },
  70467. /**
  70468. * @protected
  70469. */
  70470. doInit: function (inputRawOption) {
  70471. var thisOption = this.option;
  70472. // Disable realtime view update if canvas is not supported.
  70473. if (!env$1.canvasSupported) {
  70474. thisOption.realtime = false;
  70475. }
  70476. this._setDefaultThrottle(inputRawOption);
  70477. updateRangeUse(this, inputRawOption);
  70478. var settledOption = this.settledOption;
  70479. each$19([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  70480. // start/end has higher priority over startValue/endValue if they
  70481. // both set, but we should make chart.setOption({endValue: 1000})
  70482. // effective, rather than chart.setOption({endValue: 1000, end: null}).
  70483. if (this._rangePropMode[index] === 'value') {
  70484. thisOption[names[0]] = settledOption[names[0]] = null;
  70485. }
  70486. // Otherwise do nothing and use the merge result.
  70487. }, this);
  70488. this.textStyleModel = this.getModel('textStyle');
  70489. this._resetTarget();
  70490. this._giveAxisProxies();
  70491. },
  70492. /**
  70493. * @private
  70494. */
  70495. _giveAxisProxies: function () {
  70496. var axisProxies = this._axisProxies;
  70497. this.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel, ecModel) {
  70498. var axisModel = this.dependentModels[dimNames.axis][axisIndex];
  70499. // If exists, share axisProxy with other dataZoomModels.
  70500. var axisProxy = axisModel.__dzAxisProxy || (
  70501. // Use the first dataZoomModel as the main model of axisProxy.
  70502. axisModel.__dzAxisProxy = new AxisProxy(
  70503. dimNames.name, axisIndex, this, ecModel
  70504. )
  70505. );
  70506. // FIXME
  70507. // dispose __dzAxisProxy
  70508. axisProxies[dimNames.name + '_' + axisIndex] = axisProxy;
  70509. }, this);
  70510. },
  70511. /**
  70512. * @private
  70513. */
  70514. _resetTarget: function () {
  70515. var thisOption = this.option;
  70516. var autoMode = this._judgeAutoMode();
  70517. eachAxisDim(function (dimNames) {
  70518. var axisIndexName = dimNames.axisIndex;
  70519. thisOption[axisIndexName] = normalizeToArray(
  70520. thisOption[axisIndexName]
  70521. );
  70522. }, this);
  70523. if (autoMode === 'axisIndex') {
  70524. this._autoSetAxisIndex();
  70525. }
  70526. else if (autoMode === 'orient') {
  70527. this._autoSetOrient();
  70528. }
  70529. },
  70530. /**
  70531. * @private
  70532. */
  70533. _judgeAutoMode: function () {
  70534. // Auto set only works for setOption at the first time.
  70535. // The following is user's reponsibility. So using merged
  70536. // option is OK.
  70537. var thisOption = this.option;
  70538. var hasIndexSpecified = false;
  70539. eachAxisDim(function (dimNames) {
  70540. // When user set axisIndex as a empty array, we think that user specify axisIndex
  70541. // but do not want use auto mode. Because empty array may be encountered when
  70542. // some error occured.
  70543. if (thisOption[dimNames.axisIndex] != null) {
  70544. hasIndexSpecified = true;
  70545. }
  70546. }, this);
  70547. var orient = thisOption.orient;
  70548. if (orient == null && hasIndexSpecified) {
  70549. return 'orient';
  70550. }
  70551. else if (!hasIndexSpecified) {
  70552. if (orient == null) {
  70553. thisOption.orient = 'horizontal';
  70554. }
  70555. return 'axisIndex';
  70556. }
  70557. },
  70558. /**
  70559. * @private
  70560. */
  70561. _autoSetAxisIndex: function () {
  70562. var autoAxisIndex = true;
  70563. var orient = this.get('orient', true);
  70564. var thisOption = this.option;
  70565. var dependentModels = this.dependentModels;
  70566. if (autoAxisIndex) {
  70567. // Find axis that parallel to dataZoom as default.
  70568. var dimName = orient === 'vertical' ? 'y' : 'x';
  70569. if (dependentModels[dimName + 'Axis'].length) {
  70570. thisOption[dimName + 'AxisIndex'] = [0];
  70571. autoAxisIndex = false;
  70572. }
  70573. else {
  70574. each$19(dependentModels.singleAxis, function (singleAxisModel) {
  70575. if (autoAxisIndex && singleAxisModel.get('orient', true) === orient) {
  70576. thisOption.singleAxisIndex = [singleAxisModel.componentIndex];
  70577. autoAxisIndex = false;
  70578. }
  70579. });
  70580. }
  70581. }
  70582. if (autoAxisIndex) {
  70583. // Find the first category axis as default. (consider polar)
  70584. eachAxisDim(function (dimNames) {
  70585. if (!autoAxisIndex) {
  70586. return;
  70587. }
  70588. var axisIndices = [];
  70589. var axisModels = this.dependentModels[dimNames.axis];
  70590. if (axisModels.length && !axisIndices.length) {
  70591. for (var i = 0, len = axisModels.length; i < len; i++) {
  70592. if (axisModels[i].get('type') === 'category') {
  70593. axisIndices.push(i);
  70594. }
  70595. }
  70596. }
  70597. thisOption[dimNames.axisIndex] = axisIndices;
  70598. if (axisIndices.length) {
  70599. autoAxisIndex = false;
  70600. }
  70601. }, this);
  70602. }
  70603. if (autoAxisIndex) {
  70604. // FIXME
  70605. // 这里是兼容ec2的写法(没指定xAxisIndex和yAxisIndex时把scatter和双数值轴折柱纳入dataZoom控制),
  70606. // 但是实际是否需要Grid.js#getScaleByOption来判断(考虑time,log等axis type)?
  70607. // If both dataZoom.xAxisIndex and dataZoom.yAxisIndex is not specified,
  70608. // dataZoom component auto adopts series that reference to
  70609. // both xAxis and yAxis which type is 'value'.
  70610. this.ecModel.eachSeries(function (seriesModel) {
  70611. if (this._isSeriesHasAllAxesTypeOf(seriesModel, 'value')) {
  70612. eachAxisDim(function (dimNames) {
  70613. var axisIndices = thisOption[dimNames.axisIndex];
  70614. var axisIndex = seriesModel.get(dimNames.axisIndex);
  70615. var axisId = seriesModel.get(dimNames.axisId);
  70616. var axisModel = seriesModel.ecModel.queryComponents({
  70617. mainType: dimNames.axis,
  70618. index: axisIndex,
  70619. id: axisId
  70620. })[0];
  70621. if (__DEV__) {
  70622. if (!axisModel) {
  70623. throw new Error(
  70624. dimNames.axis + ' "' + retrieve(
  70625. axisIndex,
  70626. axisId,
  70627. 0
  70628. ) + '" not found'
  70629. );
  70630. }
  70631. }
  70632. axisIndex = axisModel.componentIndex;
  70633. if (indexOf(axisIndices, axisIndex) < 0) {
  70634. axisIndices.push(axisIndex);
  70635. }
  70636. });
  70637. }
  70638. }, this);
  70639. }
  70640. },
  70641. /**
  70642. * @private
  70643. */
  70644. _autoSetOrient: function () {
  70645. var dim;
  70646. // Find the first axis
  70647. this.eachTargetAxis(function (dimNames) {
  70648. !dim && (dim = dimNames.name);
  70649. }, this);
  70650. this.option.orient = dim === 'y' ? 'vertical' : 'horizontal';
  70651. },
  70652. /**
  70653. * @private
  70654. */
  70655. _isSeriesHasAllAxesTypeOf: function (seriesModel, axisType) {
  70656. // FIXME
  70657. // 需要series的xAxisIndex和yAxisIndex都首先自动设置上。
  70658. // 例如series.type === scatter时。
  70659. var is = true;
  70660. eachAxisDim(function (dimNames) {
  70661. var seriesAxisIndex = seriesModel.get(dimNames.axisIndex);
  70662. var axisModel = this.dependentModels[dimNames.axis][seriesAxisIndex];
  70663. if (!axisModel || axisModel.get('type') !== axisType) {
  70664. is = false;
  70665. }
  70666. }, this);
  70667. return is;
  70668. },
  70669. /**
  70670. * @private
  70671. */
  70672. _setDefaultThrottle: function (inputRawOption) {
  70673. // When first time user set throttle, auto throttle ends.
  70674. if (inputRawOption.hasOwnProperty('throttle')) {
  70675. this._autoThrottle = false;
  70676. }
  70677. if (this._autoThrottle) {
  70678. var globalOption = this.ecModel.option;
  70679. this.option.throttle = (
  70680. globalOption.animation && globalOption.animationDurationUpdate > 0
  70681. ) ? 100 : 20;
  70682. }
  70683. },
  70684. /**
  70685. * @public
  70686. */
  70687. getFirstTargetAxisModel: function () {
  70688. var firstAxisModel;
  70689. eachAxisDim(function (dimNames) {
  70690. if (firstAxisModel == null) {
  70691. var indices = this.get(dimNames.axisIndex);
  70692. if (indices.length) {
  70693. firstAxisModel = this.dependentModels[dimNames.axis][indices[0]];
  70694. }
  70695. }
  70696. }, this);
  70697. return firstAxisModel;
  70698. },
  70699. /**
  70700. * @public
  70701. * @param {Function} callback param: axisModel, dimNames, axisIndex, dataZoomModel, ecModel
  70702. */
  70703. eachTargetAxis: function (callback, context) {
  70704. var ecModel = this.ecModel;
  70705. eachAxisDim(function (dimNames) {
  70706. each$19(
  70707. this.get(dimNames.axisIndex),
  70708. function (axisIndex) {
  70709. callback.call(context, dimNames, axisIndex, this, ecModel);
  70710. },
  70711. this
  70712. );
  70713. }, this);
  70714. },
  70715. /**
  70716. * @param {string} dimName
  70717. * @param {number} axisIndex
  70718. * @return {module:echarts/component/dataZoom/AxisProxy} If not found, return null/undefined.
  70719. */
  70720. getAxisProxy: function (dimName, axisIndex) {
  70721. return this._axisProxies[dimName + '_' + axisIndex];
  70722. },
  70723. /**
  70724. * @param {string} dimName
  70725. * @param {number} axisIndex
  70726. * @return {module:echarts/model/Model} If not found, return null/undefined.
  70727. */
  70728. getAxisModel: function (dimName, axisIndex) {
  70729. var axisProxy = this.getAxisProxy(dimName, axisIndex);
  70730. return axisProxy && axisProxy.getAxisModel();
  70731. },
  70732. /**
  70733. * If not specified, set to undefined.
  70734. *
  70735. * @public
  70736. * @param {Object} opt
  70737. * @param {number} [opt.start]
  70738. * @param {number} [opt.end]
  70739. * @param {number} [opt.startValue]
  70740. * @param {number} [opt.endValue]
  70741. */
  70742. setRawRange: function (opt) {
  70743. var thisOption = this.option;
  70744. var settledOption = this.settledOption;
  70745. each$19([['start', 'startValue'], ['end', 'endValue']], function (names) {
  70746. // Consider the pair <start, startValue>:
  70747. // If one has value and the other one is `null/undefined`, we both set them
  70748. // to `settledOption`. This strategy enables the feature to clear the original
  70749. // value in `settledOption` to `null/undefined`.
  70750. // But if both of them are `null/undefined`, we do not set them to `settledOption`
  70751. // and keep `settledOption` with the original value. This strategy enables users to
  70752. // only set <end or endValue> but not set <start or startValue> when calling
  70753. // `dispatchAction`.
  70754. // The pair <end, endValue> is treated in the same way.
  70755. if (opt[names[0]] != null || opt[names[1]] != null) {
  70756. thisOption[names[0]] = settledOption[names[0]] = opt[names[0]];
  70757. thisOption[names[1]] = settledOption[names[1]] = opt[names[1]];
  70758. }
  70759. }, this);
  70760. updateRangeUse(this, opt);
  70761. },
  70762. /**
  70763. * @public
  70764. * @param {Object} opt
  70765. * @param {number} [opt.start]
  70766. * @param {number} [opt.end]
  70767. * @param {number} [opt.startValue]
  70768. * @param {number} [opt.endValue]
  70769. */
  70770. setCalculatedRange: function (opt) {
  70771. var option = this.option;
  70772. each$19(['start', 'startValue', 'end', 'endValue'], function (name) {
  70773. option[name] = opt[name];
  70774. });
  70775. },
  70776. /**
  70777. * @public
  70778. * @return {Array.<number>} [startPercent, endPercent]
  70779. */
  70780. getPercentRange: function () {
  70781. var axisProxy = this.findRepresentativeAxisProxy();
  70782. if (axisProxy) {
  70783. return axisProxy.getDataPercentWindow();
  70784. }
  70785. },
  70786. /**
  70787. * @public
  70788. * For example, chart.getModel().getComponent('dataZoom').getValueRange('y', 0);
  70789. *
  70790. * @param {string} [axisDimName]
  70791. * @param {number} [axisIndex]
  70792. * @return {Array.<number>} [startValue, endValue] value can only be '-' or finite number.
  70793. */
  70794. getValueRange: function (axisDimName, axisIndex) {
  70795. if (axisDimName == null && axisIndex == null) {
  70796. var axisProxy = this.findRepresentativeAxisProxy();
  70797. if (axisProxy) {
  70798. return axisProxy.getDataValueWindow();
  70799. }
  70800. }
  70801. else {
  70802. return this.getAxisProxy(axisDimName, axisIndex).getDataValueWindow();
  70803. }
  70804. },
  70805. /**
  70806. * @public
  70807. * @param {module:echarts/model/Model} [axisModel] If axisModel given, find axisProxy
  70808. * corresponding to the axisModel
  70809. * @return {module:echarts/component/dataZoom/AxisProxy}
  70810. */
  70811. findRepresentativeAxisProxy: function (axisModel) {
  70812. if (axisModel) {
  70813. return axisModel.__dzAxisProxy;
  70814. }
  70815. // Find the first hosted axisProxy
  70816. var axisProxies = this._axisProxies;
  70817. for (var key in axisProxies) {
  70818. if (axisProxies.hasOwnProperty(key) && axisProxies[key].hostedBy(this)) {
  70819. return axisProxies[key];
  70820. }
  70821. }
  70822. // If no hosted axis find not hosted axisProxy.
  70823. // Consider this case: dataZoomModel1 and dataZoomModel2 control the same axis,
  70824. // and the option.start or option.end settings are different. The percentRange
  70825. // should follow axisProxy.
  70826. // (We encounter this problem in toolbox data zoom.)
  70827. for (var key in axisProxies) {
  70828. if (axisProxies.hasOwnProperty(key) && !axisProxies[key].hostedBy(this)) {
  70829. return axisProxies[key];
  70830. }
  70831. }
  70832. },
  70833. /**
  70834. * @return {Array.<string>}
  70835. */
  70836. getRangePropMode: function () {
  70837. return this._rangePropMode.slice();
  70838. }
  70839. });
  70840. /**
  70841. * Retrieve the those raw params from option, which will be cached separately.
  70842. * becasue they will be overwritten by normalized/calculated values in the main
  70843. * process.
  70844. */
  70845. function retrieveRawOption(option) {
  70846. var ret = {};
  70847. each$19(
  70848. ['start', 'end', 'startValue', 'endValue', 'throttle'],
  70849. function (name) {
  70850. option.hasOwnProperty(name) && (ret[name] = option[name]);
  70851. }
  70852. );
  70853. return ret;
  70854. }
  70855. function updateRangeUse(dataZoomModel, inputRawOption) {
  70856. var rangePropMode = dataZoomModel._rangePropMode;
  70857. var rangeModeInOption = dataZoomModel.get('rangeMode');
  70858. each$19([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  70859. var percentSpecified = inputRawOption[names[0]] != null;
  70860. var valueSpecified = inputRawOption[names[1]] != null;
  70861. if (percentSpecified && !valueSpecified) {
  70862. rangePropMode[index] = 'percent';
  70863. }
  70864. else if (!percentSpecified && valueSpecified) {
  70865. rangePropMode[index] = 'value';
  70866. }
  70867. else if (rangeModeInOption) {
  70868. rangePropMode[index] = rangeModeInOption[index];
  70869. }
  70870. else if (percentSpecified) { // percentSpecified && valueSpecified
  70871. rangePropMode[index] = 'percent';
  70872. }
  70873. // else remain its original setting.
  70874. });
  70875. }
  70876. /*
  70877. * Licensed to the Apache Software Foundation (ASF) under one
  70878. * or more contributor license agreements. See the NOTICE file
  70879. * distributed with this work for additional information
  70880. * regarding copyright ownership. The ASF licenses this file
  70881. * to you under the Apache License, Version 2.0 (the
  70882. * "License"); you may not use this file except in compliance
  70883. * with the License. You may obtain a copy of the License at
  70884. *
  70885. * http://www.apache.org/licenses/LICENSE-2.0
  70886. *
  70887. * Unless required by applicable law or agreed to in writing,
  70888. * software distributed under the License is distributed on an
  70889. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  70890. * KIND, either express or implied. See the License for the
  70891. * specific language governing permissions and limitations
  70892. * under the License.
  70893. */
  70894. var DataZoomView = Component$1.extend({
  70895. type: 'dataZoom',
  70896. render: function (dataZoomModel, ecModel, api, payload) {
  70897. this.dataZoomModel = dataZoomModel;
  70898. this.ecModel = ecModel;
  70899. this.api = api;
  70900. },
  70901. /**
  70902. * Find the first target coordinate system.
  70903. *
  70904. * @protected
  70905. * @return {Object} {
  70906. * grid: [
  70907. * {model: coord0, axisModels: [axis1, axis3], coordIndex: 1},
  70908. * {model: coord1, axisModels: [axis0, axis2], coordIndex: 0},
  70909. * ...
  70910. * ], // cartesians must not be null/undefined.
  70911. * polar: [
  70912. * {model: coord0, axisModels: [axis4], coordIndex: 0},
  70913. * ...
  70914. * ], // polars must not be null/undefined.
  70915. * singleAxis: [
  70916. * {model: coord0, axisModels: [], coordIndex: 0}
  70917. * ]
  70918. */
  70919. getTargetCoordInfo: function () {
  70920. var dataZoomModel = this.dataZoomModel;
  70921. var ecModel = this.ecModel;
  70922. var coordSysLists = {};
  70923. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex) {
  70924. var axisModel = ecModel.getComponent(dimNames.axis, axisIndex);
  70925. if (axisModel) {
  70926. var coordModel = axisModel.getCoordSysModel();
  70927. coordModel && save(
  70928. coordModel,
  70929. axisModel,
  70930. coordSysLists[coordModel.mainType] || (coordSysLists[coordModel.mainType] = []),
  70931. coordModel.componentIndex
  70932. );
  70933. }
  70934. }, this);
  70935. function save(coordModel, axisModel, store, coordIndex) {
  70936. var item;
  70937. for (var i = 0; i < store.length; i++) {
  70938. if (store[i].model === coordModel) {
  70939. item = store[i];
  70940. break;
  70941. }
  70942. }
  70943. if (!item) {
  70944. store.push(item = {
  70945. model: coordModel, axisModels: [], coordIndex: coordIndex
  70946. });
  70947. }
  70948. item.axisModels.push(axisModel);
  70949. }
  70950. return coordSysLists;
  70951. }
  70952. });
  70953. /*
  70954. * Licensed to the Apache Software Foundation (ASF) under one
  70955. * or more contributor license agreements. See the NOTICE file
  70956. * distributed with this work for additional information
  70957. * regarding copyright ownership. The ASF licenses this file
  70958. * to you under the Apache License, Version 2.0 (the
  70959. * "License"); you may not use this file except in compliance
  70960. * with the License. You may obtain a copy of the License at
  70961. *
  70962. * http://www.apache.org/licenses/LICENSE-2.0
  70963. *
  70964. * Unless required by applicable law or agreed to in writing,
  70965. * software distributed under the License is distributed on an
  70966. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  70967. * KIND, either express or implied. See the License for the
  70968. * specific language governing permissions and limitations
  70969. * under the License.
  70970. */
  70971. DataZoomModel.extend({
  70972. type: 'dataZoom.select'
  70973. });
  70974. /*
  70975. * Licensed to the Apache Software Foundation (ASF) under one
  70976. * or more contributor license agreements. See the NOTICE file
  70977. * distributed with this work for additional information
  70978. * regarding copyright ownership. The ASF licenses this file
  70979. * to you under the Apache License, Version 2.0 (the
  70980. * "License"); you may not use this file except in compliance
  70981. * with the License. You may obtain a copy of the License at
  70982. *
  70983. * http://www.apache.org/licenses/LICENSE-2.0
  70984. *
  70985. * Unless required by applicable law or agreed to in writing,
  70986. * software distributed under the License is distributed on an
  70987. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  70988. * KIND, either express or implied. See the License for the
  70989. * specific language governing permissions and limitations
  70990. * under the License.
  70991. */
  70992. DataZoomView.extend({
  70993. type: 'dataZoom.select'
  70994. });
  70995. /*
  70996. * Licensed to the Apache Software Foundation (ASF) under one
  70997. * or more contributor license agreements. See the NOTICE file
  70998. * distributed with this work for additional information
  70999. * regarding copyright ownership. The ASF licenses this file
  71000. * to you under the Apache License, Version 2.0 (the
  71001. * "License"); you may not use this file except in compliance
  71002. * with the License. You may obtain a copy of the License at
  71003. *
  71004. * http://www.apache.org/licenses/LICENSE-2.0
  71005. *
  71006. * Unless required by applicable law or agreed to in writing,
  71007. * software distributed under the License is distributed on an
  71008. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71009. * KIND, either express or implied. See the License for the
  71010. * specific language governing permissions and limitations
  71011. * under the License.
  71012. */
  71013. registerProcessor({
  71014. // `dataZoomProcessor` will only be performed in needed series. Consider if
  71015. // there is a line series and a pie series, it is better not to update the
  71016. // line series if only pie series is needed to be updated.
  71017. getTargetSeries: function (ecModel) {
  71018. var seriesModelMap = createHashMap();
  71019. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  71020. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  71021. var axisProxy = dataZoomModel.getAxisProxy(dimNames.name, axisIndex);
  71022. each$1(axisProxy.getTargetSeriesModels(), function (seriesModel) {
  71023. seriesModelMap.set(seriesModel.uid, seriesModel);
  71024. });
  71025. });
  71026. });
  71027. return seriesModelMap;
  71028. },
  71029. modifyOutputEnd: true,
  71030. // Consider appendData, where filter should be performed. Because data process is
  71031. // in block mode currently, it is not need to worry about that the overallProgress
  71032. // execute every frame.
  71033. overallReset: function (ecModel, api) {
  71034. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  71035. // We calculate window and reset axis here but not in model
  71036. // init stage and not after action dispatch handler, because
  71037. // reset should be called after seriesData.restoreData.
  71038. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  71039. dataZoomModel.getAxisProxy(dimNames.name, axisIndex).reset(dataZoomModel, api);
  71040. });
  71041. // Caution: data zoom filtering is order sensitive when using
  71042. // percent range and no min/max/scale set on axis.
  71043. // For example, we have dataZoom definition:
  71044. // [
  71045. // {xAxisIndex: 0, start: 30, end: 70},
  71046. // {yAxisIndex: 0, start: 20, end: 80}
  71047. // ]
  71048. // In this case, [20, 80] of y-dataZoom should be based on data
  71049. // that have filtered by x-dataZoom using range of [30, 70],
  71050. // but should not be based on full raw data. Thus sliding
  71051. // x-dataZoom will change both ranges of xAxis and yAxis,
  71052. // while sliding y-dataZoom will only change the range of yAxis.
  71053. // So we should filter x-axis after reset x-axis immediately,
  71054. // and then reset y-axis and filter y-axis.
  71055. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  71056. dataZoomModel.getAxisProxy(dimNames.name, axisIndex).filterData(dataZoomModel, api);
  71057. });
  71058. });
  71059. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  71060. // Fullfill all of the range props so that user
  71061. // is able to get them from chart.getOption().
  71062. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  71063. var percentRange = axisProxy.getDataPercentWindow();
  71064. var valueRange = axisProxy.getDataValueWindow();
  71065. dataZoomModel.setCalculatedRange({
  71066. start: percentRange[0],
  71067. end: percentRange[1],
  71068. startValue: valueRange[0],
  71069. endValue: valueRange[1]
  71070. });
  71071. });
  71072. }
  71073. });
  71074. /*
  71075. * Licensed to the Apache Software Foundation (ASF) under one
  71076. * or more contributor license agreements. See the NOTICE file
  71077. * distributed with this work for additional information
  71078. * regarding copyright ownership. The ASF licenses this file
  71079. * to you under the Apache License, Version 2.0 (the
  71080. * "License"); you may not use this file except in compliance
  71081. * with the License. You may obtain a copy of the License at
  71082. *
  71083. * http://www.apache.org/licenses/LICENSE-2.0
  71084. *
  71085. * Unless required by applicable law or agreed to in writing,
  71086. * software distributed under the License is distributed on an
  71087. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71088. * KIND, either express or implied. See the License for the
  71089. * specific language governing permissions and limitations
  71090. * under the License.
  71091. */
  71092. registerAction('dataZoom', function (payload, ecModel) {
  71093. var linkedNodesFinder = createLinkedNodesFinder(
  71094. bind(ecModel.eachComponent, ecModel, 'dataZoom'),
  71095. eachAxisDim$1,
  71096. function (model, dimNames) {
  71097. return model.get(dimNames.axisIndex);
  71098. }
  71099. );
  71100. var effectedModels = [];
  71101. ecModel.eachComponent(
  71102. {mainType: 'dataZoom', query: payload},
  71103. function (model, index) {
  71104. effectedModels.push.apply(
  71105. effectedModels, linkedNodesFinder(model).nodes
  71106. );
  71107. }
  71108. );
  71109. each$1(effectedModels, function (dataZoomModel, index) {
  71110. dataZoomModel.setRawRange({
  71111. start: payload.start,
  71112. end: payload.end,
  71113. startValue: payload.startValue,
  71114. endValue: payload.endValue
  71115. });
  71116. });
  71117. });
  71118. /*
  71119. * Licensed to the Apache Software Foundation (ASF) under one
  71120. * or more contributor license agreements. See the NOTICE file
  71121. * distributed with this work for additional information
  71122. * regarding copyright ownership. The ASF licenses this file
  71123. * to you under the Apache License, Version 2.0 (the
  71124. * "License"); you may not use this file except in compliance
  71125. * with the License. You may obtain a copy of the License at
  71126. *
  71127. * http://www.apache.org/licenses/LICENSE-2.0
  71128. *
  71129. * Unless required by applicable law or agreed to in writing,
  71130. * software distributed under the License is distributed on an
  71131. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71132. * KIND, either express or implied. See the License for the
  71133. * specific language governing permissions and limitations
  71134. * under the License.
  71135. */
  71136. /**
  71137. * Only work for toolbox dataZoom. User
  71138. * MUST NOT import this module directly.
  71139. */
  71140. /*
  71141. * Licensed to the Apache Software Foundation (ASF) under one
  71142. * or more contributor license agreements. See the NOTICE file
  71143. * distributed with this work for additional information
  71144. * regarding copyright ownership. The ASF licenses this file
  71145. * to you under the Apache License, Version 2.0 (the
  71146. * "License"); you may not use this file except in compliance
  71147. * with the License. You may obtain a copy of the License at
  71148. *
  71149. * http://www.apache.org/licenses/LICENSE-2.0
  71150. *
  71151. * Unless required by applicable law or agreed to in writing,
  71152. * software distributed under the License is distributed on an
  71153. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71154. * KIND, either express or implied. See the License for the
  71155. * specific language governing permissions and limitations
  71156. * under the License.
  71157. */
  71158. // Use dataZoomSelect
  71159. var dataZoomLang = lang.toolbox.dataZoom;
  71160. var each$16 = each$1;
  71161. // Spectial component id start with \0ec\0, see echarts/model/Global.js~hasInnerId
  71162. var DATA_ZOOM_ID_BASE = '\0_ec_\0toolbox-dataZoom_';
  71163. function DataZoom(model, ecModel, api) {
  71164. /**
  71165. * @private
  71166. * @type {module:echarts/component/helper/BrushController}
  71167. */
  71168. (this._brushController = new BrushController(api.getZr()))
  71169. .on('brush', bind(this._onBrush, this))
  71170. .mount();
  71171. /**
  71172. * @private
  71173. * @type {boolean}
  71174. */
  71175. this._isZoomActive;
  71176. }
  71177. DataZoom.defaultOption = {
  71178. show: true,
  71179. filterMode: 'filter',
  71180. // Icon group
  71181. icon: {
  71182. zoom: 'M0,13.5h26.9 M13.5,26.9V0 M32.1,13.5H58V58H13.5 V32.1',
  71183. back: 'M22,1.4L9.9,13.5l12.3,12.3 M10.3,13.5H54.9v44.6 H10.3v-26'
  71184. },
  71185. // `zoom`, `back`
  71186. title: clone(dataZoomLang.title)
  71187. };
  71188. var proto$4 = DataZoom.prototype;
  71189. proto$4.render = function (featureModel, ecModel, api, payload) {
  71190. this.model = featureModel;
  71191. this.ecModel = ecModel;
  71192. this.api = api;
  71193. updateZoomBtnStatus(featureModel, ecModel, this, payload, api);
  71194. updateBackBtnStatus(featureModel, ecModel);
  71195. };
  71196. proto$4.onclick = function (ecModel, api, type) {
  71197. handlers$1[type].call(this);
  71198. };
  71199. proto$4.remove = function (ecModel, api) {
  71200. this._brushController.unmount();
  71201. };
  71202. proto$4.dispose = function (ecModel, api) {
  71203. this._brushController.dispose();
  71204. };
  71205. /**
  71206. * @private
  71207. */
  71208. var handlers$1 = {
  71209. zoom: function () {
  71210. var nextActive = !this._isZoomActive;
  71211. this.api.dispatchAction({
  71212. type: 'takeGlobalCursor',
  71213. key: 'dataZoomSelect',
  71214. dataZoomSelectActive: nextActive
  71215. });
  71216. },
  71217. back: function () {
  71218. this._dispatchZoomAction(pop(this.ecModel));
  71219. }
  71220. };
  71221. /**
  71222. * @private
  71223. */
  71224. proto$4._onBrush = function (areas, opt) {
  71225. if (!opt.isEnd || !areas.length) {
  71226. return;
  71227. }
  71228. var snapshot = {};
  71229. var ecModel = this.ecModel;
  71230. this._brushController.updateCovers([]); // remove cover
  71231. var brushTargetManager = new BrushTargetManager(
  71232. retrieveAxisSetting(this.model.option), ecModel, {include: ['grid']}
  71233. );
  71234. brushTargetManager.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  71235. if (coordSys.type !== 'cartesian2d') {
  71236. return;
  71237. }
  71238. var brushType = area.brushType;
  71239. if (brushType === 'rect') {
  71240. setBatch('x', coordSys, coordRange[0]);
  71241. setBatch('y', coordSys, coordRange[1]);
  71242. }
  71243. else {
  71244. setBatch(({lineX: 'x', lineY: 'y'})[brushType], coordSys, coordRange);
  71245. }
  71246. });
  71247. push(ecModel, snapshot);
  71248. this._dispatchZoomAction(snapshot);
  71249. function setBatch(dimName, coordSys, minMax) {
  71250. var axis = coordSys.getAxis(dimName);
  71251. var axisModel = axis.model;
  71252. var dataZoomModel = findDataZoom(dimName, axisModel, ecModel);
  71253. // Restrict range.
  71254. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy(axisModel).getMinMaxSpan();
  71255. if (minMaxSpan.minValueSpan != null || minMaxSpan.maxValueSpan != null) {
  71256. minMax = sliderMove(
  71257. 0, minMax.slice(), axis.scale.getExtent(), 0,
  71258. minMaxSpan.minValueSpan, minMaxSpan.maxValueSpan
  71259. );
  71260. }
  71261. dataZoomModel && (snapshot[dataZoomModel.id] = {
  71262. dataZoomId: dataZoomModel.id,
  71263. startValue: minMax[0],
  71264. endValue: minMax[1]
  71265. });
  71266. }
  71267. function findDataZoom(dimName, axisModel, ecModel) {
  71268. var found;
  71269. ecModel.eachComponent({mainType: 'dataZoom', subType: 'select'}, function (dzModel) {
  71270. var has = dzModel.getAxisModel(dimName, axisModel.componentIndex);
  71271. has && (found = dzModel);
  71272. });
  71273. return found;
  71274. }
  71275. };
  71276. /**
  71277. * @private
  71278. */
  71279. proto$4._dispatchZoomAction = function (snapshot) {
  71280. var batch = [];
  71281. // Convert from hash map to array.
  71282. each$16(snapshot, function (batchItem, dataZoomId) {
  71283. batch.push(clone(batchItem));
  71284. });
  71285. batch.length && this.api.dispatchAction({
  71286. type: 'dataZoom',
  71287. from: this.uid,
  71288. batch: batch
  71289. });
  71290. };
  71291. function retrieveAxisSetting(option) {
  71292. var setting = {};
  71293. // Compatible with previous setting: null => all axis, false => no axis.
  71294. each$1(['xAxisIndex', 'yAxisIndex'], function (name) {
  71295. setting[name] = option[name];
  71296. setting[name] == null && (setting[name] = 'all');
  71297. (setting[name] === false || setting[name] === 'none') && (setting[name] = []);
  71298. });
  71299. return setting;
  71300. }
  71301. function updateBackBtnStatus(featureModel, ecModel) {
  71302. featureModel.setIconStatus(
  71303. 'back',
  71304. count(ecModel) > 1 ? 'emphasis' : 'normal'
  71305. );
  71306. }
  71307. function updateZoomBtnStatus(featureModel, ecModel, view, payload, api) {
  71308. var zoomActive = view._isZoomActive;
  71309. if (payload && payload.type === 'takeGlobalCursor') {
  71310. zoomActive = payload.key === 'dataZoomSelect'
  71311. ? payload.dataZoomSelectActive : false;
  71312. }
  71313. view._isZoomActive = zoomActive;
  71314. featureModel.setIconStatus('zoom', zoomActive ? 'emphasis' : 'normal');
  71315. var brushTargetManager = new BrushTargetManager(
  71316. retrieveAxisSetting(featureModel.option), ecModel, {include: ['grid']}
  71317. );
  71318. view._brushController
  71319. .setPanels(brushTargetManager.makePanelOpts(api, function (targetInfo) {
  71320. return (targetInfo.xAxisDeclared && !targetInfo.yAxisDeclared)
  71321. ? 'lineX'
  71322. : (!targetInfo.xAxisDeclared && targetInfo.yAxisDeclared)
  71323. ? 'lineY'
  71324. : 'rect';
  71325. }))
  71326. .enableBrush(
  71327. zoomActive
  71328. ? {
  71329. brushType: 'auto',
  71330. brushStyle: {
  71331. // FIXME user customized?
  71332. lineWidth: 0,
  71333. fill: 'rgba(0,0,0,0.2)'
  71334. }
  71335. }
  71336. : false
  71337. );
  71338. }
  71339. register$1('dataZoom', DataZoom);
  71340. // Create special dataZoom option for select
  71341. // FIXME consider the case of merge option, where axes options are not exists.
  71342. registerPreprocessor(function (option) {
  71343. if (!option) {
  71344. return;
  71345. }
  71346. var dataZoomOpts = option.dataZoom || (option.dataZoom = []);
  71347. if (!isArray(dataZoomOpts)) {
  71348. option.dataZoom = dataZoomOpts = [dataZoomOpts];
  71349. }
  71350. var toolboxOpt = option.toolbox;
  71351. if (toolboxOpt) {
  71352. // Assume there is only one toolbox
  71353. if (isArray(toolboxOpt)) {
  71354. toolboxOpt = toolboxOpt[0];
  71355. }
  71356. if (toolboxOpt && toolboxOpt.feature) {
  71357. var dataZoomOpt = toolboxOpt.feature.dataZoom;
  71358. // FIXME: If add dataZoom when setOption in merge mode,
  71359. // no axis info to be added. See `test/dataZoom-extreme.html`
  71360. addForAxis('xAxis', dataZoomOpt);
  71361. addForAxis('yAxis', dataZoomOpt);
  71362. }
  71363. }
  71364. function addForAxis(axisName, dataZoomOpt) {
  71365. if (!dataZoomOpt) {
  71366. return;
  71367. }
  71368. // Try not to modify model, because it is not merged yet.
  71369. var axisIndicesName = axisName + 'Index';
  71370. var givenAxisIndices = dataZoomOpt[axisIndicesName];
  71371. if (givenAxisIndices != null
  71372. && givenAxisIndices !== 'all'
  71373. && !isArray(givenAxisIndices)
  71374. ) {
  71375. givenAxisIndices = (givenAxisIndices === false || givenAxisIndices === 'none') ? [] : [givenAxisIndices];
  71376. }
  71377. forEachComponent(axisName, function (axisOpt, axisIndex) {
  71378. if (givenAxisIndices != null
  71379. && givenAxisIndices !== 'all'
  71380. && indexOf(givenAxisIndices, axisIndex) === -1
  71381. ) {
  71382. return;
  71383. }
  71384. var newOpt = {
  71385. type: 'select',
  71386. $fromToolbox: true,
  71387. // Default to be filter
  71388. filterMode: dataZoomOpt.filterMode || 'filter',
  71389. // Id for merge mapping.
  71390. id: DATA_ZOOM_ID_BASE + axisName + axisIndex
  71391. };
  71392. // FIXME
  71393. // Only support one axis now.
  71394. newOpt[axisIndicesName] = axisIndex;
  71395. dataZoomOpts.push(newOpt);
  71396. });
  71397. }
  71398. function forEachComponent(mainType, cb) {
  71399. var opts = option[mainType];
  71400. if (!isArray(opts)) {
  71401. opts = opts ? [opts] : [];
  71402. }
  71403. each$16(opts, cb);
  71404. }
  71405. });
  71406. /*
  71407. * Licensed to the Apache Software Foundation (ASF) under one
  71408. * or more contributor license agreements. See the NOTICE file
  71409. * distributed with this work for additional information
  71410. * regarding copyright ownership. The ASF licenses this file
  71411. * to you under the Apache License, Version 2.0 (the
  71412. * "License"); you may not use this file except in compliance
  71413. * with the License. You may obtain a copy of the License at
  71414. *
  71415. * http://www.apache.org/licenses/LICENSE-2.0
  71416. *
  71417. * Unless required by applicable law or agreed to in writing,
  71418. * software distributed under the License is distributed on an
  71419. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71420. * KIND, either express or implied. See the License for the
  71421. * specific language governing permissions and limitations
  71422. * under the License.
  71423. */
  71424. var restoreLang = lang.toolbox.restore;
  71425. function Restore(model) {
  71426. this.model = model;
  71427. }
  71428. Restore.defaultOption = {
  71429. show: true,
  71430. /* eslint-disable */
  71431. 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',
  71432. /* eslint-enable */
  71433. title: restoreLang.title
  71434. };
  71435. var proto$6 = Restore.prototype;
  71436. proto$6.onclick = function (ecModel, api, type) {
  71437. clear$1(ecModel);
  71438. api.dispatchAction({
  71439. type: 'restore',
  71440. from: this.uid
  71441. });
  71442. };
  71443. register$1('restore', Restore);
  71444. registerAction(
  71445. {type: 'restore', event: 'restore', update: 'prepareAndUpdate'},
  71446. function (payload, ecModel) {
  71447. ecModel.resetOption('recreate');
  71448. }
  71449. );
  71450. /*
  71451. * Licensed to the Apache Software Foundation (ASF) under one
  71452. * or more contributor license agreements. See the NOTICE file
  71453. * distributed with this work for additional information
  71454. * regarding copyright ownership. The ASF licenses this file
  71455. * to you under the Apache License, Version 2.0 (the
  71456. * "License"); you may not use this file except in compliance
  71457. * with the License. You may obtain a copy of the License at
  71458. *
  71459. * http://www.apache.org/licenses/LICENSE-2.0
  71460. *
  71461. * Unless required by applicable law or agreed to in writing,
  71462. * software distributed under the License is distributed on an
  71463. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71464. * KIND, either express or implied. See the License for the
  71465. * specific language governing permissions and limitations
  71466. * under the License.
  71467. */
  71468. /*
  71469. * Licensed to the Apache Software Foundation (ASF) under one
  71470. * or more contributor license agreements. See the NOTICE file
  71471. * distributed with this work for additional information
  71472. * regarding copyright ownership. The ASF licenses this file
  71473. * to you under the Apache License, Version 2.0 (the
  71474. * "License"); you may not use this file except in compliance
  71475. * with the License. You may obtain a copy of the License at
  71476. *
  71477. * http://www.apache.org/licenses/LICENSE-2.0
  71478. *
  71479. * Unless required by applicable law or agreed to in writing,
  71480. * software distributed under the License is distributed on an
  71481. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71482. * KIND, either express or implied. See the License for the
  71483. * specific language governing permissions and limitations
  71484. * under the License.
  71485. */
  71486. extendComponentModel({
  71487. type: 'tooltip',
  71488. dependencies: ['axisPointer'],
  71489. defaultOption: {
  71490. zlevel: 0,
  71491. z: 60,
  71492. show: true,
  71493. // tooltip主体内容
  71494. showContent: true,
  71495. // 'trigger' only works on coordinate system.
  71496. // 'item' | 'axis' | 'none'
  71497. trigger: 'item',
  71498. // 'click' | 'mousemove' | 'none'
  71499. triggerOn: 'mousemove|click',
  71500. alwaysShowContent: false,
  71501. displayMode: 'single', // 'single' | 'multipleByCoordSys'
  71502. renderMode: 'auto', // 'auto' | 'html' | 'richText'
  71503. // 'auto': use html by default, and use non-html if `document` is not defined
  71504. // 'html': use html for tooltip
  71505. // 'richText': use canvas, svg, and etc. for tooltip
  71506. // 位置 {Array} | {Function}
  71507. // position: null
  71508. // Consider triggered from axisPointer handle, verticalAlign should be 'middle'
  71509. // align: null,
  71510. // verticalAlign: null,
  71511. // 是否约束 content 在 viewRect 中。默认 false 是为了兼容以前版本。
  71512. confine: false,
  71513. // 内容格式器:{string}(Template) ¦ {Function}
  71514. // formatter: null
  71515. showDelay: 0,
  71516. // 隐藏延迟,单位ms
  71517. hideDelay: 100,
  71518. // 动画变换时间,单位s
  71519. transitionDuration: 0.4,
  71520. enterable: false,
  71521. // 提示背景颜色,默认为透明度为0.7的黑色
  71522. backgroundColor: 'rgba(50,50,50,0.7)',
  71523. // 提示边框颜色
  71524. borderColor: '#333',
  71525. // 提示边框圆角,单位px,默认为4
  71526. borderRadius: 4,
  71527. // 提示边框线宽,单位px,默认为0(无边框)
  71528. borderWidth: 0,
  71529. // 提示内边距,单位px,默认各方向内边距为5,
  71530. // 接受数组分别设定上右下左边距,同css
  71531. padding: 5,
  71532. // Extra css text
  71533. extraCssText: '',
  71534. // 坐标轴指示器,坐标轴触发有效
  71535. axisPointer: {
  71536. // 默认为直线
  71537. // 可选为:'line' | 'shadow' | 'cross'
  71538. type: 'line',
  71539. // type 为 line 的时候有效,指定 tooltip line 所在的轴,可选
  71540. // 可选 'x' | 'y' | 'angle' | 'radius' | 'auto'
  71541. // 默认 'auto',会选择类型为 category 的轴,对于双数值轴,笛卡尔坐标系会默认选择 x 轴
  71542. // 极坐标系会默认选择 angle 轴
  71543. axis: 'auto',
  71544. animation: 'auto',
  71545. animationDurationUpdate: 200,
  71546. animationEasingUpdate: 'exponentialOut',
  71547. crossStyle: {
  71548. color: '#999',
  71549. width: 1,
  71550. type: 'dashed',
  71551. // TODO formatter
  71552. textStyle: {}
  71553. }
  71554. // lineStyle and shadowStyle should not be specified here,
  71555. // otherwise it will always override those styles on option.axisPointer.
  71556. },
  71557. textStyle: {
  71558. color: '#fff',
  71559. fontSize: 14
  71560. }
  71561. }
  71562. });
  71563. /*
  71564. * Licensed to the Apache Software Foundation (ASF) under one
  71565. * or more contributor license agreements. See the NOTICE file
  71566. * distributed with this work for additional information
  71567. * regarding copyright ownership. The ASF licenses this file
  71568. * to you under the Apache License, Version 2.0 (the
  71569. * "License"); you may not use this file except in compliance
  71570. * with the License. You may obtain a copy of the License at
  71571. *
  71572. * http://www.apache.org/licenses/LICENSE-2.0
  71573. *
  71574. * Unless required by applicable law or agreed to in writing,
  71575. * software distributed under the License is distributed on an
  71576. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71577. * KIND, either express or implied. See the License for the
  71578. * specific language governing permissions and limitations
  71579. * under the License.
  71580. */
  71581. var each$22 = each$1;
  71582. var toCamelCase$1 = toCamelCase;
  71583. var vendors = ['', '-webkit-', '-moz-', '-o-'];
  71584. var gCssText = 'position:absolute;display:block;border-style:solid;white-space:nowrap;z-index:9999999;';
  71585. /**
  71586. * @param {number} duration
  71587. * @return {string}
  71588. * @inner
  71589. */
  71590. function assembleTransition(duration) {
  71591. var transitionCurve = 'cubic-bezier(0.23, 1, 0.32, 1)';
  71592. var transitionText = 'left ' + duration + 's ' + transitionCurve + ','
  71593. + 'top ' + duration + 's ' + transitionCurve;
  71594. return map(vendors, function (vendorPrefix) {
  71595. return vendorPrefix + 'transition:' + transitionText;
  71596. }).join(';');
  71597. }
  71598. /**
  71599. * @param {Object} textStyle
  71600. * @return {string}
  71601. * @inner
  71602. */
  71603. function assembleFont(textStyleModel) {
  71604. var cssText = [];
  71605. var fontSize = textStyleModel.get('fontSize');
  71606. var color = textStyleModel.getTextColor();
  71607. color && cssText.push('color:' + color);
  71608. cssText.push('font:' + textStyleModel.getFont());
  71609. fontSize
  71610. && cssText.push('line-height:' + Math.round(fontSize * 3 / 2) + 'px');
  71611. each$22(['decoration', 'align'], function (name) {
  71612. var val = textStyleModel.get(name);
  71613. val && cssText.push('text-' + name + ':' + val);
  71614. });
  71615. return cssText.join(';');
  71616. }
  71617. /**
  71618. * @param {Object} tooltipModel
  71619. * @return {string}
  71620. * @inner
  71621. */
  71622. function assembleCssText(tooltipModel) {
  71623. var cssText = [];
  71624. var transitionDuration = tooltipModel.get('transitionDuration');
  71625. var backgroundColor = tooltipModel.get('backgroundColor');
  71626. var textStyleModel = tooltipModel.getModel('textStyle');
  71627. var padding = tooltipModel.get('padding');
  71628. // Animation transition. Do not animate when transitionDuration is 0.
  71629. transitionDuration
  71630. && cssText.push(assembleTransition(transitionDuration));
  71631. if (backgroundColor) {
  71632. if (env$1.canvasSupported) {
  71633. cssText.push('background-Color:' + backgroundColor);
  71634. }
  71635. else {
  71636. // for ie
  71637. cssText.push(
  71638. 'background-Color:#' + toHex(backgroundColor)
  71639. );
  71640. cssText.push('filter:alpha(opacity=70)');
  71641. }
  71642. }
  71643. // Border style
  71644. each$22(['width', 'color', 'radius'], function (name) {
  71645. var borderName = 'border-' + name;
  71646. var camelCase = toCamelCase$1(borderName);
  71647. var val = tooltipModel.get(camelCase);
  71648. val != null
  71649. && cssText.push(borderName + ':' + val + (name === 'color' ? '' : 'px'));
  71650. });
  71651. // Text style
  71652. cssText.push(assembleFont(textStyleModel));
  71653. // Padding
  71654. if (padding != null) {
  71655. cssText.push('padding:' + normalizeCssArray$1(padding).join('px ') + 'px');
  71656. }
  71657. return cssText.join(';') + ';';
  71658. }
  71659. // If not able to make, do not modify the input `out`.
  71660. function makeStyleCoord(out, zr, appendToBody, zrX, zrY) {
  71661. var zrPainter = zr && zr.painter;
  71662. if (appendToBody) {
  71663. var zrViewportRoot = zrPainter && zrPainter.getViewportRoot();
  71664. if (zrViewportRoot) {
  71665. // Some APPs might use scale on body, so we support CSS transform here.
  71666. transformLocalCoord(out, zrViewportRoot, document.body, zrX, zrY);
  71667. }
  71668. }
  71669. else {
  71670. out[0] = zrX;
  71671. out[1] = zrY;
  71672. // xy should be based on canvas root. But tooltipContent is
  71673. // the sibling of canvas root. So padding of ec container
  71674. // should be considered here.
  71675. var viewportRootOffset = zrPainter && zrPainter.getViewportRootOffset();
  71676. if (viewportRootOffset) {
  71677. out[0] += viewportRootOffset.offsetLeft;
  71678. out[1] += viewportRootOffset.offsetTop;
  71679. }
  71680. }
  71681. }
  71682. /**
  71683. * @alias module:echarts/component/tooltip/TooltipContent
  71684. * @param {HTMLElement} container
  71685. * @param {ExtensionAPI} api
  71686. * @param {Object} [opt]
  71687. * @param {boolean} [opt.appendToBody]
  71688. * `false`: the DOM element will be inside the container. Default value.
  71689. * `true`: the DOM element will be appended to HTML body, which avoid
  71690. * some overflow clip but intrude outside of the container.
  71691. * @constructor
  71692. */
  71693. function TooltipContent(container, api, opt) {
  71694. if (env$1.wxa) {
  71695. return null;
  71696. }
  71697. var el = document.createElement('div');
  71698. el.domBelongToZr = true;
  71699. this.el = el;
  71700. var zr = this._zr = api.getZr();
  71701. var appendToBody = this._appendToBody = opt && opt.appendToBody;
  71702. this._styleCoord = [0, 0];
  71703. makeStyleCoord(this._styleCoord, zr, appendToBody, api.getWidth() / 2, api.getHeight() / 2);
  71704. if (appendToBody) {
  71705. document.body.appendChild(el);
  71706. }
  71707. else {
  71708. container.appendChild(el);
  71709. }
  71710. this._container = container;
  71711. this._show = false;
  71712. /**
  71713. * @private
  71714. */
  71715. this._hideTimeout;
  71716. // FIXME
  71717. // Is it needed to trigger zr event manually if
  71718. // the browser do not support `pointer-events: none`.
  71719. var self = this;
  71720. el.onmouseenter = function () {
  71721. // clear the timeout in hideLater and keep showing tooltip
  71722. if (self._enterable) {
  71723. clearTimeout(self._hideTimeout);
  71724. self._show = true;
  71725. }
  71726. self._inContent = true;
  71727. };
  71728. el.onmousemove = function (e) {
  71729. e = e || window.event;
  71730. if (!self._enterable) {
  71731. // `pointer-events: none` is set to tooltip content div
  71732. // if `enterable` is set as `false`, and `el.onmousemove`
  71733. // can not be triggered. But in browser that do not
  71734. // support `pointer-events`, we need to do this:
  71735. // Try trigger zrender event to avoid mouse
  71736. // in and out shape too frequently
  71737. var handler = zr.handler;
  71738. var zrViewportRoot = zr.painter.getViewportRoot();
  71739. normalizeEvent(zrViewportRoot, e, true);
  71740. handler.dispatch('mousemove', e);
  71741. }
  71742. };
  71743. el.onmouseleave = function () {
  71744. if (self._enterable) {
  71745. if (self._show) {
  71746. self.hideLater(self._hideDelay);
  71747. }
  71748. }
  71749. self._inContent = false;
  71750. };
  71751. }
  71752. TooltipContent.prototype = {
  71753. constructor: TooltipContent,
  71754. /**
  71755. * @private
  71756. * @type {boolean}
  71757. */
  71758. _enterable: true,
  71759. /**
  71760. * Update when tooltip is rendered
  71761. */
  71762. update: function () {
  71763. // FIXME
  71764. // Move this logic to ec main?
  71765. var container = this._container;
  71766. var stl = container.currentStyle
  71767. || document.defaultView.getComputedStyle(container);
  71768. var domStyle = container.style;
  71769. if (domStyle.position !== 'absolute' && stl.position !== 'absolute') {
  71770. domStyle.position = 'relative';
  71771. }
  71772. // Hide the tooltip
  71773. // PENDING
  71774. // this.hide();
  71775. },
  71776. show: function (tooltipModel) {
  71777. clearTimeout(this._hideTimeout);
  71778. var el = this.el;
  71779. var styleCoord = this._styleCoord;
  71780. el.style.cssText = gCssText + assembleCssText(tooltipModel)
  71781. // Because of the reason described in:
  71782. // http://stackoverflow.com/questions/21125587/css3-transition-not-working-in-chrome-anymore
  71783. // we should set initial value to `left` and `top`.
  71784. + ';left:' + styleCoord[0] + 'px;top:' + styleCoord[1] + 'px;'
  71785. + (tooltipModel.get('extraCssText') || '');
  71786. el.style.display = el.innerHTML ? 'block' : 'none';
  71787. // If mouse occsionally move over the tooltip, a mouseout event will be
  71788. // triggered by canvas, and cuase some unexpectable result like dragging
  71789. // stop, "unfocusAdjacency". Here `pointer-events: none` is used to solve
  71790. // it. Although it is not suppored by IE8~IE10, fortunately it is a rare
  71791. // scenario.
  71792. el.style.pointerEvents = this._enterable ? 'auto' : 'none';
  71793. this._show = true;
  71794. },
  71795. setContent: function (content) {
  71796. this.el.innerHTML = content == null ? '' : content;
  71797. },
  71798. setEnterable: function (enterable) {
  71799. this._enterable = enterable;
  71800. },
  71801. getSize: function () {
  71802. var el = this.el;
  71803. return [el.clientWidth, el.clientHeight];
  71804. },
  71805. moveTo: function (zrX, zrY) {
  71806. var styleCoord = this._styleCoord;
  71807. makeStyleCoord(styleCoord, this._zr, this._appendToBody, zrX, zrY);
  71808. var style = this.el.style;
  71809. style.left = styleCoord[0] + 'px';
  71810. style.top = styleCoord[1] + 'px';
  71811. },
  71812. hide: function () {
  71813. this.el.style.display = 'none';
  71814. this._show = false;
  71815. },
  71816. hideLater: function (time) {
  71817. if (this._show && !(this._inContent && this._enterable)) {
  71818. if (time) {
  71819. this._hideDelay = time;
  71820. // Set show false to avoid invoke hideLater mutiple times
  71821. this._show = false;
  71822. this._hideTimeout = setTimeout(bind(this.hide, this), time);
  71823. }
  71824. else {
  71825. this.hide();
  71826. }
  71827. }
  71828. },
  71829. isShow: function () {
  71830. return this._show;
  71831. },
  71832. dispose: function () {
  71833. this.el.parentNode.removeChild(this.el);
  71834. },
  71835. getOuterSize: function () {
  71836. var width = this.el.clientWidth;
  71837. var height = this.el.clientHeight;
  71838. // Consider browser compatibility.
  71839. // IE8 does not support getComputedStyle.
  71840. if (document.defaultView && document.defaultView.getComputedStyle) {
  71841. var stl = document.defaultView.getComputedStyle(this.el);
  71842. if (stl) {
  71843. width += parseInt(stl.borderLeftWidth, 10) + parseInt(stl.borderRightWidth, 10);
  71844. height += parseInt(stl.borderTopWidth, 10) + parseInt(stl.borderBottomWidth, 10);
  71845. }
  71846. }
  71847. return {width: width, height: height};
  71848. }
  71849. };
  71850. /*
  71851. * Licensed to the Apache Software Foundation (ASF) under one
  71852. * or more contributor license agreements. See the NOTICE file
  71853. * distributed with this work for additional information
  71854. * regarding copyright ownership. The ASF licenses this file
  71855. * to you under the Apache License, Version 2.0 (the
  71856. * "License"); you may not use this file except in compliance
  71857. * with the License. You may obtain a copy of the License at
  71858. *
  71859. * http://www.apache.org/licenses/LICENSE-2.0
  71860. *
  71861. * Unless required by applicable law or agreed to in writing,
  71862. * software distributed under the License is distributed on an
  71863. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71864. * KIND, either express or implied. See the License for the
  71865. * specific language governing permissions and limitations
  71866. * under the License.
  71867. */
  71868. // import Group from 'zrender/src/container/Group';
  71869. /**
  71870. * @alias module:echarts/component/tooltip/TooltipRichContent
  71871. * @constructor
  71872. */
  71873. function TooltipRichContent(api) {
  71874. this._zr = api.getZr();
  71875. this._show = false;
  71876. /**
  71877. * @private
  71878. */
  71879. this._hideTimeout;
  71880. }
  71881. TooltipRichContent.prototype = {
  71882. constructor: TooltipRichContent,
  71883. /**
  71884. * @private
  71885. * @type {boolean}
  71886. */
  71887. _enterable: true,
  71888. /**
  71889. * Update when tooltip is rendered
  71890. */
  71891. update: function () {
  71892. // noop
  71893. },
  71894. show: function (tooltipModel) {
  71895. if (this._hideTimeout) {
  71896. clearTimeout(this._hideTimeout);
  71897. }
  71898. this.el.attr('show', true);
  71899. this._show = true;
  71900. },
  71901. /**
  71902. * Set tooltip content
  71903. *
  71904. * @param {string} content rich text string of content
  71905. * @param {Object} markerRich rich text style
  71906. * @param {Object} tooltipModel tooltip model
  71907. */
  71908. setContent: function (content, markerRich, tooltipModel) {
  71909. if (this.el) {
  71910. this._zr.remove(this.el);
  71911. }
  71912. var markers = {};
  71913. var text = content;
  71914. var prefix = '{marker';
  71915. var suffix = '|}';
  71916. var startId = text.indexOf(prefix);
  71917. while (startId >= 0) {
  71918. var endId = text.indexOf(suffix);
  71919. var name = text.substr(startId + prefix.length, endId - startId - prefix.length);
  71920. if (name.indexOf('sub') > -1) {
  71921. markers['marker' + name] = {
  71922. textWidth: 4,
  71923. textHeight: 4,
  71924. textBorderRadius: 2,
  71925. textBackgroundColor: markerRich[name],
  71926. // TODO: textOffset is not implemented for rich text
  71927. textOffset: [3, 0]
  71928. };
  71929. }
  71930. else {
  71931. markers['marker' + name] = {
  71932. textWidth: 10,
  71933. textHeight: 10,
  71934. textBorderRadius: 5,
  71935. textBackgroundColor: markerRich[name]
  71936. };
  71937. }
  71938. text = text.substr(endId + 1);
  71939. startId = text.indexOf('{marker');
  71940. }
  71941. this.el = new Text({
  71942. style: {
  71943. rich: markers,
  71944. text: content,
  71945. textLineHeight: 20,
  71946. textBackgroundColor: tooltipModel.get('backgroundColor'),
  71947. textBorderRadius: tooltipModel.get('borderRadius'),
  71948. textFill: tooltipModel.get('textStyle.color'),
  71949. textPadding: tooltipModel.get('padding')
  71950. },
  71951. z: tooltipModel.get('z')
  71952. });
  71953. this._zr.add(this.el);
  71954. var self = this;
  71955. this.el.on('mouseover', function () {
  71956. // clear the timeout in hideLater and keep showing tooltip
  71957. if (self._enterable) {
  71958. clearTimeout(self._hideTimeout);
  71959. self._show = true;
  71960. }
  71961. self._inContent = true;
  71962. });
  71963. this.el.on('mouseout', function () {
  71964. if (self._enterable) {
  71965. if (self._show) {
  71966. self.hideLater(self._hideDelay);
  71967. }
  71968. }
  71969. self._inContent = false;
  71970. });
  71971. },
  71972. setEnterable: function (enterable) {
  71973. this._enterable = enterable;
  71974. },
  71975. getSize: function () {
  71976. var bounding = this.el.getBoundingRect();
  71977. return [bounding.width, bounding.height];
  71978. },
  71979. moveTo: function (x, y) {
  71980. if (this.el) {
  71981. this.el.attr('position', [x, y]);
  71982. }
  71983. },
  71984. hide: function () {
  71985. if (this.el) {
  71986. this.el.hide();
  71987. }
  71988. this._show = false;
  71989. },
  71990. hideLater: function (time) {
  71991. if (this._show && !(this._inContent && this._enterable)) {
  71992. if (time) {
  71993. this._hideDelay = time;
  71994. // Set show false to avoid invoke hideLater mutiple times
  71995. this._show = false;
  71996. this._hideTimeout = setTimeout(bind(this.hide, this), time);
  71997. }
  71998. else {
  71999. this.hide();
  72000. }
  72001. }
  72002. },
  72003. isShow: function () {
  72004. return this._show;
  72005. },
  72006. getOuterSize: function () {
  72007. var size = this.getSize();
  72008. return {
  72009. width: size[0],
  72010. height: size[1]
  72011. };
  72012. }
  72013. };
  72014. /*
  72015. * Licensed to the Apache Software Foundation (ASF) under one
  72016. * or more contributor license agreements. See the NOTICE file
  72017. * distributed with this work for additional information
  72018. * regarding copyright ownership. The ASF licenses this file
  72019. * to you under the Apache License, Version 2.0 (the
  72020. * "License"); you may not use this file except in compliance
  72021. * with the License. You may obtain a copy of the License at
  72022. *
  72023. * http://www.apache.org/licenses/LICENSE-2.0
  72024. *
  72025. * Unless required by applicable law or agreed to in writing,
  72026. * software distributed under the License is distributed on an
  72027. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72028. * KIND, either express or implied. See the License for the
  72029. * specific language governing permissions and limitations
  72030. * under the License.
  72031. */
  72032. var bind$3 = bind;
  72033. var each$21 = each$1;
  72034. var parsePercent$2 = parsePercent$1;
  72035. var proxyRect = new Rect({
  72036. shape: {x: -1, y: -1, width: 2, height: 2}
  72037. });
  72038. extendComponentView({
  72039. type: 'tooltip',
  72040. init: function (ecModel, api) {
  72041. if (env$1.node) {
  72042. return;
  72043. }
  72044. var tooltipModel = ecModel.getComponent('tooltip');
  72045. var renderMode = tooltipModel.get('renderMode');
  72046. this._renderMode = getTooltipRenderMode(renderMode);
  72047. var tooltipContent;
  72048. if (this._renderMode === 'html') {
  72049. tooltipContent = new TooltipContent(api.getDom(), api, {
  72050. appendToBody: tooltipModel.get('appendToBody', true)
  72051. });
  72052. this._newLine = '<br/>';
  72053. }
  72054. else {
  72055. tooltipContent = new TooltipRichContent(api);
  72056. this._newLine = '\n';
  72057. }
  72058. this._tooltipContent = tooltipContent;
  72059. },
  72060. render: function (tooltipModel, ecModel, api) {
  72061. if (env$1.node) {
  72062. return;
  72063. }
  72064. // Reset
  72065. this.group.removeAll();
  72066. /**
  72067. * @private
  72068. * @type {module:echarts/component/tooltip/TooltipModel}
  72069. */
  72070. this._tooltipModel = tooltipModel;
  72071. /**
  72072. * @private
  72073. * @type {module:echarts/model/Global}
  72074. */
  72075. this._ecModel = ecModel;
  72076. /**
  72077. * @private
  72078. * @type {module:echarts/ExtensionAPI}
  72079. */
  72080. this._api = api;
  72081. /**
  72082. * Should be cleaned when render.
  72083. * @private
  72084. * @type {Array.<Array.<Object>>}
  72085. */
  72086. this._lastDataByCoordSys = null;
  72087. /**
  72088. * @private
  72089. * @type {boolean}
  72090. */
  72091. this._alwaysShowContent = tooltipModel.get('alwaysShowContent');
  72092. var tooltipContent = this._tooltipContent;
  72093. tooltipContent.update();
  72094. tooltipContent.setEnterable(tooltipModel.get('enterable'));
  72095. this._initGlobalListener();
  72096. this._keepShow();
  72097. },
  72098. _initGlobalListener: function () {
  72099. var tooltipModel = this._tooltipModel;
  72100. var triggerOn = tooltipModel.get('triggerOn');
  72101. register(
  72102. 'itemTooltip',
  72103. this._api,
  72104. bind$3(function (currTrigger, e, dispatchAction) {
  72105. // If 'none', it is not controlled by mouse totally.
  72106. if (triggerOn !== 'none') {
  72107. if (triggerOn.indexOf(currTrigger) >= 0) {
  72108. this._tryShow(e, dispatchAction);
  72109. }
  72110. else if (currTrigger === 'leave') {
  72111. this._hide(dispatchAction);
  72112. }
  72113. }
  72114. }, this)
  72115. );
  72116. },
  72117. _keepShow: function () {
  72118. var tooltipModel = this._tooltipModel;
  72119. var ecModel = this._ecModel;
  72120. var api = this._api;
  72121. // Try to keep the tooltip show when refreshing
  72122. if (this._lastX != null
  72123. && this._lastY != null
  72124. // When user is willing to control tooltip totally using API,
  72125. // self.manuallyShowTip({x, y}) might cause tooltip hide,
  72126. // which is not expected.
  72127. && tooltipModel.get('triggerOn') !== 'none'
  72128. ) {
  72129. var self = this;
  72130. clearTimeout(this._refreshUpdateTimeout);
  72131. this._refreshUpdateTimeout = setTimeout(function () {
  72132. // Show tip next tick after other charts are rendered
  72133. // In case highlight action has wrong result
  72134. // FIXME
  72135. !api.isDisposed() && self.manuallyShowTip(tooltipModel, ecModel, api, {
  72136. x: self._lastX,
  72137. y: self._lastY
  72138. });
  72139. });
  72140. }
  72141. },
  72142. /**
  72143. * Show tip manually by
  72144. * dispatchAction({
  72145. * type: 'showTip',
  72146. * x: 10,
  72147. * y: 10
  72148. * });
  72149. * Or
  72150. * dispatchAction({
  72151. * type: 'showTip',
  72152. * seriesIndex: 0,
  72153. * dataIndex or dataIndexInside or name
  72154. * });
  72155. *
  72156. * TODO Batch
  72157. */
  72158. manuallyShowTip: function (tooltipModel, ecModel, api, payload) {
  72159. if (payload.from === this.uid || env$1.node) {
  72160. return;
  72161. }
  72162. var dispatchAction = makeDispatchAction$1(payload, api);
  72163. // Reset ticket
  72164. this._ticket = '';
  72165. // When triggered from axisPointer.
  72166. var dataByCoordSys = payload.dataByCoordSys;
  72167. if (payload.tooltip && payload.x != null && payload.y != null) {
  72168. var el = proxyRect;
  72169. el.position = [payload.x, payload.y];
  72170. el.update();
  72171. el.tooltip = payload.tooltip;
  72172. // Manually show tooltip while view is not using zrender elements.
  72173. this._tryShow({
  72174. offsetX: payload.x,
  72175. offsetY: payload.y,
  72176. target: el
  72177. }, dispatchAction);
  72178. }
  72179. else if (dataByCoordSys) {
  72180. this._tryShow({
  72181. offsetX: payload.x,
  72182. offsetY: payload.y,
  72183. position: payload.position,
  72184. dataByCoordSys: payload.dataByCoordSys,
  72185. tooltipOption: payload.tooltipOption
  72186. }, dispatchAction);
  72187. }
  72188. else if (payload.seriesIndex != null) {
  72189. if (this._manuallyAxisShowTip(tooltipModel, ecModel, api, payload)) {
  72190. return;
  72191. }
  72192. var pointInfo = findPointFromSeries(payload, ecModel);
  72193. var cx = pointInfo.point[0];
  72194. var cy = pointInfo.point[1];
  72195. if (cx != null && cy != null) {
  72196. this._tryShow({
  72197. offsetX: cx,
  72198. offsetY: cy,
  72199. position: payload.position,
  72200. target: pointInfo.el
  72201. }, dispatchAction);
  72202. }
  72203. }
  72204. else if (payload.x != null && payload.y != null) {
  72205. // FIXME
  72206. // should wrap dispatchAction like `axisPointer/globalListener` ?
  72207. api.dispatchAction({
  72208. type: 'updateAxisPointer',
  72209. x: payload.x,
  72210. y: payload.y
  72211. });
  72212. this._tryShow({
  72213. offsetX: payload.x,
  72214. offsetY: payload.y,
  72215. position: payload.position,
  72216. target: api.getZr().findHover(payload.x, payload.y).target
  72217. }, dispatchAction);
  72218. }
  72219. },
  72220. manuallyHideTip: function (tooltipModel, ecModel, api, payload) {
  72221. var tooltipContent = this._tooltipContent;
  72222. if (!this._alwaysShowContent && this._tooltipModel) {
  72223. tooltipContent.hideLater(this._tooltipModel.get('hideDelay'));
  72224. }
  72225. this._lastX = this._lastY = null;
  72226. if (payload.from !== this.uid) {
  72227. this._hide(makeDispatchAction$1(payload, api));
  72228. }
  72229. },
  72230. // Be compatible with previous design, that is, when tooltip.type is 'axis' and
  72231. // dispatchAction 'showTip' with seriesIndex and dataIndex will trigger axis pointer
  72232. // and tooltip.
  72233. _manuallyAxisShowTip: function (tooltipModel, ecModel, api, payload) {
  72234. var seriesIndex = payload.seriesIndex;
  72235. var dataIndex = payload.dataIndex;
  72236. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
  72237. if (seriesIndex == null || dataIndex == null || coordSysAxesInfo == null) {
  72238. return;
  72239. }
  72240. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  72241. if (!seriesModel) {
  72242. return;
  72243. }
  72244. var data = seriesModel.getData();
  72245. var tooltipModel = buildTooltipModel([
  72246. data.getItemModel(dataIndex),
  72247. seriesModel,
  72248. (seriesModel.coordinateSystem || {}).model,
  72249. tooltipModel
  72250. ]);
  72251. if (tooltipModel.get('trigger') !== 'axis') {
  72252. return;
  72253. }
  72254. api.dispatchAction({
  72255. type: 'updateAxisPointer',
  72256. seriesIndex: seriesIndex,
  72257. dataIndex: dataIndex,
  72258. position: payload.position
  72259. });
  72260. return true;
  72261. },
  72262. _tryShow: function (e, dispatchAction) {
  72263. var el = e.target;
  72264. var tooltipModel = this._tooltipModel;
  72265. if (!tooltipModel) {
  72266. return;
  72267. }
  72268. // Save mouse x, mouse y. So we can try to keep showing the tip if chart is refreshed
  72269. this._lastX = e.offsetX;
  72270. this._lastY = e.offsetY;
  72271. var dataByCoordSys = e.dataByCoordSys;
  72272. if (dataByCoordSys && dataByCoordSys.length) {
  72273. this._showAxisTooltip(dataByCoordSys, e);
  72274. }
  72275. // Always show item tooltip if mouse is on the element with dataIndex
  72276. else if (el && el.dataIndex != null) {
  72277. this._lastDataByCoordSys = null;
  72278. this._showSeriesItemTooltip(e, el, dispatchAction);
  72279. }
  72280. // Tooltip provided directly. Like legend.
  72281. else if (el && el.tooltip) {
  72282. this._lastDataByCoordSys = null;
  72283. this._showComponentItemTooltip(e, el, dispatchAction);
  72284. }
  72285. else {
  72286. this._lastDataByCoordSys = null;
  72287. this._hide(dispatchAction);
  72288. }
  72289. },
  72290. _showOrMove: function (tooltipModel, cb) {
  72291. // showDelay is used in this case: tooltip.enterable is set
  72292. // as true. User intent to move mouse into tooltip and click
  72293. // something. `showDelay` makes it easyer to enter the content
  72294. // but tooltip do not move immediately.
  72295. var delay = tooltipModel.get('showDelay');
  72296. cb = bind(cb, this);
  72297. clearTimeout(this._showTimout);
  72298. delay > 0
  72299. ? (this._showTimout = setTimeout(cb, delay))
  72300. : cb();
  72301. },
  72302. _showAxisTooltip: function (dataByCoordSys, e) {
  72303. var ecModel = this._ecModel;
  72304. var globalTooltipModel = this._tooltipModel;
  72305. var point = [e.offsetX, e.offsetY];
  72306. var singleDefaultHTML = [];
  72307. var singleParamsList = [];
  72308. var singleTooltipModel = buildTooltipModel([
  72309. e.tooltipOption,
  72310. globalTooltipModel
  72311. ]);
  72312. var renderMode = this._renderMode;
  72313. var newLine = this._newLine;
  72314. var markers = {};
  72315. each$21(dataByCoordSys, function (itemCoordSys) {
  72316. // var coordParamList = [];
  72317. // var coordDefaultHTML = [];
  72318. // var coordTooltipModel = buildTooltipModel([
  72319. // e.tooltipOption,
  72320. // itemCoordSys.tooltipOption,
  72321. // ecModel.getComponent(itemCoordSys.coordSysMainType, itemCoordSys.coordSysIndex),
  72322. // globalTooltipModel
  72323. // ]);
  72324. // var displayMode = coordTooltipModel.get('displayMode');
  72325. // var paramsList = displayMode === 'single' ? singleParamsList : [];
  72326. each$21(itemCoordSys.dataByAxis, function (item) {
  72327. var axisModel = ecModel.getComponent(item.axisDim + 'Axis', item.axisIndex);
  72328. var axisValue = item.value;
  72329. var seriesDefaultHTML = [];
  72330. if (!axisModel || axisValue == null) {
  72331. return;
  72332. }
  72333. var valueLabel = getValueLabel(
  72334. axisValue, axisModel.axis, ecModel,
  72335. item.seriesDataIndices,
  72336. item.valueLabelOpt
  72337. );
  72338. each$1(item.seriesDataIndices, function (idxItem) {
  72339. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  72340. var dataIndex = idxItem.dataIndexInside;
  72341. var dataParams = series && series.getDataParams(dataIndex);
  72342. dataParams.axisDim = item.axisDim;
  72343. dataParams.axisIndex = item.axisIndex;
  72344. dataParams.axisType = item.axisType;
  72345. dataParams.axisId = item.axisId;
  72346. dataParams.axisValue = getAxisRawValue(axisModel.axis, axisValue);
  72347. dataParams.axisValueLabel = valueLabel;
  72348. if (dataParams) {
  72349. singleParamsList.push(dataParams);
  72350. var seriesTooltip = series.formatTooltip(dataIndex, true, null, renderMode);
  72351. var html;
  72352. if (isObject$1(seriesTooltip)) {
  72353. html = seriesTooltip.html;
  72354. var newMarkers = seriesTooltip.markers;
  72355. merge(markers, newMarkers);
  72356. }
  72357. else {
  72358. html = seriesTooltip;
  72359. }
  72360. seriesDefaultHTML.push(html);
  72361. }
  72362. });
  72363. // Default tooltip content
  72364. // FIXME
  72365. // (1) shold be the first data which has name?
  72366. // (2) themeRiver, firstDataIndex is array, and first line is unnecessary.
  72367. var firstLine = valueLabel;
  72368. if (renderMode !== 'html') {
  72369. singleDefaultHTML.push(seriesDefaultHTML.join(newLine));
  72370. }
  72371. else {
  72372. singleDefaultHTML.push(
  72373. (firstLine ? encodeHTML(firstLine) + newLine : '')
  72374. + seriesDefaultHTML.join(newLine)
  72375. );
  72376. }
  72377. });
  72378. }, this);
  72379. // In most case, the second axis is shown upper than the first one.
  72380. singleDefaultHTML.reverse();
  72381. singleDefaultHTML = singleDefaultHTML.join(this._newLine + this._newLine);
  72382. var positionExpr = e.position;
  72383. this._showOrMove(singleTooltipModel, function () {
  72384. if (this._updateContentNotChangedOnAxis(dataByCoordSys)) {
  72385. this._updatePosition(
  72386. singleTooltipModel,
  72387. positionExpr,
  72388. point[0], point[1],
  72389. this._tooltipContent,
  72390. singleParamsList
  72391. );
  72392. }
  72393. else {
  72394. this._showTooltipContent(
  72395. singleTooltipModel, singleDefaultHTML, singleParamsList, Math.random(),
  72396. point[0], point[1], positionExpr, undefined, markers
  72397. );
  72398. }
  72399. });
  72400. // Do not trigger events here, because this branch only be entered
  72401. // from dispatchAction.
  72402. },
  72403. _showSeriesItemTooltip: function (e, el, dispatchAction) {
  72404. var ecModel = this._ecModel;
  72405. // Use dataModel in element if possible
  72406. // Used when mouseover on a element like markPoint or edge
  72407. // In which case, the data is not main data in series.
  72408. var seriesIndex = el.seriesIndex;
  72409. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  72410. // For example, graph link.
  72411. var dataModel = el.dataModel || seriesModel;
  72412. var dataIndex = el.dataIndex;
  72413. var dataType = el.dataType;
  72414. var data = dataModel.getData(dataType);
  72415. var tooltipModel = buildTooltipModel([
  72416. data.getItemModel(dataIndex),
  72417. dataModel,
  72418. seriesModel && (seriesModel.coordinateSystem || {}).model,
  72419. this._tooltipModel
  72420. ]);
  72421. var tooltipTrigger = tooltipModel.get('trigger');
  72422. if (tooltipTrigger != null && tooltipTrigger !== 'item') {
  72423. return;
  72424. }
  72425. var params = dataModel.getDataParams(dataIndex, dataType);
  72426. var seriesTooltip = dataModel.formatTooltip(dataIndex, false, dataType, this._renderMode);
  72427. var defaultHtml;
  72428. var markers;
  72429. if (isObject$1(seriesTooltip)) {
  72430. defaultHtml = seriesTooltip.html;
  72431. markers = seriesTooltip.markers;
  72432. }
  72433. else {
  72434. defaultHtml = seriesTooltip;
  72435. markers = null;
  72436. }
  72437. var asyncTicket = 'item_' + dataModel.name + '_' + dataIndex;
  72438. this._showOrMove(tooltipModel, function () {
  72439. this._showTooltipContent(
  72440. tooltipModel, defaultHtml, params, asyncTicket,
  72441. e.offsetX, e.offsetY, e.position, e.target, markers
  72442. );
  72443. });
  72444. // FIXME
  72445. // duplicated showtip if manuallyShowTip is called from dispatchAction.
  72446. dispatchAction({
  72447. type: 'showTip',
  72448. dataIndexInside: dataIndex,
  72449. dataIndex: data.getRawIndex(dataIndex),
  72450. seriesIndex: seriesIndex,
  72451. from: this.uid
  72452. });
  72453. },
  72454. _showComponentItemTooltip: function (e, el, dispatchAction) {
  72455. var tooltipOpt = el.tooltip;
  72456. if (typeof tooltipOpt === 'string') {
  72457. var content = tooltipOpt;
  72458. tooltipOpt = {
  72459. content: content,
  72460. // Fixed formatter
  72461. formatter: content
  72462. };
  72463. }
  72464. var subTooltipModel = new Model(tooltipOpt, this._tooltipModel, this._ecModel);
  72465. var defaultHtml = subTooltipModel.get('content');
  72466. var asyncTicket = Math.random();
  72467. // Do not check whether `trigger` is 'none' here, because `trigger`
  72468. // only works on cooridinate system. In fact, we have not found case
  72469. // that requires setting `trigger` nothing on component yet.
  72470. this._showOrMove(subTooltipModel, function () {
  72471. this._showTooltipContent(
  72472. subTooltipModel, defaultHtml, subTooltipModel.get('formatterParams') || {},
  72473. asyncTicket, e.offsetX, e.offsetY, e.position, el
  72474. );
  72475. });
  72476. // If not dispatch showTip, tip may be hide triggered by axis.
  72477. dispatchAction({
  72478. type: 'showTip',
  72479. from: this.uid
  72480. });
  72481. },
  72482. _showTooltipContent: function (
  72483. tooltipModel, defaultHtml, params, asyncTicket, x, y, positionExpr, el, markers
  72484. ) {
  72485. // Reset ticket
  72486. this._ticket = '';
  72487. if (!tooltipModel.get('showContent') || !tooltipModel.get('show')) {
  72488. return;
  72489. }
  72490. var tooltipContent = this._tooltipContent;
  72491. var formatter = tooltipModel.get('formatter');
  72492. positionExpr = positionExpr || tooltipModel.get('position');
  72493. var html = defaultHtml;
  72494. if (formatter && typeof formatter === 'string') {
  72495. html = formatTpl(formatter, params, true);
  72496. }
  72497. else if (typeof formatter === 'function') {
  72498. var callback = bind$3(function (cbTicket, html) {
  72499. if (cbTicket === this._ticket) {
  72500. tooltipContent.setContent(html, markers, tooltipModel);
  72501. this._updatePosition(
  72502. tooltipModel, positionExpr, x, y, tooltipContent, params, el
  72503. );
  72504. }
  72505. }, this);
  72506. this._ticket = asyncTicket;
  72507. html = formatter(params, asyncTicket, callback);
  72508. }
  72509. tooltipContent.setContent(html, markers, tooltipModel);
  72510. tooltipContent.show(tooltipModel);
  72511. this._updatePosition(
  72512. tooltipModel, positionExpr, x, y, tooltipContent, params, el
  72513. );
  72514. },
  72515. /**
  72516. * @param {string|Function|Array.<number>|Object} positionExpr
  72517. * @param {number} x Mouse x
  72518. * @param {number} y Mouse y
  72519. * @param {boolean} confine Whether confine tooltip content in view rect.
  72520. * @param {Object|<Array.<Object>} params
  72521. * @param {module:zrender/Element} el target element
  72522. * @param {module:echarts/ExtensionAPI} api
  72523. * @return {Array.<number>}
  72524. */
  72525. _updatePosition: function (tooltipModel, positionExpr, x, y, content, params, el) {
  72526. var viewWidth = this._api.getWidth();
  72527. var viewHeight = this._api.getHeight();
  72528. positionExpr = positionExpr || tooltipModel.get('position');
  72529. var contentSize = content.getSize();
  72530. var align = tooltipModel.get('align');
  72531. var vAlign = tooltipModel.get('verticalAlign');
  72532. var rect = el && el.getBoundingRect().clone();
  72533. el && rect.applyTransform(el.transform);
  72534. if (typeof positionExpr === 'function') {
  72535. // Callback of position can be an array or a string specify the position
  72536. positionExpr = positionExpr([x, y], params, content.el, rect, {
  72537. viewSize: [viewWidth, viewHeight],
  72538. contentSize: contentSize.slice()
  72539. });
  72540. }
  72541. if (isArray(positionExpr)) {
  72542. x = parsePercent$2(positionExpr[0], viewWidth);
  72543. y = parsePercent$2(positionExpr[1], viewHeight);
  72544. }
  72545. else if (isObject$1(positionExpr)) {
  72546. positionExpr.width = contentSize[0];
  72547. positionExpr.height = contentSize[1];
  72548. var layoutRect = getLayoutRect(
  72549. positionExpr, {width: viewWidth, height: viewHeight}
  72550. );
  72551. x = layoutRect.x;
  72552. y = layoutRect.y;
  72553. align = null;
  72554. // When positionExpr is left/top/right/bottom,
  72555. // align and verticalAlign will not work.
  72556. vAlign = null;
  72557. }
  72558. // Specify tooltip position by string 'top' 'bottom' 'left' 'right' around graphic element
  72559. else if (typeof positionExpr === 'string' && el) {
  72560. var pos = calcTooltipPosition(
  72561. positionExpr, rect, contentSize
  72562. );
  72563. x = pos[0];
  72564. y = pos[1];
  72565. }
  72566. else {
  72567. var pos = refixTooltipPosition(
  72568. x, y, content, viewWidth, viewHeight, align ? null : 20, vAlign ? null : 20
  72569. );
  72570. x = pos[0];
  72571. y = pos[1];
  72572. }
  72573. align && (x -= isCenterAlign(align) ? contentSize[0] / 2 : align === 'right' ? contentSize[0] : 0);
  72574. vAlign && (y -= isCenterAlign(vAlign) ? contentSize[1] / 2 : vAlign === 'bottom' ? contentSize[1] : 0);
  72575. if (tooltipModel.get('confine')) {
  72576. var pos = confineTooltipPosition(
  72577. x, y, content, viewWidth, viewHeight
  72578. );
  72579. x = pos[0];
  72580. y = pos[1];
  72581. }
  72582. content.moveTo(x, y);
  72583. },
  72584. // FIXME
  72585. // Should we remove this but leave this to user?
  72586. _updateContentNotChangedOnAxis: function (dataByCoordSys) {
  72587. var lastCoordSys = this._lastDataByCoordSys;
  72588. var contentNotChanged = !!lastCoordSys
  72589. && lastCoordSys.length === dataByCoordSys.length;
  72590. contentNotChanged && each$21(lastCoordSys, function (lastItemCoordSys, indexCoordSys) {
  72591. var lastDataByAxis = lastItemCoordSys.dataByAxis || {};
  72592. var thisItemCoordSys = dataByCoordSys[indexCoordSys] || {};
  72593. var thisDataByAxis = thisItemCoordSys.dataByAxis || [];
  72594. contentNotChanged &= lastDataByAxis.length === thisDataByAxis.length;
  72595. contentNotChanged && each$21(lastDataByAxis, function (lastItem, indexAxis) {
  72596. var thisItem = thisDataByAxis[indexAxis] || {};
  72597. var lastIndices = lastItem.seriesDataIndices || [];
  72598. var newIndices = thisItem.seriesDataIndices || [];
  72599. contentNotChanged
  72600. &= lastItem.value === thisItem.value
  72601. && lastItem.axisType === thisItem.axisType
  72602. && lastItem.axisId === thisItem.axisId
  72603. && lastIndices.length === newIndices.length;
  72604. contentNotChanged && each$21(lastIndices, function (lastIdxItem, j) {
  72605. var newIdxItem = newIndices[j];
  72606. contentNotChanged
  72607. &= lastIdxItem.seriesIndex === newIdxItem.seriesIndex
  72608. && lastIdxItem.dataIndex === newIdxItem.dataIndex;
  72609. });
  72610. });
  72611. });
  72612. this._lastDataByCoordSys = dataByCoordSys;
  72613. return !!contentNotChanged;
  72614. },
  72615. _hide: function (dispatchAction) {
  72616. // Do not directly hideLater here, because this behavior may be prevented
  72617. // in dispatchAction when showTip is dispatched.
  72618. // FIXME
  72619. // duplicated hideTip if manuallyHideTip is called from dispatchAction.
  72620. this._lastDataByCoordSys = null;
  72621. dispatchAction({
  72622. type: 'hideTip',
  72623. from: this.uid
  72624. });
  72625. },
  72626. dispose: function (ecModel, api) {
  72627. if (env$1.node) {
  72628. return;
  72629. }
  72630. this._tooltipContent.dispose();
  72631. unregister('itemTooltip', api);
  72632. }
  72633. });
  72634. /**
  72635. * @param {Array.<Object|module:echarts/model/Model>} modelCascade
  72636. * From top to bottom. (the last one should be globalTooltipModel);
  72637. */
  72638. function buildTooltipModel(modelCascade) {
  72639. var resultModel = modelCascade.pop();
  72640. while (modelCascade.length) {
  72641. var tooltipOpt = modelCascade.pop();
  72642. if (tooltipOpt) {
  72643. if (Model.isInstance(tooltipOpt)) {
  72644. tooltipOpt = tooltipOpt.get('tooltip', true);
  72645. }
  72646. // In each data item tooltip can be simply write:
  72647. // {
  72648. // value: 10,
  72649. // tooltip: 'Something you need to know'
  72650. // }
  72651. if (typeof tooltipOpt === 'string') {
  72652. tooltipOpt = {formatter: tooltipOpt};
  72653. }
  72654. resultModel = new Model(tooltipOpt, resultModel, resultModel.ecModel);
  72655. }
  72656. }
  72657. return resultModel;
  72658. }
  72659. function makeDispatchAction$1(payload, api) {
  72660. return payload.dispatchAction || bind(api.dispatchAction, api);
  72661. }
  72662. function refixTooltipPosition(x, y, content, viewWidth, viewHeight, gapH, gapV) {
  72663. var size = content.getOuterSize();
  72664. var width = size.width;
  72665. var height = size.height;
  72666. if (gapH != null) {
  72667. if (x + width + gapH > viewWidth) {
  72668. x -= width + gapH;
  72669. }
  72670. else {
  72671. x += gapH;
  72672. }
  72673. }
  72674. if (gapV != null) {
  72675. if (y + height + gapV > viewHeight) {
  72676. y -= height + gapV;
  72677. }
  72678. else {
  72679. y += gapV;
  72680. }
  72681. }
  72682. return [x, y];
  72683. }
  72684. function confineTooltipPosition(x, y, content, viewWidth, viewHeight) {
  72685. var size = content.getOuterSize();
  72686. var width = size.width;
  72687. var height = size.height;
  72688. x = Math.min(x + width, viewWidth) - width;
  72689. y = Math.min(y + height, viewHeight) - height;
  72690. x = Math.max(x, 0);
  72691. y = Math.max(y, 0);
  72692. return [x, y];
  72693. }
  72694. function calcTooltipPosition(position, rect, contentSize) {
  72695. var domWidth = contentSize[0];
  72696. var domHeight = contentSize[1];
  72697. var gap = 5;
  72698. var x = 0;
  72699. var y = 0;
  72700. var rectWidth = rect.width;
  72701. var rectHeight = rect.height;
  72702. switch (position) {
  72703. case 'inside':
  72704. x = rect.x + rectWidth / 2 - domWidth / 2;
  72705. y = rect.y + rectHeight / 2 - domHeight / 2;
  72706. break;
  72707. case 'top':
  72708. x = rect.x + rectWidth / 2 - domWidth / 2;
  72709. y = rect.y - domHeight - gap;
  72710. break;
  72711. case 'bottom':
  72712. x = rect.x + rectWidth / 2 - domWidth / 2;
  72713. y = rect.y + rectHeight + gap;
  72714. break;
  72715. case 'left':
  72716. x = rect.x - domWidth - gap;
  72717. y = rect.y + rectHeight / 2 - domHeight / 2;
  72718. break;
  72719. case 'right':
  72720. x = rect.x + rectWidth + gap;
  72721. y = rect.y + rectHeight / 2 - domHeight / 2;
  72722. }
  72723. return [x, y];
  72724. }
  72725. function isCenterAlign(align) {
  72726. return align === 'center' || align === 'middle';
  72727. }
  72728. /*
  72729. * Licensed to the Apache Software Foundation (ASF) under one
  72730. * or more contributor license agreements. See the NOTICE file
  72731. * distributed with this work for additional information
  72732. * regarding copyright ownership. The ASF licenses this file
  72733. * to you under the Apache License, Version 2.0 (the
  72734. * "License"); you may not use this file except in compliance
  72735. * with the License. You may obtain a copy of the License at
  72736. *
  72737. * http://www.apache.org/licenses/LICENSE-2.0
  72738. *
  72739. * Unless required by applicable law or agreed to in writing,
  72740. * software distributed under the License is distributed on an
  72741. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72742. * KIND, either express or implied. See the License for the
  72743. * specific language governing permissions and limitations
  72744. * under the License.
  72745. */
  72746. // FIXME Better way to pack data in graphic element
  72747. /**
  72748. * @action
  72749. * @property {string} type
  72750. * @property {number} seriesIndex
  72751. * @property {number} dataIndex
  72752. * @property {number} [x]
  72753. * @property {number} [y]
  72754. */
  72755. registerAction(
  72756. {
  72757. type: 'showTip',
  72758. event: 'showTip',
  72759. update: 'tooltip:manuallyShowTip'
  72760. },
  72761. // noop
  72762. function () {}
  72763. );
  72764. registerAction(
  72765. {
  72766. type: 'hideTip',
  72767. event: 'hideTip',
  72768. update: 'tooltip:manuallyHideTip'
  72769. },
  72770. // noop
  72771. function () {}
  72772. );
  72773. /*
  72774. * Licensed to the Apache Software Foundation (ASF) under one
  72775. * or more contributor license agreements. See the NOTICE file
  72776. * distributed with this work for additional information
  72777. * regarding copyright ownership. The ASF licenses this file
  72778. * to you under the Apache License, Version 2.0 (the
  72779. * "License"); you may not use this file except in compliance
  72780. * with the License. You may obtain a copy of the License at
  72781. *
  72782. * http://www.apache.org/licenses/LICENSE-2.0
  72783. *
  72784. * Unless required by applicable law or agreed to in writing,
  72785. * software distributed under the License is distributed on an
  72786. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72787. * KIND, either express or implied. See the License for the
  72788. * specific language governing permissions and limitations
  72789. * under the License.
  72790. */
  72791. var DEFAULT_TOOLBOX_BTNS = ['rect', 'polygon', 'keep', 'clear'];
  72792. var preprocessor$1 = function (option, isNew) {
  72793. var brushComponents = option && option.brush;
  72794. if (!isArray(brushComponents)) {
  72795. brushComponents = brushComponents ? [brushComponents] : [];
  72796. }
  72797. if (!brushComponents.length) {
  72798. return;
  72799. }
  72800. var brushComponentSpecifiedBtns = [];
  72801. each$1(brushComponents, function (brushOpt) {
  72802. var tbs = brushOpt.hasOwnProperty('toolbox')
  72803. ? brushOpt.toolbox : [];
  72804. if (tbs instanceof Array) {
  72805. brushComponentSpecifiedBtns = brushComponentSpecifiedBtns.concat(tbs);
  72806. }
  72807. });
  72808. var toolbox = option && option.toolbox;
  72809. if (isArray(toolbox)) {
  72810. toolbox = toolbox[0];
  72811. }
  72812. if (!toolbox) {
  72813. toolbox = {feature: {}};
  72814. option.toolbox = [toolbox];
  72815. }
  72816. var toolboxFeature = (toolbox.feature || (toolbox.feature = {}));
  72817. var toolboxBrush = toolboxFeature.brush || (toolboxFeature.brush = {});
  72818. var brushTypes = toolboxBrush.type || (toolboxBrush.type = []);
  72819. brushTypes.push.apply(brushTypes, brushComponentSpecifiedBtns);
  72820. removeDuplicate(brushTypes);
  72821. if (isNew && !brushTypes.length) {
  72822. brushTypes.push.apply(brushTypes, DEFAULT_TOOLBOX_BTNS);
  72823. }
  72824. };
  72825. function removeDuplicate(arr) {
  72826. var map$$1 = {};
  72827. each$1(arr, function (val) {
  72828. map$$1[val] = 1;
  72829. });
  72830. arr.length = 0;
  72831. each$1(map$$1, function (flag, val) {
  72832. arr.push(val);
  72833. });
  72834. }
  72835. /*
  72836. * Licensed to the Apache Software Foundation (ASF) under one
  72837. * or more contributor license agreements. See the NOTICE file
  72838. * distributed with this work for additional information
  72839. * regarding copyright ownership. The ASF licenses this file
  72840. * to you under the Apache License, Version 2.0 (the
  72841. * "License"); you may not use this file except in compliance
  72842. * with the License. You may obtain a copy of the License at
  72843. *
  72844. * http://www.apache.org/licenses/LICENSE-2.0
  72845. *
  72846. * Unless required by applicable law or agreed to in writing,
  72847. * software distributed under the License is distributed on an
  72848. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72849. * KIND, either express or implied. See the License for the
  72850. * specific language governing permissions and limitations
  72851. * under the License.
  72852. */
  72853. /**
  72854. * @file Visual solution, for consistent option specification.
  72855. */
  72856. var each$23 = each$1;
  72857. function hasKeys(obj) {
  72858. if (obj) {
  72859. for (var name in obj) {
  72860. if (obj.hasOwnProperty(name)) {
  72861. return true;
  72862. }
  72863. }
  72864. }
  72865. }
  72866. /**
  72867. * @param {Object} option
  72868. * @param {Array.<string>} stateList
  72869. * @param {Function} [supplementVisualOption]
  72870. * @return {Object} visualMappings <state, <visualType, module:echarts/visual/VisualMapping>>
  72871. */
  72872. function createVisualMappings(option, stateList, supplementVisualOption) {
  72873. var visualMappings = {};
  72874. each$23(stateList, function (state) {
  72875. var mappings = visualMappings[state] = createMappings();
  72876. each$23(option[state], function (visualData, visualType) {
  72877. if (!VisualMapping.isValidType(visualType)) {
  72878. return;
  72879. }
  72880. var mappingOption = {
  72881. type: visualType,
  72882. visual: visualData
  72883. };
  72884. supplementVisualOption && supplementVisualOption(mappingOption, state);
  72885. mappings[visualType] = new VisualMapping(mappingOption);
  72886. // Prepare a alpha for opacity, for some case that opacity
  72887. // is not supported, such as rendering using gradient color.
  72888. if (visualType === 'opacity') {
  72889. mappingOption = clone(mappingOption);
  72890. mappingOption.type = 'colorAlpha';
  72891. mappings.__hidden.__alphaForOpacity = new VisualMapping(mappingOption);
  72892. }
  72893. });
  72894. });
  72895. return visualMappings;
  72896. function createMappings() {
  72897. var Creater = function () {};
  72898. // Make sure hidden fields will not be visited by
  72899. // object iteration (with hasOwnProperty checking).
  72900. Creater.prototype.__hidden = Creater.prototype;
  72901. var obj = new Creater();
  72902. return obj;
  72903. }
  72904. }
  72905. /**
  72906. * @param {Object} thisOption
  72907. * @param {Object} newOption
  72908. * @param {Array.<string>} keys
  72909. */
  72910. function replaceVisualOption(thisOption, newOption, keys) {
  72911. // Visual attributes merge is not supported, otherwise it
  72912. // brings overcomplicated merge logic. See #2853. So if
  72913. // newOption has anyone of these keys, all of these keys
  72914. // will be reset. Otherwise, all keys remain.
  72915. var has;
  72916. each$1(keys, function (key) {
  72917. if (newOption.hasOwnProperty(key) && hasKeys(newOption[key])) {
  72918. has = true;
  72919. }
  72920. });
  72921. has && each$1(keys, function (key) {
  72922. if (newOption.hasOwnProperty(key) && hasKeys(newOption[key])) {
  72923. thisOption[key] = clone(newOption[key]);
  72924. }
  72925. else {
  72926. delete thisOption[key];
  72927. }
  72928. });
  72929. }
  72930. /**
  72931. * @param {Array.<string>} stateList
  72932. * @param {Object} visualMappings <state, Object.<visualType, module:echarts/visual/VisualMapping>>
  72933. * @param {module:echarts/data/List} list
  72934. * @param {Function} getValueState param: valueOrIndex, return: state.
  72935. * @param {object} [scope] Scope for getValueState
  72936. * @param {string} [dimension] Concrete dimension, if used.
  72937. */
  72938. // ???! handle brush?
  72939. function applyVisual(stateList, visualMappings, data, getValueState, scope, dimension) {
  72940. var visualTypesMap = {};
  72941. each$1(stateList, function (state) {
  72942. var visualTypes = VisualMapping.prepareVisualTypes(visualMappings[state]);
  72943. visualTypesMap[state] = visualTypes;
  72944. });
  72945. var dataIndex;
  72946. function getVisual(key) {
  72947. return data.getItemVisual(dataIndex, key);
  72948. }
  72949. function setVisual(key, value) {
  72950. data.setItemVisual(dataIndex, key, value);
  72951. }
  72952. if (dimension == null) {
  72953. data.each(eachItem);
  72954. }
  72955. else {
  72956. data.each([dimension], eachItem);
  72957. }
  72958. function eachItem(valueOrIndex, index) {
  72959. dataIndex = dimension == null ? valueOrIndex : index;
  72960. var rawDataItem = data.getRawDataItem(dataIndex);
  72961. // Consider performance
  72962. if (rawDataItem && rawDataItem.visualMap === false) {
  72963. return;
  72964. }
  72965. var valueState = getValueState.call(scope, valueOrIndex);
  72966. var mappings = visualMappings[valueState];
  72967. var visualTypes = visualTypesMap[valueState];
  72968. for (var i = 0, len = visualTypes.length; i < len; i++) {
  72969. var type = visualTypes[i];
  72970. mappings[type] && mappings[type].applyVisual(
  72971. valueOrIndex, getVisual, setVisual
  72972. );
  72973. }
  72974. }
  72975. }
  72976. /**
  72977. * @param {module:echarts/data/List} data
  72978. * @param {Array.<string>} stateList
  72979. * @param {Object} visualMappings <state, Object.<visualType, module:echarts/visual/VisualMapping>>
  72980. * @param {Function} getValueState param: valueOrIndex, return: state.
  72981. * @param {number} [dim] dimension or dimension index.
  72982. */
  72983. function incrementalApplyVisual(stateList, visualMappings, getValueState, dim) {
  72984. var visualTypesMap = {};
  72985. each$1(stateList, function (state) {
  72986. var visualTypes = VisualMapping.prepareVisualTypes(visualMappings[state]);
  72987. visualTypesMap[state] = visualTypes;
  72988. });
  72989. function progress(params, data) {
  72990. if (dim != null) {
  72991. dim = data.getDimension(dim);
  72992. }
  72993. function getVisual(key) {
  72994. return data.getItemVisual(dataIndex, key);
  72995. }
  72996. function setVisual(key, value) {
  72997. data.setItemVisual(dataIndex, key, value);
  72998. }
  72999. var dataIndex;
  73000. while ((dataIndex = params.next()) != null) {
  73001. var rawDataItem = data.getRawDataItem(dataIndex);
  73002. // Consider performance
  73003. if (rawDataItem && rawDataItem.visualMap === false) {
  73004. continue;
  73005. }
  73006. var value = dim != null
  73007. ? data.get(dim, dataIndex, true)
  73008. : dataIndex;
  73009. var valueState = getValueState(value);
  73010. var mappings = visualMappings[valueState];
  73011. var visualTypes = visualTypesMap[valueState];
  73012. for (var i = 0, len = visualTypes.length; i < len; i++) {
  73013. var type = visualTypes[i];
  73014. mappings[type] && mappings[type].applyVisual(value, getVisual, setVisual);
  73015. }
  73016. }
  73017. }
  73018. return {progress: progress};
  73019. }
  73020. /*
  73021. * Licensed to the Apache Software Foundation (ASF) under one
  73022. * or more contributor license agreements. See the NOTICE file
  73023. * distributed with this work for additional information
  73024. * regarding copyright ownership. The ASF licenses this file
  73025. * to you under the Apache License, Version 2.0 (the
  73026. * "License"); you may not use this file except in compliance
  73027. * with the License. You may obtain a copy of the License at
  73028. *
  73029. * http://www.apache.org/licenses/LICENSE-2.0
  73030. *
  73031. * Unless required by applicable law or agreed to in writing,
  73032. * software distributed under the License is distributed on an
  73033. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73034. * KIND, either express or implied. See the License for the
  73035. * specific language governing permissions and limitations
  73036. * under the License.
  73037. */
  73038. // Key of the first level is brushType: `line`, `rect`, `polygon`.
  73039. // Key of the second level is chart element type: `point`, `rect`.
  73040. // See moudule:echarts/component/helper/BrushController
  73041. // function param:
  73042. // {Object} itemLayout fetch from data.getItemLayout(dataIndex)
  73043. // {Object} selectors {point: selector, rect: selector, ...}
  73044. // {Object} area {range: [[], [], ..], boudingRect}
  73045. // function return:
  73046. // {boolean} Whether in the given brush.
  73047. var selector = {
  73048. lineX: getLineSelectors(0),
  73049. lineY: getLineSelectors(1),
  73050. rect: {
  73051. point: function (itemLayout, selectors, area) {
  73052. return itemLayout && area.boundingRect.contain(itemLayout[0], itemLayout[1]);
  73053. },
  73054. rect: function (itemLayout, selectors, area) {
  73055. return itemLayout && area.boundingRect.intersect(itemLayout);
  73056. }
  73057. },
  73058. polygon: {
  73059. point: function (itemLayout, selectors, area) {
  73060. return itemLayout
  73061. && area.boundingRect.contain(itemLayout[0], itemLayout[1])
  73062. && contain$1(area.range, itemLayout[0], itemLayout[1]);
  73063. },
  73064. rect: function (itemLayout, selectors, area) {
  73065. var points = area.range;
  73066. if (!itemLayout || points.length <= 1) {
  73067. return false;
  73068. }
  73069. var x = itemLayout.x;
  73070. var y = itemLayout.y;
  73071. var width = itemLayout.width;
  73072. var height = itemLayout.height;
  73073. var p = points[0];
  73074. if (contain$1(points, x, y)
  73075. || contain$1(points, x + width, y)
  73076. || contain$1(points, x, y + height)
  73077. || contain$1(points, x + width, y + height)
  73078. || BoundingRect.create(itemLayout).contain(p[0], p[1])
  73079. || linePolygonIntersect(x, y, x + width, y, points)
  73080. || linePolygonIntersect(x, y, x, y + height, points)
  73081. || linePolygonIntersect(x + width, y, x + width, y + height, points)
  73082. || linePolygonIntersect(x, y + height, x + width, y + height, points)
  73083. ) {
  73084. return true;
  73085. }
  73086. }
  73087. }
  73088. };
  73089. function getLineSelectors(xyIndex) {
  73090. var xy = ['x', 'y'];
  73091. var wh = ['width', 'height'];
  73092. return {
  73093. point: function (itemLayout, selectors, area) {
  73094. if (itemLayout) {
  73095. var range = area.range;
  73096. var p = itemLayout[xyIndex];
  73097. return inLineRange(p, range);
  73098. }
  73099. },
  73100. rect: function (itemLayout, selectors, area) {
  73101. if (itemLayout) {
  73102. var range = area.range;
  73103. var layoutRange = [
  73104. itemLayout[xy[xyIndex]],
  73105. itemLayout[xy[xyIndex]] + itemLayout[wh[xyIndex]]
  73106. ];
  73107. layoutRange[1] < layoutRange[0] && layoutRange.reverse();
  73108. return inLineRange(layoutRange[0], range)
  73109. || inLineRange(layoutRange[1], range)
  73110. || inLineRange(range[0], layoutRange)
  73111. || inLineRange(range[1], layoutRange);
  73112. }
  73113. }
  73114. };
  73115. }
  73116. function inLineRange(p, range) {
  73117. return range[0] <= p && p <= range[1];
  73118. }
  73119. /*
  73120. * Licensed to the Apache Software Foundation (ASF) under one
  73121. * or more contributor license agreements. See the NOTICE file
  73122. * distributed with this work for additional information
  73123. * regarding copyright ownership. The ASF licenses this file
  73124. * to you under the Apache License, Version 2.0 (the
  73125. * "License"); you may not use this file except in compliance
  73126. * with the License. You may obtain a copy of the License at
  73127. *
  73128. * http://www.apache.org/licenses/LICENSE-2.0
  73129. *
  73130. * Unless required by applicable law or agreed to in writing,
  73131. * software distributed under the License is distributed on an
  73132. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73133. * KIND, either express or implied. See the License for the
  73134. * specific language governing permissions and limitations
  73135. * under the License.
  73136. */
  73137. var STATE_LIST = ['inBrush', 'outOfBrush'];
  73138. var DISPATCH_METHOD = '__ecBrushSelect';
  73139. var DISPATCH_FLAG = '__ecInBrushSelectEvent';
  73140. var PRIORITY_BRUSH = PRIORITY.VISUAL.BRUSH;
  73141. /**
  73142. * Layout for visual, the priority higher than other layout, and before brush visual.
  73143. */
  73144. registerLayout(PRIORITY_BRUSH, function (ecModel, api, payload) {
  73145. ecModel.eachComponent({mainType: 'brush'}, function (brushModel) {
  73146. payload && payload.type === 'takeGlobalCursor' && brushModel.setBrushOption(
  73147. payload.key === 'brush' ? payload.brushOption : {brushType: false}
  73148. );
  73149. });
  73150. layoutCovers(ecModel);
  73151. });
  73152. function layoutCovers(ecModel) {
  73153. ecModel.eachComponent({mainType: 'brush'}, function (brushModel) {
  73154. var brushTargetManager = brushModel.brushTargetManager = new BrushTargetManager(brushModel.option, ecModel);
  73155. brushTargetManager.setInputRanges(brushModel.areas, ecModel);
  73156. });
  73157. }
  73158. /**
  73159. * Register the visual encoding if this modules required.
  73160. */
  73161. registerVisual(PRIORITY_BRUSH, function (ecModel, api, payload) {
  73162. var brushSelected = [];
  73163. var throttleType;
  73164. var throttleDelay;
  73165. ecModel.eachComponent({mainType: 'brush'}, function (brushModel, brushIndex) {
  73166. var thisBrushSelected = {
  73167. brushId: brushModel.id,
  73168. brushIndex: brushIndex,
  73169. brushName: brushModel.name,
  73170. areas: clone(brushModel.areas),
  73171. selected: []
  73172. };
  73173. // Every brush component exists in event params, convenient
  73174. // for user to find by index.
  73175. brushSelected.push(thisBrushSelected);
  73176. var brushOption = brushModel.option;
  73177. var brushLink = brushOption.brushLink;
  73178. var linkedSeriesMap = [];
  73179. var selectedDataIndexForLink = [];
  73180. var rangeInfoBySeries = [];
  73181. var hasBrushExists = 0;
  73182. if (!brushIndex) { // Only the first throttle setting works.
  73183. throttleType = brushOption.throttleType;
  73184. throttleDelay = brushOption.throttleDelay;
  73185. }
  73186. // Add boundingRect and selectors to range.
  73187. var areas = map(brushModel.areas, function (area) {
  73188. return bindSelector(
  73189. defaults(
  73190. {boundingRect: boundingRectBuilders[area.brushType](area)},
  73191. area
  73192. )
  73193. );
  73194. });
  73195. var visualMappings = createVisualMappings(
  73196. brushModel.option, STATE_LIST, function (mappingOption) {
  73197. mappingOption.mappingMethod = 'fixed';
  73198. }
  73199. );
  73200. isArray(brushLink) && each$1(brushLink, function (seriesIndex) {
  73201. linkedSeriesMap[seriesIndex] = 1;
  73202. });
  73203. function linkOthers(seriesIndex) {
  73204. return brushLink === 'all' || linkedSeriesMap[seriesIndex];
  73205. }
  73206. // If no supported brush or no brush on the series,
  73207. // all visuals should be in original state.
  73208. function brushed(rangeInfoList) {
  73209. return !!rangeInfoList.length;
  73210. }
  73211. /**
  73212. * Logic for each series: (If the logic has to be modified one day, do it carefully!)
  73213. *
  73214. * ( brushed ┬ && ┬hasBrushExist ┬ && linkOthers ) => StepA: ┬record, ┬ StepB: ┬visualByRecord.
  73215. * !brushed┘ ├hasBrushExist ┤ └nothing,┘ ├visualByRecord.
  73216. * └!hasBrushExist┘ └nothing.
  73217. * ( !brushed && ┬hasBrushExist ┬ && linkOthers ) => StepA: nothing, StepB: ┬visualByRecord.
  73218. * └!hasBrushExist┘ └nothing.
  73219. * ( brushed ┬ && !linkOthers ) => StepA: nothing, StepB: ┬visualByCheck.
  73220. * !brushed┘ └nothing.
  73221. * ( !brushed && !linkOthers ) => StepA: nothing, StepB: nothing.
  73222. */
  73223. // Step A
  73224. ecModel.eachSeries(function (seriesModel, seriesIndex) {
  73225. var rangeInfoList = rangeInfoBySeries[seriesIndex] = [];
  73226. seriesModel.subType === 'parallel'
  73227. ? stepAParallel(seriesModel, seriesIndex, rangeInfoList)
  73228. : stepAOthers(seriesModel, seriesIndex, rangeInfoList);
  73229. });
  73230. function stepAParallel(seriesModel, seriesIndex) {
  73231. var coordSys = seriesModel.coordinateSystem;
  73232. hasBrushExists |= coordSys.hasAxisBrushed();
  73233. linkOthers(seriesIndex) && coordSys.eachActiveState(
  73234. seriesModel.getData(),
  73235. function (activeState, dataIndex) {
  73236. activeState === 'active' && (selectedDataIndexForLink[dataIndex] = 1);
  73237. }
  73238. );
  73239. }
  73240. function stepAOthers(seriesModel, seriesIndex, rangeInfoList) {
  73241. var selectorsByBrushType = getSelectorsByBrushType(seriesModel);
  73242. if (!selectorsByBrushType || brushModelNotControll(brushModel, seriesIndex)) {
  73243. return;
  73244. }
  73245. each$1(areas, function (area) {
  73246. selectorsByBrushType[area.brushType]
  73247. && brushModel.brushTargetManager.controlSeries(area, seriesModel, ecModel)
  73248. && rangeInfoList.push(area);
  73249. hasBrushExists |= brushed(rangeInfoList);
  73250. });
  73251. if (linkOthers(seriesIndex) && brushed(rangeInfoList)) {
  73252. var data = seriesModel.getData();
  73253. data.each(function (dataIndex) {
  73254. if (checkInRange(selectorsByBrushType, rangeInfoList, data, dataIndex)) {
  73255. selectedDataIndexForLink[dataIndex] = 1;
  73256. }
  73257. });
  73258. }
  73259. }
  73260. // Step B
  73261. ecModel.eachSeries(function (seriesModel, seriesIndex) {
  73262. var seriesBrushSelected = {
  73263. seriesId: seriesModel.id,
  73264. seriesIndex: seriesIndex,
  73265. seriesName: seriesModel.name,
  73266. dataIndex: []
  73267. };
  73268. // Every series exists in event params, convenient
  73269. // for user to find series by seriesIndex.
  73270. thisBrushSelected.selected.push(seriesBrushSelected);
  73271. var selectorsByBrushType = getSelectorsByBrushType(seriesModel);
  73272. var rangeInfoList = rangeInfoBySeries[seriesIndex];
  73273. var data = seriesModel.getData();
  73274. var getValueState = linkOthers(seriesIndex)
  73275. ? function (dataIndex) {
  73276. return selectedDataIndexForLink[dataIndex]
  73277. ? (seriesBrushSelected.dataIndex.push(data.getRawIndex(dataIndex)), 'inBrush')
  73278. : 'outOfBrush';
  73279. }
  73280. : function (dataIndex) {
  73281. return checkInRange(selectorsByBrushType, rangeInfoList, data, dataIndex)
  73282. ? (seriesBrushSelected.dataIndex.push(data.getRawIndex(dataIndex)), 'inBrush')
  73283. : 'outOfBrush';
  73284. };
  73285. // If no supported brush or no brush, all visuals are in original state.
  73286. (linkOthers(seriesIndex) ? hasBrushExists : brushed(rangeInfoList))
  73287. && applyVisual(
  73288. STATE_LIST, visualMappings, data, getValueState
  73289. );
  73290. });
  73291. });
  73292. dispatchAction(api, throttleType, throttleDelay, brushSelected, payload);
  73293. });
  73294. function dispatchAction(api, throttleType, throttleDelay, brushSelected, payload) {
  73295. // This event will not be triggered when `setOpion`, otherwise dead lock may
  73296. // triggered when do `setOption` in event listener, which we do not find
  73297. // satisfactory way to solve yet. Some considered resolutions:
  73298. // (a) Diff with prevoius selected data ant only trigger event when changed.
  73299. // But store previous data and diff precisely (i.e., not only by dataIndex, but
  73300. // also detect value changes in selected data) might bring complexity or fragility.
  73301. // (b) Use spectial param like `silent` to suppress event triggering.
  73302. // But such kind of volatile param may be weird in `setOption`.
  73303. if (!payload) {
  73304. return;
  73305. }
  73306. var zr = api.getZr();
  73307. if (zr[DISPATCH_FLAG]) {
  73308. return;
  73309. }
  73310. if (!zr[DISPATCH_METHOD]) {
  73311. zr[DISPATCH_METHOD] = doDispatch;
  73312. }
  73313. var fn = createOrUpdate(zr, DISPATCH_METHOD, throttleDelay, throttleType);
  73314. fn(api, brushSelected);
  73315. }
  73316. function doDispatch(api, brushSelected) {
  73317. if (!api.isDisposed()) {
  73318. var zr = api.getZr();
  73319. zr[DISPATCH_FLAG] = true;
  73320. api.dispatchAction({
  73321. type: 'brushSelect',
  73322. batch: brushSelected
  73323. });
  73324. zr[DISPATCH_FLAG] = false;
  73325. }
  73326. }
  73327. function checkInRange(selectorsByBrushType, rangeInfoList, data, dataIndex) {
  73328. for (var i = 0, len = rangeInfoList.length; i < len; i++) {
  73329. var area = rangeInfoList[i];
  73330. if (selectorsByBrushType[area.brushType](
  73331. dataIndex, data, area.selectors, area
  73332. )) {
  73333. return true;
  73334. }
  73335. }
  73336. }
  73337. function getSelectorsByBrushType(seriesModel) {
  73338. var brushSelector = seriesModel.brushSelector;
  73339. if (isString(brushSelector)) {
  73340. var sels = [];
  73341. each$1(selector, function (selectorsByElementType, brushType) {
  73342. sels[brushType] = function (dataIndex, data, selectors, area) {
  73343. var itemLayout = data.getItemLayout(dataIndex);
  73344. return selectorsByElementType[brushSelector](itemLayout, selectors, area);
  73345. };
  73346. });
  73347. return sels;
  73348. }
  73349. else if (isFunction$1(brushSelector)) {
  73350. var bSelector = {};
  73351. each$1(selector, function (sel, brushType) {
  73352. bSelector[brushType] = brushSelector;
  73353. });
  73354. return bSelector;
  73355. }
  73356. return brushSelector;
  73357. }
  73358. function brushModelNotControll(brushModel, seriesIndex) {
  73359. var seriesIndices = brushModel.option.seriesIndex;
  73360. return seriesIndices != null
  73361. && seriesIndices !== 'all'
  73362. && (
  73363. isArray(seriesIndices)
  73364. ? indexOf(seriesIndices, seriesIndex) < 0
  73365. : seriesIndex !== seriesIndices
  73366. );
  73367. }
  73368. function bindSelector(area) {
  73369. var selectors = area.selectors = {};
  73370. each$1(selector[area.brushType], function (selFn, elType) {
  73371. // Do not use function binding or curry for performance.
  73372. selectors[elType] = function (itemLayout) {
  73373. return selFn(itemLayout, selectors, area);
  73374. };
  73375. });
  73376. return area;
  73377. }
  73378. var boundingRectBuilders = {
  73379. lineX: noop,
  73380. lineY: noop,
  73381. rect: function (area) {
  73382. return getBoundingRectFromMinMax(area.range);
  73383. },
  73384. polygon: function (area) {
  73385. var minMax;
  73386. var range = area.range;
  73387. for (var i = 0, len = range.length; i < len; i++) {
  73388. minMax = minMax || [[Infinity, -Infinity], [Infinity, -Infinity]];
  73389. var rg = range[i];
  73390. rg[0] < minMax[0][0] && (minMax[0][0] = rg[0]);
  73391. rg[0] > minMax[0][1] && (minMax[0][1] = rg[0]);
  73392. rg[1] < minMax[1][0] && (minMax[1][0] = rg[1]);
  73393. rg[1] > minMax[1][1] && (minMax[1][1] = rg[1]);
  73394. }
  73395. return minMax && getBoundingRectFromMinMax(minMax);
  73396. }
  73397. };
  73398. function getBoundingRectFromMinMax(minMax) {
  73399. return new BoundingRect(
  73400. minMax[0][0],
  73401. minMax[1][0],
  73402. minMax[0][1] - minMax[0][0],
  73403. minMax[1][1] - minMax[1][0]
  73404. );
  73405. }
  73406. /*
  73407. * Licensed to the Apache Software Foundation (ASF) under one
  73408. * or more contributor license agreements. See the NOTICE file
  73409. * distributed with this work for additional information
  73410. * regarding copyright ownership. The ASF licenses this file
  73411. * to you under the Apache License, Version 2.0 (the
  73412. * "License"); you may not use this file except in compliance
  73413. * with the License. You may obtain a copy of the License at
  73414. *
  73415. * http://www.apache.org/licenses/LICENSE-2.0
  73416. *
  73417. * Unless required by applicable law or agreed to in writing,
  73418. * software distributed under the License is distributed on an
  73419. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73420. * KIND, either express or implied. See the License for the
  73421. * specific language governing permissions and limitations
  73422. * under the License.
  73423. */
  73424. var DEFAULT_OUT_OF_BRUSH_COLOR = ['#ddd'];
  73425. var BrushModel = extendComponentModel({
  73426. type: 'brush',
  73427. dependencies: ['geo', 'grid', 'xAxis', 'yAxis', 'parallel', 'series'],
  73428. /**
  73429. * @protected
  73430. */
  73431. defaultOption: {
  73432. // inBrush: null,
  73433. // outOfBrush: null,
  73434. toolbox: null, // Default value see preprocessor.
  73435. brushLink: null, // Series indices array, broadcast using dataIndex.
  73436. // or 'all', which means all series. 'none' or null means no series.
  73437. seriesIndex: 'all', // seriesIndex array, specify series controlled by this brush component.
  73438. geoIndex: null, //
  73439. xAxisIndex: null,
  73440. yAxisIndex: null,
  73441. brushType: 'rect', // Default brushType, see BrushController.
  73442. brushMode: 'single', // Default brushMode, 'single' or 'multiple'
  73443. transformable: true, // Default transformable.
  73444. brushStyle: { // Default brushStyle
  73445. borderWidth: 1,
  73446. color: 'rgba(120,140,180,0.3)',
  73447. borderColor: 'rgba(120,140,180,0.8)'
  73448. },
  73449. throttleType: 'fixRate', // Throttle in brushSelected event. 'fixRate' or 'debounce'.
  73450. // If null, no throttle. Valid only in the first brush component
  73451. throttleDelay: 0, // Unit: ms, 0 means every event will be triggered.
  73452. // FIXME
  73453. // 试验效果
  73454. removeOnClick: true,
  73455. z: 10000
  73456. },
  73457. /**
  73458. * @readOnly
  73459. * @type {Array.<Object>}
  73460. */
  73461. areas: [],
  73462. /**
  73463. * Current activated brush type.
  73464. * If null, brush is inactived.
  73465. * see module:echarts/component/helper/BrushController
  73466. * @readOnly
  73467. * @type {string}
  73468. */
  73469. brushType: null,
  73470. /**
  73471. * Current brush opt.
  73472. * see module:echarts/component/helper/BrushController
  73473. * @readOnly
  73474. * @type {Object}
  73475. */
  73476. brushOption: {},
  73477. /**
  73478. * @readOnly
  73479. * @type {Array.<Object>}
  73480. */
  73481. coordInfoList: [],
  73482. optionUpdated: function (newOption, isInit) {
  73483. var thisOption = this.option;
  73484. !isInit && replaceVisualOption(
  73485. thisOption, newOption, ['inBrush', 'outOfBrush']
  73486. );
  73487. var inBrush = thisOption.inBrush = thisOption.inBrush || {};
  73488. // Always give default visual, consider setOption at the second time.
  73489. thisOption.outOfBrush = thisOption.outOfBrush || {color: DEFAULT_OUT_OF_BRUSH_COLOR};
  73490. if (!inBrush.hasOwnProperty('liftZ')) {
  73491. // Bigger than the highlight z lift, otherwise it will
  73492. // be effected by the highlight z when brush.
  73493. inBrush.liftZ = 5;
  73494. }
  73495. },
  73496. /**
  73497. * If ranges is null/undefined, range state remain.
  73498. *
  73499. * @param {Array.<Object>} [ranges]
  73500. */
  73501. setAreas: function (areas) {
  73502. if (__DEV__) {
  73503. assert$1(isArray(areas));
  73504. each$1(areas, function (area) {
  73505. assert$1(area.brushType, 'Illegal areas');
  73506. });
  73507. }
  73508. // If ranges is null/undefined, range state remain.
  73509. // This helps user to dispatchAction({type: 'brush'}) with no areas
  73510. // set but just want to get the current brush select info from a `brush` event.
  73511. if (!areas) {
  73512. return;
  73513. }
  73514. this.areas = map(areas, function (area) {
  73515. return generateBrushOption(this.option, area);
  73516. }, this);
  73517. },
  73518. /**
  73519. * see module:echarts/component/helper/BrushController
  73520. * @param {Object} brushOption
  73521. */
  73522. setBrushOption: function (brushOption) {
  73523. this.brushOption = generateBrushOption(this.option, brushOption);
  73524. this.brushType = this.brushOption.brushType;
  73525. }
  73526. });
  73527. function generateBrushOption(option, brushOption) {
  73528. return merge(
  73529. {
  73530. brushType: option.brushType,
  73531. brushMode: option.brushMode,
  73532. transformable: option.transformable,
  73533. brushStyle: new Model(option.brushStyle).getItemStyle(),
  73534. removeOnClick: option.removeOnClick,
  73535. z: option.z
  73536. },
  73537. brushOption,
  73538. true
  73539. );
  73540. }
  73541. /*
  73542. * Licensed to the Apache Software Foundation (ASF) under one
  73543. * or more contributor license agreements. See the NOTICE file
  73544. * distributed with this work for additional information
  73545. * regarding copyright ownership. The ASF licenses this file
  73546. * to you under the Apache License, Version 2.0 (the
  73547. * "License"); you may not use this file except in compliance
  73548. * with the License. You may obtain a copy of the License at
  73549. *
  73550. * http://www.apache.org/licenses/LICENSE-2.0
  73551. *
  73552. * Unless required by applicable law or agreed to in writing,
  73553. * software distributed under the License is distributed on an
  73554. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73555. * KIND, either express or implied. See the License for the
  73556. * specific language governing permissions and limitations
  73557. * under the License.
  73558. */
  73559. extendComponentView({
  73560. type: 'brush',
  73561. init: function (ecModel, api) {
  73562. /**
  73563. * @readOnly
  73564. * @type {module:echarts/model/Global}
  73565. */
  73566. this.ecModel = ecModel;
  73567. /**
  73568. * @readOnly
  73569. * @type {module:echarts/ExtensionAPI}
  73570. */
  73571. this.api = api;
  73572. /**
  73573. * @readOnly
  73574. * @type {module:echarts/component/brush/BrushModel}
  73575. */
  73576. this.model;
  73577. /**
  73578. * @private
  73579. * @type {module:echarts/component/helper/BrushController}
  73580. */
  73581. (this._brushController = new BrushController(api.getZr()))
  73582. .on('brush', bind(this._onBrush, this))
  73583. .mount();
  73584. },
  73585. /**
  73586. * @override
  73587. */
  73588. render: function (brushModel) {
  73589. this.model = brushModel;
  73590. return updateController.apply(this, arguments);
  73591. },
  73592. /**
  73593. * @override
  73594. */
  73595. updateTransform: function (brushModel, ecModel) {
  73596. // PENDING: `updateTransform` is a little tricky, whose layout need
  73597. // to be calculate mandatorily and other stages will not be performed.
  73598. // Take care the correctness of the logic. See #11754 .
  73599. layoutCovers(ecModel);
  73600. return updateController.apply(this, arguments);
  73601. },
  73602. /**
  73603. * @override
  73604. */
  73605. updateView: updateController,
  73606. // /**
  73607. // * @override
  73608. // */
  73609. // updateLayout: updateController,
  73610. // /**
  73611. // * @override
  73612. // */
  73613. // updateVisual: updateController,
  73614. /**
  73615. * @override
  73616. */
  73617. dispose: function () {
  73618. this._brushController.dispose();
  73619. },
  73620. /**
  73621. * @private
  73622. */
  73623. _onBrush: function (areas, opt) {
  73624. var modelId = this.model.id;
  73625. this.model.brushTargetManager.setOutputRanges(areas, this.ecModel);
  73626. // Action is not dispatched on drag end, because the drag end
  73627. // emits the same params with the last drag move event, and
  73628. // may have some delay when using touch pad, which makes
  73629. // animation not smooth (when using debounce).
  73630. (!opt.isEnd || opt.removeOnClick) && this.api.dispatchAction({
  73631. type: 'brush',
  73632. brushId: modelId,
  73633. areas: clone(areas),
  73634. $from: modelId
  73635. });
  73636. opt.isEnd && this.api.dispatchAction({
  73637. type: 'brushEnd',
  73638. brushId: modelId,
  73639. areas: clone(areas),
  73640. $from: modelId
  73641. });
  73642. }
  73643. });
  73644. function updateController(brushModel, ecModel, api, payload) {
  73645. // Do not update controller when drawing.
  73646. (!payload || payload.$from !== brushModel.id) && this._brushController
  73647. .setPanels(brushModel.brushTargetManager.makePanelOpts(api))
  73648. .enableBrush(brushModel.brushOption)
  73649. .updateCovers(brushModel.areas.slice());
  73650. }
  73651. /*
  73652. * Licensed to the Apache Software Foundation (ASF) under one
  73653. * or more contributor license agreements. See the NOTICE file
  73654. * distributed with this work for additional information
  73655. * regarding copyright ownership. The ASF licenses this file
  73656. * to you under the Apache License, Version 2.0 (the
  73657. * "License"); you may not use this file except in compliance
  73658. * with the License. You may obtain a copy of the License at
  73659. *
  73660. * http://www.apache.org/licenses/LICENSE-2.0
  73661. *
  73662. * Unless required by applicable law or agreed to in writing,
  73663. * software distributed under the License is distributed on an
  73664. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73665. * KIND, either express or implied. See the License for the
  73666. * specific language governing permissions and limitations
  73667. * under the License.
  73668. */
  73669. /**
  73670. * payload: {
  73671. * brushIndex: number, or,
  73672. * brushId: string, or,
  73673. * brushName: string,
  73674. * globalRanges: Array
  73675. * }
  73676. */
  73677. registerAction(
  73678. {type: 'brush', event: 'brush' /*, update: 'updateView' */},
  73679. function (payload, ecModel) {
  73680. ecModel.eachComponent({mainType: 'brush', query: payload}, function (brushModel) {
  73681. brushModel.setAreas(payload.areas);
  73682. });
  73683. }
  73684. );
  73685. /**
  73686. * payload: {
  73687. * brushComponents: [
  73688. * {
  73689. * brushId,
  73690. * brushIndex,
  73691. * brushName,
  73692. * series: [
  73693. * {
  73694. * seriesId,
  73695. * seriesIndex,
  73696. * seriesName,
  73697. * rawIndices: [21, 34, ...]
  73698. * },
  73699. * ...
  73700. * ]
  73701. * },
  73702. * ...
  73703. * ]
  73704. * }
  73705. */
  73706. registerAction(
  73707. {type: 'brushSelect', event: 'brushSelected', update: 'none'},
  73708. function () {}
  73709. );
  73710. registerAction(
  73711. {type: 'brushEnd', event: 'brushEnd', update: 'none'},
  73712. function () {}
  73713. );
  73714. /*
  73715. * Licensed to the Apache Software Foundation (ASF) under one
  73716. * or more contributor license agreements. See the NOTICE file
  73717. * distributed with this work for additional information
  73718. * regarding copyright ownership. The ASF licenses this file
  73719. * to you under the Apache License, Version 2.0 (the
  73720. * "License"); you may not use this file except in compliance
  73721. * with the License. You may obtain a copy of the License at
  73722. *
  73723. * http://www.apache.org/licenses/LICENSE-2.0
  73724. *
  73725. * Unless required by applicable law or agreed to in writing,
  73726. * software distributed under the License is distributed on an
  73727. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73728. * KIND, either express or implied. See the License for the
  73729. * specific language governing permissions and limitations
  73730. * under the License.
  73731. */
  73732. var brushLang = lang.toolbox.brush;
  73733. function Brush(model, ecModel, api) {
  73734. this.model = model;
  73735. this.ecModel = ecModel;
  73736. this.api = api;
  73737. /**
  73738. * @private
  73739. * @type {string}
  73740. */
  73741. this._brushType;
  73742. /**
  73743. * @private
  73744. * @type {string}
  73745. */
  73746. this._brushMode;
  73747. }
  73748. Brush.defaultOption = {
  73749. show: true,
  73750. type: ['rect', 'polygon', 'lineX', 'lineY', 'keep', 'clear'],
  73751. icon: {
  73752. /* eslint-disable */
  73753. rect: 'M7.3,34.7 M0.4,10V-0.2h9.8 M89.6,10V-0.2h-9.8 M0.4,60v10.2h9.8 M89.6,60v10.2h-9.8 M12.3,22.4V10.5h13.1 M33.6,10.5h7.8 M49.1,10.5h7.8 M77.5,22.4V10.5h-13 M12.3,31.1v8.2 M77.7,31.1v8.2 M12.3,47.6v11.9h13.1 M33.6,59.5h7.6 M49.1,59.5 h7.7 M77.5,47.6v11.9h-13', // jshint ignore:line
  73754. polygon: 'M55.2,34.9c1.7,0,3.1,1.4,3.1,3.1s-1.4,3.1-3.1,3.1 s-3.1-1.4-3.1-3.1S53.5,34.9,55.2,34.9z M50.4,51c1.7,0,3.1,1.4,3.1,3.1c0,1.7-1.4,3.1-3.1,3.1c-1.7,0-3.1-1.4-3.1-3.1 C47.3,52.4,48.7,51,50.4,51z M55.6,37.1l1.5-7.8 M60.1,13.5l1.6-8.7l-7.8,4 M59,19l-1,5.3 M24,16.1l6.4,4.9l6.4-3.3 M48.5,11.6 l-5.9,3.1 M19.1,12.8L9.7,5.1l1.1,7.7 M13.4,29.8l1,7.3l6.6,1.6 M11.6,18.4l1,6.1 M32.8,41.9 M26.6,40.4 M27.3,40.2l6.1,1.6 M49.9,52.1l-5.6-7.6l-4.9-1.2', // jshint ignore:line
  73755. lineX: 'M15.2,30 M19.7,15.6V1.9H29 M34.8,1.9H40.4 M55.3,15.6V1.9H45.9 M19.7,44.4V58.1H29 M34.8,58.1H40.4 M55.3,44.4 V58.1H45.9 M12.5,20.3l-9.4,9.6l9.6,9.8 M3.1,29.9h16.5 M62.5,20.3l9.4,9.6L62.3,39.7 M71.9,29.9H55.4', // jshint ignore:line
  73756. lineY: 'M38.8,7.7 M52.7,12h13.2v9 M65.9,26.6V32 M52.7,46.3h13.2v-9 M24.9,12H11.8v9 M11.8,26.6V32 M24.9,46.3H11.8v-9 M48.2,5.1l-9.3-9l-9.4,9.2 M38.9-3.9V12 M48.2,53.3l-9.3,9l-9.4-9.2 M38.9,62.3V46.4', // jshint ignore:line
  73757. keep: 'M4,10.5V1h10.3 M20.7,1h6.1 M33,1h6.1 M55.4,10.5V1H45.2 M4,17.3v6.6 M55.6,17.3v6.6 M4,30.5V40h10.3 M20.7,40 h6.1 M33,40h6.1 M55.4,30.5V40H45.2 M21,18.9h62.9v48.6H21V18.9z', // jshint ignore:line
  73758. 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
  73759. /* eslint-enable */
  73760. },
  73761. // `rect`, `polygon`, `lineX`, `lineY`, `keep`, `clear`
  73762. title: clone(brushLang.title)
  73763. };
  73764. var proto$7 = Brush.prototype;
  73765. // proto.updateLayout = function (featureModel, ecModel, api) {
  73766. /* eslint-disable */
  73767. proto$7.render =
  73768. /* eslint-enable */
  73769. proto$7.updateView = function (featureModel, ecModel, api) {
  73770. var brushType;
  73771. var brushMode;
  73772. var isBrushed;
  73773. ecModel.eachComponent({mainType: 'brush'}, function (brushModel) {
  73774. brushType = brushModel.brushType;
  73775. brushMode = brushModel.brushOption.brushMode || 'single';
  73776. isBrushed |= brushModel.areas.length;
  73777. });
  73778. this._brushType = brushType;
  73779. this._brushMode = brushMode;
  73780. each$1(featureModel.get('type', true), function (type) {
  73781. featureModel.setIconStatus(
  73782. type,
  73783. (
  73784. type === 'keep'
  73785. ? brushMode === 'multiple'
  73786. : type === 'clear'
  73787. ? isBrushed
  73788. : type === brushType
  73789. ) ? 'emphasis' : 'normal'
  73790. );
  73791. });
  73792. };
  73793. proto$7.getIcons = function () {
  73794. var model = this.model;
  73795. var availableIcons = model.get('icon', true);
  73796. var icons = {};
  73797. each$1(model.get('type', true), function (type) {
  73798. if (availableIcons[type]) {
  73799. icons[type] = availableIcons[type];
  73800. }
  73801. });
  73802. return icons;
  73803. };
  73804. proto$7.onclick = function (ecModel, api, type) {
  73805. var brushType = this._brushType;
  73806. var brushMode = this._brushMode;
  73807. if (type === 'clear') {
  73808. // Trigger parallel action firstly
  73809. api.dispatchAction({
  73810. type: 'axisAreaSelect',
  73811. intervals: []
  73812. });
  73813. api.dispatchAction({
  73814. type: 'brush',
  73815. command: 'clear',
  73816. // Clear all areas of all brush components.
  73817. areas: []
  73818. });
  73819. }
  73820. else {
  73821. api.dispatchAction({
  73822. type: 'takeGlobalCursor',
  73823. key: 'brush',
  73824. brushOption: {
  73825. brushType: type === 'keep'
  73826. ? brushType
  73827. : (brushType === type ? false : type),
  73828. brushMode: type === 'keep'
  73829. ? (brushMode === 'multiple' ? 'single' : 'multiple')
  73830. : brushMode
  73831. }
  73832. });
  73833. }
  73834. };
  73835. register$1('brush', Brush);
  73836. /*
  73837. * Licensed to the Apache Software Foundation (ASF) under one
  73838. * or more contributor license agreements. See the NOTICE file
  73839. * distributed with this work for additional information
  73840. * regarding copyright ownership. The ASF licenses this file
  73841. * to you under the Apache License, Version 2.0 (the
  73842. * "License"); you may not use this file except in compliance
  73843. * with the License. You may obtain a copy of the License at
  73844. *
  73845. * http://www.apache.org/licenses/LICENSE-2.0
  73846. *
  73847. * Unless required by applicable law or agreed to in writing,
  73848. * software distributed under the License is distributed on an
  73849. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73850. * KIND, either express or implied. See the License for the
  73851. * specific language governing permissions and limitations
  73852. * under the License.
  73853. */
  73854. /**
  73855. * Brush component entry
  73856. */
  73857. registerPreprocessor(preprocessor$1);
  73858. /*
  73859. * Licensed to the Apache Software Foundation (ASF) under one
  73860. * or more contributor license agreements. See the NOTICE file
  73861. * distributed with this work for additional information
  73862. * regarding copyright ownership. The ASF licenses this file
  73863. * to you under the Apache License, Version 2.0 (the
  73864. * "License"); you may not use this file except in compliance
  73865. * with the License. You may obtain a copy of the License at
  73866. *
  73867. * http://www.apache.org/licenses/LICENSE-2.0
  73868. *
  73869. * Unless required by applicable law or agreed to in writing,
  73870. * software distributed under the License is distributed on an
  73871. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73872. * KIND, either express or implied. See the License for the
  73873. * specific language governing permissions and limitations
  73874. * under the License.
  73875. */
  73876. // Model
  73877. extendComponentModel({
  73878. type: 'title',
  73879. layoutMode: {type: 'box', ignoreSize: true},
  73880. defaultOption: {
  73881. // 一级层叠
  73882. zlevel: 0,
  73883. // 二级层叠
  73884. z: 6,
  73885. show: true,
  73886. text: '',
  73887. // 超链接跳转
  73888. // link: null,
  73889. // 仅支持self | blank
  73890. target: 'blank',
  73891. subtext: '',
  73892. // 超链接跳转
  73893. // sublink: null,
  73894. // 仅支持self | blank
  73895. subtarget: 'blank',
  73896. // 'center' ¦ 'left' ¦ 'right'
  73897. // ¦ {number}(x坐标,单位px)
  73898. left: 0,
  73899. // 'top' ¦ 'bottom' ¦ 'center'
  73900. // ¦ {number}(y坐标,单位px)
  73901. top: 0,
  73902. // 水平对齐
  73903. // 'auto' | 'left' | 'right' | 'center'
  73904. // 默认根据 left 的位置判断是左对齐还是右对齐
  73905. // textAlign: null
  73906. //
  73907. // 垂直对齐
  73908. // 'auto' | 'top' | 'bottom' | 'middle'
  73909. // 默认根据 top 位置判断是上对齐还是下对齐
  73910. // textVerticalAlign: null
  73911. // textBaseline: null // The same as textVerticalAlign.
  73912. backgroundColor: 'rgba(0,0,0,0)',
  73913. // 标题边框颜色
  73914. borderColor: '#ccc',
  73915. // 标题边框线宽,单位px,默认为0(无边框)
  73916. borderWidth: 0,
  73917. // 标题内边距,单位px,默认各方向内边距为5,
  73918. // 接受数组分别设定上右下左边距,同css
  73919. padding: 5,
  73920. // 主副标题纵向间隔,单位px,默认为10,
  73921. itemGap: 10,
  73922. textStyle: {
  73923. fontSize: 18,
  73924. fontWeight: 'bolder',
  73925. color: '#333'
  73926. },
  73927. subtextStyle: {
  73928. color: '#aaa'
  73929. }
  73930. }
  73931. });
  73932. // View
  73933. extendComponentView({
  73934. type: 'title',
  73935. render: function (titleModel, ecModel, api) {
  73936. this.group.removeAll();
  73937. if (!titleModel.get('show')) {
  73938. return;
  73939. }
  73940. var group = this.group;
  73941. var textStyleModel = titleModel.getModel('textStyle');
  73942. var subtextStyleModel = titleModel.getModel('subtextStyle');
  73943. var textAlign = titleModel.get('textAlign');
  73944. var textVerticalAlign = retrieve2(
  73945. titleModel.get('textBaseline'), titleModel.get('textVerticalAlign')
  73946. );
  73947. var textEl = new Text({
  73948. style: setTextStyle({}, textStyleModel, {
  73949. text: titleModel.get('text'),
  73950. textFill: textStyleModel.getTextColor()
  73951. }, {disableBox: true}),
  73952. z2: 10
  73953. });
  73954. var textRect = textEl.getBoundingRect();
  73955. var subText = titleModel.get('subtext');
  73956. var subTextEl = new Text({
  73957. style: setTextStyle({}, subtextStyleModel, {
  73958. text: subText,
  73959. textFill: subtextStyleModel.getTextColor(),
  73960. y: textRect.height + titleModel.get('itemGap'),
  73961. textVerticalAlign: 'top'
  73962. }, {disableBox: true}),
  73963. z2: 10
  73964. });
  73965. var link = titleModel.get('link');
  73966. var sublink = titleModel.get('sublink');
  73967. var triggerEvent = titleModel.get('triggerEvent', true);
  73968. textEl.silent = !link && !triggerEvent;
  73969. subTextEl.silent = !sublink && !triggerEvent;
  73970. if (link) {
  73971. textEl.on('click', function () {
  73972. windowOpen(link, '_' + titleModel.get('target'));
  73973. });
  73974. }
  73975. if (sublink) {
  73976. subTextEl.on('click', function () {
  73977. windowOpen(link, '_' + titleModel.get('subtarget'));
  73978. });
  73979. }
  73980. textEl.eventData = subTextEl.eventData = triggerEvent
  73981. ? {
  73982. componentType: 'title',
  73983. componentIndex: titleModel.componentIndex
  73984. }
  73985. : null;
  73986. group.add(textEl);
  73987. subText && group.add(subTextEl);
  73988. // If no subText, but add subTextEl, there will be an empty line.
  73989. var groupRect = group.getBoundingRect();
  73990. var layoutOption = titleModel.getBoxLayoutParams();
  73991. layoutOption.width = groupRect.width;
  73992. layoutOption.height = groupRect.height;
  73993. var layoutRect = getLayoutRect(
  73994. layoutOption, {
  73995. width: api.getWidth(),
  73996. height: api.getHeight()
  73997. }, titleModel.get('padding')
  73998. );
  73999. // Adjust text align based on position
  74000. if (!textAlign) {
  74001. // Align left if title is on the left. center and right is same
  74002. textAlign = titleModel.get('left') || titleModel.get('right');
  74003. if (textAlign === 'middle') {
  74004. textAlign = 'center';
  74005. }
  74006. // Adjust layout by text align
  74007. if (textAlign === 'right') {
  74008. layoutRect.x += layoutRect.width;
  74009. }
  74010. else if (textAlign === 'center') {
  74011. layoutRect.x += layoutRect.width / 2;
  74012. }
  74013. }
  74014. if (!textVerticalAlign) {
  74015. textVerticalAlign = titleModel.get('top') || titleModel.get('bottom');
  74016. if (textVerticalAlign === 'center') {
  74017. textVerticalAlign = 'middle';
  74018. }
  74019. if (textVerticalAlign === 'bottom') {
  74020. layoutRect.y += layoutRect.height;
  74021. }
  74022. else if (textVerticalAlign === 'middle') {
  74023. layoutRect.y += layoutRect.height / 2;
  74024. }
  74025. textVerticalAlign = textVerticalAlign || 'top';
  74026. }
  74027. group.attr('position', [layoutRect.x, layoutRect.y]);
  74028. var alignStyle = {
  74029. textAlign: textAlign,
  74030. textVerticalAlign: textVerticalAlign
  74031. };
  74032. textEl.setStyle(alignStyle);
  74033. subTextEl.setStyle(alignStyle);
  74034. // Render background
  74035. // Get groupRect again because textAlign has been changed
  74036. groupRect = group.getBoundingRect();
  74037. var padding = layoutRect.margin;
  74038. var style = titleModel.getItemStyle(['color', 'opacity']);
  74039. style.fill = titleModel.get('backgroundColor');
  74040. var rect = new Rect({
  74041. shape: {
  74042. x: groupRect.x - padding[3],
  74043. y: groupRect.y - padding[0],
  74044. width: groupRect.width + padding[1] + padding[3],
  74045. height: groupRect.height + padding[0] + padding[2],
  74046. r: titleModel.get('borderRadius')
  74047. },
  74048. style: style,
  74049. subPixelOptimize: true,
  74050. silent: true
  74051. });
  74052. group.add(rect);
  74053. }
  74054. });
  74055. /*
  74056. * Licensed to the Apache Software Foundation (ASF) under one
  74057. * or more contributor license agreements. See the NOTICE file
  74058. * distributed with this work for additional information
  74059. * regarding copyright ownership. The ASF licenses this file
  74060. * to you under the Apache License, Version 2.0 (the
  74061. * "License"); you may not use this file except in compliance
  74062. * with the License. You may obtain a copy of the License at
  74063. *
  74064. * http://www.apache.org/licenses/LICENSE-2.0
  74065. *
  74066. * Unless required by applicable law or agreed to in writing,
  74067. * software distributed under the License is distributed on an
  74068. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74069. * KIND, either express or implied. See the License for the
  74070. * specific language governing permissions and limitations
  74071. * under the License.
  74072. */
  74073. var preprocessor$2 = function (option) {
  74074. var timelineOpt = option && option.timeline;
  74075. if (!isArray(timelineOpt)) {
  74076. timelineOpt = timelineOpt ? [timelineOpt] : [];
  74077. }
  74078. each$1(timelineOpt, function (opt) {
  74079. if (!opt) {
  74080. return;
  74081. }
  74082. compatibleEC2(opt);
  74083. });
  74084. };
  74085. function compatibleEC2(opt) {
  74086. var type = opt.type;
  74087. var ec2Types = {'number': 'value', 'time': 'time'};
  74088. // Compatible with ec2
  74089. if (ec2Types[type]) {
  74090. opt.axisType = ec2Types[type];
  74091. delete opt.type;
  74092. }
  74093. transferItem(opt);
  74094. if (has$1(opt, 'controlPosition')) {
  74095. var controlStyle = opt.controlStyle || (opt.controlStyle = {});
  74096. if (!has$1(controlStyle, 'position')) {
  74097. controlStyle.position = opt.controlPosition;
  74098. }
  74099. if (controlStyle.position === 'none' && !has$1(controlStyle, 'show')) {
  74100. controlStyle.show = false;
  74101. delete controlStyle.position;
  74102. }
  74103. delete opt.controlPosition;
  74104. }
  74105. each$1(opt.data || [], function (dataItem) {
  74106. if (isObject$1(dataItem) && !isArray(dataItem)) {
  74107. if (!has$1(dataItem, 'value') && has$1(dataItem, 'name')) {
  74108. // In ec2, using name as value.
  74109. dataItem.value = dataItem.name;
  74110. }
  74111. transferItem(dataItem);
  74112. }
  74113. });
  74114. }
  74115. function transferItem(opt) {
  74116. var itemStyle = opt.itemStyle || (opt.itemStyle = {});
  74117. var itemStyleEmphasis = itemStyle.emphasis || (itemStyle.emphasis = {});
  74118. // Transfer label out
  74119. var label = opt.label || (opt.label || {});
  74120. var labelNormal = label.normal || (label.normal = {});
  74121. var excludeLabelAttr = {normal: 1, emphasis: 1};
  74122. each$1(label, function (value, name) {
  74123. if (!excludeLabelAttr[name] && !has$1(labelNormal, name)) {
  74124. labelNormal[name] = value;
  74125. }
  74126. });
  74127. if (itemStyleEmphasis.label && !has$1(label, 'emphasis')) {
  74128. label.emphasis = itemStyleEmphasis.label;
  74129. delete itemStyleEmphasis.label;
  74130. }
  74131. }
  74132. function has$1(obj, attr) {
  74133. return obj.hasOwnProperty(attr);
  74134. }
  74135. /*
  74136. * Licensed to the Apache Software Foundation (ASF) under one
  74137. * or more contributor license agreements. See the NOTICE file
  74138. * distributed with this work for additional information
  74139. * regarding copyright ownership. The ASF licenses this file
  74140. * to you under the Apache License, Version 2.0 (the
  74141. * "License"); you may not use this file except in compliance
  74142. * with the License. You may obtain a copy of the License at
  74143. *
  74144. * http://www.apache.org/licenses/LICENSE-2.0
  74145. *
  74146. * Unless required by applicable law or agreed to in writing,
  74147. * software distributed under the License is distributed on an
  74148. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74149. * KIND, either express or implied. See the License for the
  74150. * specific language governing permissions and limitations
  74151. * under the License.
  74152. */
  74153. ComponentModel.registerSubTypeDefaulter('timeline', function () {
  74154. // Only slider now.
  74155. return 'slider';
  74156. });
  74157. /*
  74158. * Licensed to the Apache Software Foundation (ASF) under one
  74159. * or more contributor license agreements. See the NOTICE file
  74160. * distributed with this work for additional information
  74161. * regarding copyright ownership. The ASF licenses this file
  74162. * to you under the Apache License, Version 2.0 (the
  74163. * "License"); you may not use this file except in compliance
  74164. * with the License. You may obtain a copy of the License at
  74165. *
  74166. * http://www.apache.org/licenses/LICENSE-2.0
  74167. *
  74168. * Unless required by applicable law or agreed to in writing,
  74169. * software distributed under the License is distributed on an
  74170. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74171. * KIND, either express or implied. See the License for the
  74172. * specific language governing permissions and limitations
  74173. * under the License.
  74174. */
  74175. registerAction(
  74176. {type: 'timelineChange', event: 'timelineChanged', update: 'prepareAndUpdate'},
  74177. function (payload, ecModel) {
  74178. var timelineModel = ecModel.getComponent('timeline');
  74179. if (timelineModel && payload.currentIndex != null) {
  74180. timelineModel.setCurrentIndex(payload.currentIndex);
  74181. if (!timelineModel.get('loop', true) && timelineModel.isIndexMax()) {
  74182. timelineModel.setPlayState(false);
  74183. }
  74184. }
  74185. // Set normalized currentIndex to payload.
  74186. ecModel.resetOption('timeline');
  74187. return defaults({
  74188. currentIndex: timelineModel.option.currentIndex
  74189. }, payload);
  74190. }
  74191. );
  74192. registerAction(
  74193. {type: 'timelinePlayChange', event: 'timelinePlayChanged', update: 'update'},
  74194. function (payload, ecModel) {
  74195. var timelineModel = ecModel.getComponent('timeline');
  74196. if (timelineModel && payload.playState != null) {
  74197. timelineModel.setPlayState(payload.playState);
  74198. }
  74199. }
  74200. );
  74201. /*
  74202. * Licensed to the Apache Software Foundation (ASF) under one
  74203. * or more contributor license agreements. See the NOTICE file
  74204. * distributed with this work for additional information
  74205. * regarding copyright ownership. The ASF licenses this file
  74206. * to you under the Apache License, Version 2.0 (the
  74207. * "License"); you may not use this file except in compliance
  74208. * with the License. You may obtain a copy of the License at
  74209. *
  74210. * http://www.apache.org/licenses/LICENSE-2.0
  74211. *
  74212. * Unless required by applicable law or agreed to in writing,
  74213. * software distributed under the License is distributed on an
  74214. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74215. * KIND, either express or implied. See the License for the
  74216. * specific language governing permissions and limitations
  74217. * under the License.
  74218. */
  74219. var TimelineModel = ComponentModel.extend({
  74220. type: 'timeline',
  74221. layoutMode: 'box',
  74222. /**
  74223. * @protected
  74224. */
  74225. defaultOption: {
  74226. zlevel: 0, // 一级层叠
  74227. z: 4, // 二级层叠
  74228. show: true,
  74229. axisType: 'time', // 模式是时间类型,支持 value, category
  74230. realtime: true,
  74231. left: '20%',
  74232. top: null,
  74233. right: '20%',
  74234. bottom: 0,
  74235. width: null,
  74236. height: 40,
  74237. padding: 5,
  74238. controlPosition: 'left', // 'left' 'right' 'top' 'bottom' 'none'
  74239. autoPlay: false,
  74240. rewind: false, // 反向播放
  74241. loop: true,
  74242. playInterval: 2000, // 播放时间间隔,单位ms
  74243. currentIndex: 0,
  74244. itemStyle: {},
  74245. label: {
  74246. color: '#000'
  74247. },
  74248. data: []
  74249. },
  74250. /**
  74251. * @override
  74252. */
  74253. init: function (option, parentModel, ecModel) {
  74254. /**
  74255. * @private
  74256. * @type {module:echarts/data/List}
  74257. */
  74258. this._data;
  74259. /**
  74260. * @private
  74261. * @type {Array.<string>}
  74262. */
  74263. this._names;
  74264. this.mergeDefaultAndTheme(option, ecModel);
  74265. this._initData();
  74266. },
  74267. /**
  74268. * @override
  74269. */
  74270. mergeOption: function (option) {
  74271. TimelineModel.superApply(this, 'mergeOption', arguments);
  74272. this._initData();
  74273. },
  74274. /**
  74275. * @param {number} [currentIndex]
  74276. */
  74277. setCurrentIndex: function (currentIndex) {
  74278. if (currentIndex == null) {
  74279. currentIndex = this.option.currentIndex;
  74280. }
  74281. var count = this._data.count();
  74282. if (this.option.loop) {
  74283. currentIndex = (currentIndex % count + count) % count;
  74284. }
  74285. else {
  74286. currentIndex >= count && (currentIndex = count - 1);
  74287. currentIndex < 0 && (currentIndex = 0);
  74288. }
  74289. this.option.currentIndex = currentIndex;
  74290. },
  74291. /**
  74292. * @return {number} currentIndex
  74293. */
  74294. getCurrentIndex: function () {
  74295. return this.option.currentIndex;
  74296. },
  74297. /**
  74298. * @return {boolean}
  74299. */
  74300. isIndexMax: function () {
  74301. return this.getCurrentIndex() >= this._data.count() - 1;
  74302. },
  74303. /**
  74304. * @param {boolean} state true: play, false: stop
  74305. */
  74306. setPlayState: function (state) {
  74307. this.option.autoPlay = !!state;
  74308. },
  74309. /**
  74310. * @return {boolean} true: play, false: stop
  74311. */
  74312. getPlayState: function () {
  74313. return !!this.option.autoPlay;
  74314. },
  74315. /**
  74316. * @private
  74317. */
  74318. _initData: function () {
  74319. var thisOption = this.option;
  74320. var dataArr = thisOption.data || [];
  74321. var axisType = thisOption.axisType;
  74322. var names = this._names = [];
  74323. if (axisType === 'category') {
  74324. var idxArr = [];
  74325. each$1(dataArr, function (item, index) {
  74326. var value = getDataItemValue(item);
  74327. var newItem;
  74328. if (isObject$1(item)) {
  74329. newItem = clone(item);
  74330. newItem.value = index;
  74331. }
  74332. else {
  74333. newItem = index;
  74334. }
  74335. idxArr.push(newItem);
  74336. if (!isString(value) && (value == null || isNaN(value))) {
  74337. value = '';
  74338. }
  74339. names.push(value + '');
  74340. });
  74341. dataArr = idxArr;
  74342. }
  74343. var dimType = ({category: 'ordinal', time: 'time'})[axisType] || 'number';
  74344. var data = this._data = new List([{name: 'value', type: dimType}], this);
  74345. data.initData(dataArr, names);
  74346. },
  74347. getData: function () {
  74348. return this._data;
  74349. },
  74350. /**
  74351. * @public
  74352. * @return {Array.<string>} categoreis
  74353. */
  74354. getCategories: function () {
  74355. if (this.get('axisType') === 'category') {
  74356. return this._names.slice();
  74357. }
  74358. }
  74359. });
  74360. /*
  74361. * Licensed to the Apache Software Foundation (ASF) under one
  74362. * or more contributor license agreements. See the NOTICE file
  74363. * distributed with this work for additional information
  74364. * regarding copyright ownership. The ASF licenses this file
  74365. * to you under the Apache License, Version 2.0 (the
  74366. * "License"); you may not use this file except in compliance
  74367. * with the License. You may obtain a copy of the License at
  74368. *
  74369. * http://www.apache.org/licenses/LICENSE-2.0
  74370. *
  74371. * Unless required by applicable law or agreed to in writing,
  74372. * software distributed under the License is distributed on an
  74373. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74374. * KIND, either express or implied. See the License for the
  74375. * specific language governing permissions and limitations
  74376. * under the License.
  74377. */
  74378. var SliderTimelineModel = TimelineModel.extend({
  74379. type: 'timeline.slider',
  74380. /**
  74381. * @protected
  74382. */
  74383. defaultOption: {
  74384. backgroundColor: 'rgba(0,0,0,0)', // 时间轴背景颜色
  74385. borderColor: '#ccc', // 时间轴边框颜色
  74386. borderWidth: 0, // 时间轴边框线宽,单位px,默认为0(无边框)
  74387. orient: 'horizontal', // 'vertical'
  74388. inverse: false,
  74389. tooltip: { // boolean or Object
  74390. trigger: 'item' // data item may also have tootip attr.
  74391. },
  74392. symbol: 'emptyCircle',
  74393. symbolSize: 10,
  74394. lineStyle: {
  74395. show: true,
  74396. width: 2,
  74397. color: '#304654'
  74398. },
  74399. label: { // 文本标签
  74400. position: 'auto', // auto left right top bottom
  74401. // When using number, label position is not
  74402. // restricted by viewRect.
  74403. // positive: right/bottom, negative: left/top
  74404. show: true,
  74405. interval: 'auto',
  74406. rotate: 0,
  74407. // formatter: null,
  74408. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  74409. color: '#304654'
  74410. },
  74411. itemStyle: {
  74412. color: '#304654',
  74413. borderWidth: 1
  74414. },
  74415. checkpointStyle: {
  74416. symbol: 'circle',
  74417. symbolSize: 13,
  74418. color: '#c23531',
  74419. borderWidth: 5,
  74420. borderColor: 'rgba(194,53,49, 0.5)',
  74421. animation: true,
  74422. animationDuration: 300,
  74423. animationEasing: 'quinticInOut'
  74424. },
  74425. controlStyle: {
  74426. show: true,
  74427. showPlayBtn: true,
  74428. showPrevBtn: true,
  74429. showNextBtn: true,
  74430. itemSize: 22,
  74431. itemGap: 12,
  74432. position: 'left', // 'left' 'right' 'top' 'bottom'
  74433. playIcon: 'path://M31.6,53C17.5,53,6,41.5,6,27.4S17.5,1.8,31.6,1.8C45.7,1.8,57.2,13.3,57.2,27.4S45.7,53,31.6,53z M31.6,3.3 C18.4,3.3,7.5,14.1,7.5,27.4c0,13.3,10.8,24.1,24.1,24.1C44.9,51.5,55.7,40.7,55.7,27.4C55.7,14.1,44.9,3.3,31.6,3.3z M24.9,21.3 c0-2.2,1.6-3.1,3.5-2l10.5,6.1c1.899,1.1,1.899,2.9,0,4l-10.5,6.1c-1.9,1.1-3.5,0.2-3.5-2V21.3z', // jshint ignore:line
  74434. stopIcon: 'path://M30.9,53.2C16.8,53.2,5.3,41.7,5.3,27.6S16.8,2,30.9,2C45,2,56.4,13.5,56.4,27.6S45,53.2,30.9,53.2z M30.9,3.5C17.6,3.5,6.8,14.4,6.8,27.6c0,13.3,10.8,24.1,24.101,24.1C44.2,51.7,55,40.9,55,27.6C54.9,14.4,44.1,3.5,30.9,3.5z M36.9,35.8c0,0.601-0.4,1-0.9,1h-1.3c-0.5,0-0.9-0.399-0.9-1V19.5c0-0.6,0.4-1,0.9-1H36c0.5,0,0.9,0.4,0.9,1V35.8z M27.8,35.8 c0,0.601-0.4,1-0.9,1h-1.3c-0.5,0-0.9-0.399-0.9-1V19.5c0-0.6,0.4-1,0.9-1H27c0.5,0,0.9,0.4,0.9,1L27.8,35.8L27.8,35.8z', // jshint ignore:line
  74435. nextIcon: 'path://M18.6,50.8l22.5-22.5c0.2-0.2,0.3-0.4,0.3-0.7c0-0.3-0.1-0.5-0.3-0.7L18.7,4.4c-0.1-0.1-0.2-0.3-0.2-0.5 c0-0.4,0.3-0.8,0.8-0.8c0.2,0,0.5,0.1,0.6,0.3l23.5,23.5l0,0c0.2,0.2,0.3,0.4,0.3,0.7c0,0.3-0.1,0.5-0.3,0.7l-0.1,0.1L19.7,52 c-0.1,0.1-0.3,0.2-0.5,0.2c-0.4,0-0.8-0.3-0.8-0.8C18.4,51.2,18.5,51,18.6,50.8z', // jshint ignore:line
  74436. prevIcon: 'path://M43,52.8L20.4,30.3c-0.2-0.2-0.3-0.4-0.3-0.7c0-0.3,0.1-0.5,0.3-0.7L42.9,6.4c0.1-0.1,0.2-0.3,0.2-0.5 c0-0.4-0.3-0.8-0.8-0.8c-0.2,0-0.5,0.1-0.6,0.3L18.3,28.8l0,0c-0.2,0.2-0.3,0.4-0.3,0.7c0,0.3,0.1,0.5,0.3,0.7l0.1,0.1L41.9,54 c0.1,0.1,0.3,0.2,0.5,0.2c0.4,0,0.8-0.3,0.8-0.8C43.2,53.2,43.1,53,43,52.8z', // jshint ignore:line
  74437. color: '#304654',
  74438. borderColor: '#304654',
  74439. borderWidth: 1
  74440. },
  74441. emphasis: {
  74442. label: {
  74443. show: true,
  74444. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  74445. color: '#c23531'
  74446. },
  74447. itemStyle: {
  74448. color: '#c23531'
  74449. },
  74450. controlStyle: {
  74451. color: '#c23531',
  74452. borderColor: '#c23531',
  74453. borderWidth: 2
  74454. }
  74455. },
  74456. data: []
  74457. }
  74458. });
  74459. mixin(SliderTimelineModel, dataFormatMixin);
  74460. /*
  74461. * Licensed to the Apache Software Foundation (ASF) under one
  74462. * or more contributor license agreements. See the NOTICE file
  74463. * distributed with this work for additional information
  74464. * regarding copyright ownership. The ASF licenses this file
  74465. * to you under the Apache License, Version 2.0 (the
  74466. * "License"); you may not use this file except in compliance
  74467. * with the License. You may obtain a copy of the License at
  74468. *
  74469. * http://www.apache.org/licenses/LICENSE-2.0
  74470. *
  74471. * Unless required by applicable law or agreed to in writing,
  74472. * software distributed under the License is distributed on an
  74473. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74474. * KIND, either express or implied. See the License for the
  74475. * specific language governing permissions and limitations
  74476. * under the License.
  74477. */
  74478. var TimelineView = Component$1.extend({
  74479. type: 'timeline'
  74480. });
  74481. /*
  74482. * Licensed to the Apache Software Foundation (ASF) under one
  74483. * or more contributor license agreements. See the NOTICE file
  74484. * distributed with this work for additional information
  74485. * regarding copyright ownership. The ASF licenses this file
  74486. * to you under the Apache License, Version 2.0 (the
  74487. * "License"); you may not use this file except in compliance
  74488. * with the License. You may obtain a copy of the License at
  74489. *
  74490. * http://www.apache.org/licenses/LICENSE-2.0
  74491. *
  74492. * Unless required by applicable law or agreed to in writing,
  74493. * software distributed under the License is distributed on an
  74494. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74495. * KIND, either express or implied. See the License for the
  74496. * specific language governing permissions and limitations
  74497. * under the License.
  74498. */
  74499. /**
  74500. * Extend axis 2d
  74501. * @constructor module:echarts/coord/cartesian/Axis2D
  74502. * @extends {module:echarts/coord/cartesian/Axis}
  74503. * @param {string} dim
  74504. * @param {*} scale
  74505. * @param {Array.<number>} coordExtent
  74506. * @param {string} axisType
  74507. * @param {string} position
  74508. */
  74509. var TimelineAxis = function (dim, scale, coordExtent, axisType) {
  74510. Axis.call(this, dim, scale, coordExtent);
  74511. /**
  74512. * Axis type
  74513. * - 'category'
  74514. * - 'value'
  74515. * - 'time'
  74516. * - 'log'
  74517. * @type {string}
  74518. */
  74519. this.type = axisType || 'value';
  74520. /**
  74521. * Axis model
  74522. * @param {module:echarts/component/TimelineModel}
  74523. */
  74524. this.model = null;
  74525. };
  74526. TimelineAxis.prototype = {
  74527. constructor: TimelineAxis,
  74528. /**
  74529. * @override
  74530. */
  74531. getLabelModel: function () {
  74532. return this.model.getModel('label');
  74533. },
  74534. /**
  74535. * @override
  74536. */
  74537. isHorizontal: function () {
  74538. return this.model.get('orient') === 'horizontal';
  74539. }
  74540. };
  74541. inherits(TimelineAxis, Axis);
  74542. /*
  74543. * Licensed to the Apache Software Foundation (ASF) under one
  74544. * or more contributor license agreements. See the NOTICE file
  74545. * distributed with this work for additional information
  74546. * regarding copyright ownership. The ASF licenses this file
  74547. * to you under the Apache License, Version 2.0 (the
  74548. * "License"); you may not use this file except in compliance
  74549. * with the License. You may obtain a copy of the License at
  74550. *
  74551. * http://www.apache.org/licenses/LICENSE-2.0
  74552. *
  74553. * Unless required by applicable law or agreed to in writing,
  74554. * software distributed under the License is distributed on an
  74555. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74556. * KIND, either express or implied. See the License for the
  74557. * specific language governing permissions and limitations
  74558. * under the License.
  74559. */
  74560. var bind$4 = bind;
  74561. var each$24 = each$1;
  74562. var PI$5 = Math.PI;
  74563. TimelineView.extend({
  74564. type: 'timeline.slider',
  74565. init: function (ecModel, api) {
  74566. this.api = api;
  74567. /**
  74568. * @private
  74569. * @type {module:echarts/component/timeline/TimelineAxis}
  74570. */
  74571. this._axis;
  74572. /**
  74573. * @private
  74574. * @type {module:zrender/core/BoundingRect}
  74575. */
  74576. this._viewRect;
  74577. /**
  74578. * @type {number}
  74579. */
  74580. this._timer;
  74581. /**
  74582. * @type {module:zrender/Element}
  74583. */
  74584. this._currentPointer;
  74585. /**
  74586. * @type {module:zrender/container/Group}
  74587. */
  74588. this._mainGroup;
  74589. /**
  74590. * @type {module:zrender/container/Group}
  74591. */
  74592. this._labelGroup;
  74593. },
  74594. /**
  74595. * @override
  74596. */
  74597. render: function (timelineModel, ecModel, api, payload) {
  74598. this.model = timelineModel;
  74599. this.api = api;
  74600. this.ecModel = ecModel;
  74601. this.group.removeAll();
  74602. if (timelineModel.get('show', true)) {
  74603. var layoutInfo = this._layout(timelineModel, api);
  74604. var mainGroup = this._createGroup('mainGroup');
  74605. var labelGroup = this._createGroup('labelGroup');
  74606. /**
  74607. * @private
  74608. * @type {module:echarts/component/timeline/TimelineAxis}
  74609. */
  74610. var axis = this._axis = this._createAxis(layoutInfo, timelineModel);
  74611. timelineModel.formatTooltip = function (dataIndex) {
  74612. return encodeHTML(axis.scale.getLabel(dataIndex));
  74613. };
  74614. each$24(
  74615. ['AxisLine', 'AxisTick', 'Control', 'CurrentPointer'],
  74616. function (name) {
  74617. this['_render' + name](layoutInfo, mainGroup, axis, timelineModel);
  74618. },
  74619. this
  74620. );
  74621. this._renderAxisLabel(layoutInfo, labelGroup, axis, timelineModel);
  74622. this._position(layoutInfo, timelineModel);
  74623. }
  74624. this._doPlayStop();
  74625. },
  74626. /**
  74627. * @override
  74628. */
  74629. remove: function () {
  74630. this._clearTimer();
  74631. this.group.removeAll();
  74632. },
  74633. /**
  74634. * @override
  74635. */
  74636. dispose: function () {
  74637. this._clearTimer();
  74638. },
  74639. _layout: function (timelineModel, api) {
  74640. var labelPosOpt = timelineModel.get('label.position');
  74641. var orient = timelineModel.get('orient');
  74642. var viewRect = getViewRect$5(timelineModel, api);
  74643. // Auto label offset.
  74644. if (labelPosOpt == null || labelPosOpt === 'auto') {
  74645. labelPosOpt = orient === 'horizontal'
  74646. ? ((viewRect.y + viewRect.height / 2) < api.getHeight() / 2 ? '-' : '+')
  74647. : ((viewRect.x + viewRect.width / 2) < api.getWidth() / 2 ? '+' : '-');
  74648. }
  74649. else if (isNaN(labelPosOpt)) {
  74650. labelPosOpt = ({
  74651. horizontal: {top: '-', bottom: '+'},
  74652. vertical: {left: '-', right: '+'}
  74653. })[orient][labelPosOpt];
  74654. }
  74655. var labelAlignMap = {
  74656. horizontal: 'center',
  74657. vertical: (labelPosOpt >= 0 || labelPosOpt === '+') ? 'left' : 'right'
  74658. };
  74659. var labelBaselineMap = {
  74660. horizontal: (labelPosOpt >= 0 || labelPosOpt === '+') ? 'top' : 'bottom',
  74661. vertical: 'middle'
  74662. };
  74663. var rotationMap = {
  74664. horizontal: 0,
  74665. vertical: PI$5 / 2
  74666. };
  74667. // Position
  74668. var mainLength = orient === 'vertical' ? viewRect.height : viewRect.width;
  74669. var controlModel = timelineModel.getModel('controlStyle');
  74670. var showControl = controlModel.get('show', true);
  74671. var controlSize = showControl ? controlModel.get('itemSize') : 0;
  74672. var controlGap = showControl ? controlModel.get('itemGap') : 0;
  74673. var sizePlusGap = controlSize + controlGap;
  74674. // Special label rotate.
  74675. var labelRotation = timelineModel.get('label.rotate') || 0;
  74676. labelRotation = labelRotation * PI$5 / 180; // To radian.
  74677. var playPosition;
  74678. var prevBtnPosition;
  74679. var nextBtnPosition;
  74680. var axisExtent;
  74681. var controlPosition = controlModel.get('position', true);
  74682. var showPlayBtn = showControl && controlModel.get('showPlayBtn', true);
  74683. var showPrevBtn = showControl && controlModel.get('showPrevBtn', true);
  74684. var showNextBtn = showControl && controlModel.get('showNextBtn', true);
  74685. var xLeft = 0;
  74686. var xRight = mainLength;
  74687. // position[0] means left, position[1] means middle.
  74688. if (controlPosition === 'left' || controlPosition === 'bottom') {
  74689. showPlayBtn && (playPosition = [0, 0], xLeft += sizePlusGap);
  74690. showPrevBtn && (prevBtnPosition = [xLeft, 0], xLeft += sizePlusGap);
  74691. showNextBtn && (nextBtnPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
  74692. }
  74693. else { // 'top' 'right'
  74694. showPlayBtn && (playPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
  74695. showPrevBtn && (prevBtnPosition = [0, 0], xLeft += sizePlusGap);
  74696. showNextBtn && (nextBtnPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
  74697. }
  74698. axisExtent = [xLeft, xRight];
  74699. if (timelineModel.get('inverse')) {
  74700. axisExtent.reverse();
  74701. }
  74702. return {
  74703. viewRect: viewRect,
  74704. mainLength: mainLength,
  74705. orient: orient,
  74706. rotation: rotationMap[orient],
  74707. labelRotation: labelRotation,
  74708. labelPosOpt: labelPosOpt,
  74709. labelAlign: timelineModel.get('label.align') || labelAlignMap[orient],
  74710. labelBaseline: timelineModel.get('label.verticalAlign')
  74711. || timelineModel.get('label.baseline')
  74712. || labelBaselineMap[orient],
  74713. // Based on mainGroup.
  74714. playPosition: playPosition,
  74715. prevBtnPosition: prevBtnPosition,
  74716. nextBtnPosition: nextBtnPosition,
  74717. axisExtent: axisExtent,
  74718. controlSize: controlSize,
  74719. controlGap: controlGap
  74720. };
  74721. },
  74722. _position: function (layoutInfo, timelineModel) {
  74723. // Position is be called finally, because bounding rect is needed for
  74724. // adapt content to fill viewRect (auto adapt offset).
  74725. // Timeline may be not all in the viewRect when 'offset' is specified
  74726. // as a number, because it is more appropriate that label aligns at
  74727. // 'offset' but not the other edge defined by viewRect.
  74728. var mainGroup = this._mainGroup;
  74729. var labelGroup = this._labelGroup;
  74730. var viewRect = layoutInfo.viewRect;
  74731. if (layoutInfo.orient === 'vertical') {
  74732. // transform to horizontal, inverse rotate by left-top point.
  74733. var m = create$1();
  74734. var rotateOriginX = viewRect.x;
  74735. var rotateOriginY = viewRect.y + viewRect.height;
  74736. translate(m, m, [-rotateOriginX, -rotateOriginY]);
  74737. rotate(m, m, -PI$5 / 2);
  74738. translate(m, m, [rotateOriginX, rotateOriginY]);
  74739. viewRect = viewRect.clone();
  74740. viewRect.applyTransform(m);
  74741. }
  74742. var viewBound = getBound(viewRect);
  74743. var mainBound = getBound(mainGroup.getBoundingRect());
  74744. var labelBound = getBound(labelGroup.getBoundingRect());
  74745. var mainPosition = mainGroup.position;
  74746. var labelsPosition = labelGroup.position;
  74747. labelsPosition[0] = mainPosition[0] = viewBound[0][0];
  74748. var labelPosOpt = layoutInfo.labelPosOpt;
  74749. if (isNaN(labelPosOpt)) { // '+' or '-'
  74750. var mainBoundIdx = labelPosOpt === '+' ? 0 : 1;
  74751. toBound(mainPosition, mainBound, viewBound, 1, mainBoundIdx);
  74752. toBound(labelsPosition, labelBound, viewBound, 1, 1 - mainBoundIdx);
  74753. }
  74754. else {
  74755. var mainBoundIdx = labelPosOpt >= 0 ? 0 : 1;
  74756. toBound(mainPosition, mainBound, viewBound, 1, mainBoundIdx);
  74757. labelsPosition[1] = mainPosition[1] + labelPosOpt;
  74758. }
  74759. mainGroup.attr('position', mainPosition);
  74760. labelGroup.attr('position', labelsPosition);
  74761. mainGroup.rotation = labelGroup.rotation = layoutInfo.rotation;
  74762. setOrigin(mainGroup);
  74763. setOrigin(labelGroup);
  74764. function setOrigin(targetGroup) {
  74765. var pos = targetGroup.position;
  74766. targetGroup.origin = [
  74767. viewBound[0][0] - pos[0],
  74768. viewBound[1][0] - pos[1]
  74769. ];
  74770. }
  74771. function getBound(rect) {
  74772. // [[xmin, xmax], [ymin, ymax]]
  74773. return [
  74774. [rect.x, rect.x + rect.width],
  74775. [rect.y, rect.y + rect.height]
  74776. ];
  74777. }
  74778. function toBound(fromPos, from, to, dimIdx, boundIdx) {
  74779. fromPos[dimIdx] += to[dimIdx][boundIdx] - from[dimIdx][boundIdx];
  74780. }
  74781. },
  74782. _createAxis: function (layoutInfo, timelineModel) {
  74783. var data = timelineModel.getData();
  74784. var axisType = timelineModel.get('axisType');
  74785. var scale = createScaleByModel(timelineModel, axisType);
  74786. // Customize scale. The `tickValue` is `dataIndex`.
  74787. scale.getTicks = function () {
  74788. return data.mapArray(['value'], function (value) {
  74789. return value;
  74790. });
  74791. };
  74792. var dataExtent = data.getDataExtent('value');
  74793. scale.setExtent(dataExtent[0], dataExtent[1]);
  74794. scale.niceTicks();
  74795. var axis = new TimelineAxis('value', scale, layoutInfo.axisExtent, axisType);
  74796. axis.model = timelineModel;
  74797. return axis;
  74798. },
  74799. _createGroup: function (name) {
  74800. var newGroup = this['_' + name] = new Group();
  74801. this.group.add(newGroup);
  74802. return newGroup;
  74803. },
  74804. _renderAxisLine: function (layoutInfo, group, axis, timelineModel) {
  74805. var axisExtent = axis.getExtent();
  74806. if (!timelineModel.get('lineStyle.show')) {
  74807. return;
  74808. }
  74809. group.add(new Line({
  74810. shape: {
  74811. x1: axisExtent[0], y1: 0,
  74812. x2: axisExtent[1], y2: 0
  74813. },
  74814. style: extend(
  74815. {lineCap: 'round'},
  74816. timelineModel.getModel('lineStyle').getLineStyle()
  74817. ),
  74818. silent: true,
  74819. z2: 1
  74820. }));
  74821. },
  74822. /**
  74823. * @private
  74824. */
  74825. _renderAxisTick: function (layoutInfo, group, axis, timelineModel) {
  74826. var data = timelineModel.getData();
  74827. // Show all ticks, despite ignoring strategy.
  74828. var ticks = axis.scale.getTicks();
  74829. // The value is dataIndex, see the costomized scale.
  74830. each$24(ticks, function (value) {
  74831. var tickCoord = axis.dataToCoord(value);
  74832. var itemModel = data.getItemModel(value);
  74833. var itemStyleModel = itemModel.getModel('itemStyle');
  74834. var hoverStyleModel = itemModel.getModel('emphasis.itemStyle');
  74835. var symbolOpt = {
  74836. position: [tickCoord, 0],
  74837. onclick: bind$4(this._changeTimeline, this, value)
  74838. };
  74839. var el = giveSymbol(itemModel, itemStyleModel, group, symbolOpt);
  74840. setHoverStyle(el, hoverStyleModel.getItemStyle());
  74841. if (itemModel.get('tooltip')) {
  74842. el.dataIndex = value;
  74843. el.dataModel = timelineModel;
  74844. }
  74845. else {
  74846. el.dataIndex = el.dataModel = null;
  74847. }
  74848. }, this);
  74849. },
  74850. /**
  74851. * @private
  74852. */
  74853. _renderAxisLabel: function (layoutInfo, group, axis, timelineModel) {
  74854. var labelModel = axis.getLabelModel();
  74855. if (!labelModel.get('show')) {
  74856. return;
  74857. }
  74858. var data = timelineModel.getData();
  74859. var labels = axis.getViewLabels();
  74860. each$24(labels, function (labelItem) {
  74861. // The tickValue is dataIndex, see the costomized scale.
  74862. var dataIndex = labelItem.tickValue;
  74863. var itemModel = data.getItemModel(dataIndex);
  74864. var normalLabelModel = itemModel.getModel('label');
  74865. var hoverLabelModel = itemModel.getModel('emphasis.label');
  74866. var tickCoord = axis.dataToCoord(labelItem.tickValue);
  74867. var textEl = new Text({
  74868. position: [tickCoord, 0],
  74869. rotation: layoutInfo.labelRotation - layoutInfo.rotation,
  74870. onclick: bind$4(this._changeTimeline, this, dataIndex),
  74871. silent: false
  74872. });
  74873. setTextStyle(textEl.style, normalLabelModel, {
  74874. text: labelItem.formattedLabel,
  74875. textAlign: layoutInfo.labelAlign,
  74876. textVerticalAlign: layoutInfo.labelBaseline
  74877. });
  74878. group.add(textEl);
  74879. setHoverStyle(
  74880. textEl, setTextStyle({}, hoverLabelModel)
  74881. );
  74882. }, this);
  74883. },
  74884. /**
  74885. * @private
  74886. */
  74887. _renderControl: function (layoutInfo, group, axis, timelineModel) {
  74888. var controlSize = layoutInfo.controlSize;
  74889. var rotation = layoutInfo.rotation;
  74890. var itemStyle = timelineModel.getModel('controlStyle').getItemStyle();
  74891. var hoverStyle = timelineModel.getModel('emphasis.controlStyle').getItemStyle();
  74892. var rect = [0, -controlSize / 2, controlSize, controlSize];
  74893. var playState = timelineModel.getPlayState();
  74894. var inverse = timelineModel.get('inverse', true);
  74895. makeBtn(
  74896. layoutInfo.nextBtnPosition,
  74897. 'controlStyle.nextIcon',
  74898. bind$4(this._changeTimeline, this, inverse ? '-' : '+')
  74899. );
  74900. makeBtn(
  74901. layoutInfo.prevBtnPosition,
  74902. 'controlStyle.prevIcon',
  74903. bind$4(this._changeTimeline, this, inverse ? '+' : '-')
  74904. );
  74905. makeBtn(
  74906. layoutInfo.playPosition,
  74907. 'controlStyle.' + (playState ? 'stopIcon' : 'playIcon'),
  74908. bind$4(this._handlePlayClick, this, !playState),
  74909. true
  74910. );
  74911. function makeBtn(position, iconPath, onclick, willRotate) {
  74912. if (!position) {
  74913. return;
  74914. }
  74915. var opt = {
  74916. position: position,
  74917. origin: [controlSize / 2, 0],
  74918. rotation: willRotate ? -rotation : 0,
  74919. rectHover: true,
  74920. style: itemStyle,
  74921. onclick: onclick
  74922. };
  74923. var btn = makeIcon(timelineModel, iconPath, rect, opt);
  74924. group.add(btn);
  74925. setHoverStyle(btn, hoverStyle);
  74926. }
  74927. },
  74928. _renderCurrentPointer: function (layoutInfo, group, axis, timelineModel) {
  74929. var data = timelineModel.getData();
  74930. var currentIndex = timelineModel.getCurrentIndex();
  74931. var pointerModel = data.getItemModel(currentIndex).getModel('checkpointStyle');
  74932. var me = this;
  74933. var callback = {
  74934. onCreate: function (pointer) {
  74935. pointer.draggable = true;
  74936. pointer.drift = bind$4(me._handlePointerDrag, me);
  74937. pointer.ondragend = bind$4(me._handlePointerDragend, me);
  74938. pointerMoveTo(pointer, currentIndex, axis, timelineModel, true);
  74939. },
  74940. onUpdate: function (pointer) {
  74941. pointerMoveTo(pointer, currentIndex, axis, timelineModel);
  74942. }
  74943. };
  74944. // Reuse when exists, for animation and drag.
  74945. this._currentPointer = giveSymbol(
  74946. pointerModel, pointerModel, this._mainGroup, {}, this._currentPointer, callback
  74947. );
  74948. },
  74949. _handlePlayClick: function (nextState) {
  74950. this._clearTimer();
  74951. this.api.dispatchAction({
  74952. type: 'timelinePlayChange',
  74953. playState: nextState,
  74954. from: this.uid
  74955. });
  74956. },
  74957. _handlePointerDrag: function (dx, dy, e) {
  74958. this._clearTimer();
  74959. this._pointerChangeTimeline([e.offsetX, e.offsetY]);
  74960. },
  74961. _handlePointerDragend: function (e) {
  74962. this._pointerChangeTimeline([e.offsetX, e.offsetY], true);
  74963. },
  74964. _pointerChangeTimeline: function (mousePos, trigger) {
  74965. var toCoord = this._toAxisCoord(mousePos)[0];
  74966. var axis = this._axis;
  74967. var axisExtent = asc(axis.getExtent().slice());
  74968. toCoord > axisExtent[1] && (toCoord = axisExtent[1]);
  74969. toCoord < axisExtent[0] && (toCoord = axisExtent[0]);
  74970. this._currentPointer.position[0] = toCoord;
  74971. this._currentPointer.dirty();
  74972. var targetDataIndex = this._findNearestTick(toCoord);
  74973. var timelineModel = this.model;
  74974. if (trigger || (
  74975. targetDataIndex !== timelineModel.getCurrentIndex()
  74976. && timelineModel.get('realtime')
  74977. )) {
  74978. this._changeTimeline(targetDataIndex);
  74979. }
  74980. },
  74981. _doPlayStop: function () {
  74982. this._clearTimer();
  74983. if (this.model.getPlayState()) {
  74984. this._timer = setTimeout(
  74985. bind$4(handleFrame, this),
  74986. this.model.get('playInterval')
  74987. );
  74988. }
  74989. function handleFrame() {
  74990. // Do not cache
  74991. var timelineModel = this.model;
  74992. this._changeTimeline(
  74993. timelineModel.getCurrentIndex()
  74994. + (timelineModel.get('rewind', true) ? -1 : 1)
  74995. );
  74996. }
  74997. },
  74998. _toAxisCoord: function (vertex) {
  74999. var trans = this._mainGroup.getLocalTransform();
  75000. return applyTransform$1(vertex, trans, true);
  75001. },
  75002. _findNearestTick: function (axisCoord) {
  75003. var data = this.model.getData();
  75004. var dist = Infinity;
  75005. var targetDataIndex;
  75006. var axis = this._axis;
  75007. data.each(['value'], function (value, dataIndex) {
  75008. var coord = axis.dataToCoord(value);
  75009. var d = Math.abs(coord - axisCoord);
  75010. if (d < dist) {
  75011. dist = d;
  75012. targetDataIndex = dataIndex;
  75013. }
  75014. });
  75015. return targetDataIndex;
  75016. },
  75017. _clearTimer: function () {
  75018. if (this._timer) {
  75019. clearTimeout(this._timer);
  75020. this._timer = null;
  75021. }
  75022. },
  75023. _changeTimeline: function (nextIndex) {
  75024. var currentIndex = this.model.getCurrentIndex();
  75025. if (nextIndex === '+') {
  75026. nextIndex = currentIndex + 1;
  75027. }
  75028. else if (nextIndex === '-') {
  75029. nextIndex = currentIndex - 1;
  75030. }
  75031. this.api.dispatchAction({
  75032. type: 'timelineChange',
  75033. currentIndex: nextIndex,
  75034. from: this.uid
  75035. });
  75036. }
  75037. });
  75038. function getViewRect$5(model, api) {
  75039. return getLayoutRect(
  75040. model.getBoxLayoutParams(),
  75041. {
  75042. width: api.getWidth(),
  75043. height: api.getHeight()
  75044. },
  75045. model.get('padding')
  75046. );
  75047. }
  75048. function makeIcon(timelineModel, objPath, rect, opts) {
  75049. var icon = makePath(
  75050. timelineModel.get(objPath).replace(/^path:\/\//, ''),
  75051. clone(opts || {}),
  75052. new BoundingRect(rect[0], rect[1], rect[2], rect[3]),
  75053. 'center'
  75054. );
  75055. return icon;
  75056. }
  75057. /**
  75058. * Create symbol or update symbol
  75059. * opt: basic position and event handlers
  75060. */
  75061. function giveSymbol(hostModel, itemStyleModel, group, opt, symbol, callback) {
  75062. var color = itemStyleModel.get('color');
  75063. if (!symbol) {
  75064. var symbolType = hostModel.get('symbol');
  75065. symbol = createSymbol(symbolType, -1, -1, 2, 2, color);
  75066. symbol.setStyle('strokeNoScale', true);
  75067. group.add(symbol);
  75068. callback && callback.onCreate(symbol);
  75069. }
  75070. else {
  75071. symbol.setColor(color);
  75072. group.add(symbol); // Group may be new, also need to add.
  75073. callback && callback.onUpdate(symbol);
  75074. }
  75075. // Style
  75076. var itemStyle = itemStyleModel.getItemStyle(['color', 'symbol', 'symbolSize']);
  75077. symbol.setStyle(itemStyle);
  75078. // Transform and events.
  75079. opt = merge({
  75080. rectHover: true,
  75081. z2: 100
  75082. }, opt, true);
  75083. var symbolSize = hostModel.get('symbolSize');
  75084. symbolSize = symbolSize instanceof Array
  75085. ? symbolSize.slice()
  75086. : [+symbolSize, +symbolSize];
  75087. symbolSize[0] /= 2;
  75088. symbolSize[1] /= 2;
  75089. opt.scale = symbolSize;
  75090. var symbolOffset = hostModel.get('symbolOffset');
  75091. if (symbolOffset) {
  75092. var pos = opt.position = opt.position || [0, 0];
  75093. pos[0] += parsePercent$1(symbolOffset[0], symbolSize[0]);
  75094. pos[1] += parsePercent$1(symbolOffset[1], symbolSize[1]);
  75095. }
  75096. var symbolRotate = hostModel.get('symbolRotate');
  75097. opt.rotation = (symbolRotate || 0) * Math.PI / 180 || 0;
  75098. symbol.attr(opt);
  75099. // FIXME
  75100. // (1) When symbol.style.strokeNoScale is true and updateTransform is not performed,
  75101. // getBoundingRect will return wrong result.
  75102. // (This is supposed to be resolved in zrender, but it is a little difficult to
  75103. // leverage performance and auto updateTransform)
  75104. // (2) All of ancesters of symbol do not scale, so we can just updateTransform symbol.
  75105. symbol.updateTransform();
  75106. return symbol;
  75107. }
  75108. function pointerMoveTo(pointer, dataIndex, axis, timelineModel, noAnimation) {
  75109. if (pointer.dragging) {
  75110. return;
  75111. }
  75112. var pointerModel = timelineModel.getModel('checkpointStyle');
  75113. var toCoord = axis.dataToCoord(timelineModel.getData().get(['value'], dataIndex));
  75114. if (noAnimation || !pointerModel.get('animation', true)) {
  75115. pointer.attr({position: [toCoord, 0]});
  75116. }
  75117. else {
  75118. pointer.stopAnimation(true);
  75119. pointer.animateTo(
  75120. {position: [toCoord, 0]},
  75121. pointerModel.get('animationDuration', true),
  75122. pointerModel.get('animationEasing', true)
  75123. );
  75124. }
  75125. }
  75126. /*
  75127. * Licensed to the Apache Software Foundation (ASF) under one
  75128. * or more contributor license agreements. See the NOTICE file
  75129. * distributed with this work for additional information
  75130. * regarding copyright ownership. The ASF licenses this file
  75131. * to you under the Apache License, Version 2.0 (the
  75132. * "License"); you may not use this file except in compliance
  75133. * with the License. You may obtain a copy of the License at
  75134. *
  75135. * http://www.apache.org/licenses/LICENSE-2.0
  75136. *
  75137. * Unless required by applicable law or agreed to in writing,
  75138. * software distributed under the License is distributed on an
  75139. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  75140. * KIND, either express or implied. See the License for the
  75141. * specific language governing permissions and limitations
  75142. * under the License.
  75143. */
  75144. /**
  75145. * DataZoom component entry
  75146. */
  75147. registerPreprocessor(preprocessor$2);
  75148. /*
  75149. * Licensed to the Apache Software Foundation (ASF) under one
  75150. * or more contributor license agreements. See the NOTICE file
  75151. * distributed with this work for additional information
  75152. * regarding copyright ownership. The ASF licenses this file
  75153. * to you under the Apache License, Version 2.0 (the
  75154. * "License"); you may not use this file except in compliance
  75155. * with the License. You may obtain a copy of the License at
  75156. *
  75157. * http://www.apache.org/licenses/LICENSE-2.0
  75158. *
  75159. * Unless required by applicable law or agreed to in writing,
  75160. * software distributed under the License is distributed on an
  75161. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  75162. * KIND, either express or implied. See the License for the
  75163. * specific language governing permissions and limitations
  75164. * under the License.
  75165. */
  75166. var addCommas$1 = addCommas;
  75167. var encodeHTML$1 = encodeHTML;
  75168. function fillLabel(opt) {
  75169. defaultEmphasis(opt, 'label', ['show']);
  75170. }
  75171. var MarkerModel = extendComponentModel({
  75172. type: 'marker',
  75173. dependencies: ['series', 'grid', 'polar', 'geo'],
  75174. /**
  75175. * @overrite
  75176. */
  75177. init: function (option, parentModel, ecModel) {
  75178. if (__DEV__) {
  75179. if (this.type === 'marker') {
  75180. throw new Error('Marker component is abstract component. Use markLine, markPoint, markArea instead.');
  75181. }
  75182. }
  75183. this.mergeDefaultAndTheme(option, ecModel);
  75184. this._mergeOption(option, ecModel, false, true);
  75185. },
  75186. /**
  75187. * @return {boolean}
  75188. */
  75189. isAnimationEnabled: function () {
  75190. if (env$1.node) {
  75191. return false;
  75192. }
  75193. var hostSeries = this.__hostSeries;
  75194. return this.getShallow('animation') && hostSeries && hostSeries.isAnimationEnabled();
  75195. },
  75196. /**
  75197. * @overrite
  75198. */
  75199. mergeOption: function (newOpt, ecModel) {
  75200. this._mergeOption(newOpt, ecModel, false, false);
  75201. },
  75202. _mergeOption: function (newOpt, ecModel, createdBySelf, isInit) {
  75203. var MarkerModel = this.constructor;
  75204. var modelPropName = this.mainType + 'Model';
  75205. if (!createdBySelf) {
  75206. ecModel.eachSeries(function (seriesModel) {
  75207. var markerOpt = seriesModel.get(this.mainType, true);
  75208. var markerModel = seriesModel[modelPropName];
  75209. if (!markerOpt || !markerOpt.data) {
  75210. seriesModel[modelPropName] = null;
  75211. return;
  75212. }
  75213. if (!markerModel) {
  75214. if (isInit) {
  75215. // Default label emphasis `position` and `show`
  75216. fillLabel(markerOpt);
  75217. }
  75218. each$1(markerOpt.data, function (item) {
  75219. // FIXME Overwrite fillLabel method ?
  75220. if (item instanceof Array) {
  75221. fillLabel(item[0]);
  75222. fillLabel(item[1]);
  75223. }
  75224. else {
  75225. fillLabel(item);
  75226. }
  75227. });
  75228. markerModel = new MarkerModel(
  75229. markerOpt, this, ecModel
  75230. );
  75231. extend(markerModel, {
  75232. mainType: this.mainType,
  75233. // Use the same series index and name
  75234. seriesIndex: seriesModel.seriesIndex,
  75235. name: seriesModel.name,
  75236. createdBySelf: true
  75237. });
  75238. markerModel.__hostSeries = seriesModel;
  75239. }
  75240. else {
  75241. markerModel._mergeOption(markerOpt, ecModel, true);
  75242. }
  75243. seriesModel[modelPropName] = markerModel;
  75244. }, this);
  75245. }
  75246. },
  75247. formatTooltip: function (dataIndex) {
  75248. var data = this.getData();
  75249. var value = this.getRawValue(dataIndex);
  75250. var formattedValue = isArray(value)
  75251. ? map(value, addCommas$1).join(', ') : addCommas$1(value);
  75252. var name = data.getName(dataIndex);
  75253. var html = encodeHTML$1(this.name);
  75254. if (value != null || name) {
  75255. html += '<br />';
  75256. }
  75257. if (name) {
  75258. html += encodeHTML$1(name);
  75259. if (value != null) {
  75260. html += ' : ';
  75261. }
  75262. }
  75263. if (value != null) {
  75264. html += encodeHTML$1(formattedValue);
  75265. }
  75266. return html;
  75267. },
  75268. getData: function () {
  75269. return this._data;
  75270. },
  75271. setData: function (data) {
  75272. this._data = data;
  75273. }
  75274. });
  75275. mixin(MarkerModel, dataFormatMixin);
  75276. /*
  75277. * Licensed to the Apache Software Foundation (ASF) under one
  75278. * or more contributor license agreements. See the NOTICE file
  75279. * distributed with this work for additional information
  75280. * regarding copyright ownership. The ASF licenses this file
  75281. * to you under the Apache License, Version 2.0 (the
  75282. * "License"); you may not use this file except in compliance
  75283. * with the License. You may obtain a copy of the License at
  75284. *
  75285. * http://www.apache.org/licenses/LICENSE-2.0
  75286. *
  75287. * Unless required by applicable law or agreed to in writing,
  75288. * software distributed under the License is distributed on an
  75289. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  75290. * KIND, either express or implied. See the License for the
  75291. * specific language governing permissions and limitations
  75292. * under the License.
  75293. */
  75294. MarkerModel.extend({
  75295. type: 'markPoint',
  75296. defaultOption: {
  75297. zlevel: 0,
  75298. z: 5,
  75299. symbol: 'pin',
  75300. symbolSize: 50,
  75301. //symbolRotate: 0,
  75302. //symbolOffset: [0, 0]
  75303. tooltip: {
  75304. trigger: 'item'
  75305. },
  75306. label: {
  75307. show: true,
  75308. position: 'inside'
  75309. },
  75310. itemStyle: {
  75311. borderWidth: 2
  75312. },
  75313. emphasis: {
  75314. label: {
  75315. show: true
  75316. }
  75317. }
  75318. }
  75319. });
  75320. /*
  75321. * Licensed to the Apache Software Foundation (ASF) under one
  75322. * or more contributor license agreements. See the NOTICE file
  75323. * distributed with this work for additional information
  75324. * regarding copyright ownership. The ASF licenses this file
  75325. * to you under the Apache License, Version 2.0 (the
  75326. * "License"); you may not use this file except in compliance
  75327. * with the License. You may obtain a copy of the License at
  75328. *
  75329. * http://www.apache.org/licenses/LICENSE-2.0
  75330. *
  75331. * Unless required by applicable law or agreed to in writing,
  75332. * software distributed under the License is distributed on an
  75333. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  75334. * KIND, either express or implied. See the License for the
  75335. * specific language governing permissions and limitations
  75336. * under the License.
  75337. */
  75338. var indexOf$2 = indexOf;
  75339. function hasXOrY(item) {
  75340. return !(isNaN(parseFloat(item.x)) && isNaN(parseFloat(item.y)));
  75341. }
  75342. function hasXAndY(item) {
  75343. return !isNaN(parseFloat(item.x)) && !isNaN(parseFloat(item.y));
  75344. }
  75345. // Make it simple, do not visit all stacked value to count precision.
  75346. // function getPrecision(data, valueAxisDim, dataIndex) {
  75347. // var precision = -1;
  75348. // var stackedDim = data.mapDimension(valueAxisDim);
  75349. // do {
  75350. // precision = Math.max(
  75351. // numberUtil.getPrecision(data.get(stackedDim, dataIndex)),
  75352. // precision
  75353. // );
  75354. // var stackedOnSeries = data.getCalculationInfo('stackedOnSeries');
  75355. // if (stackedOnSeries) {
  75356. // var byValue = data.get(data.getCalculationInfo('stackedByDimension'), dataIndex);
  75357. // data = stackedOnSeries.getData();
  75358. // dataIndex = data.indexOf(data.getCalculationInfo('stackedByDimension'), byValue);
  75359. // stackedDim = data.getCalculationInfo('stackedDimension');
  75360. // }
  75361. // else {
  75362. // data = null;
  75363. // }
  75364. // } while (data);
  75365. // return precision;
  75366. // }
  75367. function markerTypeCalculatorWithExtent(
  75368. mlType, data, otherDataDim, targetDataDim, otherCoordIndex, targetCoordIndex
  75369. ) {
  75370. var coordArr = [];
  75371. var stacked = isDimensionStacked(data, targetDataDim /*, otherDataDim*/);
  75372. var calcDataDim = stacked
  75373. ? data.getCalculationInfo('stackResultDimension')
  75374. : targetDataDim;
  75375. var value = numCalculate(data, calcDataDim, mlType);
  75376. var dataIndex = data.indicesOfNearest(calcDataDim, value)[0];
  75377. coordArr[otherCoordIndex] = data.get(otherDataDim, dataIndex);
  75378. coordArr[targetCoordIndex] = data.get(calcDataDim, dataIndex);
  75379. var coordArrValue = data.get(targetDataDim, dataIndex);
  75380. // Make it simple, do not visit all stacked value to count precision.
  75381. var precision = getPrecision(data.get(targetDataDim, dataIndex));
  75382. precision = Math.min(precision, 20);
  75383. if (precision >= 0) {
  75384. coordArr[targetCoordIndex] = +coordArr[targetCoordIndex].toFixed(precision);
  75385. }
  75386. return [coordArr, coordArrValue];
  75387. }
  75388. var curry$5 = curry;
  75389. // TODO Specified percent
  75390. var markerTypeCalculator = {
  75391. /**
  75392. * @method
  75393. * @param {module:echarts/data/List} data
  75394. * @param {string} baseAxisDim
  75395. * @param {string} valueAxisDim
  75396. */
  75397. min: curry$5(markerTypeCalculatorWithExtent, 'min'),
  75398. /**
  75399. * @method
  75400. * @param {module:echarts/data/List} data
  75401. * @param {string} baseAxisDim
  75402. * @param {string} valueAxisDim
  75403. */
  75404. max: curry$5(markerTypeCalculatorWithExtent, 'max'),
  75405. /**
  75406. * @method
  75407. * @param {module:echarts/data/List} data
  75408. * @param {string} baseAxisDim
  75409. * @param {string} valueAxisDim
  75410. */
  75411. average: curry$5(markerTypeCalculatorWithExtent, 'average')
  75412. };
  75413. /**
  75414. * Transform markPoint data item to format used in List by do the following
  75415. * 1. Calculate statistic like `max`, `min`, `average`
  75416. * 2. Convert `item.xAxis`, `item.yAxis` to `item.coord` array
  75417. * @param {module:echarts/model/Series} seriesModel
  75418. * @param {module:echarts/coord/*} [coordSys]
  75419. * @param {Object} item
  75420. * @return {Object}
  75421. */
  75422. function dataTransform(seriesModel, item) {
  75423. var data = seriesModel.getData();
  75424. var coordSys = seriesModel.coordinateSystem;
  75425. // 1. If not specify the position with pixel directly
  75426. // 2. If `coord` is not a data array. Which uses `xAxis`,
  75427. // `yAxis` to specify the coord on each dimension
  75428. // parseFloat first because item.x and item.y can be percent string like '20%'
  75429. if (item && !hasXAndY(item) && !isArray(item.coord) && coordSys) {
  75430. var dims = coordSys.dimensions;
  75431. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel);
  75432. // Clone the option
  75433. // Transform the properties xAxis, yAxis, radiusAxis, angleAxis, geoCoord to value
  75434. item = clone(item);
  75435. if (item.type
  75436. && markerTypeCalculator[item.type]
  75437. && axisInfo.baseAxis && axisInfo.valueAxis
  75438. ) {
  75439. var otherCoordIndex = indexOf$2(dims, axisInfo.baseAxis.dim);
  75440. var targetCoordIndex = indexOf$2(dims, axisInfo.valueAxis.dim);
  75441. var coordInfo = markerTypeCalculator[item.type](
  75442. data, axisInfo.baseDataDim, axisInfo.valueDataDim,
  75443. otherCoordIndex, targetCoordIndex
  75444. );
  75445. item.coord = coordInfo[0];
  75446. // Force to use the value of calculated value.
  75447. // let item use the value without stack.
  75448. item.value = coordInfo[1];
  75449. }
  75450. else {
  75451. // FIXME Only has one of xAxis and yAxis.
  75452. var coord = [
  75453. item.xAxis != null ? item.xAxis : item.radiusAxis,
  75454. item.yAxis != null ? item.yAxis : item.angleAxis
  75455. ];
  75456. // Each coord support max, min, average
  75457. for (var i = 0; i < 2; i++) {
  75458. if (markerTypeCalculator[coord[i]]) {
  75459. coord[i] = numCalculate(data, data.mapDimension(dims[i]), coord[i]);
  75460. }
  75461. }
  75462. item.coord = coord;
  75463. }
  75464. }
  75465. return item;
  75466. }
  75467. function getAxisInfo$1(item, data, coordSys, seriesModel) {
  75468. var ret = {};
  75469. if (item.valueIndex != null || item.valueDim != null) {
  75470. ret.valueDataDim = item.valueIndex != null
  75471. ? data.getDimension(item.valueIndex) : item.valueDim;
  75472. ret.valueAxis = coordSys.getAxis(dataDimToCoordDim(seriesModel, ret.valueDataDim));
  75473. ret.baseAxis = coordSys.getOtherAxis(ret.valueAxis);
  75474. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  75475. }
  75476. else {
  75477. ret.baseAxis = seriesModel.getBaseAxis();
  75478. ret.valueAxis = coordSys.getOtherAxis(ret.baseAxis);
  75479. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  75480. ret.valueDataDim = data.mapDimension(ret.valueAxis.dim);
  75481. }
  75482. return ret;
  75483. }
  75484. function dataDimToCoordDim(seriesModel, dataDim) {
  75485. var data = seriesModel.getData();
  75486. var dimensions = data.dimensions;
  75487. dataDim = data.getDimension(dataDim);
  75488. for (var i = 0; i < dimensions.length; i++) {
  75489. var dimItem = data.getDimensionInfo(dimensions[i]);
  75490. if (dimItem.name === dataDim) {
  75491. return dimItem.coordDim;
  75492. }
  75493. }
  75494. }
  75495. /**
  75496. * Filter data which is out of coordinateSystem range
  75497. * [dataFilter description]
  75498. * @param {module:echarts/coord/*} [coordSys]
  75499. * @param {Object} item
  75500. * @return {boolean}
  75501. */
  75502. function dataFilter$1(coordSys, item) {
  75503. // Alwalys return true if there is no coordSys
  75504. return (coordSys && coordSys.containData && item.coord && !hasXOrY(item))
  75505. ? coordSys.containData(item.coord) : true;
  75506. }
  75507. function dimValueGetter(item, dimName, dataIndex, dimIndex) {
  75508. // x, y, radius, angle
  75509. if (dimIndex < 2) {
  75510. return item.coord && item.coord[dimIndex];
  75511. }
  75512. return item.value;
  75513. }
  75514. function numCalculate(data, valueDataDim, type) {
  75515. if (type === 'average') {
  75516. var sum = 0;
  75517. var count = 0;
  75518. data.each(valueDataDim, function (val, idx) {
  75519. if (!isNaN(val)) {
  75520. sum += val;
  75521. count++;
  75522. }
  75523. });
  75524. return sum / count;
  75525. }
  75526. else if (type === 'median') {
  75527. return data.getMedian(valueDataDim);
  75528. }
  75529. else {
  75530. // max & min
  75531. return data.getDataExtent(valueDataDim, true)[type === 'max' ? 1 : 0];
  75532. }
  75533. }
  75534. /*
  75535. * Licensed to the Apache Software Foundation (ASF) under one
  75536. * or more contributor license agreements. See the NOTICE file
  75537. * distributed with this work for additional information
  75538. * regarding copyright ownership. The ASF licenses this file
  75539. * to you under the Apache License, Version 2.0 (the
  75540. * "License"); you may not use this file except in compliance
  75541. * with the License. You may obtain a copy of the License at
  75542. *
  75543. * http://www.apache.org/licenses/LICENSE-2.0
  75544. *
  75545. * Unless required by applicable law or agreed to in writing,
  75546. * software distributed under the License is distributed on an
  75547. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  75548. * KIND, either express or implied. See the License for the
  75549. * specific language governing permissions and limitations
  75550. * under the License.
  75551. */
  75552. var MarkerView = extendComponentView({
  75553. type: 'marker',
  75554. init: function () {
  75555. /**
  75556. * Markline grouped by series
  75557. * @private
  75558. * @type {module:zrender/core/util.HashMap}
  75559. */
  75560. this.markerGroupMap = createHashMap();
  75561. },
  75562. render: function (markerModel, ecModel, api) {
  75563. var markerGroupMap = this.markerGroupMap;
  75564. markerGroupMap.each(function (item) {
  75565. item.__keep = false;
  75566. });
  75567. var markerModelKey = this.type + 'Model';
  75568. ecModel.eachSeries(function (seriesModel) {
  75569. var markerModel = seriesModel[markerModelKey];
  75570. markerModel && this.renderSeries(seriesModel, markerModel, ecModel, api);
  75571. }, this);
  75572. markerGroupMap.each(function (item) {
  75573. !item.__keep && this.group.remove(item.group);
  75574. }, this);
  75575. },
  75576. renderSeries: function () {}
  75577. });
  75578. /*
  75579. * Licensed to the Apache Software Foundation (ASF) under one
  75580. * or more contributor license agreements. See the NOTICE file
  75581. * distributed with this work for additional information
  75582. * regarding copyright ownership. The ASF licenses this file
  75583. * to you under the Apache License, Version 2.0 (the
  75584. * "License"); you may not use this file except in compliance
  75585. * with the License. You may obtain a copy of the License at
  75586. *
  75587. * http://www.apache.org/licenses/LICENSE-2.0
  75588. *
  75589. * Unless required by applicable law or agreed to in writing,
  75590. * software distributed under the License is distributed on an
  75591. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  75592. * KIND, either express or implied. See the License for the
  75593. * specific language governing permissions and limitations
  75594. * under the License.
  75595. */
  75596. function updateMarkerLayout(mpData, seriesModel, api) {
  75597. var coordSys = seriesModel.coordinateSystem;
  75598. mpData.each(function (idx) {
  75599. var itemModel = mpData.getItemModel(idx);
  75600. var point;
  75601. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  75602. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  75603. if (!isNaN(xPx) && !isNaN(yPx)) {
  75604. point = [xPx, yPx];
  75605. }
  75606. // Chart like bar may have there own marker positioning logic
  75607. else if (seriesModel.getMarkerPosition) {
  75608. // Use the getMarkerPoisition
  75609. point = seriesModel.getMarkerPosition(
  75610. mpData.getValues(mpData.dimensions, idx)
  75611. );
  75612. }
  75613. else if (coordSys) {
  75614. var x = mpData.get(coordSys.dimensions[0], idx);
  75615. var y = mpData.get(coordSys.dimensions[1], idx);
  75616. point = coordSys.dataToPoint([x, y]);
  75617. }
  75618. // Use x, y if has any
  75619. if (!isNaN(xPx)) {
  75620. point[0] = xPx;
  75621. }
  75622. if (!isNaN(yPx)) {
  75623. point[1] = yPx;
  75624. }
  75625. mpData.setItemLayout(idx, point);
  75626. });
  75627. }
  75628. MarkerView.extend({
  75629. type: 'markPoint',
  75630. // updateLayout: function (markPointModel, ecModel, api) {
  75631. // ecModel.eachSeries(function (seriesModel) {
  75632. // var mpModel = seriesModel.markPointModel;
  75633. // if (mpModel) {
  75634. // updateMarkerLayout(mpModel.getData(), seriesModel, api);
  75635. // this.markerGroupMap.get(seriesModel.id).updateLayout(mpModel);
  75636. // }
  75637. // }, this);
  75638. // },
  75639. updateTransform: function (markPointModel, ecModel, api) {
  75640. ecModel.eachSeries(function (seriesModel) {
  75641. var mpModel = seriesModel.markPointModel;
  75642. if (mpModel) {
  75643. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  75644. this.markerGroupMap.get(seriesModel.id).updateLayout(mpModel);
  75645. }
  75646. }, this);
  75647. },
  75648. renderSeries: function (seriesModel, mpModel, ecModel, api) {
  75649. var coordSys = seriesModel.coordinateSystem;
  75650. var seriesId = seriesModel.id;
  75651. var seriesData = seriesModel.getData();
  75652. var symbolDrawMap = this.markerGroupMap;
  75653. var symbolDraw = symbolDrawMap.get(seriesId)
  75654. || symbolDrawMap.set(seriesId, new SymbolDraw());
  75655. var mpData = createList$1(coordSys, seriesModel, mpModel);
  75656. // FIXME
  75657. mpModel.setData(mpData);
  75658. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  75659. mpData.each(function (idx) {
  75660. var itemModel = mpData.getItemModel(idx);
  75661. var symbol = itemModel.getShallow('symbol');
  75662. var symbolSize = itemModel.getShallow('symbolSize');
  75663. var isFnSymbol = isFunction$1(symbol);
  75664. var isFnSymbolSize = isFunction$1(symbolSize);
  75665. if (isFnSymbol || isFnSymbolSize) {
  75666. var rawIdx = mpModel.getRawValue(idx);
  75667. var dataParams = mpModel.getDataParams(idx);
  75668. if (isFnSymbol) {
  75669. symbol = symbol(rawIdx, dataParams);
  75670. }
  75671. if (isFnSymbolSize) {
  75672. // FIXME 这里不兼容 ECharts 2.x,2.x 貌似参数是整个数据?
  75673. symbolSize = symbolSize(rawIdx, dataParams);
  75674. }
  75675. }
  75676. mpData.setItemVisual(idx, {
  75677. symbol: symbol,
  75678. symbolSize: symbolSize,
  75679. color: itemModel.get('itemStyle.color')
  75680. || seriesData.getVisual('color')
  75681. });
  75682. });
  75683. // TODO Text are wrong
  75684. symbolDraw.updateData(mpData);
  75685. this.group.add(symbolDraw.group);
  75686. // Set host model for tooltip
  75687. // FIXME
  75688. mpData.eachItemGraphicEl(function (el) {
  75689. el.traverse(function (child) {
  75690. child.dataModel = mpModel;
  75691. });
  75692. });
  75693. symbolDraw.__keep = true;
  75694. symbolDraw.group.silent = mpModel.get('silent') || seriesModel.get('silent');
  75695. }
  75696. });
  75697. /**
  75698. * @inner
  75699. * @param {module:echarts/coord/*} [coordSys]
  75700. * @param {module:echarts/model/Series} seriesModel
  75701. * @param {module:echarts/model/Model} mpModel
  75702. */
  75703. function createList$1(coordSys, seriesModel, mpModel) {
  75704. var coordDimsInfos;
  75705. if (coordSys) {
  75706. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  75707. var info = seriesModel.getData().getDimensionInfo(
  75708. seriesModel.getData().mapDimension(coordDim)
  75709. ) || {};
  75710. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  75711. return defaults({name: coordDim}, info);
  75712. });
  75713. }
  75714. else {
  75715. coordDimsInfos = [{
  75716. name: 'value',
  75717. type: 'float'
  75718. }];
  75719. }
  75720. var mpData = new List(coordDimsInfos, mpModel);
  75721. var dataOpt = map(mpModel.get('data'), curry(
  75722. dataTransform, seriesModel
  75723. ));
  75724. if (coordSys) {
  75725. dataOpt = filter(
  75726. dataOpt, curry(dataFilter$1, coordSys)
  75727. );
  75728. }
  75729. mpData.initData(dataOpt, null,
  75730. coordSys ? dimValueGetter : function (item) {
  75731. return item.value;
  75732. }
  75733. );
  75734. return mpData;
  75735. }
  75736. /*
  75737. * Licensed to the Apache Software Foundation (ASF) under one
  75738. * or more contributor license agreements. See the NOTICE file
  75739. * distributed with this work for additional information
  75740. * regarding copyright ownership. The ASF licenses this file
  75741. * to you under the Apache License, Version 2.0 (the
  75742. * "License"); you may not use this file except in compliance
  75743. * with the License. You may obtain a copy of the License at
  75744. *
  75745. * http://www.apache.org/licenses/LICENSE-2.0
  75746. *
  75747. * Unless required by applicable law or agreed to in writing,
  75748. * software distributed under the License is distributed on an
  75749. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  75750. * KIND, either express or implied. See the License for the
  75751. * specific language governing permissions and limitations
  75752. * under the License.
  75753. */
  75754. // HINT Markpoint can't be used too much
  75755. registerPreprocessor(function (opt) {
  75756. // Make sure markPoint component is enabled
  75757. opt.markPoint = opt.markPoint || {};
  75758. });
  75759. /*
  75760. * Licensed to the Apache Software Foundation (ASF) under one
  75761. * or more contributor license agreements. See the NOTICE file
  75762. * distributed with this work for additional information
  75763. * regarding copyright ownership. The ASF licenses this file
  75764. * to you under the Apache License, Version 2.0 (the
  75765. * "License"); you may not use this file except in compliance
  75766. * with the License. You may obtain a copy of the License at
  75767. *
  75768. * http://www.apache.org/licenses/LICENSE-2.0
  75769. *
  75770. * Unless required by applicable law or agreed to in writing,
  75771. * software distributed under the License is distributed on an
  75772. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  75773. * KIND, either express or implied. See the License for the
  75774. * specific language governing permissions and limitations
  75775. * under the License.
  75776. */
  75777. MarkerModel.extend({
  75778. type: 'markLine',
  75779. defaultOption: {
  75780. zlevel: 0,
  75781. z: 5,
  75782. symbol: ['circle', 'arrow'],
  75783. symbolSize: [8, 16],
  75784. //symbolRotate: 0,
  75785. precision: 2,
  75786. tooltip: {
  75787. trigger: 'item'
  75788. },
  75789. label: {
  75790. show: true,
  75791. position: 'end',
  75792. distance: 5
  75793. },
  75794. lineStyle: {
  75795. type: 'dashed'
  75796. },
  75797. emphasis: {
  75798. label: {
  75799. show: true
  75800. },
  75801. lineStyle: {
  75802. width: 3
  75803. }
  75804. },
  75805. animationEasing: 'linear'
  75806. }
  75807. });
  75808. /*
  75809. * Licensed to the Apache Software Foundation (ASF) under one
  75810. * or more contributor license agreements. See the NOTICE file
  75811. * distributed with this work for additional information
  75812. * regarding copyright ownership. The ASF licenses this file
  75813. * to you under the Apache License, Version 2.0 (the
  75814. * "License"); you may not use this file except in compliance
  75815. * with the License. You may obtain a copy of the License at
  75816. *
  75817. * http://www.apache.org/licenses/LICENSE-2.0
  75818. *
  75819. * Unless required by applicable law or agreed to in writing,
  75820. * software distributed under the License is distributed on an
  75821. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  75822. * KIND, either express or implied. See the License for the
  75823. * specific language governing permissions and limitations
  75824. * under the License.
  75825. */
  75826. var markLineTransform = function (seriesModel, coordSys, mlModel, item) {
  75827. var data = seriesModel.getData();
  75828. // Special type markLine like 'min', 'max', 'average', 'median'
  75829. var mlType = item.type;
  75830. if (!isArray(item)
  75831. && (
  75832. mlType === 'min' || mlType === 'max' || mlType === 'average' || mlType === 'median'
  75833. // In case
  75834. // data: [{
  75835. // yAxis: 10
  75836. // }]
  75837. || (item.xAxis != null || item.yAxis != null)
  75838. )
  75839. ) {
  75840. var valueAxis;
  75841. var value;
  75842. if (item.yAxis != null || item.xAxis != null) {
  75843. valueAxis = coordSys.getAxis(item.yAxis != null ? 'y' : 'x');
  75844. value = retrieve(item.yAxis, item.xAxis);
  75845. }
  75846. else {
  75847. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel);
  75848. valueAxis = axisInfo.valueAxis;
  75849. var valueDataDim = getStackedDimension(data, axisInfo.valueDataDim);
  75850. value = numCalculate(data, valueDataDim, mlType);
  75851. }
  75852. var valueIndex = valueAxis.dim === 'x' ? 0 : 1;
  75853. var baseIndex = 1 - valueIndex;
  75854. var mlFrom = clone(item);
  75855. var mlTo = {};
  75856. mlFrom.type = null;
  75857. mlFrom.coord = [];
  75858. mlTo.coord = [];
  75859. mlFrom.coord[baseIndex] = -Infinity;
  75860. mlTo.coord[baseIndex] = Infinity;
  75861. var precision = mlModel.get('precision');
  75862. if (precision >= 0 && typeof value === 'number') {
  75863. value = +value.toFixed(Math.min(precision, 20));
  75864. }
  75865. mlFrom.coord[valueIndex] = mlTo.coord[valueIndex] = value;
  75866. item = [mlFrom, mlTo, { // Extra option for tooltip and label
  75867. type: mlType,
  75868. valueIndex: item.valueIndex,
  75869. // Force to use the value of calculated value.
  75870. value: value
  75871. }];
  75872. }
  75873. item = [
  75874. dataTransform(seriesModel, item[0]),
  75875. dataTransform(seriesModel, item[1]),
  75876. extend({}, item[2])
  75877. ];
  75878. // Avoid line data type is extended by from(to) data type
  75879. item[2].type = item[2].type || '';
  75880. // Merge from option and to option into line option
  75881. merge(item[2], item[0]);
  75882. merge(item[2], item[1]);
  75883. return item;
  75884. };
  75885. function isInifinity(val) {
  75886. return !isNaN(val) && !isFinite(val);
  75887. }
  75888. // If a markLine has one dim
  75889. function ifMarkLineHasOnlyDim(dimIndex, fromCoord, toCoord, coordSys) {
  75890. var otherDimIndex = 1 - dimIndex;
  75891. var dimName = coordSys.dimensions[dimIndex];
  75892. return isInifinity(fromCoord[otherDimIndex]) && isInifinity(toCoord[otherDimIndex])
  75893. && fromCoord[dimIndex] === toCoord[dimIndex] && coordSys.getAxis(dimName).containData(fromCoord[dimIndex]);
  75894. }
  75895. function markLineFilter(coordSys, item) {
  75896. if (coordSys.type === 'cartesian2d') {
  75897. var fromCoord = item[0].coord;
  75898. var toCoord = item[1].coord;
  75899. // In case
  75900. // {
  75901. // markLine: {
  75902. // data: [{ yAxis: 2 }]
  75903. // }
  75904. // }
  75905. if (
  75906. fromCoord && toCoord
  75907. && (ifMarkLineHasOnlyDim(1, fromCoord, toCoord, coordSys)
  75908. || ifMarkLineHasOnlyDim(0, fromCoord, toCoord, coordSys))
  75909. ) {
  75910. return true;
  75911. }
  75912. }
  75913. return dataFilter$1(coordSys, item[0])
  75914. && dataFilter$1(coordSys, item[1]);
  75915. }
  75916. function updateSingleMarkerEndLayout(
  75917. data, idx, isFrom, seriesModel, api
  75918. ) {
  75919. var coordSys = seriesModel.coordinateSystem;
  75920. var itemModel = data.getItemModel(idx);
  75921. var point;
  75922. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  75923. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  75924. if (!isNaN(xPx) && !isNaN(yPx)) {
  75925. point = [xPx, yPx];
  75926. }
  75927. else {
  75928. // Chart like bar may have there own marker positioning logic
  75929. if (seriesModel.getMarkerPosition) {
  75930. // Use the getMarkerPoisition
  75931. point = seriesModel.getMarkerPosition(
  75932. data.getValues(data.dimensions, idx)
  75933. );
  75934. }
  75935. else {
  75936. var dims = coordSys.dimensions;
  75937. var x = data.get(dims[0], idx);
  75938. var y = data.get(dims[1], idx);
  75939. point = coordSys.dataToPoint([x, y]);
  75940. }
  75941. // Expand line to the edge of grid if value on one axis is Inifnity
  75942. // In case
  75943. // markLine: {
  75944. // data: [{
  75945. // yAxis: 2
  75946. // // or
  75947. // type: 'average'
  75948. // }]
  75949. // }
  75950. if (coordSys.type === 'cartesian2d') {
  75951. var xAxis = coordSys.getAxis('x');
  75952. var yAxis = coordSys.getAxis('y');
  75953. var dims = coordSys.dimensions;
  75954. if (isInifinity(data.get(dims[0], idx))) {
  75955. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[isFrom ? 0 : 1]);
  75956. }
  75957. else if (isInifinity(data.get(dims[1], idx))) {
  75958. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[isFrom ? 0 : 1]);
  75959. }
  75960. }
  75961. // Use x, y if has any
  75962. if (!isNaN(xPx)) {
  75963. point[0] = xPx;
  75964. }
  75965. if (!isNaN(yPx)) {
  75966. point[1] = yPx;
  75967. }
  75968. }
  75969. data.setItemLayout(idx, point);
  75970. }
  75971. MarkerView.extend({
  75972. type: 'markLine',
  75973. // updateLayout: function (markLineModel, ecModel, api) {
  75974. // ecModel.eachSeries(function (seriesModel) {
  75975. // var mlModel = seriesModel.markLineModel;
  75976. // if (mlModel) {
  75977. // var mlData = mlModel.getData();
  75978. // var fromData = mlModel.__from;
  75979. // var toData = mlModel.__to;
  75980. // // Update visual and layout of from symbol and to symbol
  75981. // fromData.each(function (idx) {
  75982. // updateSingleMarkerEndLayout(fromData, idx, true, seriesModel, api);
  75983. // updateSingleMarkerEndLayout(toData, idx, false, seriesModel, api);
  75984. // });
  75985. // // Update layout of line
  75986. // mlData.each(function (idx) {
  75987. // mlData.setItemLayout(idx, [
  75988. // fromData.getItemLayout(idx),
  75989. // toData.getItemLayout(idx)
  75990. // ]);
  75991. // });
  75992. // this.markerGroupMap.get(seriesModel.id).updateLayout();
  75993. // }
  75994. // }, this);
  75995. // },
  75996. updateTransform: function (markLineModel, ecModel, api) {
  75997. ecModel.eachSeries(function (seriesModel) {
  75998. var mlModel = seriesModel.markLineModel;
  75999. if (mlModel) {
  76000. var mlData = mlModel.getData();
  76001. var fromData = mlModel.__from;
  76002. var toData = mlModel.__to;
  76003. // Update visual and layout of from symbol and to symbol
  76004. fromData.each(function (idx) {
  76005. updateSingleMarkerEndLayout(fromData, idx, true, seriesModel, api);
  76006. updateSingleMarkerEndLayout(toData, idx, false, seriesModel, api);
  76007. });
  76008. // Update layout of line
  76009. mlData.each(function (idx) {
  76010. mlData.setItemLayout(idx, [
  76011. fromData.getItemLayout(idx),
  76012. toData.getItemLayout(idx)
  76013. ]);
  76014. });
  76015. this.markerGroupMap.get(seriesModel.id).updateLayout();
  76016. }
  76017. }, this);
  76018. },
  76019. renderSeries: function (seriesModel, mlModel, ecModel, api) {
  76020. var coordSys = seriesModel.coordinateSystem;
  76021. var seriesId = seriesModel.id;
  76022. var seriesData = seriesModel.getData();
  76023. var lineDrawMap = this.markerGroupMap;
  76024. var lineDraw = lineDrawMap.get(seriesId)
  76025. || lineDrawMap.set(seriesId, new LineDraw());
  76026. this.group.add(lineDraw.group);
  76027. var mlData = createList$2(coordSys, seriesModel, mlModel);
  76028. var fromData = mlData.from;
  76029. var toData = mlData.to;
  76030. var lineData = mlData.line;
  76031. mlModel.__from = fromData;
  76032. mlModel.__to = toData;
  76033. // Line data for tooltip and formatter
  76034. mlModel.setData(lineData);
  76035. var symbolType = mlModel.get('symbol');
  76036. var symbolSize = mlModel.get('symbolSize');
  76037. if (!isArray(symbolType)) {
  76038. symbolType = [symbolType, symbolType];
  76039. }
  76040. if (typeof symbolSize === 'number') {
  76041. symbolSize = [symbolSize, symbolSize];
  76042. }
  76043. // Update visual and layout of from symbol and to symbol
  76044. mlData.from.each(function (idx) {
  76045. updateDataVisualAndLayout(fromData, idx, true);
  76046. updateDataVisualAndLayout(toData, idx, false);
  76047. });
  76048. // Update visual and layout of line
  76049. lineData.each(function (idx) {
  76050. var lineColor = lineData.getItemModel(idx).get('lineStyle.color');
  76051. lineData.setItemVisual(idx, {
  76052. color: lineColor || fromData.getItemVisual(idx, 'color')
  76053. });
  76054. lineData.setItemLayout(idx, [
  76055. fromData.getItemLayout(idx),
  76056. toData.getItemLayout(idx)
  76057. ]);
  76058. lineData.setItemVisual(idx, {
  76059. 'fromSymbolSize': fromData.getItemVisual(idx, 'symbolSize'),
  76060. 'fromSymbol': fromData.getItemVisual(idx, 'symbol'),
  76061. 'toSymbolSize': toData.getItemVisual(idx, 'symbolSize'),
  76062. 'toSymbol': toData.getItemVisual(idx, 'symbol')
  76063. });
  76064. });
  76065. lineDraw.updateData(lineData);
  76066. // Set host model for tooltip
  76067. // FIXME
  76068. mlData.line.eachItemGraphicEl(function (el, idx) {
  76069. el.traverse(function (child) {
  76070. child.dataModel = mlModel;
  76071. });
  76072. });
  76073. function updateDataVisualAndLayout(data, idx, isFrom) {
  76074. var itemModel = data.getItemModel(idx);
  76075. updateSingleMarkerEndLayout(
  76076. data, idx, isFrom, seriesModel, api
  76077. );
  76078. data.setItemVisual(idx, {
  76079. symbolSize: itemModel.get('symbolSize') || symbolSize[isFrom ? 0 : 1],
  76080. symbol: itemModel.get('symbol', true) || symbolType[isFrom ? 0 : 1],
  76081. color: itemModel.get('itemStyle.color') || seriesData.getVisual('color')
  76082. });
  76083. }
  76084. lineDraw.__keep = true;
  76085. lineDraw.group.silent = mlModel.get('silent') || seriesModel.get('silent');
  76086. }
  76087. });
  76088. /**
  76089. * @inner
  76090. * @param {module:echarts/coord/*} coordSys
  76091. * @param {module:echarts/model/Series} seriesModel
  76092. * @param {module:echarts/model/Model} mpModel
  76093. */
  76094. function createList$2(coordSys, seriesModel, mlModel) {
  76095. var coordDimsInfos;
  76096. if (coordSys) {
  76097. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  76098. var info = seriesModel.getData().getDimensionInfo(
  76099. seriesModel.getData().mapDimension(coordDim)
  76100. ) || {};
  76101. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  76102. return defaults({name: coordDim}, info);
  76103. });
  76104. }
  76105. else {
  76106. coordDimsInfos = [{
  76107. name: 'value',
  76108. type: 'float'
  76109. }];
  76110. }
  76111. var fromData = new List(coordDimsInfos, mlModel);
  76112. var toData = new List(coordDimsInfos, mlModel);
  76113. // No dimensions
  76114. var lineData = new List([], mlModel);
  76115. var optData = map(mlModel.get('data'), curry(
  76116. markLineTransform, seriesModel, coordSys, mlModel
  76117. ));
  76118. if (coordSys) {
  76119. optData = filter(
  76120. optData, curry(markLineFilter, coordSys)
  76121. );
  76122. }
  76123. var dimValueGetter$$1 = coordSys ? dimValueGetter : function (item) {
  76124. return item.value;
  76125. };
  76126. fromData.initData(
  76127. map(optData, function (item) {
  76128. return item[0];
  76129. }),
  76130. null,
  76131. dimValueGetter$$1
  76132. );
  76133. toData.initData(
  76134. map(optData, function (item) {
  76135. return item[1];
  76136. }),
  76137. null,
  76138. dimValueGetter$$1
  76139. );
  76140. lineData.initData(
  76141. map(optData, function (item) {
  76142. return item[2];
  76143. })
  76144. );
  76145. lineData.hasItemOption = true;
  76146. return {
  76147. from: fromData,
  76148. to: toData,
  76149. line: lineData
  76150. };
  76151. }
  76152. /*
  76153. * Licensed to the Apache Software Foundation (ASF) under one
  76154. * or more contributor license agreements. See the NOTICE file
  76155. * distributed with this work for additional information
  76156. * regarding copyright ownership. The ASF licenses this file
  76157. * to you under the Apache License, Version 2.0 (the
  76158. * "License"); you may not use this file except in compliance
  76159. * with the License. You may obtain a copy of the License at
  76160. *
  76161. * http://www.apache.org/licenses/LICENSE-2.0
  76162. *
  76163. * Unless required by applicable law or agreed to in writing,
  76164. * software distributed under the License is distributed on an
  76165. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  76166. * KIND, either express or implied. See the License for the
  76167. * specific language governing permissions and limitations
  76168. * under the License.
  76169. */
  76170. registerPreprocessor(function (opt) {
  76171. // Make sure markLine component is enabled
  76172. opt.markLine = opt.markLine || {};
  76173. });
  76174. /*
  76175. * Licensed to the Apache Software Foundation (ASF) under one
  76176. * or more contributor license agreements. See the NOTICE file
  76177. * distributed with this work for additional information
  76178. * regarding copyright ownership. The ASF licenses this file
  76179. * to you under the Apache License, Version 2.0 (the
  76180. * "License"); you may not use this file except in compliance
  76181. * with the License. You may obtain a copy of the License at
  76182. *
  76183. * http://www.apache.org/licenses/LICENSE-2.0
  76184. *
  76185. * Unless required by applicable law or agreed to in writing,
  76186. * software distributed under the License is distributed on an
  76187. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  76188. * KIND, either express or implied. See the License for the
  76189. * specific language governing permissions and limitations
  76190. * under the License.
  76191. */
  76192. MarkerModel.extend({
  76193. type: 'markArea',
  76194. defaultOption: {
  76195. zlevel: 0,
  76196. // PENDING
  76197. z: 1,
  76198. tooltip: {
  76199. trigger: 'item'
  76200. },
  76201. // markArea should fixed on the coordinate system
  76202. animation: false,
  76203. label: {
  76204. show: true,
  76205. position: 'top'
  76206. },
  76207. itemStyle: {
  76208. // color and borderColor default to use color from series
  76209. // color: 'auto'
  76210. // borderColor: 'auto'
  76211. borderWidth: 0
  76212. },
  76213. emphasis: {
  76214. label: {
  76215. show: true,
  76216. position: 'top'
  76217. }
  76218. }
  76219. }
  76220. });
  76221. /*
  76222. * Licensed to the Apache Software Foundation (ASF) under one
  76223. * or more contributor license agreements. See the NOTICE file
  76224. * distributed with this work for additional information
  76225. * regarding copyright ownership. The ASF licenses this file
  76226. * to you under the Apache License, Version 2.0 (the
  76227. * "License"); you may not use this file except in compliance
  76228. * with the License. You may obtain a copy of the License at
  76229. *
  76230. * http://www.apache.org/licenses/LICENSE-2.0
  76231. *
  76232. * Unless required by applicable law or agreed to in writing,
  76233. * software distributed under the License is distributed on an
  76234. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  76235. * KIND, either express or implied. See the License for the
  76236. * specific language governing permissions and limitations
  76237. * under the License.
  76238. */
  76239. // TODO Better on polar
  76240. var markAreaTransform = function (seriesModel, coordSys, maModel, item) {
  76241. var lt = dataTransform(seriesModel, item[0]);
  76242. var rb = dataTransform(seriesModel, item[1]);
  76243. var retrieve$$1 = retrieve;
  76244. // FIXME make sure lt is less than rb
  76245. var ltCoord = lt.coord;
  76246. var rbCoord = rb.coord;
  76247. ltCoord[0] = retrieve$$1(ltCoord[0], -Infinity);
  76248. ltCoord[1] = retrieve$$1(ltCoord[1], -Infinity);
  76249. rbCoord[0] = retrieve$$1(rbCoord[0], Infinity);
  76250. rbCoord[1] = retrieve$$1(rbCoord[1], Infinity);
  76251. // Merge option into one
  76252. var result = mergeAll([{}, lt, rb]);
  76253. result.coord = [
  76254. lt.coord, rb.coord
  76255. ];
  76256. result.x0 = lt.x;
  76257. result.y0 = lt.y;
  76258. result.x1 = rb.x;
  76259. result.y1 = rb.y;
  76260. return result;
  76261. };
  76262. function isInifinity$1(val) {
  76263. return !isNaN(val) && !isFinite(val);
  76264. }
  76265. // If a markArea has one dim
  76266. function ifMarkLineHasOnlyDim$1(dimIndex, fromCoord, toCoord, coordSys) {
  76267. var otherDimIndex = 1 - dimIndex;
  76268. return isInifinity$1(fromCoord[otherDimIndex]) && isInifinity$1(toCoord[otherDimIndex]);
  76269. }
  76270. function markAreaFilter(coordSys, item) {
  76271. var fromCoord = item.coord[0];
  76272. var toCoord = item.coord[1];
  76273. if (coordSys.type === 'cartesian2d') {
  76274. // In case
  76275. // {
  76276. // markArea: {
  76277. // data: [{ yAxis: 2 }]
  76278. // }
  76279. // }
  76280. if (
  76281. fromCoord && toCoord
  76282. && (ifMarkLineHasOnlyDim$1(1, fromCoord, toCoord, coordSys)
  76283. || ifMarkLineHasOnlyDim$1(0, fromCoord, toCoord, coordSys))
  76284. ) {
  76285. return true;
  76286. }
  76287. }
  76288. return dataFilter$1(coordSys, {
  76289. coord: fromCoord,
  76290. x: item.x0,
  76291. y: item.y0
  76292. })
  76293. || dataFilter$1(coordSys, {
  76294. coord: toCoord,
  76295. x: item.x1,
  76296. y: item.y1
  76297. });
  76298. }
  76299. // dims can be ['x0', 'y0'], ['x1', 'y1'], ['x0', 'y1'], ['x1', 'y0']
  76300. function getSingleMarkerEndPoint(data, idx, dims, seriesModel, api) {
  76301. var coordSys = seriesModel.coordinateSystem;
  76302. var itemModel = data.getItemModel(idx);
  76303. var point;
  76304. var xPx = parsePercent$1(itemModel.get(dims[0]), api.getWidth());
  76305. var yPx = parsePercent$1(itemModel.get(dims[1]), api.getHeight());
  76306. if (!isNaN(xPx) && !isNaN(yPx)) {
  76307. point = [xPx, yPx];
  76308. }
  76309. else {
  76310. // Chart like bar may have there own marker positioning logic
  76311. if (seriesModel.getMarkerPosition) {
  76312. // Use the getMarkerPoisition
  76313. point = seriesModel.getMarkerPosition(
  76314. data.getValues(dims, idx)
  76315. );
  76316. }
  76317. else {
  76318. var x = data.get(dims[0], idx);
  76319. var y = data.get(dims[1], idx);
  76320. var pt = [x, y];
  76321. coordSys.clampData && coordSys.clampData(pt, pt);
  76322. point = coordSys.dataToPoint(pt, true);
  76323. }
  76324. if (coordSys.type === 'cartesian2d') {
  76325. var xAxis = coordSys.getAxis('x');
  76326. var yAxis = coordSys.getAxis('y');
  76327. var x = data.get(dims[0], idx);
  76328. var y = data.get(dims[1], idx);
  76329. if (isInifinity$1(x)) {
  76330. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[dims[0] === 'x0' ? 0 : 1]);
  76331. }
  76332. else if (isInifinity$1(y)) {
  76333. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[dims[1] === 'y0' ? 0 : 1]);
  76334. }
  76335. }
  76336. // Use x, y if has any
  76337. if (!isNaN(xPx)) {
  76338. point[0] = xPx;
  76339. }
  76340. if (!isNaN(yPx)) {
  76341. point[1] = yPx;
  76342. }
  76343. }
  76344. return point;
  76345. }
  76346. var dimPermutations = [['x0', 'y0'], ['x1', 'y0'], ['x1', 'y1'], ['x0', 'y1']];
  76347. MarkerView.extend({
  76348. type: 'markArea',
  76349. // updateLayout: function (markAreaModel, ecModel, api) {
  76350. // ecModel.eachSeries(function (seriesModel) {
  76351. // var maModel = seriesModel.markAreaModel;
  76352. // if (maModel) {
  76353. // var areaData = maModel.getData();
  76354. // areaData.each(function (idx) {
  76355. // var points = zrUtil.map(dimPermutations, function (dim) {
  76356. // return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  76357. // });
  76358. // // Layout
  76359. // areaData.setItemLayout(idx, points);
  76360. // var el = areaData.getItemGraphicEl(idx);
  76361. // el.setShape('points', points);
  76362. // });
  76363. // }
  76364. // }, this);
  76365. // },
  76366. updateTransform: function (markAreaModel, ecModel, api) {
  76367. ecModel.eachSeries(function (seriesModel) {
  76368. var maModel = seriesModel.markAreaModel;
  76369. if (maModel) {
  76370. var areaData = maModel.getData();
  76371. areaData.each(function (idx) {
  76372. var points = map(dimPermutations, function (dim) {
  76373. return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  76374. });
  76375. // Layout
  76376. areaData.setItemLayout(idx, points);
  76377. var el = areaData.getItemGraphicEl(idx);
  76378. el.setShape('points', points);
  76379. });
  76380. }
  76381. }, this);
  76382. },
  76383. renderSeries: function (seriesModel, maModel, ecModel, api) {
  76384. var coordSys = seriesModel.coordinateSystem;
  76385. var seriesId = seriesModel.id;
  76386. var seriesData = seriesModel.getData();
  76387. var areaGroupMap = this.markerGroupMap;
  76388. var polygonGroup = areaGroupMap.get(seriesId)
  76389. || areaGroupMap.set(seriesId, {group: new Group()});
  76390. this.group.add(polygonGroup.group);
  76391. polygonGroup.__keep = true;
  76392. var areaData = createList$3(coordSys, seriesModel, maModel);
  76393. // Line data for tooltip and formatter
  76394. maModel.setData(areaData);
  76395. // Update visual and layout of line
  76396. areaData.each(function (idx) {
  76397. // Layout
  76398. areaData.setItemLayout(idx, map(dimPermutations, function (dim) {
  76399. return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  76400. }));
  76401. // Visual
  76402. areaData.setItemVisual(idx, {
  76403. color: seriesData.getVisual('color')
  76404. });
  76405. });
  76406. areaData.diff(polygonGroup.__data)
  76407. .add(function (idx) {
  76408. var polygon = new Polygon({
  76409. shape: {
  76410. points: areaData.getItemLayout(idx)
  76411. }
  76412. });
  76413. areaData.setItemGraphicEl(idx, polygon);
  76414. polygonGroup.group.add(polygon);
  76415. })
  76416. .update(function (newIdx, oldIdx) {
  76417. var polygon = polygonGroup.__data.getItemGraphicEl(oldIdx);
  76418. updateProps(polygon, {
  76419. shape: {
  76420. points: areaData.getItemLayout(newIdx)
  76421. }
  76422. }, maModel, newIdx);
  76423. polygonGroup.group.add(polygon);
  76424. areaData.setItemGraphicEl(newIdx, polygon);
  76425. })
  76426. .remove(function (idx) {
  76427. var polygon = polygonGroup.__data.getItemGraphicEl(idx);
  76428. polygonGroup.group.remove(polygon);
  76429. })
  76430. .execute();
  76431. areaData.eachItemGraphicEl(function (polygon, idx) {
  76432. var itemModel = areaData.getItemModel(idx);
  76433. var labelModel = itemModel.getModel('label');
  76434. var labelHoverModel = itemModel.getModel('emphasis.label');
  76435. var color = areaData.getItemVisual(idx, 'color');
  76436. polygon.useStyle(
  76437. defaults(
  76438. itemModel.getModel('itemStyle').getItemStyle(),
  76439. {
  76440. fill: modifyAlpha(color, 0.4),
  76441. stroke: color
  76442. }
  76443. )
  76444. );
  76445. polygon.hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  76446. setLabelStyle(
  76447. polygon.style, polygon.hoverStyle, labelModel, labelHoverModel,
  76448. {
  76449. labelFetcher: maModel,
  76450. labelDataIndex: idx,
  76451. defaultText: areaData.getName(idx) || '',
  76452. isRectText: true,
  76453. autoColor: color
  76454. }
  76455. );
  76456. setHoverStyle(polygon, {});
  76457. polygon.dataModel = maModel;
  76458. });
  76459. polygonGroup.__data = areaData;
  76460. polygonGroup.group.silent = maModel.get('silent') || seriesModel.get('silent');
  76461. }
  76462. });
  76463. /**
  76464. * @inner
  76465. * @param {module:echarts/coord/*} coordSys
  76466. * @param {module:echarts/model/Series} seriesModel
  76467. * @param {module:echarts/model/Model} mpModel
  76468. */
  76469. function createList$3(coordSys, seriesModel, maModel) {
  76470. var coordDimsInfos;
  76471. var areaData;
  76472. var dims = ['x0', 'y0', 'x1', 'y1'];
  76473. if (coordSys) {
  76474. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  76475. var data = seriesModel.getData();
  76476. var info = data.getDimensionInfo(
  76477. data.mapDimension(coordDim)
  76478. ) || {};
  76479. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  76480. return defaults({name: coordDim}, info);
  76481. });
  76482. areaData = new List(map(dims, function (dim, idx) {
  76483. return {
  76484. name: dim,
  76485. type: coordDimsInfos[idx % 2].type
  76486. };
  76487. }), maModel);
  76488. }
  76489. else {
  76490. coordDimsInfos = [{
  76491. name: 'value',
  76492. type: 'float'
  76493. }];
  76494. areaData = new List(coordDimsInfos, maModel);
  76495. }
  76496. var optData = map(maModel.get('data'), curry(
  76497. markAreaTransform, seriesModel, coordSys, maModel
  76498. ));
  76499. if (coordSys) {
  76500. optData = filter(
  76501. optData, curry(markAreaFilter, coordSys)
  76502. );
  76503. }
  76504. var dimValueGetter$$1 = coordSys ? function (item, dimName, dataIndex, dimIndex) {
  76505. return item.coord[Math.floor(dimIndex / 2)][dimIndex % 2];
  76506. } : function (item) {
  76507. return item.value;
  76508. };
  76509. areaData.initData(optData, null, dimValueGetter$$1);
  76510. areaData.hasItemOption = true;
  76511. return areaData;
  76512. }
  76513. /*
  76514. * Licensed to the Apache Software Foundation (ASF) under one
  76515. * or more contributor license agreements. See the NOTICE file
  76516. * distributed with this work for additional information
  76517. * regarding copyright ownership. The ASF licenses this file
  76518. * to you under the Apache License, Version 2.0 (the
  76519. * "License"); you may not use this file except in compliance
  76520. * with the License. You may obtain a copy of the License at
  76521. *
  76522. * http://www.apache.org/licenses/LICENSE-2.0
  76523. *
  76524. * Unless required by applicable law or agreed to in writing,
  76525. * software distributed under the License is distributed on an
  76526. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  76527. * KIND, either express or implied. See the License for the
  76528. * specific language governing permissions and limitations
  76529. * under the License.
  76530. */
  76531. registerPreprocessor(function (opt) {
  76532. // Make sure markArea component is enabled
  76533. opt.markArea = opt.markArea || {};
  76534. });
  76535. /*
  76536. * Licensed to the Apache Software Foundation (ASF) under one
  76537. * or more contributor license agreements. See the NOTICE file
  76538. * distributed with this work for additional information
  76539. * regarding copyright ownership. The ASF licenses this file
  76540. * to you under the Apache License, Version 2.0 (the
  76541. * "License"); you may not use this file except in compliance
  76542. * with the License. You may obtain a copy of the License at
  76543. *
  76544. * http://www.apache.org/licenses/LICENSE-2.0
  76545. *
  76546. * Unless required by applicable law or agreed to in writing,
  76547. * software distributed under the License is distributed on an
  76548. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  76549. * KIND, either express or implied. See the License for the
  76550. * specific language governing permissions and limitations
  76551. * under the License.
  76552. */
  76553. var langSelector = lang.legend.selector;
  76554. var defaultSelectorOption = {
  76555. all: {
  76556. type: 'all',
  76557. title: clone(langSelector.all)
  76558. },
  76559. inverse: {
  76560. type: 'inverse',
  76561. title: clone(langSelector.inverse)
  76562. }
  76563. };
  76564. var LegendModel = extendComponentModel({
  76565. type: 'legend.plain',
  76566. dependencies: ['series'],
  76567. layoutMode: {
  76568. type: 'box',
  76569. // legend.width/height are maxWidth/maxHeight actually,
  76570. // whereas realy width/height is calculated by its content.
  76571. // (Setting {left: 10, right: 10} does not make sense).
  76572. // So consider the case:
  76573. // `setOption({legend: {left: 10});`
  76574. // then `setOption({legend: {right: 10});`
  76575. // The previous `left` should be cleared by setting `ignoreSize`.
  76576. ignoreSize: true
  76577. },
  76578. init: function (option, parentModel, ecModel) {
  76579. this.mergeDefaultAndTheme(option, ecModel);
  76580. option.selected = option.selected || {};
  76581. this._updateSelector(option);
  76582. },
  76583. mergeOption: function (option) {
  76584. LegendModel.superCall(this, 'mergeOption', option);
  76585. this._updateSelector(option);
  76586. },
  76587. _updateSelector: function (option) {
  76588. var selector = option.selector;
  76589. if (selector === true) {
  76590. selector = option.selector = ['all', 'inverse'];
  76591. }
  76592. if (isArray(selector)) {
  76593. each$1(selector, function (item, index) {
  76594. isString(item) && (item = {type: item});
  76595. selector[index] = merge(item, defaultSelectorOption[item.type]);
  76596. });
  76597. }
  76598. },
  76599. optionUpdated: function () {
  76600. this._updateData(this.ecModel);
  76601. var legendData = this._data;
  76602. // If selectedMode is single, try to select one
  76603. if (legendData[0] && this.get('selectedMode') === 'single') {
  76604. var hasSelected = false;
  76605. // If has any selected in option.selected
  76606. for (var i = 0; i < legendData.length; i++) {
  76607. var name = legendData[i].get('name');
  76608. if (this.isSelected(name)) {
  76609. // Force to unselect others
  76610. this.select(name);
  76611. hasSelected = true;
  76612. break;
  76613. }
  76614. }
  76615. // Try select the first if selectedMode is single
  76616. !hasSelected && this.select(legendData[0].get('name'));
  76617. }
  76618. },
  76619. _updateData: function (ecModel) {
  76620. var potentialData = [];
  76621. var availableNames = [];
  76622. ecModel.eachRawSeries(function (seriesModel) {
  76623. var seriesName = seriesModel.name;
  76624. availableNames.push(seriesName);
  76625. var isPotential;
  76626. if (seriesModel.legendVisualProvider) {
  76627. var provider = seriesModel.legendVisualProvider;
  76628. var names = provider.getAllNames();
  76629. if (!ecModel.isSeriesFiltered(seriesModel)) {
  76630. availableNames = availableNames.concat(names);
  76631. }
  76632. if (names.length) {
  76633. potentialData = potentialData.concat(names);
  76634. }
  76635. else {
  76636. isPotential = true;
  76637. }
  76638. }
  76639. else {
  76640. isPotential = true;
  76641. }
  76642. if (isPotential && isNameSpecified(seriesModel)) {
  76643. potentialData.push(seriesModel.name);
  76644. }
  76645. });
  76646. /**
  76647. * @type {Array.<string>}
  76648. * @private
  76649. */
  76650. this._availableNames = availableNames;
  76651. // If legend.data not specified in option, use availableNames as data,
  76652. // which is convinient for user preparing option.
  76653. var rawData = this.get('data') || potentialData;
  76654. var legendData = map(rawData, function (dataItem) {
  76655. // Can be string or number
  76656. if (typeof dataItem === 'string' || typeof dataItem === 'number') {
  76657. dataItem = {
  76658. name: dataItem
  76659. };
  76660. }
  76661. return new Model(dataItem, this, this.ecModel);
  76662. }, this);
  76663. /**
  76664. * @type {Array.<module:echarts/model/Model>}
  76665. * @private
  76666. */
  76667. this._data = legendData;
  76668. },
  76669. /**
  76670. * @return {Array.<module:echarts/model/Model>}
  76671. */
  76672. getData: function () {
  76673. return this._data;
  76674. },
  76675. /**
  76676. * @param {string} name
  76677. */
  76678. select: function (name) {
  76679. var selected = this.option.selected;
  76680. var selectedMode = this.get('selectedMode');
  76681. if (selectedMode === 'single') {
  76682. var data = this._data;
  76683. each$1(data, function (dataItem) {
  76684. selected[dataItem.get('name')] = false;
  76685. });
  76686. }
  76687. selected[name] = true;
  76688. },
  76689. /**
  76690. * @param {string} name
  76691. */
  76692. unSelect: function (name) {
  76693. if (this.get('selectedMode') !== 'single') {
  76694. this.option.selected[name] = false;
  76695. }
  76696. },
  76697. /**
  76698. * @param {string} name
  76699. */
  76700. toggleSelected: function (name) {
  76701. var selected = this.option.selected;
  76702. // Default is true
  76703. if (!selected.hasOwnProperty(name)) {
  76704. selected[name] = true;
  76705. }
  76706. this[selected[name] ? 'unSelect' : 'select'](name);
  76707. },
  76708. allSelect: function () {
  76709. var data = this._data;
  76710. var selected = this.option.selected;
  76711. each$1(data, function (dataItem) {
  76712. selected[dataItem.get('name', true)] = true;
  76713. });
  76714. },
  76715. inverseSelect: function () {
  76716. var data = this._data;
  76717. var selected = this.option.selected;
  76718. each$1(data, function (dataItem) {
  76719. var name = dataItem.get('name', true);
  76720. // Initially, default value is true
  76721. if (!selected.hasOwnProperty(name)) {
  76722. selected[name] = true;
  76723. }
  76724. selected[name] = !selected[name];
  76725. });
  76726. },
  76727. /**
  76728. * @param {string} name
  76729. */
  76730. isSelected: function (name) {
  76731. var selected = this.option.selected;
  76732. return !(selected.hasOwnProperty(name) && !selected[name])
  76733. && indexOf(this._availableNames, name) >= 0;
  76734. },
  76735. getOrient: function () {
  76736. return this.get('orient') === 'vertical'
  76737. ? {index: 1, name: 'vertical'}
  76738. : {index: 0, name: 'horizontal'};
  76739. },
  76740. defaultOption: {
  76741. // 一级层叠
  76742. zlevel: 0,
  76743. // 二级层叠
  76744. z: 4,
  76745. show: true,
  76746. // 布局方式,默认为水平布局,可选为:
  76747. // 'horizontal' | 'vertical'
  76748. orient: 'horizontal',
  76749. left: 'center',
  76750. // right: 'center',
  76751. top: 0,
  76752. // bottom: null,
  76753. // 水平对齐
  76754. // 'auto' | 'left' | 'right'
  76755. // 默认为 'auto', 根据 x 的位置判断是左对齐还是右对齐
  76756. align: 'auto',
  76757. backgroundColor: 'rgba(0,0,0,0)',
  76758. // 图例边框颜色
  76759. borderColor: '#ccc',
  76760. borderRadius: 0,
  76761. // 图例边框线宽,单位px,默认为0(无边框)
  76762. borderWidth: 0,
  76763. // 图例内边距,单位px,默认各方向内边距为5,
  76764. // 接受数组分别设定上右下左边距,同css
  76765. padding: 5,
  76766. // 各个item之间的间隔,单位px,默认为10,
  76767. // 横向布局时为水平间隔,纵向布局时为纵向间隔
  76768. itemGap: 10,
  76769. // the width of legend symbol
  76770. itemWidth: 25,
  76771. // the height of legend symbol
  76772. itemHeight: 14,
  76773. // the color of unselected legend symbol
  76774. inactiveColor: '#ccc',
  76775. // the borderColor of unselected legend symbol
  76776. inactiveBorderColor: '#ccc',
  76777. itemStyle: {
  76778. // the default borderWidth of legend symbol
  76779. borderWidth: 0
  76780. },
  76781. textStyle: {
  76782. // 图例文字颜色
  76783. color: '#333'
  76784. },
  76785. // formatter: '',
  76786. // 选择模式,默认开启图例开关
  76787. selectedMode: true,
  76788. // 配置默认选中状态,可配合LEGEND.SELECTED事件做动态数据载入
  76789. // selected: null,
  76790. // 图例内容(详见legend.data,数组中每一项代表一个item
  76791. // data: [],
  76792. // Usage:
  76793. // selector: [{type: 'all or inverse', title: xxx}]
  76794. // or
  76795. // selector: true
  76796. // or
  76797. // selector: ['all', 'inverse']
  76798. selector: false,
  76799. selectorLabel: {
  76800. show: true,
  76801. borderRadius: 10,
  76802. padding: [3, 5, 3, 5],
  76803. fontSize: 12,
  76804. fontFamily: ' sans-serif',
  76805. color: '#666',
  76806. borderWidth: 1,
  76807. borderColor: '#666'
  76808. },
  76809. emphasis: {
  76810. selectorLabel: {
  76811. show: true,
  76812. color: '#eee',
  76813. backgroundColor: '#666'
  76814. }
  76815. },
  76816. // Value can be 'start' or 'end'
  76817. selectorPosition: 'auto',
  76818. selectorItemGap: 7,
  76819. selectorButtonGap: 10,
  76820. // Tooltip 相关配置
  76821. tooltip: {
  76822. show: false
  76823. }
  76824. }
  76825. });
  76826. /*
  76827. * Licensed to the Apache Software Foundation (ASF) under one
  76828. * or more contributor license agreements. See the NOTICE file
  76829. * distributed with this work for additional information
  76830. * regarding copyright ownership. The ASF licenses this file
  76831. * to you under the Apache License, Version 2.0 (the
  76832. * "License"); you may not use this file except in compliance
  76833. * with the License. You may obtain a copy of the License at
  76834. *
  76835. * http://www.apache.org/licenses/LICENSE-2.0
  76836. *
  76837. * Unless required by applicable law or agreed to in writing,
  76838. * software distributed under the License is distributed on an
  76839. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  76840. * KIND, either express or implied. See the License for the
  76841. * specific language governing permissions and limitations
  76842. * under the License.
  76843. */
  76844. function legendSelectActionHandler(methodName, payload, ecModel) {
  76845. var selectedMap = {};
  76846. var isToggleSelect = methodName === 'toggleSelected';
  76847. var isSelected;
  76848. // Update all legend components
  76849. ecModel.eachComponent('legend', function (legendModel) {
  76850. if (isToggleSelect && isSelected != null) {
  76851. // Force other legend has same selected status
  76852. // Or the first is toggled to true and other are toggled to false
  76853. // In the case one legend has some item unSelected in option. And if other legend
  76854. // doesn't has the item, they will assume it is selected.
  76855. legendModel[isSelected ? 'select' : 'unSelect'](payload.name);
  76856. }
  76857. else if (methodName === 'allSelect' || methodName === 'inverseSelect') {
  76858. legendModel[methodName]();
  76859. }
  76860. else {
  76861. legendModel[methodName](payload.name);
  76862. isSelected = legendModel.isSelected(payload.name);
  76863. }
  76864. var legendData = legendModel.getData();
  76865. each$1(legendData, function (model) {
  76866. var name = model.get('name');
  76867. // Wrap element
  76868. if (name === '\n' || name === '') {
  76869. return;
  76870. }
  76871. var isItemSelected = legendModel.isSelected(name);
  76872. if (selectedMap.hasOwnProperty(name)) {
  76873. // Unselected if any legend is unselected
  76874. selectedMap[name] = selectedMap[name] && isItemSelected;
  76875. }
  76876. else {
  76877. selectedMap[name] = isItemSelected;
  76878. }
  76879. });
  76880. });
  76881. // Return the event explicitly
  76882. return (methodName === 'allSelect' || methodName === 'inverseSelect')
  76883. ? {
  76884. selected: selectedMap
  76885. }
  76886. : {
  76887. name: payload.name,
  76888. selected: selectedMap
  76889. };
  76890. }
  76891. /**
  76892. * @event legendToggleSelect
  76893. * @type {Object}
  76894. * @property {string} type 'legendToggleSelect'
  76895. * @property {string} [from]
  76896. * @property {string} name Series name or data item name
  76897. */
  76898. registerAction(
  76899. 'legendToggleSelect', 'legendselectchanged',
  76900. curry(legendSelectActionHandler, 'toggleSelected')
  76901. );
  76902. registerAction(
  76903. 'legendAllSelect', 'legendselectall',
  76904. curry(legendSelectActionHandler, 'allSelect')
  76905. );
  76906. registerAction(
  76907. 'legendInverseSelect', 'legendinverseselect',
  76908. curry(legendSelectActionHandler, 'inverseSelect')
  76909. );
  76910. /**
  76911. * @event legendSelect
  76912. * @type {Object}
  76913. * @property {string} type 'legendSelect'
  76914. * @property {string} name Series name or data item name
  76915. */
  76916. registerAction(
  76917. 'legendSelect', 'legendselected',
  76918. curry(legendSelectActionHandler, 'select')
  76919. );
  76920. /**
  76921. * @event legendUnSelect
  76922. * @type {Object}
  76923. * @property {string} type 'legendUnSelect'
  76924. * @property {string} name Series name or data item name
  76925. */
  76926. registerAction(
  76927. 'legendUnSelect', 'legendunselected',
  76928. curry(legendSelectActionHandler, 'unSelect')
  76929. );
  76930. /*
  76931. * Licensed to the Apache Software Foundation (ASF) under one
  76932. * or more contributor license agreements. See the NOTICE file
  76933. * distributed with this work for additional information
  76934. * regarding copyright ownership. The ASF licenses this file
  76935. * to you under the Apache License, Version 2.0 (the
  76936. * "License"); you may not use this file except in compliance
  76937. * with the License. You may obtain a copy of the License at
  76938. *
  76939. * http://www.apache.org/licenses/LICENSE-2.0
  76940. *
  76941. * Unless required by applicable law or agreed to in writing,
  76942. * software distributed under the License is distributed on an
  76943. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  76944. * KIND, either express or implied. See the License for the
  76945. * specific language governing permissions and limitations
  76946. * under the License.
  76947. */
  76948. var curry$6 = curry;
  76949. var each$25 = each$1;
  76950. var Group$3 = Group;
  76951. var LegendView = extendComponentView({
  76952. type: 'legend.plain',
  76953. newlineDisabled: false,
  76954. /**
  76955. * @override
  76956. */
  76957. init: function () {
  76958. /**
  76959. * @private
  76960. * @type {module:zrender/container/Group}
  76961. */
  76962. this.group.add(this._contentGroup = new Group$3());
  76963. /**
  76964. * @private
  76965. * @type {module:zrender/Element}
  76966. */
  76967. this._backgroundEl;
  76968. /**
  76969. * @private
  76970. * @type {module:zrender/container/Group}
  76971. */
  76972. this.group.add(this._selectorGroup = new Group$3());
  76973. /**
  76974. * If first rendering, `contentGroup.position` is [0, 0], which
  76975. * does not make sense and may cause unexepcted animation if adopted.
  76976. * @private
  76977. * @type {boolean}
  76978. */
  76979. this._isFirstRender = true;
  76980. },
  76981. /**
  76982. * @protected
  76983. */
  76984. getContentGroup: function () {
  76985. return this._contentGroup;
  76986. },
  76987. /**
  76988. * @protected
  76989. */
  76990. getSelectorGroup: function () {
  76991. return this._selectorGroup;
  76992. },
  76993. /**
  76994. * @override
  76995. */
  76996. render: function (legendModel, ecModel, api) {
  76997. var isFirstRender = this._isFirstRender;
  76998. this._isFirstRender = false;
  76999. this.resetInner();
  77000. if (!legendModel.get('show', true)) {
  77001. return;
  77002. }
  77003. var itemAlign = legendModel.get('align');
  77004. var orient = legendModel.get('orient');
  77005. if (!itemAlign || itemAlign === 'auto') {
  77006. itemAlign = (
  77007. legendModel.get('left') === 'right'
  77008. && orient === 'vertical'
  77009. ) ? 'right' : 'left';
  77010. }
  77011. var selector = legendModel.get('selector', true);
  77012. var selectorPosition = legendModel.get('selectorPosition', true);
  77013. if (selector && (!selectorPosition || selectorPosition === 'auto')) {
  77014. selectorPosition = orient === 'horizontal' ? 'end' : 'start';
  77015. }
  77016. this.renderInner(itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition);
  77017. // Perform layout.
  77018. var positionInfo = legendModel.getBoxLayoutParams();
  77019. var viewportSize = {width: api.getWidth(), height: api.getHeight()};
  77020. var padding = legendModel.get('padding');
  77021. var maxSize = getLayoutRect(positionInfo, viewportSize, padding);
  77022. var mainRect = this.layoutInner(legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition);
  77023. // Place mainGroup, based on the calculated `mainRect`.
  77024. var layoutRect = getLayoutRect(
  77025. defaults({width: mainRect.width, height: mainRect.height}, positionInfo),
  77026. viewportSize,
  77027. padding
  77028. );
  77029. this.group.attr('position', [layoutRect.x - mainRect.x, layoutRect.y - mainRect.y]);
  77030. // Render background after group is layout.
  77031. this.group.add(
  77032. this._backgroundEl = makeBackground(mainRect, legendModel)
  77033. );
  77034. },
  77035. /**
  77036. * @protected
  77037. */
  77038. resetInner: function () {
  77039. this.getContentGroup().removeAll();
  77040. this._backgroundEl && this.group.remove(this._backgroundEl);
  77041. this.getSelectorGroup().removeAll();
  77042. },
  77043. /**
  77044. * @protected
  77045. */
  77046. renderInner: function (itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition) {
  77047. var contentGroup = this.getContentGroup();
  77048. var legendDrawnMap = createHashMap();
  77049. var selectMode = legendModel.get('selectedMode');
  77050. var excludeSeriesId = [];
  77051. ecModel.eachRawSeries(function (seriesModel) {
  77052. !seriesModel.get('legendHoverLink') && excludeSeriesId.push(seriesModel.id);
  77053. });
  77054. each$25(legendModel.getData(), function (itemModel, dataIndex) {
  77055. var name = itemModel.get('name');
  77056. // Use empty string or \n as a newline string
  77057. if (!this.newlineDisabled && (name === '' || name === '\n')) {
  77058. contentGroup.add(new Group$3({
  77059. newline: true
  77060. }));
  77061. return;
  77062. }
  77063. // Representitive series.
  77064. var seriesModel = ecModel.getSeriesByName(name)[0];
  77065. if (legendDrawnMap.get(name)) {
  77066. // Have been drawed
  77067. return;
  77068. }
  77069. // Legend to control series.
  77070. if (seriesModel) {
  77071. var data = seriesModel.getData();
  77072. var color = data.getVisual('color');
  77073. var borderColor = data.getVisual('borderColor');
  77074. // If color is a callback function
  77075. if (typeof color === 'function') {
  77076. // Use the first data
  77077. color = color(seriesModel.getDataParams(0));
  77078. }
  77079. // If borderColor is a callback function
  77080. if (typeof borderColor === 'function') {
  77081. // Use the first data
  77082. borderColor = borderColor(seriesModel.getDataParams(0));
  77083. }
  77084. // Using rect symbol defaultly
  77085. var legendSymbolType = data.getVisual('legendSymbol') || 'roundRect';
  77086. var symbolType = data.getVisual('symbol');
  77087. var itemGroup = this._createItem(
  77088. name, dataIndex, itemModel, legendModel,
  77089. legendSymbolType, symbolType,
  77090. itemAlign, color, borderColor,
  77091. selectMode
  77092. );
  77093. itemGroup.on('click', curry$6(dispatchSelectAction, name, null, api, excludeSeriesId))
  77094. .on('mouseover', curry$6(dispatchHighlightAction, seriesModel.name, null, api, excludeSeriesId))
  77095. .on('mouseout', curry$6(dispatchDownplayAction, seriesModel.name, null, api, excludeSeriesId));
  77096. legendDrawnMap.set(name, true);
  77097. }
  77098. else {
  77099. // Legend to control data. In pie and funnel.
  77100. ecModel.eachRawSeries(function (seriesModel) {
  77101. // In case multiple series has same data name
  77102. if (legendDrawnMap.get(name)) {
  77103. return;
  77104. }
  77105. if (seriesModel.legendVisualProvider) {
  77106. var provider = seriesModel.legendVisualProvider;
  77107. if (!provider.containName(name)) {
  77108. return;
  77109. }
  77110. var idx = provider.indexOfName(name);
  77111. var color = provider.getItemVisual(idx, 'color');
  77112. var borderColor = provider.getItemVisual(idx, 'borderColor');
  77113. var legendSymbolType = 'roundRect';
  77114. var itemGroup = this._createItem(
  77115. name, dataIndex, itemModel, legendModel,
  77116. legendSymbolType, null,
  77117. itemAlign, color, borderColor,
  77118. selectMode
  77119. );
  77120. // FIXME: consider different series has items with the same name.
  77121. itemGroup.on('click', curry$6(dispatchSelectAction, null, name, api, excludeSeriesId))
  77122. // Should not specify the series name, consider legend controls
  77123. // more than one pie series.
  77124. .on('mouseover', curry$6(dispatchHighlightAction, null, name, api, excludeSeriesId))
  77125. .on('mouseout', curry$6(dispatchDownplayAction, null, name, api, excludeSeriesId));
  77126. legendDrawnMap.set(name, true);
  77127. }
  77128. }, this);
  77129. }
  77130. if (__DEV__) {
  77131. if (!legendDrawnMap.get(name)) {
  77132. console.warn(
  77133. name + ' series not exists. Legend data should be same with series name or data name.'
  77134. );
  77135. }
  77136. }
  77137. }, this);
  77138. if (selector) {
  77139. this._createSelector(selector, legendModel, api, orient, selectorPosition);
  77140. }
  77141. },
  77142. _createSelector: function (selector, legendModel, api, orient, selectorPosition) {
  77143. var selectorGroup = this.getSelectorGroup();
  77144. each$25(selector, function (selectorItem) {
  77145. createSelectorButton(selectorItem);
  77146. });
  77147. function createSelectorButton(selectorItem) {
  77148. var type = selectorItem.type;
  77149. var labelText = new Text({
  77150. style: {
  77151. x: 0,
  77152. y: 0,
  77153. align: 'center',
  77154. verticalAlign: 'middle'
  77155. },
  77156. onclick: function () {
  77157. api.dispatchAction({
  77158. type: type === 'all' ? 'legendAllSelect' : 'legendInverseSelect'
  77159. });
  77160. }
  77161. });
  77162. selectorGroup.add(labelText);
  77163. var labelModel = legendModel.getModel('selectorLabel');
  77164. var emphasisLabelModel = legendModel.getModel('emphasis.selectorLabel');
  77165. setLabelStyle(
  77166. labelText.style, labelText.hoverStyle = {}, labelModel, emphasisLabelModel,
  77167. {
  77168. defaultText: selectorItem.title,
  77169. isRectText: false
  77170. }
  77171. );
  77172. setHoverStyle(labelText);
  77173. }
  77174. },
  77175. _createItem: function (
  77176. name, dataIndex, itemModel, legendModel,
  77177. legendSymbolType, symbolType,
  77178. itemAlign, color, borderColor, selectMode
  77179. ) {
  77180. var itemWidth = legendModel.get('itemWidth');
  77181. var itemHeight = legendModel.get('itemHeight');
  77182. var inactiveColor = legendModel.get('inactiveColor');
  77183. var inactiveBorderColor = legendModel.get('inactiveBorderColor');
  77184. var symbolKeepAspect = legendModel.get('symbolKeepAspect');
  77185. var legendModelItemStyle = legendModel.getModel('itemStyle');
  77186. var isSelected = legendModel.isSelected(name);
  77187. var itemGroup = new Group$3();
  77188. var textStyleModel = itemModel.getModel('textStyle');
  77189. var itemIcon = itemModel.get('icon');
  77190. var tooltipModel = itemModel.getModel('tooltip');
  77191. var legendGlobalTooltipModel = tooltipModel.parentModel;
  77192. // Use user given icon first
  77193. legendSymbolType = itemIcon || legendSymbolType;
  77194. var legendSymbol = createSymbol(
  77195. legendSymbolType,
  77196. 0,
  77197. 0,
  77198. itemWidth,
  77199. itemHeight,
  77200. isSelected ? color : inactiveColor,
  77201. // symbolKeepAspect default true for legend
  77202. symbolKeepAspect == null ? true : symbolKeepAspect
  77203. );
  77204. itemGroup.add(
  77205. setSymbolStyle(
  77206. legendSymbol, legendSymbolType, legendModelItemStyle,
  77207. borderColor, inactiveBorderColor, isSelected
  77208. )
  77209. );
  77210. // Compose symbols
  77211. // PENDING
  77212. if (!itemIcon && symbolType
  77213. // At least show one symbol, can't be all none
  77214. && ((symbolType !== legendSymbolType) || symbolType === 'none')
  77215. ) {
  77216. var size = itemHeight * 0.8;
  77217. if (symbolType === 'none') {
  77218. symbolType = 'circle';
  77219. }
  77220. var legendSymbolCenter = createSymbol(
  77221. symbolType,
  77222. (itemWidth - size) / 2,
  77223. (itemHeight - size) / 2,
  77224. size,
  77225. size,
  77226. isSelected ? color : inactiveColor,
  77227. // symbolKeepAspect default true for legend
  77228. symbolKeepAspect == null ? true : symbolKeepAspect
  77229. );
  77230. // Put symbol in the center
  77231. itemGroup.add(
  77232. setSymbolStyle(
  77233. legendSymbolCenter, symbolType, legendModelItemStyle,
  77234. borderColor, inactiveBorderColor, isSelected
  77235. )
  77236. );
  77237. }
  77238. var textX = itemAlign === 'left' ? itemWidth + 5 : -5;
  77239. var textAlign = itemAlign;
  77240. var formatter = legendModel.get('formatter');
  77241. var content = name;
  77242. if (typeof formatter === 'string' && formatter) {
  77243. content = formatter.replace('{name}', name != null ? name : '');
  77244. }
  77245. else if (typeof formatter === 'function') {
  77246. content = formatter(name);
  77247. }
  77248. itemGroup.add(new Text({
  77249. style: setTextStyle({}, textStyleModel, {
  77250. text: content,
  77251. x: textX,
  77252. y: itemHeight / 2,
  77253. textFill: isSelected ? textStyleModel.getTextColor() : inactiveColor,
  77254. textAlign: textAlign,
  77255. textVerticalAlign: 'middle'
  77256. })
  77257. }));
  77258. // Add a invisible rect to increase the area of mouse hover
  77259. var hitRect = new Rect({
  77260. shape: itemGroup.getBoundingRect(),
  77261. invisible: true,
  77262. tooltip: tooltipModel.get('show') ? extend({
  77263. content: name,
  77264. // Defaul formatter
  77265. formatter: legendGlobalTooltipModel.get('formatter', true) || function () {
  77266. return name;
  77267. },
  77268. formatterParams: {
  77269. componentType: 'legend',
  77270. legendIndex: legendModel.componentIndex,
  77271. name: name,
  77272. $vars: ['name']
  77273. }
  77274. }, tooltipModel.option) : null
  77275. });
  77276. itemGroup.add(hitRect);
  77277. itemGroup.eachChild(function (child) {
  77278. child.silent = true;
  77279. });
  77280. hitRect.silent = !selectMode;
  77281. this.getContentGroup().add(itemGroup);
  77282. setHoverStyle(itemGroup);
  77283. itemGroup.__legendDataIndex = dataIndex;
  77284. return itemGroup;
  77285. },
  77286. /**
  77287. * @protected
  77288. */
  77289. layoutInner: function (legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition) {
  77290. var contentGroup = this.getContentGroup();
  77291. var selectorGroup = this.getSelectorGroup();
  77292. // Place items in contentGroup.
  77293. box(
  77294. legendModel.get('orient'),
  77295. contentGroup,
  77296. legendModel.get('itemGap'),
  77297. maxSize.width,
  77298. maxSize.height
  77299. );
  77300. var contentRect = contentGroup.getBoundingRect();
  77301. var contentPos = [-contentRect.x, -contentRect.y];
  77302. if (selector) {
  77303. // Place buttons in selectorGroup
  77304. box(
  77305. // Buttons in selectorGroup always layout horizontally
  77306. 'horizontal',
  77307. selectorGroup,
  77308. legendModel.get('selectorItemGap', true)
  77309. );
  77310. var selectorRect = selectorGroup.getBoundingRect();
  77311. var selectorPos = [-selectorRect.x, -selectorRect.y];
  77312. var selectorButtonGap = legendModel.get('selectorButtonGap', true);
  77313. var orientIdx = legendModel.getOrient().index;
  77314. var wh = orientIdx === 0 ? 'width' : 'height';
  77315. var hw = orientIdx === 0 ? 'height' : 'width';
  77316. var yx = orientIdx === 0 ? 'y' : 'x';
  77317. if (selectorPosition === 'end') {
  77318. selectorPos[orientIdx] += contentRect[wh] + selectorButtonGap;
  77319. }
  77320. else {
  77321. contentPos[orientIdx] += selectorRect[wh] + selectorButtonGap;
  77322. }
  77323. //Always align selector to content as 'middle'
  77324. selectorPos[1 - orientIdx] += contentRect[hw] / 2 - selectorRect[hw] / 2;
  77325. selectorGroup.attr('position', selectorPos);
  77326. contentGroup.attr('position', contentPos);
  77327. var mainRect = {x: 0, y: 0};
  77328. mainRect[wh] = contentRect[wh] + selectorButtonGap + selectorRect[wh];
  77329. mainRect[hw] = Math.max(contentRect[hw], selectorRect[hw]);
  77330. mainRect[yx] = Math.min(0, selectorRect[yx] + selectorPos[1 - orientIdx]);
  77331. return mainRect;
  77332. }
  77333. else {
  77334. contentGroup.attr('position', contentPos);
  77335. return this.group.getBoundingRect();
  77336. }
  77337. },
  77338. /**
  77339. * @protected
  77340. */
  77341. remove: function () {
  77342. this.getContentGroup().removeAll();
  77343. this._isFirstRender = true;
  77344. }
  77345. });
  77346. function setSymbolStyle(symbol, symbolType, legendModelItemStyle, borderColor, inactiveBorderColor, isSelected) {
  77347. var itemStyle;
  77348. if (symbolType !== 'line' && symbolType.indexOf('empty') < 0) {
  77349. itemStyle = legendModelItemStyle.getItemStyle();
  77350. symbol.style.stroke = borderColor;
  77351. if (!isSelected) {
  77352. itemStyle.stroke = inactiveBorderColor;
  77353. }
  77354. }
  77355. else {
  77356. itemStyle = legendModelItemStyle.getItemStyle(['borderWidth', 'borderColor']);
  77357. }
  77358. return symbol.setStyle(itemStyle);
  77359. }
  77360. function dispatchSelectAction(seriesName, dataName, api, excludeSeriesId) {
  77361. // downplay before unselect
  77362. dispatchDownplayAction(seriesName, dataName, api, excludeSeriesId);
  77363. api.dispatchAction({
  77364. type: 'legendToggleSelect',
  77365. name: seriesName != null ? seriesName : dataName
  77366. });
  77367. // highlight after select
  77368. dispatchHighlightAction(seriesName, dataName, api, excludeSeriesId);
  77369. }
  77370. function dispatchHighlightAction(seriesName, dataName, api, excludeSeriesId) {
  77371. // If element hover will move to a hoverLayer.
  77372. var el = api.getZr().storage.getDisplayList()[0];
  77373. if (!(el && el.useHoverLayer)) {
  77374. api.dispatchAction({
  77375. type: 'highlight',
  77376. seriesName: seriesName,
  77377. name: dataName,
  77378. excludeSeriesId: excludeSeriesId
  77379. });
  77380. }
  77381. }
  77382. function dispatchDownplayAction(seriesName, dataName, api, excludeSeriesId) {
  77383. // If element hover will move to a hoverLayer.
  77384. var el = api.getZr().storage.getDisplayList()[0];
  77385. if (!(el && el.useHoverLayer)) {
  77386. api.dispatchAction({
  77387. type: 'downplay',
  77388. seriesName: seriesName,
  77389. name: dataName,
  77390. excludeSeriesId: excludeSeriesId
  77391. });
  77392. }
  77393. }
  77394. /*
  77395. * Licensed to the Apache Software Foundation (ASF) under one
  77396. * or more contributor license agreements. See the NOTICE file
  77397. * distributed with this work for additional information
  77398. * regarding copyright ownership. The ASF licenses this file
  77399. * to you under the Apache License, Version 2.0 (the
  77400. * "License"); you may not use this file except in compliance
  77401. * with the License. You may obtain a copy of the License at
  77402. *
  77403. * http://www.apache.org/licenses/LICENSE-2.0
  77404. *
  77405. * Unless required by applicable law or agreed to in writing,
  77406. * software distributed under the License is distributed on an
  77407. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  77408. * KIND, either express or implied. See the License for the
  77409. * specific language governing permissions and limitations
  77410. * under the License.
  77411. */
  77412. var legendFilter = function (ecModel) {
  77413. var legendModels = ecModel.findComponents({
  77414. mainType: 'legend'
  77415. });
  77416. if (legendModels && legendModels.length) {
  77417. ecModel.filterSeries(function (series) {
  77418. // If in any legend component the status is not selected.
  77419. // Because in legend series is assumed selected when it is not in the legend data.
  77420. for (var i = 0; i < legendModels.length; i++) {
  77421. if (!legendModels[i].isSelected(series.name)) {
  77422. return false;
  77423. }
  77424. }
  77425. return true;
  77426. });
  77427. }
  77428. };
  77429. /*
  77430. * Licensed to the Apache Software Foundation (ASF) under one
  77431. * or more contributor license agreements. See the NOTICE file
  77432. * distributed with this work for additional information
  77433. * regarding copyright ownership. The ASF licenses this file
  77434. * to you under the Apache License, Version 2.0 (the
  77435. * "License"); you may not use this file except in compliance
  77436. * with the License. You may obtain a copy of the License at
  77437. *
  77438. * http://www.apache.org/licenses/LICENSE-2.0
  77439. *
  77440. * Unless required by applicable law or agreed to in writing,
  77441. * software distributed under the License is distributed on an
  77442. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  77443. * KIND, either express or implied. See the License for the
  77444. * specific language governing permissions and limitations
  77445. * under the License.
  77446. */
  77447. // Do not contain scrollable legend, for sake of file size.
  77448. // Series Filter
  77449. registerProcessor(PRIORITY.PROCESSOR.SERIES_FILTER, legendFilter);
  77450. ComponentModel.registerSubTypeDefaulter('legend', function () {
  77451. // Default 'plain' when no type specified.
  77452. return 'plain';
  77453. });
  77454. /*
  77455. * Licensed to the Apache Software Foundation (ASF) under one
  77456. * or more contributor license agreements. See the NOTICE file
  77457. * distributed with this work for additional information
  77458. * regarding copyright ownership. The ASF licenses this file
  77459. * to you under the Apache License, Version 2.0 (the
  77460. * "License"); you may not use this file except in compliance
  77461. * with the License. You may obtain a copy of the License at
  77462. *
  77463. * http://www.apache.org/licenses/LICENSE-2.0
  77464. *
  77465. * Unless required by applicable law or agreed to in writing,
  77466. * software distributed under the License is distributed on an
  77467. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  77468. * KIND, either express or implied. See the License for the
  77469. * specific language governing permissions and limitations
  77470. * under the License.
  77471. */
  77472. var ScrollableLegendModel = LegendModel.extend({
  77473. type: 'legend.scroll',
  77474. /**
  77475. * @param {number} scrollDataIndex
  77476. */
  77477. setScrollDataIndex: function (scrollDataIndex) {
  77478. this.option.scrollDataIndex = scrollDataIndex;
  77479. },
  77480. defaultOption: {
  77481. scrollDataIndex: 0,
  77482. pageButtonItemGap: 5,
  77483. pageButtonGap: null,
  77484. pageButtonPosition: 'end', // 'start' or 'end'
  77485. pageFormatter: '{current}/{total}', // If null/undefined, do not show page.
  77486. pageIcons: {
  77487. horizontal: ['M0,0L12,-10L12,10z', 'M0,0L-12,-10L-12,10z'],
  77488. vertical: ['M0,0L20,0L10,-20z', 'M0,0L20,0L10,20z']
  77489. },
  77490. pageIconColor: '#2f4554',
  77491. pageIconInactiveColor: '#aaa',
  77492. pageIconSize: 15, // Can be [10, 3], which represents [width, height]
  77493. pageTextStyle: {
  77494. color: '#333'
  77495. },
  77496. animationDurationUpdate: 800
  77497. },
  77498. /**
  77499. * @override
  77500. */
  77501. init: function (option, parentModel, ecModel, extraOpt) {
  77502. var inputPositionParams = getLayoutParams(option);
  77503. ScrollableLegendModel.superCall(this, 'init', option, parentModel, ecModel, extraOpt);
  77504. mergeAndNormalizeLayoutParams$1(this, option, inputPositionParams);
  77505. },
  77506. /**
  77507. * @override
  77508. */
  77509. mergeOption: function (option, extraOpt) {
  77510. ScrollableLegendModel.superCall(this, 'mergeOption', option, extraOpt);
  77511. mergeAndNormalizeLayoutParams$1(this, this.option, option);
  77512. }
  77513. });
  77514. // Do not `ignoreSize` to enable setting {left: 10, right: 10}.
  77515. function mergeAndNormalizeLayoutParams$1(legendModel, target, raw) {
  77516. var orient = legendModel.getOrient();
  77517. var ignoreSize = [1, 1];
  77518. ignoreSize[orient.index] = 0;
  77519. mergeLayoutParam(target, raw, {
  77520. type: 'box', ignoreSize: ignoreSize
  77521. });
  77522. }
  77523. /*
  77524. * Licensed to the Apache Software Foundation (ASF) under one
  77525. * or more contributor license agreements. See the NOTICE file
  77526. * distributed with this work for additional information
  77527. * regarding copyright ownership. The ASF licenses this file
  77528. * to you under the Apache License, Version 2.0 (the
  77529. * "License"); you may not use this file except in compliance
  77530. * with the License. You may obtain a copy of the License at
  77531. *
  77532. * http://www.apache.org/licenses/LICENSE-2.0
  77533. *
  77534. * Unless required by applicable law or agreed to in writing,
  77535. * software distributed under the License is distributed on an
  77536. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  77537. * KIND, either express or implied. See the License for the
  77538. * specific language governing permissions and limitations
  77539. * under the License.
  77540. */
  77541. /**
  77542. * Separate legend and scrollable legend to reduce package size.
  77543. */
  77544. var Group$4 = Group;
  77545. var WH$1 = ['width', 'height'];
  77546. var XY$1 = ['x', 'y'];
  77547. var ScrollableLegendView = LegendView.extend({
  77548. type: 'legend.scroll',
  77549. newlineDisabled: true,
  77550. init: function () {
  77551. ScrollableLegendView.superCall(this, 'init');
  77552. /**
  77553. * @private
  77554. * @type {number} For `scroll`.
  77555. */
  77556. this._currentIndex = 0;
  77557. /**
  77558. * @private
  77559. * @type {module:zrender/container/Group}
  77560. */
  77561. this.group.add(this._containerGroup = new Group$4());
  77562. this._containerGroup.add(this.getContentGroup());
  77563. /**
  77564. * @private
  77565. * @type {module:zrender/container/Group}
  77566. */
  77567. this.group.add(this._controllerGroup = new Group$4());
  77568. /**
  77569. *
  77570. * @private
  77571. */
  77572. this._showController;
  77573. },
  77574. /**
  77575. * @override
  77576. */
  77577. resetInner: function () {
  77578. ScrollableLegendView.superCall(this, 'resetInner');
  77579. this._controllerGroup.removeAll();
  77580. this._containerGroup.removeClipPath();
  77581. this._containerGroup.__rectSize = null;
  77582. },
  77583. /**
  77584. * @override
  77585. */
  77586. renderInner: function (itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition) {
  77587. var me = this;
  77588. // Render content items.
  77589. ScrollableLegendView.superCall(this, 'renderInner', itemAlign,
  77590. legendModel, ecModel, api, selector, orient, selectorPosition);
  77591. var controllerGroup = this._controllerGroup;
  77592. // FIXME: support be 'auto' adapt to size number text length,
  77593. // e.g., '3/12345' should not overlap with the control arrow button.
  77594. var pageIconSize = legendModel.get('pageIconSize', true);
  77595. if (!isArray(pageIconSize)) {
  77596. pageIconSize = [pageIconSize, pageIconSize];
  77597. }
  77598. createPageButton('pagePrev', 0);
  77599. var pageTextStyleModel = legendModel.getModel('pageTextStyle');
  77600. controllerGroup.add(new Text({
  77601. name: 'pageText',
  77602. style: {
  77603. textFill: pageTextStyleModel.getTextColor(),
  77604. font: pageTextStyleModel.getFont(),
  77605. textVerticalAlign: 'middle',
  77606. textAlign: 'center'
  77607. },
  77608. silent: true
  77609. }));
  77610. createPageButton('pageNext', 1);
  77611. function createPageButton(name, iconIdx) {
  77612. var pageDataIndexName = name + 'DataIndex';
  77613. var icon = createIcon(
  77614. legendModel.get('pageIcons', true)[legendModel.getOrient().name][iconIdx],
  77615. {
  77616. // Buttons will be created in each render, so we do not need
  77617. // to worry about avoiding using legendModel kept in scope.
  77618. onclick: bind(
  77619. me._pageGo, me, pageDataIndexName, legendModel, api
  77620. )
  77621. },
  77622. {
  77623. x: -pageIconSize[0] / 2,
  77624. y: -pageIconSize[1] / 2,
  77625. width: pageIconSize[0],
  77626. height: pageIconSize[1]
  77627. }
  77628. );
  77629. icon.name = name;
  77630. controllerGroup.add(icon);
  77631. }
  77632. },
  77633. /**
  77634. * @override
  77635. */
  77636. layoutInner: function (legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition) {
  77637. var selectorGroup = this.getSelectorGroup();
  77638. var orientIdx = legendModel.getOrient().index;
  77639. var wh = WH$1[orientIdx];
  77640. var xy = XY$1[orientIdx];
  77641. var hw = WH$1[1 - orientIdx];
  77642. var yx = XY$1[1 - orientIdx];
  77643. selector && box(
  77644. // Buttons in selectorGroup always layout horizontally
  77645. 'horizontal',
  77646. selectorGroup,
  77647. legendModel.get('selectorItemGap', true)
  77648. );
  77649. var selectorButtonGap = legendModel.get('selectorButtonGap', true);
  77650. var selectorRect = selectorGroup.getBoundingRect();
  77651. var selectorPos = [-selectorRect.x, -selectorRect.y];
  77652. var processMaxSize = clone(maxSize);
  77653. selector && (processMaxSize[wh] = maxSize[wh] - selectorRect[wh] - selectorButtonGap);
  77654. var mainRect = this._layoutContentAndController(legendModel, isFirstRender,
  77655. processMaxSize, orientIdx, wh, hw, yx
  77656. );
  77657. if (selector) {
  77658. if (selectorPosition === 'end') {
  77659. selectorPos[orientIdx] += mainRect[wh] + selectorButtonGap;
  77660. }
  77661. else {
  77662. var offset = selectorRect[wh] + selectorButtonGap;
  77663. selectorPos[orientIdx] -= offset;
  77664. mainRect[xy] -= offset;
  77665. }
  77666. mainRect[wh] += selectorRect[wh] + selectorButtonGap;
  77667. selectorPos[1 - orientIdx] += mainRect[yx] + mainRect[hw] / 2 - selectorRect[hw] / 2;
  77668. mainRect[hw] = Math.max(mainRect[hw], selectorRect[hw]);
  77669. mainRect[yx] = Math.min(mainRect[yx], selectorRect[yx] + selectorPos[1 - orientIdx]);
  77670. selectorGroup.attr('position', selectorPos);
  77671. }
  77672. return mainRect;
  77673. },
  77674. _layoutContentAndController: function (legendModel, isFirstRender, maxSize, orientIdx, wh, hw, yx) {
  77675. var contentGroup = this.getContentGroup();
  77676. var containerGroup = this._containerGroup;
  77677. var controllerGroup = this._controllerGroup;
  77678. // Place items in contentGroup.
  77679. box(
  77680. legendModel.get('orient'),
  77681. contentGroup,
  77682. legendModel.get('itemGap'),
  77683. !orientIdx ? null : maxSize.width,
  77684. orientIdx ? null : maxSize.height
  77685. );
  77686. box(
  77687. // Buttons in controller are layout always horizontally.
  77688. 'horizontal',
  77689. controllerGroup,
  77690. legendModel.get('pageButtonItemGap', true)
  77691. );
  77692. var contentRect = contentGroup.getBoundingRect();
  77693. var controllerRect = controllerGroup.getBoundingRect();
  77694. var showController = this._showController = contentRect[wh] > maxSize[wh];
  77695. var contentPos = [-contentRect.x, -contentRect.y];
  77696. // Remain contentPos when scroll animation perfroming.
  77697. // If first rendering, `contentGroup.position` is [0, 0], which
  77698. // does not make sense and may cause unexepcted animation if adopted.
  77699. if (!isFirstRender) {
  77700. contentPos[orientIdx] = contentGroup.position[orientIdx];
  77701. }
  77702. // Layout container group based on 0.
  77703. var containerPos = [0, 0];
  77704. var controllerPos = [-controllerRect.x, -controllerRect.y];
  77705. var pageButtonGap = retrieve2(
  77706. legendModel.get('pageButtonGap', true), legendModel.get('itemGap', true)
  77707. );
  77708. // Place containerGroup and controllerGroup and contentGroup.
  77709. if (showController) {
  77710. var pageButtonPosition = legendModel.get('pageButtonPosition', true);
  77711. // controller is on the right / bottom.
  77712. if (pageButtonPosition === 'end') {
  77713. controllerPos[orientIdx] += maxSize[wh] - controllerRect[wh];
  77714. }
  77715. // controller is on the left / top.
  77716. else {
  77717. containerPos[orientIdx] += controllerRect[wh] + pageButtonGap;
  77718. }
  77719. }
  77720. // Always align controller to content as 'middle'.
  77721. controllerPos[1 - orientIdx] += contentRect[hw] / 2 - controllerRect[hw] / 2;
  77722. contentGroup.attr('position', contentPos);
  77723. containerGroup.attr('position', containerPos);
  77724. controllerGroup.attr('position', controllerPos);
  77725. // Calculate `mainRect` and set `clipPath`.
  77726. // mainRect should not be calculated by `this.group.getBoundingRect()`
  77727. // for sake of the overflow.
  77728. var mainRect = {x: 0, y: 0};
  77729. // Consider content may be overflow (should be clipped).
  77730. mainRect[wh] = showController ? maxSize[wh] : contentRect[wh];
  77731. mainRect[hw] = Math.max(contentRect[hw], controllerRect[hw]);
  77732. // `containerRect[yx] + containerPos[1 - orientIdx]` is 0.
  77733. mainRect[yx] = Math.min(0, controllerRect[yx] + controllerPos[1 - orientIdx]);
  77734. containerGroup.__rectSize = maxSize[wh];
  77735. if (showController) {
  77736. var clipShape = {x: 0, y: 0};
  77737. clipShape[wh] = Math.max(maxSize[wh] - controllerRect[wh] - pageButtonGap, 0);
  77738. clipShape[hw] = mainRect[hw];
  77739. containerGroup.setClipPath(new Rect({shape: clipShape}));
  77740. // Consider content may be larger than container, container rect
  77741. // can not be obtained from `containerGroup.getBoundingRect()`.
  77742. containerGroup.__rectSize = clipShape[wh];
  77743. }
  77744. else {
  77745. // Do not remove or ignore controller. Keep them set as placeholders.
  77746. controllerGroup.eachChild(function (child) {
  77747. child.attr({invisible: true, silent: true});
  77748. });
  77749. }
  77750. // Content translate animation.
  77751. var pageInfo = this._getPageInfo(legendModel);
  77752. pageInfo.pageIndex != null && updateProps(
  77753. contentGroup,
  77754. {position: pageInfo.contentPosition},
  77755. // When switch from "show controller" to "not show controller", view should be
  77756. // updated immediately without animation, otherwise causes weird effect.
  77757. showController ? legendModel : false
  77758. );
  77759. this._updatePageInfoView(legendModel, pageInfo);
  77760. return mainRect;
  77761. },
  77762. _pageGo: function (to, legendModel, api) {
  77763. var scrollDataIndex = this._getPageInfo(legendModel)[to];
  77764. scrollDataIndex != null && api.dispatchAction({
  77765. type: 'legendScroll',
  77766. scrollDataIndex: scrollDataIndex,
  77767. legendId: legendModel.id
  77768. });
  77769. },
  77770. _updatePageInfoView: function (legendModel, pageInfo) {
  77771. var controllerGroup = this._controllerGroup;
  77772. each$1(['pagePrev', 'pageNext'], function (name) {
  77773. var canJump = pageInfo[name + 'DataIndex'] != null;
  77774. var icon = controllerGroup.childOfName(name);
  77775. if (icon) {
  77776. icon.setStyle(
  77777. 'fill',
  77778. canJump
  77779. ? legendModel.get('pageIconColor', true)
  77780. : legendModel.get('pageIconInactiveColor', true)
  77781. );
  77782. icon.cursor = canJump ? 'pointer' : 'default';
  77783. }
  77784. });
  77785. var pageText = controllerGroup.childOfName('pageText');
  77786. var pageFormatter = legendModel.get('pageFormatter');
  77787. var pageIndex = pageInfo.pageIndex;
  77788. var current = pageIndex != null ? pageIndex + 1 : 0;
  77789. var total = pageInfo.pageCount;
  77790. pageText && pageFormatter && pageText.setStyle(
  77791. 'text',
  77792. isString(pageFormatter)
  77793. ? pageFormatter.replace('{current}', current).replace('{total}', total)
  77794. : pageFormatter({current: current, total: total})
  77795. );
  77796. },
  77797. /**
  77798. * @param {module:echarts/model/Model} legendModel
  77799. * @return {Object} {
  77800. * contentPosition: Array.<number>, null when data item not found.
  77801. * pageIndex: number, null when data item not found.
  77802. * pageCount: number, always be a number, can be 0.
  77803. * pagePrevDataIndex: number, null when no previous page.
  77804. * pageNextDataIndex: number, null when no next page.
  77805. * }
  77806. */
  77807. _getPageInfo: function (legendModel) {
  77808. var scrollDataIndex = legendModel.get('scrollDataIndex', true);
  77809. var contentGroup = this.getContentGroup();
  77810. var containerRectSize = this._containerGroup.__rectSize;
  77811. var orientIdx = legendModel.getOrient().index;
  77812. var wh = WH$1[orientIdx];
  77813. var xy = XY$1[orientIdx];
  77814. var targetItemIndex = this._findTargetItemIndex(scrollDataIndex);
  77815. var children = contentGroup.children();
  77816. var targetItem = children[targetItemIndex];
  77817. var itemCount = children.length;
  77818. var pCount = !itemCount ? 0 : 1;
  77819. var result = {
  77820. contentPosition: contentGroup.position.slice(),
  77821. pageCount: pCount,
  77822. pageIndex: pCount - 1,
  77823. pagePrevDataIndex: null,
  77824. pageNextDataIndex: null
  77825. };
  77826. if (!targetItem) {
  77827. return result;
  77828. }
  77829. var targetItemInfo = getItemInfo(targetItem);
  77830. result.contentPosition[orientIdx] = -targetItemInfo.s;
  77831. // Strategy:
  77832. // (1) Always align based on the left/top most item.
  77833. // (2) It is user-friendly that the last item shown in the
  77834. // current window is shown at the begining of next window.
  77835. // Otherwise if half of the last item is cut by the window,
  77836. // it will have no chance to display entirely.
  77837. // (3) Consider that item size probably be different, we
  77838. // have calculate pageIndex by size rather than item index,
  77839. // and we can not get page index directly by division.
  77840. // (4) The window is to narrow to contain more than
  77841. // one item, we should make sure that the page can be fliped.
  77842. for (var i = targetItemIndex + 1,
  77843. winStartItemInfo = targetItemInfo,
  77844. winEndItemInfo = targetItemInfo,
  77845. currItemInfo = null;
  77846. i <= itemCount;
  77847. ++i
  77848. ) {
  77849. currItemInfo = getItemInfo(children[i]);
  77850. if (
  77851. // Half of the last item is out of the window.
  77852. (!currItemInfo && winEndItemInfo.e > winStartItemInfo.s + containerRectSize)
  77853. // If the current item does not intersect with the window, the new page
  77854. // can be started at the current item or the last item.
  77855. || (currItemInfo && !intersect(currItemInfo, winStartItemInfo.s))
  77856. ) {
  77857. if (winEndItemInfo.i > winStartItemInfo.i) {
  77858. winStartItemInfo = winEndItemInfo;
  77859. }
  77860. else { // e.g., when page size is smaller than item size.
  77861. winStartItemInfo = currItemInfo;
  77862. }
  77863. if (winStartItemInfo) {
  77864. if (result.pageNextDataIndex == null) {
  77865. result.pageNextDataIndex = winStartItemInfo.i;
  77866. }
  77867. ++result.pageCount;
  77868. }
  77869. }
  77870. winEndItemInfo = currItemInfo;
  77871. }
  77872. for (var i = targetItemIndex - 1,
  77873. winStartItemInfo = targetItemInfo,
  77874. winEndItemInfo = targetItemInfo,
  77875. currItemInfo = null;
  77876. i >= -1;
  77877. --i
  77878. ) {
  77879. currItemInfo = getItemInfo(children[i]);
  77880. if (
  77881. // If the the end item does not intersect with the window started
  77882. // from the current item, a page can be settled.
  77883. (!currItemInfo || !intersect(winEndItemInfo, currItemInfo.s))
  77884. // e.g., when page size is smaller than item size.
  77885. && winStartItemInfo.i < winEndItemInfo.i
  77886. ) {
  77887. winEndItemInfo = winStartItemInfo;
  77888. if (result.pagePrevDataIndex == null) {
  77889. result.pagePrevDataIndex = winStartItemInfo.i;
  77890. }
  77891. ++result.pageCount;
  77892. ++result.pageIndex;
  77893. }
  77894. winStartItemInfo = currItemInfo;
  77895. }
  77896. return result;
  77897. function getItemInfo(el) {
  77898. if (el) {
  77899. var itemRect = el.getBoundingRect();
  77900. var start = itemRect[xy] + el.position[orientIdx];
  77901. return {
  77902. s: start,
  77903. e: start + itemRect[wh],
  77904. i: el.__legendDataIndex
  77905. };
  77906. }
  77907. }
  77908. function intersect(itemInfo, winStart) {
  77909. return itemInfo.e >= winStart && itemInfo.s <= winStart + containerRectSize;
  77910. }
  77911. },
  77912. _findTargetItemIndex: function (targetDataIndex) {
  77913. if (!this._showController) {
  77914. return 0;
  77915. }
  77916. var index;
  77917. var contentGroup = this.getContentGroup();
  77918. var defaultIndex;
  77919. contentGroup.eachChild(function (child, idx) {
  77920. var legendDataIdx = child.__legendDataIndex;
  77921. // FIXME
  77922. // If the given targetDataIndex (from model) is illegal,
  77923. // we use defualtIndex. But the index on the legend model and
  77924. // action payload is still illegal. That case will not be
  77925. // changed until some scenario requires.
  77926. if (defaultIndex == null && legendDataIdx != null) {
  77927. defaultIndex = idx;
  77928. }
  77929. if (legendDataIdx === targetDataIndex) {
  77930. index = idx;
  77931. }
  77932. });
  77933. return index != null ? index : defaultIndex;
  77934. }
  77935. });
  77936. /*
  77937. * Licensed to the Apache Software Foundation (ASF) under one
  77938. * or more contributor license agreements. See the NOTICE file
  77939. * distributed with this work for additional information
  77940. * regarding copyright ownership. The ASF licenses this file
  77941. * to you under the Apache License, Version 2.0 (the
  77942. * "License"); you may not use this file except in compliance
  77943. * with the License. You may obtain a copy of the License at
  77944. *
  77945. * http://www.apache.org/licenses/LICENSE-2.0
  77946. *
  77947. * Unless required by applicable law or agreed to in writing,
  77948. * software distributed under the License is distributed on an
  77949. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  77950. * KIND, either express or implied. See the License for the
  77951. * specific language governing permissions and limitations
  77952. * under the License.
  77953. */
  77954. /**
  77955. * @event legendScroll
  77956. * @type {Object}
  77957. * @property {string} type 'legendScroll'
  77958. * @property {string} scrollDataIndex
  77959. */
  77960. registerAction(
  77961. 'legendScroll', 'legendscroll',
  77962. function (payload, ecModel) {
  77963. var scrollDataIndex = payload.scrollDataIndex;
  77964. scrollDataIndex != null && ecModel.eachComponent(
  77965. {mainType: 'legend', subType: 'scroll', query: payload},
  77966. function (legendModel) {
  77967. legendModel.setScrollDataIndex(scrollDataIndex);
  77968. }
  77969. );
  77970. }
  77971. );
  77972. /*
  77973. * Licensed to the Apache Software Foundation (ASF) under one
  77974. * or more contributor license agreements. See the NOTICE file
  77975. * distributed with this work for additional information
  77976. * regarding copyright ownership. The ASF licenses this file
  77977. * to you under the Apache License, Version 2.0 (the
  77978. * "License"); you may not use this file except in compliance
  77979. * with the License. You may obtain a copy of the License at
  77980. *
  77981. * http://www.apache.org/licenses/LICENSE-2.0
  77982. *
  77983. * Unless required by applicable law or agreed to in writing,
  77984. * software distributed under the License is distributed on an
  77985. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  77986. * KIND, either express or implied. See the License for the
  77987. * specific language governing permissions and limitations
  77988. * under the License.
  77989. */
  77990. /**
  77991. * Legend component entry file8
  77992. */
  77993. /*
  77994. * Licensed to the Apache Software Foundation (ASF) under one
  77995. * or more contributor license agreements. See the NOTICE file
  77996. * distributed with this work for additional information
  77997. * regarding copyright ownership. The ASF licenses this file
  77998. * to you under the Apache License, Version 2.0 (the
  77999. * "License"); you may not use this file except in compliance
  78000. * with the License. You may obtain a copy of the License at
  78001. *
  78002. * http://www.apache.org/licenses/LICENSE-2.0
  78003. *
  78004. * Unless required by applicable law or agreed to in writing,
  78005. * software distributed under the License is distributed on an
  78006. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  78007. * KIND, either express or implied. See the License for the
  78008. * specific language governing permissions and limitations
  78009. * under the License.
  78010. */
  78011. var SliderZoomModel = DataZoomModel.extend({
  78012. type: 'dataZoom.slider',
  78013. layoutMode: 'box',
  78014. /**
  78015. * @protected
  78016. */
  78017. defaultOption: {
  78018. show: true,
  78019. // ph => placeholder. Using placehoder here because
  78020. // deault value can only be drived in view stage.
  78021. right: 'ph', // Default align to grid rect.
  78022. top: 'ph', // Default align to grid rect.
  78023. width: 'ph', // Default align to grid rect.
  78024. height: 'ph', // Default align to grid rect.
  78025. left: null, // Default align to grid rect.
  78026. bottom: null, // Default align to grid rect.
  78027. backgroundColor: 'rgba(47,69,84,0)', // Background of slider zoom component.
  78028. // dataBackgroundColor: '#ddd', // Background coor of data shadow and border of box,
  78029. // highest priority, remain for compatibility of
  78030. // previous version, but not recommended any more.
  78031. dataBackground: {
  78032. lineStyle: {
  78033. color: '#2f4554',
  78034. width: 0.5,
  78035. opacity: 0.3
  78036. },
  78037. areaStyle: {
  78038. color: 'rgba(47,69,84,0.3)',
  78039. opacity: 0.3
  78040. }
  78041. },
  78042. borderColor: '#ddd', // border color of the box. For compatibility,
  78043. // if dataBackgroundColor is set, borderColor
  78044. // is ignored.
  78045. fillerColor: 'rgba(167,183,204,0.4)', // Color of selected area.
  78046. // handleColor: 'rgba(89,170,216,0.95)', // Color of handle.
  78047. // 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',
  78048. /* eslint-disable */
  78049. 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',
  78050. /* eslint-enable */
  78051. // Percent of the slider height
  78052. handleSize: '100%',
  78053. handleStyle: {
  78054. color: '#a7b7cc'
  78055. },
  78056. labelPrecision: null,
  78057. labelFormatter: null,
  78058. showDetail: true,
  78059. showDataShadow: 'auto', // Default auto decision.
  78060. realtime: true,
  78061. zoomLock: false, // Whether disable zoom.
  78062. textStyle: {
  78063. color: '#333'
  78064. }
  78065. }
  78066. });
  78067. /*
  78068. * Licensed to the Apache Software Foundation (ASF) under one
  78069. * or more contributor license agreements. See the NOTICE file
  78070. * distributed with this work for additional information
  78071. * regarding copyright ownership. The ASF licenses this file
  78072. * to you under the Apache License, Version 2.0 (the
  78073. * "License"); you may not use this file except in compliance
  78074. * with the License. You may obtain a copy of the License at
  78075. *
  78076. * http://www.apache.org/licenses/LICENSE-2.0
  78077. *
  78078. * Unless required by applicable law or agreed to in writing,
  78079. * software distributed under the License is distributed on an
  78080. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  78081. * KIND, either express or implied. See the License for the
  78082. * specific language governing permissions and limitations
  78083. * under the License.
  78084. */
  78085. var Rect$2 = Rect;
  78086. var linearMap$1 = linearMap;
  78087. var asc$2 = asc;
  78088. var bind$5 = bind;
  78089. var each$26 = each$1;
  78090. // Constants
  78091. var DEFAULT_LOCATION_EDGE_GAP = 7;
  78092. var DEFAULT_FRAME_BORDER_WIDTH = 1;
  78093. var DEFAULT_FILLER_SIZE = 30;
  78094. var HORIZONTAL = 'horizontal';
  78095. var VERTICAL = 'vertical';
  78096. var LABEL_GAP = 5;
  78097. var SHOW_DATA_SHADOW_SERIES_TYPE = ['line', 'bar', 'candlestick', 'scatter'];
  78098. var SliderZoomView = DataZoomView.extend({
  78099. type: 'dataZoom.slider',
  78100. init: function (ecModel, api) {
  78101. /**
  78102. * @private
  78103. * @type {Object}
  78104. */
  78105. this._displayables = {};
  78106. /**
  78107. * @private
  78108. * @type {string}
  78109. */
  78110. this._orient;
  78111. /**
  78112. * [0, 100]
  78113. * @private
  78114. */
  78115. this._range;
  78116. /**
  78117. * [coord of the first handle, coord of the second handle]
  78118. * @private
  78119. */
  78120. this._handleEnds;
  78121. /**
  78122. * [length, thick]
  78123. * @private
  78124. * @type {Array.<number>}
  78125. */
  78126. this._size;
  78127. /**
  78128. * @private
  78129. * @type {number}
  78130. */
  78131. this._handleWidth;
  78132. /**
  78133. * @private
  78134. * @type {number}
  78135. */
  78136. this._handleHeight;
  78137. /**
  78138. * @private
  78139. */
  78140. this._location;
  78141. /**
  78142. * @private
  78143. */
  78144. this._dragging;
  78145. /**
  78146. * @private
  78147. */
  78148. this._dataShadowInfo;
  78149. this.api = api;
  78150. },
  78151. /**
  78152. * @override
  78153. */
  78154. render: function (dataZoomModel, ecModel, api, payload) {
  78155. SliderZoomView.superApply(this, 'render', arguments);
  78156. createOrUpdate(
  78157. this,
  78158. '_dispatchZoomAction',
  78159. this.dataZoomModel.get('throttle'),
  78160. 'fixRate'
  78161. );
  78162. this._orient = dataZoomModel.get('orient');
  78163. if (this.dataZoomModel.get('show') === false) {
  78164. this.group.removeAll();
  78165. return;
  78166. }
  78167. // Notice: this._resetInterval() should not be executed when payload.type
  78168. // is 'dataZoom', origin this._range should be maintained, otherwise 'pan'
  78169. // or 'zoom' info will be missed because of 'throttle' of this.dispatchAction,
  78170. if (!payload || payload.type !== 'dataZoom' || payload.from !== this.uid) {
  78171. this._buildView();
  78172. }
  78173. this._updateView();
  78174. },
  78175. /**
  78176. * @override
  78177. */
  78178. remove: function () {
  78179. SliderZoomView.superApply(this, 'remove', arguments);
  78180. clear(this, '_dispatchZoomAction');
  78181. },
  78182. /**
  78183. * @override
  78184. */
  78185. dispose: function () {
  78186. SliderZoomView.superApply(this, 'dispose', arguments);
  78187. clear(this, '_dispatchZoomAction');
  78188. },
  78189. _buildView: function () {
  78190. var thisGroup = this.group;
  78191. thisGroup.removeAll();
  78192. this._resetLocation();
  78193. this._resetInterval();
  78194. var barGroup = this._displayables.barGroup = new Group();
  78195. this._renderBackground();
  78196. this._renderHandle();
  78197. this._renderDataShadow();
  78198. thisGroup.add(barGroup);
  78199. this._positionGroup();
  78200. },
  78201. /**
  78202. * @private
  78203. */
  78204. _resetLocation: function () {
  78205. var dataZoomModel = this.dataZoomModel;
  78206. var api = this.api;
  78207. // If some of x/y/width/height are not specified,
  78208. // auto-adapt according to target grid.
  78209. var coordRect = this._findCoordRect();
  78210. var ecSize = {width: api.getWidth(), height: api.getHeight()};
  78211. // Default align by coordinate system rect.
  78212. var positionInfo = this._orient === HORIZONTAL
  78213. ? {
  78214. // Why using 'right', because right should be used in vertical,
  78215. // and it is better to be consistent for dealing with position param merge.
  78216. right: ecSize.width - coordRect.x - coordRect.width,
  78217. top: (ecSize.height - DEFAULT_FILLER_SIZE - DEFAULT_LOCATION_EDGE_GAP),
  78218. width: coordRect.width,
  78219. height: DEFAULT_FILLER_SIZE
  78220. }
  78221. : { // vertical
  78222. right: DEFAULT_LOCATION_EDGE_GAP,
  78223. top: coordRect.y,
  78224. width: DEFAULT_FILLER_SIZE,
  78225. height: coordRect.height
  78226. };
  78227. // Do not write back to option and replace value 'ph', because
  78228. // the 'ph' value should be recalculated when resize.
  78229. var layoutParams = getLayoutParams(dataZoomModel.option);
  78230. // Replace the placeholder value.
  78231. each$1(['right', 'top', 'width', 'height'], function (name) {
  78232. if (layoutParams[name] === 'ph') {
  78233. layoutParams[name] = positionInfo[name];
  78234. }
  78235. });
  78236. var layoutRect = getLayoutRect(
  78237. layoutParams,
  78238. ecSize,
  78239. dataZoomModel.padding
  78240. );
  78241. this._location = {x: layoutRect.x, y: layoutRect.y};
  78242. this._size = [layoutRect.width, layoutRect.height];
  78243. this._orient === VERTICAL && this._size.reverse();
  78244. },
  78245. /**
  78246. * @private
  78247. */
  78248. _positionGroup: function () {
  78249. var thisGroup = this.group;
  78250. var location = this._location;
  78251. var orient = this._orient;
  78252. // Just use the first axis to determine mapping.
  78253. var targetAxisModel = this.dataZoomModel.getFirstTargetAxisModel();
  78254. var inverse = targetAxisModel && targetAxisModel.get('inverse');
  78255. var barGroup = this._displayables.barGroup;
  78256. var otherAxisInverse = (this._dataShadowInfo || {}).otherAxisInverse;
  78257. // Transform barGroup.
  78258. barGroup.attr(
  78259. (orient === HORIZONTAL && !inverse)
  78260. ? {scale: otherAxisInverse ? [1, 1] : [1, -1]}
  78261. : (orient === HORIZONTAL && inverse)
  78262. ? {scale: otherAxisInverse ? [-1, 1] : [-1, -1]}
  78263. : (orient === VERTICAL && !inverse)
  78264. ? {scale: otherAxisInverse ? [1, -1] : [1, 1], rotation: Math.PI / 2}
  78265. // Dont use Math.PI, considering shadow direction.
  78266. : {scale: otherAxisInverse ? [-1, -1] : [-1, 1], rotation: Math.PI / 2}
  78267. );
  78268. // Position barGroup
  78269. var rect = thisGroup.getBoundingRect([barGroup]);
  78270. thisGroup.attr('position', [location.x - rect.x, location.y - rect.y]);
  78271. },
  78272. /**
  78273. * @private
  78274. */
  78275. _getViewExtent: function () {
  78276. return [0, this._size[0]];
  78277. },
  78278. _renderBackground: function () {
  78279. var dataZoomModel = this.dataZoomModel;
  78280. var size = this._size;
  78281. var barGroup = this._displayables.barGroup;
  78282. barGroup.add(new Rect$2({
  78283. silent: true,
  78284. shape: {
  78285. x: 0, y: 0, width: size[0], height: size[1]
  78286. },
  78287. style: {
  78288. fill: dataZoomModel.get('backgroundColor')
  78289. },
  78290. z2: -40
  78291. }));
  78292. // Click panel, over shadow, below handles.
  78293. barGroup.add(new Rect$2({
  78294. shape: {
  78295. x: 0, y: 0, width: size[0], height: size[1]
  78296. },
  78297. style: {
  78298. fill: 'transparent'
  78299. },
  78300. z2: 0,
  78301. onclick: bind(this._onClickPanelClick, this)
  78302. }));
  78303. },
  78304. _renderDataShadow: function () {
  78305. var info = this._dataShadowInfo = this._prepareDataShadowInfo();
  78306. if (!info) {
  78307. return;
  78308. }
  78309. var size = this._size;
  78310. var seriesModel = info.series;
  78311. var data = seriesModel.getRawData();
  78312. var otherDim = seriesModel.getShadowDim
  78313. ? seriesModel.getShadowDim() // @see candlestick
  78314. : info.otherDim;
  78315. if (otherDim == null) {
  78316. return;
  78317. }
  78318. var otherDataExtent = data.getDataExtent(otherDim);
  78319. // Nice extent.
  78320. var otherOffset = (otherDataExtent[1] - otherDataExtent[0]) * 0.3;
  78321. otherDataExtent = [
  78322. otherDataExtent[0] - otherOffset,
  78323. otherDataExtent[1] + otherOffset
  78324. ];
  78325. var otherShadowExtent = [0, size[1]];
  78326. var thisShadowExtent = [0, size[0]];
  78327. var areaPoints = [[size[0], 0], [0, 0]];
  78328. var linePoints = [];
  78329. var step = thisShadowExtent[1] / (data.count() - 1);
  78330. var thisCoord = 0;
  78331. // Optimize for large data shadow
  78332. var stride = Math.round(data.count() / size[0]);
  78333. var lastIsEmpty;
  78334. data.each([otherDim], function (value, index) {
  78335. if (stride > 0 && (index % stride)) {
  78336. thisCoord += step;
  78337. return;
  78338. }
  78339. // FIXME
  78340. // Should consider axis.min/axis.max when drawing dataShadow.
  78341. // FIXME
  78342. // 应该使用统一的空判断?还是在list里进行空判断?
  78343. var isEmpty = value == null || isNaN(value) || value === '';
  78344. // See #4235.
  78345. var otherCoord = isEmpty
  78346. ? 0 : linearMap$1(value, otherDataExtent, otherShadowExtent, true);
  78347. // Attempt to draw data shadow precisely when there are empty value.
  78348. if (isEmpty && !lastIsEmpty && index) {
  78349. areaPoints.push([areaPoints[areaPoints.length - 1][0], 0]);
  78350. linePoints.push([linePoints[linePoints.length - 1][0], 0]);
  78351. }
  78352. else if (!isEmpty && lastIsEmpty) {
  78353. areaPoints.push([thisCoord, 0]);
  78354. linePoints.push([thisCoord, 0]);
  78355. }
  78356. areaPoints.push([thisCoord, otherCoord]);
  78357. linePoints.push([thisCoord, otherCoord]);
  78358. thisCoord += step;
  78359. lastIsEmpty = isEmpty;
  78360. });
  78361. var dataZoomModel = this.dataZoomModel;
  78362. // var dataBackgroundModel = dataZoomModel.getModel('dataBackground');
  78363. this._displayables.barGroup.add(new Polygon({
  78364. shape: {points: areaPoints},
  78365. style: defaults(
  78366. {fill: dataZoomModel.get('dataBackgroundColor')},
  78367. dataZoomModel.getModel('dataBackground.areaStyle').getAreaStyle()
  78368. ),
  78369. silent: true,
  78370. z2: -20
  78371. }));
  78372. this._displayables.barGroup.add(new Polyline({
  78373. shape: {points: linePoints},
  78374. style: dataZoomModel.getModel('dataBackground.lineStyle').getLineStyle(),
  78375. silent: true,
  78376. z2: -19
  78377. }));
  78378. },
  78379. _prepareDataShadowInfo: function () {
  78380. var dataZoomModel = this.dataZoomModel;
  78381. var showDataShadow = dataZoomModel.get('showDataShadow');
  78382. if (showDataShadow === false) {
  78383. return;
  78384. }
  78385. // Find a representative series.
  78386. var result;
  78387. var ecModel = this.ecModel;
  78388. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex) {
  78389. var seriesModels = dataZoomModel
  78390. .getAxisProxy(dimNames.name, axisIndex)
  78391. .getTargetSeriesModels();
  78392. each$1(seriesModels, function (seriesModel) {
  78393. if (result) {
  78394. return;
  78395. }
  78396. if (showDataShadow !== true && indexOf(
  78397. SHOW_DATA_SHADOW_SERIES_TYPE, seriesModel.get('type')
  78398. ) < 0
  78399. ) {
  78400. return;
  78401. }
  78402. var thisAxis = ecModel.getComponent(dimNames.axis, axisIndex).axis;
  78403. var otherDim = getOtherDim(dimNames.name);
  78404. var otherAxisInverse;
  78405. var coordSys = seriesModel.coordinateSystem;
  78406. if (otherDim != null && coordSys.getOtherAxis) {
  78407. otherAxisInverse = coordSys.getOtherAxis(thisAxis).inverse;
  78408. }
  78409. otherDim = seriesModel.getData().mapDimension(otherDim);
  78410. result = {
  78411. thisAxis: thisAxis,
  78412. series: seriesModel,
  78413. thisDim: dimNames.name,
  78414. otherDim: otherDim,
  78415. otherAxisInverse: otherAxisInverse
  78416. };
  78417. }, this);
  78418. }, this);
  78419. return result;
  78420. },
  78421. _renderHandle: function () {
  78422. var displaybles = this._displayables;
  78423. var handles = displaybles.handles = [];
  78424. var handleLabels = displaybles.handleLabels = [];
  78425. var barGroup = this._displayables.barGroup;
  78426. var size = this._size;
  78427. var dataZoomModel = this.dataZoomModel;
  78428. barGroup.add(displaybles.filler = new Rect$2({
  78429. draggable: true,
  78430. cursor: getCursor(this._orient),
  78431. drift: bind$5(this._onDragMove, this, 'all'),
  78432. ondragstart: bind$5(this._showDataInfo, this, true),
  78433. ondragend: bind$5(this._onDragEnd, this),
  78434. onmouseover: bind$5(this._showDataInfo, this, true),
  78435. onmouseout: bind$5(this._showDataInfo, this, false),
  78436. style: {
  78437. fill: dataZoomModel.get('fillerColor'),
  78438. textPosition: 'inside'
  78439. }
  78440. }));
  78441. // Frame border.
  78442. barGroup.add(new Rect$2({
  78443. silent: true,
  78444. subPixelOptimize: true,
  78445. shape: {
  78446. x: 0,
  78447. y: 0,
  78448. width: size[0],
  78449. height: size[1]
  78450. },
  78451. style: {
  78452. stroke: dataZoomModel.get('dataBackgroundColor')
  78453. || dataZoomModel.get('borderColor'),
  78454. lineWidth: DEFAULT_FRAME_BORDER_WIDTH,
  78455. fill: 'rgba(0,0,0,0)'
  78456. }
  78457. }));
  78458. each$26([0, 1], function (handleIndex) {
  78459. var path = createIcon(
  78460. dataZoomModel.get('handleIcon'),
  78461. {
  78462. cursor: getCursor(this._orient),
  78463. draggable: true,
  78464. drift: bind$5(this._onDragMove, this, handleIndex),
  78465. ondragend: bind$5(this._onDragEnd, this),
  78466. onmouseover: bind$5(this._showDataInfo, this, true),
  78467. onmouseout: bind$5(this._showDataInfo, this, false)
  78468. },
  78469. {x: -1, y: 0, width: 2, height: 2}
  78470. );
  78471. var bRect = path.getBoundingRect();
  78472. this._handleHeight = parsePercent$1(dataZoomModel.get('handleSize'), this._size[1]);
  78473. this._handleWidth = bRect.width / bRect.height * this._handleHeight;
  78474. path.setStyle(dataZoomModel.getModel('handleStyle').getItemStyle());
  78475. var handleColor = dataZoomModel.get('handleColor');
  78476. // Compatitable with previous version
  78477. if (handleColor != null) {
  78478. path.style.fill = handleColor;
  78479. }
  78480. barGroup.add(handles[handleIndex] = path);
  78481. var textStyleModel = dataZoomModel.textStyleModel;
  78482. this.group.add(
  78483. handleLabels[handleIndex] = new Text({
  78484. silent: true,
  78485. invisible: true,
  78486. style: {
  78487. x: 0, y: 0, text: '',
  78488. textVerticalAlign: 'middle',
  78489. textAlign: 'center',
  78490. textFill: textStyleModel.getTextColor(),
  78491. textFont: textStyleModel.getFont()
  78492. },
  78493. z2: 10
  78494. }));
  78495. }, this);
  78496. },
  78497. /**
  78498. * @private
  78499. */
  78500. _resetInterval: function () {
  78501. var range = this._range = this.dataZoomModel.getPercentRange();
  78502. var viewExtent = this._getViewExtent();
  78503. this._handleEnds = [
  78504. linearMap$1(range[0], [0, 100], viewExtent, true),
  78505. linearMap$1(range[1], [0, 100], viewExtent, true)
  78506. ];
  78507. },
  78508. /**
  78509. * @private
  78510. * @param {(number|string)} handleIndex 0 or 1 or 'all'
  78511. * @param {number} delta
  78512. * @return {boolean} changed
  78513. */
  78514. _updateInterval: function (handleIndex, delta) {
  78515. var dataZoomModel = this.dataZoomModel;
  78516. var handleEnds = this._handleEnds;
  78517. var viewExtend = this._getViewExtent();
  78518. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  78519. var percentExtent = [0, 100];
  78520. sliderMove(
  78521. delta,
  78522. handleEnds,
  78523. viewExtend,
  78524. dataZoomModel.get('zoomLock') ? 'all' : handleIndex,
  78525. minMaxSpan.minSpan != null
  78526. ? linearMap$1(minMaxSpan.minSpan, percentExtent, viewExtend, true) : null,
  78527. minMaxSpan.maxSpan != null
  78528. ? linearMap$1(minMaxSpan.maxSpan, percentExtent, viewExtend, true) : null
  78529. );
  78530. var lastRange = this._range;
  78531. var range = this._range = asc$2([
  78532. linearMap$1(handleEnds[0], viewExtend, percentExtent, true),
  78533. linearMap$1(handleEnds[1], viewExtend, percentExtent, true)
  78534. ]);
  78535. return !lastRange || lastRange[0] !== range[0] || lastRange[1] !== range[1];
  78536. },
  78537. /**
  78538. * @private
  78539. */
  78540. _updateView: function (nonRealtime) {
  78541. var displaybles = this._displayables;
  78542. var handleEnds = this._handleEnds;
  78543. var handleInterval = asc$2(handleEnds.slice());
  78544. var size = this._size;
  78545. each$26([0, 1], function (handleIndex) {
  78546. // Handles
  78547. var handle = displaybles.handles[handleIndex];
  78548. var handleHeight = this._handleHeight;
  78549. handle.attr({
  78550. scale: [handleHeight / 2, handleHeight / 2],
  78551. position: [handleEnds[handleIndex], size[1] / 2 - handleHeight / 2]
  78552. });
  78553. }, this);
  78554. // Filler
  78555. displaybles.filler.setShape({
  78556. x: handleInterval[0],
  78557. y: 0,
  78558. width: handleInterval[1] - handleInterval[0],
  78559. height: size[1]
  78560. });
  78561. this._updateDataInfo(nonRealtime);
  78562. },
  78563. /**
  78564. * @private
  78565. */
  78566. _updateDataInfo: function (nonRealtime) {
  78567. var dataZoomModel = this.dataZoomModel;
  78568. var displaybles = this._displayables;
  78569. var handleLabels = displaybles.handleLabels;
  78570. var orient = this._orient;
  78571. var labelTexts = ['', ''];
  78572. // FIXME
  78573. // date型,支持formatter,autoformatter(ec2 date.getAutoFormatter)
  78574. if (dataZoomModel.get('showDetail')) {
  78575. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  78576. if (axisProxy) {
  78577. var axis = axisProxy.getAxisModel().axis;
  78578. var range = this._range;
  78579. var dataInterval = nonRealtime
  78580. // See #4434, data and axis are not processed and reset yet in non-realtime mode.
  78581. ? axisProxy.calculateDataWindow({
  78582. start: range[0], end: range[1]
  78583. }).valueWindow
  78584. : axisProxy.getDataValueWindow();
  78585. labelTexts = [
  78586. this._formatLabel(dataInterval[0], axis),
  78587. this._formatLabel(dataInterval[1], axis)
  78588. ];
  78589. }
  78590. }
  78591. var orderedHandleEnds = asc$2(this._handleEnds.slice());
  78592. setLabel.call(this, 0);
  78593. setLabel.call(this, 1);
  78594. function setLabel(handleIndex) {
  78595. // Label
  78596. // Text should not transform by barGroup.
  78597. // Ignore handlers transform
  78598. var barTransform = getTransform(
  78599. displaybles.handles[handleIndex].parent, this.group
  78600. );
  78601. var direction = transformDirection(
  78602. handleIndex === 0 ? 'right' : 'left', barTransform
  78603. );
  78604. var offset = this._handleWidth / 2 + LABEL_GAP;
  78605. var textPoint = applyTransform$1(
  78606. [
  78607. orderedHandleEnds[handleIndex] + (handleIndex === 0 ? -offset : offset),
  78608. this._size[1] / 2
  78609. ],
  78610. barTransform
  78611. );
  78612. handleLabels[handleIndex].setStyle({
  78613. x: textPoint[0],
  78614. y: textPoint[1],
  78615. textVerticalAlign: orient === HORIZONTAL ? 'middle' : direction,
  78616. textAlign: orient === HORIZONTAL ? direction : 'center',
  78617. text: labelTexts[handleIndex]
  78618. });
  78619. }
  78620. },
  78621. /**
  78622. * @private
  78623. */
  78624. _formatLabel: function (value, axis) {
  78625. var dataZoomModel = this.dataZoomModel;
  78626. var labelFormatter = dataZoomModel.get('labelFormatter');
  78627. var labelPrecision = dataZoomModel.get('labelPrecision');
  78628. if (labelPrecision == null || labelPrecision === 'auto') {
  78629. labelPrecision = axis.getPixelPrecision();
  78630. }
  78631. var valueStr = (value == null || isNaN(value))
  78632. ? ''
  78633. // FIXME Glue code
  78634. : (axis.type === 'category' || axis.type === 'time')
  78635. ? axis.scale.getLabel(Math.round(value))
  78636. // param of toFixed should less then 20.
  78637. : value.toFixed(Math.min(labelPrecision, 20));
  78638. return isFunction$1(labelFormatter)
  78639. ? labelFormatter(value, valueStr)
  78640. : isString(labelFormatter)
  78641. ? labelFormatter.replace('{value}', valueStr)
  78642. : valueStr;
  78643. },
  78644. /**
  78645. * @private
  78646. * @param {boolean} showOrHide true: show, false: hide
  78647. */
  78648. _showDataInfo: function (showOrHide) {
  78649. // Always show when drgging.
  78650. showOrHide = this._dragging || showOrHide;
  78651. var handleLabels = this._displayables.handleLabels;
  78652. handleLabels[0].attr('invisible', !showOrHide);
  78653. handleLabels[1].attr('invisible', !showOrHide);
  78654. },
  78655. _onDragMove: function (handleIndex, dx, dy, event) {
  78656. this._dragging = true;
  78657. // For mobile device, prevent screen slider on the button.
  78658. stop(event.event);
  78659. // Transform dx, dy to bar coordination.
  78660. var barTransform = this._displayables.barGroup.getLocalTransform();
  78661. var vertex = applyTransform$1([dx, dy], barTransform, true);
  78662. var changed = this._updateInterval(handleIndex, vertex[0]);
  78663. var realtime = this.dataZoomModel.get('realtime');
  78664. this._updateView(!realtime);
  78665. // Avoid dispatch dataZoom repeatly but range not changed,
  78666. // which cause bad visual effect when progressive enabled.
  78667. changed && realtime && this._dispatchZoomAction();
  78668. },
  78669. _onDragEnd: function () {
  78670. this._dragging = false;
  78671. this._showDataInfo(false);
  78672. // While in realtime mode and stream mode, dispatch action when
  78673. // drag end will cause the whole view rerender, which is unnecessary.
  78674. var realtime = this.dataZoomModel.get('realtime');
  78675. !realtime && this._dispatchZoomAction();
  78676. },
  78677. _onClickPanelClick: function (e) {
  78678. var size = this._size;
  78679. var localPoint = this._displayables.barGroup.transformCoordToLocal(e.offsetX, e.offsetY);
  78680. if (localPoint[0] < 0 || localPoint[0] > size[0]
  78681. || localPoint[1] < 0 || localPoint[1] > size[1]
  78682. ) {
  78683. return;
  78684. }
  78685. var handleEnds = this._handleEnds;
  78686. var center = (handleEnds[0] + handleEnds[1]) / 2;
  78687. var changed = this._updateInterval('all', localPoint[0] - center);
  78688. this._updateView();
  78689. changed && this._dispatchZoomAction();
  78690. },
  78691. /**
  78692. * This action will be throttled.
  78693. * @private
  78694. */
  78695. _dispatchZoomAction: function () {
  78696. var range = this._range;
  78697. this.api.dispatchAction({
  78698. type: 'dataZoom',
  78699. from: this.uid,
  78700. dataZoomId: this.dataZoomModel.id,
  78701. start: range[0],
  78702. end: range[1]
  78703. });
  78704. },
  78705. /**
  78706. * @private
  78707. */
  78708. _findCoordRect: function () {
  78709. // Find the grid coresponding to the first axis referred by dataZoom.
  78710. var rect;
  78711. each$26(this.getTargetCoordInfo(), function (coordInfoList) {
  78712. if (!rect && coordInfoList.length) {
  78713. var coordSys = coordInfoList[0].model.coordinateSystem;
  78714. rect = coordSys.getRect && coordSys.getRect();
  78715. }
  78716. });
  78717. if (!rect) {
  78718. var width = this.api.getWidth();
  78719. var height = this.api.getHeight();
  78720. rect = {
  78721. x: width * 0.2,
  78722. y: height * 0.2,
  78723. width: width * 0.6,
  78724. height: height * 0.6
  78725. };
  78726. }
  78727. return rect;
  78728. }
  78729. });
  78730. function getOtherDim(thisDim) {
  78731. // FIXME
  78732. // 这个逻辑和getOtherAxis里一致,但是写在这里是否不好
  78733. var map$$1 = {x: 'y', y: 'x', radius: 'angle', angle: 'radius'};
  78734. return map$$1[thisDim];
  78735. }
  78736. function getCursor(orient) {
  78737. return orient === 'vertical' ? 'ns-resize' : 'ew-resize';
  78738. }
  78739. /*
  78740. * Licensed to the Apache Software Foundation (ASF) under one
  78741. * or more contributor license agreements. See the NOTICE file
  78742. * distributed with this work for additional information
  78743. * regarding copyright ownership. The ASF licenses this file
  78744. * to you under the Apache License, Version 2.0 (the
  78745. * "License"); you may not use this file except in compliance
  78746. * with the License. You may obtain a copy of the License at
  78747. *
  78748. * http://www.apache.org/licenses/LICENSE-2.0
  78749. *
  78750. * Unless required by applicable law or agreed to in writing,
  78751. * software distributed under the License is distributed on an
  78752. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  78753. * KIND, either express or implied. See the License for the
  78754. * specific language governing permissions and limitations
  78755. * under the License.
  78756. */
  78757. /*
  78758. * Licensed to the Apache Software Foundation (ASF) under one
  78759. * or more contributor license agreements. See the NOTICE file
  78760. * distributed with this work for additional information
  78761. * regarding copyright ownership. The ASF licenses this file
  78762. * to you under the Apache License, Version 2.0 (the
  78763. * "License"); you may not use this file except in compliance
  78764. * with the License. You may obtain a copy of the License at
  78765. *
  78766. * http://www.apache.org/licenses/LICENSE-2.0
  78767. *
  78768. * Unless required by applicable law or agreed to in writing,
  78769. * software distributed under the License is distributed on an
  78770. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  78771. * KIND, either express or implied. See the License for the
  78772. * specific language governing permissions and limitations
  78773. * under the License.
  78774. */
  78775. DataZoomModel.extend({
  78776. type: 'dataZoom.inside',
  78777. /**
  78778. * @protected
  78779. */
  78780. defaultOption: {
  78781. disabled: false, // Whether disable this inside zoom.
  78782. zoomLock: false, // Whether disable zoom but only pan.
  78783. zoomOnMouseWheel: true, // Can be: true / false / 'shift' / 'ctrl' / 'alt'.
  78784. moveOnMouseMove: true, // Can be: true / false / 'shift' / 'ctrl' / 'alt'.
  78785. moveOnMouseWheel: false, // Can be: true / false / 'shift' / 'ctrl' / 'alt'.
  78786. preventDefaultMouseMove: true
  78787. }
  78788. });
  78789. /*
  78790. * Licensed to the Apache Software Foundation (ASF) under one
  78791. * or more contributor license agreements. See the NOTICE file
  78792. * distributed with this work for additional information
  78793. * regarding copyright ownership. The ASF licenses this file
  78794. * to you under the Apache License, Version 2.0 (the
  78795. * "License"); you may not use this file except in compliance
  78796. * with the License. You may obtain a copy of the License at
  78797. *
  78798. * http://www.apache.org/licenses/LICENSE-2.0
  78799. *
  78800. * Unless required by applicable law or agreed to in writing,
  78801. * software distributed under the License is distributed on an
  78802. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  78803. * KIND, either express or implied. See the License for the
  78804. * specific language governing permissions and limitations
  78805. * under the License.
  78806. */
  78807. // Only create one roam controller for each coordinate system.
  78808. // one roam controller might be refered by two inside data zoom
  78809. // components (for example, one for x and one for y). When user
  78810. // pan or zoom, only dispatch one action for those data zoom
  78811. // components.
  78812. var ATTR$2 = '\0_ec_dataZoom_roams';
  78813. /**
  78814. * @public
  78815. * @param {module:echarts/ExtensionAPI} api
  78816. * @param {Object} dataZoomInfo
  78817. * @param {string} dataZoomInfo.coordId
  78818. * @param {Function} dataZoomInfo.containsPoint
  78819. * @param {Array.<string>} dataZoomInfo.allCoordIds
  78820. * @param {string} dataZoomInfo.dataZoomId
  78821. * @param {Object} dataZoomInfo.getRange
  78822. * @param {Function} dataZoomInfo.getRange.pan
  78823. * @param {Function} dataZoomInfo.getRange.zoom
  78824. * @param {Function} dataZoomInfo.getRange.scrollMove
  78825. * @param {boolean} dataZoomInfo.dataZoomModel
  78826. */
  78827. function register$2(api, dataZoomInfo) {
  78828. var store = giveStore$1(api);
  78829. var theDataZoomId = dataZoomInfo.dataZoomId;
  78830. var theCoordId = dataZoomInfo.coordId;
  78831. // Do clean when a dataZoom changes its target coordnate system.
  78832. // Avoid memory leak, dispose all not-used-registered.
  78833. each$1(store, function (record, coordId) {
  78834. var dataZoomInfos = record.dataZoomInfos;
  78835. if (dataZoomInfos[theDataZoomId]
  78836. && indexOf(dataZoomInfo.allCoordIds, theCoordId) < 0
  78837. ) {
  78838. delete dataZoomInfos[theDataZoomId];
  78839. record.count--;
  78840. }
  78841. });
  78842. cleanStore(store);
  78843. var record = store[theCoordId];
  78844. // Create if needed.
  78845. if (!record) {
  78846. record = store[theCoordId] = {
  78847. coordId: theCoordId,
  78848. dataZoomInfos: {},
  78849. count: 0
  78850. };
  78851. record.controller = createController(api, record);
  78852. record.dispatchAction = curry(dispatchAction$1, api);
  78853. }
  78854. // Update reference of dataZoom.
  78855. !(record.dataZoomInfos[theDataZoomId]) && record.count++;
  78856. record.dataZoomInfos[theDataZoomId] = dataZoomInfo;
  78857. var controllerParams = mergeControllerParams(record.dataZoomInfos);
  78858. record.controller.enable(controllerParams.controlType, controllerParams.opt);
  78859. // Consider resize, area should be always updated.
  78860. record.controller.setPointerChecker(dataZoomInfo.containsPoint);
  78861. // Update throttle.
  78862. createOrUpdate(
  78863. record,
  78864. 'dispatchAction',
  78865. dataZoomInfo.dataZoomModel.get('throttle', true),
  78866. 'fixRate'
  78867. );
  78868. }
  78869. /**
  78870. * @public
  78871. * @param {module:echarts/ExtensionAPI} api
  78872. * @param {string} dataZoomId
  78873. */
  78874. function unregister$1(api, dataZoomId) {
  78875. var store = giveStore$1(api);
  78876. each$1(store, function (record) {
  78877. record.controller.dispose();
  78878. var dataZoomInfos = record.dataZoomInfos;
  78879. if (dataZoomInfos[dataZoomId]) {
  78880. delete dataZoomInfos[dataZoomId];
  78881. record.count--;
  78882. }
  78883. });
  78884. cleanStore(store);
  78885. }
  78886. /**
  78887. * @public
  78888. */
  78889. function generateCoordId(coordModel) {
  78890. return coordModel.type + '\0_' + coordModel.id;
  78891. }
  78892. /**
  78893. * Key: coordId, value: {dataZoomInfos: [], count, controller}
  78894. * @type {Array.<Object>}
  78895. */
  78896. function giveStore$1(api) {
  78897. // Mount store on zrender instance, so that we do not
  78898. // need to worry about dispose.
  78899. var zr = api.getZr();
  78900. return zr[ATTR$2] || (zr[ATTR$2] = {});
  78901. }
  78902. function createController(api, newRecord) {
  78903. var controller = new RoamController(api.getZr());
  78904. each$1(['pan', 'zoom', 'scrollMove'], function (eventName) {
  78905. controller.on(eventName, function (event) {
  78906. var batch = [];
  78907. each$1(newRecord.dataZoomInfos, function (info) {
  78908. // Check whether the behaviors (zoomOnMouseWheel, moveOnMouseMove,
  78909. // moveOnMouseWheel, ...) enabled.
  78910. if (!event.isAvailableBehavior(info.dataZoomModel.option)) {
  78911. return;
  78912. }
  78913. var method = (info.getRange || {})[eventName];
  78914. var range = method && method(newRecord.controller, event);
  78915. !info.dataZoomModel.get('disabled', true) && range && batch.push({
  78916. dataZoomId: info.dataZoomId,
  78917. start: range[0],
  78918. end: range[1]
  78919. });
  78920. });
  78921. batch.length && newRecord.dispatchAction(batch);
  78922. });
  78923. });
  78924. return controller;
  78925. }
  78926. function cleanStore(store) {
  78927. each$1(store, function (record, coordId) {
  78928. if (!record.count) {
  78929. record.controller.dispose();
  78930. delete store[coordId];
  78931. }
  78932. });
  78933. }
  78934. /**
  78935. * This action will be throttled.
  78936. */
  78937. function dispatchAction$1(api, batch) {
  78938. api.dispatchAction({
  78939. type: 'dataZoom',
  78940. batch: batch
  78941. });
  78942. }
  78943. /**
  78944. * Merge roamController settings when multiple dataZooms share one roamController.
  78945. */
  78946. function mergeControllerParams(dataZoomInfos) {
  78947. var controlType;
  78948. // DO NOT use reserved word (true, false, undefined) as key literally. Even if encapsulated
  78949. // as string, it is probably revert to reserved word by compress tool. See #7411.
  78950. var prefix = 'type_';
  78951. var typePriority = {
  78952. 'type_true': 2,
  78953. 'type_move': 1,
  78954. 'type_false': 0,
  78955. 'type_undefined': -1
  78956. };
  78957. var preventDefaultMouseMove = true;
  78958. each$1(dataZoomInfos, function (dataZoomInfo) {
  78959. var dataZoomModel = dataZoomInfo.dataZoomModel;
  78960. var oneType = dataZoomModel.get('disabled', true)
  78961. ? false
  78962. : dataZoomModel.get('zoomLock', true)
  78963. ? 'move'
  78964. : true;
  78965. if (typePriority[prefix + oneType] > typePriority[prefix + controlType]) {
  78966. controlType = oneType;
  78967. }
  78968. // Prevent default move event by default. If one false, do not prevent. Otherwise
  78969. // users may be confused why it does not work when multiple insideZooms exist.
  78970. preventDefaultMouseMove &= dataZoomModel.get('preventDefaultMouseMove', true);
  78971. });
  78972. return {
  78973. controlType: controlType,
  78974. opt: {
  78975. // RoamController will enable all of these functionalities,
  78976. // and the final behavior is determined by its event listener
  78977. // provided by each inside zoom.
  78978. zoomOnMouseWheel: true,
  78979. moveOnMouseMove: true,
  78980. moveOnMouseWheel: true,
  78981. preventDefaultMouseMove: !!preventDefaultMouseMove
  78982. }
  78983. };
  78984. }
  78985. /*
  78986. * Licensed to the Apache Software Foundation (ASF) under one
  78987. * or more contributor license agreements. See the NOTICE file
  78988. * distributed with this work for additional information
  78989. * regarding copyright ownership. The ASF licenses this file
  78990. * to you under the Apache License, Version 2.0 (the
  78991. * "License"); you may not use this file except in compliance
  78992. * with the License. You may obtain a copy of the License at
  78993. *
  78994. * http://www.apache.org/licenses/LICENSE-2.0
  78995. *
  78996. * Unless required by applicable law or agreed to in writing,
  78997. * software distributed under the License is distributed on an
  78998. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  78999. * KIND, either express or implied. See the License for the
  79000. * specific language governing permissions and limitations
  79001. * under the License.
  79002. */
  79003. var bind$6 = bind;
  79004. var InsideZoomView = DataZoomView.extend({
  79005. type: 'dataZoom.inside',
  79006. /**
  79007. * @override
  79008. */
  79009. init: function (ecModel, api) {
  79010. /**
  79011. * 'throttle' is used in this.dispatchAction, so we save range
  79012. * to avoid missing some 'pan' info.
  79013. * @private
  79014. * @type {Array.<number>}
  79015. */
  79016. this._range;
  79017. },
  79018. /**
  79019. * @override
  79020. */
  79021. render: function (dataZoomModel, ecModel, api, payload) {
  79022. InsideZoomView.superApply(this, 'render', arguments);
  79023. // Hence the `throttle` util ensures to preserve command order,
  79024. // here simply updating range all the time will not cause missing
  79025. // any of the the roam change.
  79026. this._range = dataZoomModel.getPercentRange();
  79027. // Reset controllers.
  79028. each$1(this.getTargetCoordInfo(), function (coordInfoList, coordSysName) {
  79029. var allCoordIds = map(coordInfoList, function (coordInfo) {
  79030. return generateCoordId(coordInfo.model);
  79031. });
  79032. each$1(coordInfoList, function (coordInfo) {
  79033. var coordModel = coordInfo.model;
  79034. var getRange = {};
  79035. each$1(['pan', 'zoom', 'scrollMove'], function (eventName) {
  79036. getRange[eventName] = bind$6(roamHandlers[eventName], this, coordInfo, coordSysName);
  79037. }, this);
  79038. register$2(
  79039. api,
  79040. {
  79041. coordId: generateCoordId(coordModel),
  79042. allCoordIds: allCoordIds,
  79043. containsPoint: function (e, x, y) {
  79044. return coordModel.coordinateSystem.containPoint([x, y]);
  79045. },
  79046. dataZoomId: dataZoomModel.id,
  79047. dataZoomModel: dataZoomModel,
  79048. getRange: getRange
  79049. }
  79050. );
  79051. }, this);
  79052. }, this);
  79053. },
  79054. /**
  79055. * @override
  79056. */
  79057. dispose: function () {
  79058. unregister$1(this.api, this.dataZoomModel.id);
  79059. InsideZoomView.superApply(this, 'dispose', arguments);
  79060. this._range = null;
  79061. }
  79062. });
  79063. var roamHandlers = {
  79064. /**
  79065. * @this {module:echarts/component/dataZoom/InsideZoomView}
  79066. */
  79067. zoom: function (coordInfo, coordSysName, controller, e) {
  79068. var lastRange = this._range;
  79069. var range = lastRange.slice();
  79070. // Calculate transform by the first axis.
  79071. var axisModel = coordInfo.axisModels[0];
  79072. if (!axisModel) {
  79073. return;
  79074. }
  79075. var directionInfo = getDirectionInfo[coordSysName](
  79076. null, [e.originX, e.originY], axisModel, controller, coordInfo
  79077. );
  79078. var percentPoint = (
  79079. directionInfo.signal > 0
  79080. ? (directionInfo.pixelStart + directionInfo.pixelLength - directionInfo.pixel)
  79081. : (directionInfo.pixel - directionInfo.pixelStart)
  79082. ) / directionInfo.pixelLength * (range[1] - range[0]) + range[0];
  79083. var scale = Math.max(1 / e.scale, 0);
  79084. range[0] = (range[0] - percentPoint) * scale + percentPoint;
  79085. range[1] = (range[1] - percentPoint) * scale + percentPoint;
  79086. // Restrict range.
  79087. var minMaxSpan = this.dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  79088. sliderMove(0, range, [0, 100], 0, minMaxSpan.minSpan, minMaxSpan.maxSpan);
  79089. this._range = range;
  79090. if (lastRange[0] !== range[0] || lastRange[1] !== range[1]) {
  79091. return range;
  79092. }
  79093. },
  79094. /**
  79095. * @this {module:echarts/component/dataZoom/InsideZoomView}
  79096. */
  79097. pan: makeMover(function (range, axisModel, coordInfo, coordSysName, controller, e) {
  79098. var directionInfo = getDirectionInfo[coordSysName](
  79099. [e.oldX, e.oldY], [e.newX, e.newY], axisModel, controller, coordInfo
  79100. );
  79101. return directionInfo.signal
  79102. * (range[1] - range[0])
  79103. * directionInfo.pixel / directionInfo.pixelLength;
  79104. }),
  79105. /**
  79106. * @this {module:echarts/component/dataZoom/InsideZoomView}
  79107. */
  79108. scrollMove: makeMover(function (range, axisModel, coordInfo, coordSysName, controller, e) {
  79109. var directionInfo = getDirectionInfo[coordSysName](
  79110. [0, 0], [e.scrollDelta, e.scrollDelta], axisModel, controller, coordInfo
  79111. );
  79112. return directionInfo.signal * (range[1] - range[0]) * e.scrollDelta;
  79113. })
  79114. };
  79115. function makeMover(getPercentDelta) {
  79116. return function (coordInfo, coordSysName, controller, e) {
  79117. var lastRange = this._range;
  79118. var range = lastRange.slice();
  79119. // Calculate transform by the first axis.
  79120. var axisModel = coordInfo.axisModels[0];
  79121. if (!axisModel) {
  79122. return;
  79123. }
  79124. var percentDelta = getPercentDelta(
  79125. range, axisModel, coordInfo, coordSysName, controller, e
  79126. );
  79127. sliderMove(percentDelta, range, [0, 100], 'all');
  79128. this._range = range;
  79129. if (lastRange[0] !== range[0] || lastRange[1] !== range[1]) {
  79130. return range;
  79131. }
  79132. };
  79133. }
  79134. var getDirectionInfo = {
  79135. grid: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  79136. var axis = axisModel.axis;
  79137. var ret = {};
  79138. var rect = coordInfo.model.coordinateSystem.getRect();
  79139. oldPoint = oldPoint || [0, 0];
  79140. if (axis.dim === 'x') {
  79141. ret.pixel = newPoint[0] - oldPoint[0];
  79142. ret.pixelLength = rect.width;
  79143. ret.pixelStart = rect.x;
  79144. ret.signal = axis.inverse ? 1 : -1;
  79145. }
  79146. else { // axis.dim === 'y'
  79147. ret.pixel = newPoint[1] - oldPoint[1];
  79148. ret.pixelLength = rect.height;
  79149. ret.pixelStart = rect.y;
  79150. ret.signal = axis.inverse ? -1 : 1;
  79151. }
  79152. return ret;
  79153. },
  79154. polar: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  79155. var axis = axisModel.axis;
  79156. var ret = {};
  79157. var polar = coordInfo.model.coordinateSystem;
  79158. var radiusExtent = polar.getRadiusAxis().getExtent();
  79159. var angleExtent = polar.getAngleAxis().getExtent();
  79160. oldPoint = oldPoint ? polar.pointToCoord(oldPoint) : [0, 0];
  79161. newPoint = polar.pointToCoord(newPoint);
  79162. if (axisModel.mainType === 'radiusAxis') {
  79163. ret.pixel = newPoint[0] - oldPoint[0];
  79164. // ret.pixelLength = Math.abs(radiusExtent[1] - radiusExtent[0]);
  79165. // ret.pixelStart = Math.min(radiusExtent[0], radiusExtent[1]);
  79166. ret.pixelLength = radiusExtent[1] - radiusExtent[0];
  79167. ret.pixelStart = radiusExtent[0];
  79168. ret.signal = axis.inverse ? 1 : -1;
  79169. }
  79170. else { // 'angleAxis'
  79171. ret.pixel = newPoint[1] - oldPoint[1];
  79172. // ret.pixelLength = Math.abs(angleExtent[1] - angleExtent[0]);
  79173. // ret.pixelStart = Math.min(angleExtent[0], angleExtent[1]);
  79174. ret.pixelLength = angleExtent[1] - angleExtent[0];
  79175. ret.pixelStart = angleExtent[0];
  79176. ret.signal = axis.inverse ? -1 : 1;
  79177. }
  79178. return ret;
  79179. },
  79180. singleAxis: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  79181. var axis = axisModel.axis;
  79182. var rect = coordInfo.model.coordinateSystem.getRect();
  79183. var ret = {};
  79184. oldPoint = oldPoint || [0, 0];
  79185. if (axis.orient === 'horizontal') {
  79186. ret.pixel = newPoint[0] - oldPoint[0];
  79187. ret.pixelLength = rect.width;
  79188. ret.pixelStart = rect.x;
  79189. ret.signal = axis.inverse ? 1 : -1;
  79190. }
  79191. else { // 'vertical'
  79192. ret.pixel = newPoint[1] - oldPoint[1];
  79193. ret.pixelLength = rect.height;
  79194. ret.pixelStart = rect.y;
  79195. ret.signal = axis.inverse ? -1 : 1;
  79196. }
  79197. return ret;
  79198. }
  79199. };
  79200. /*
  79201. * Licensed to the Apache Software Foundation (ASF) under one
  79202. * or more contributor license agreements. See the NOTICE file
  79203. * distributed with this work for additional information
  79204. * regarding copyright ownership. The ASF licenses this file
  79205. * to you under the Apache License, Version 2.0 (the
  79206. * "License"); you may not use this file except in compliance
  79207. * with the License. You may obtain a copy of the License at
  79208. *
  79209. * http://www.apache.org/licenses/LICENSE-2.0
  79210. *
  79211. * Unless required by applicable law or agreed to in writing,
  79212. * software distributed under the License is distributed on an
  79213. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  79214. * KIND, either express or implied. See the License for the
  79215. * specific language governing permissions and limitations
  79216. * under the License.
  79217. */
  79218. /*
  79219. * Licensed to the Apache Software Foundation (ASF) under one
  79220. * or more contributor license agreements. See the NOTICE file
  79221. * distributed with this work for additional information
  79222. * regarding copyright ownership. The ASF licenses this file
  79223. * to you under the Apache License, Version 2.0 (the
  79224. * "License"); you may not use this file except in compliance
  79225. * with the License. You may obtain a copy of the License at
  79226. *
  79227. * http://www.apache.org/licenses/LICENSE-2.0
  79228. *
  79229. * Unless required by applicable law or agreed to in writing,
  79230. * software distributed under the License is distributed on an
  79231. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  79232. * KIND, either express or implied. See the License for the
  79233. * specific language governing permissions and limitations
  79234. * under the License.
  79235. */
  79236. // Do not include './dataZoomSelect',
  79237. // since it only work for toolbox dataZoom.
  79238. /*
  79239. * Licensed to the Apache Software Foundation (ASF) under one
  79240. * or more contributor license agreements. See the NOTICE file
  79241. * distributed with this work for additional information
  79242. * regarding copyright ownership. The ASF licenses this file
  79243. * to you under the Apache License, Version 2.0 (the
  79244. * "License"); you may not use this file except in compliance
  79245. * with the License. You may obtain a copy of the License at
  79246. *
  79247. * http://www.apache.org/licenses/LICENSE-2.0
  79248. *
  79249. * Unless required by applicable law or agreed to in writing,
  79250. * software distributed under the License is distributed on an
  79251. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  79252. * KIND, either express or implied. See the License for the
  79253. * specific language governing permissions and limitations
  79254. * under the License.
  79255. */
  79256. var each$27 = each$1;
  79257. var preprocessor$3 = function (option) {
  79258. var visualMap = option && option.visualMap;
  79259. if (!isArray(visualMap)) {
  79260. visualMap = visualMap ? [visualMap] : [];
  79261. }
  79262. each$27(visualMap, function (opt) {
  79263. if (!opt) {
  79264. return;
  79265. }
  79266. // rename splitList to pieces
  79267. if (has$2(opt, 'splitList') && !has$2(opt, 'pieces')) {
  79268. opt.pieces = opt.splitList;
  79269. delete opt.splitList;
  79270. }
  79271. var pieces = opt.pieces;
  79272. if (pieces && isArray(pieces)) {
  79273. each$27(pieces, function (piece) {
  79274. if (isObject$1(piece)) {
  79275. if (has$2(piece, 'start') && !has$2(piece, 'min')) {
  79276. piece.min = piece.start;
  79277. }
  79278. if (has$2(piece, 'end') && !has$2(piece, 'max')) {
  79279. piece.max = piece.end;
  79280. }
  79281. }
  79282. });
  79283. }
  79284. });
  79285. };
  79286. function has$2(obj, name) {
  79287. return obj && obj.hasOwnProperty && obj.hasOwnProperty(name);
  79288. }
  79289. /*
  79290. * Licensed to the Apache Software Foundation (ASF) under one
  79291. * or more contributor license agreements. See the NOTICE file
  79292. * distributed with this work for additional information
  79293. * regarding copyright ownership. The ASF licenses this file
  79294. * to you under the Apache License, Version 2.0 (the
  79295. * "License"); you may not use this file except in compliance
  79296. * with the License. You may obtain a copy of the License at
  79297. *
  79298. * http://www.apache.org/licenses/LICENSE-2.0
  79299. *
  79300. * Unless required by applicable law or agreed to in writing,
  79301. * software distributed under the License is distributed on an
  79302. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  79303. * KIND, either express or implied. See the License for the
  79304. * specific language governing permissions and limitations
  79305. * under the License.
  79306. */
  79307. ComponentModel.registerSubTypeDefaulter('visualMap', function (option) {
  79308. // Compatible with ec2, when splitNumber === 0, continuous visualMap will be used.
  79309. return (
  79310. !option.categories
  79311. && (
  79312. !(
  79313. option.pieces
  79314. ? option.pieces.length > 0
  79315. : option.splitNumber > 0
  79316. )
  79317. || option.calculable
  79318. )
  79319. )
  79320. ? 'continuous' : 'piecewise';
  79321. });
  79322. /*
  79323. * Licensed to the Apache Software Foundation (ASF) under one
  79324. * or more contributor license agreements. See the NOTICE file
  79325. * distributed with this work for additional information
  79326. * regarding copyright ownership. The ASF licenses this file
  79327. * to you under the Apache License, Version 2.0 (the
  79328. * "License"); you may not use this file except in compliance
  79329. * with the License. You may obtain a copy of the License at
  79330. *
  79331. * http://www.apache.org/licenses/LICENSE-2.0
  79332. *
  79333. * Unless required by applicable law or agreed to in writing,
  79334. * software distributed under the License is distributed on an
  79335. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  79336. * KIND, either express or implied. See the License for the
  79337. * specific language governing permissions and limitations
  79338. * under the License.
  79339. */
  79340. var VISUAL_PRIORITY = PRIORITY.VISUAL.COMPONENT;
  79341. registerVisual(VISUAL_PRIORITY, {
  79342. createOnAllSeries: true,
  79343. reset: function (seriesModel, ecModel) {
  79344. var resetDefines = [];
  79345. ecModel.eachComponent('visualMap', function (visualMapModel) {
  79346. var pipelineContext = seriesModel.pipelineContext;
  79347. if (!visualMapModel.isTargetSeries(seriesModel)
  79348. || (pipelineContext && pipelineContext.large)
  79349. ) {
  79350. return;
  79351. }
  79352. resetDefines.push(incrementalApplyVisual(
  79353. visualMapModel.stateList,
  79354. visualMapModel.targetVisuals,
  79355. bind(visualMapModel.getValueState, visualMapModel),
  79356. visualMapModel.getDataDimension(seriesModel.getData())
  79357. ));
  79358. });
  79359. return resetDefines;
  79360. }
  79361. });
  79362. // Only support color.
  79363. registerVisual(VISUAL_PRIORITY, {
  79364. createOnAllSeries: true,
  79365. reset: function (seriesModel, ecModel) {
  79366. var data = seriesModel.getData();
  79367. var visualMetaList = [];
  79368. ecModel.eachComponent('visualMap', function (visualMapModel) {
  79369. if (visualMapModel.isTargetSeries(seriesModel)) {
  79370. var visualMeta = visualMapModel.getVisualMeta(
  79371. bind(getColorVisual, null, seriesModel, visualMapModel)
  79372. ) || {stops: [], outerColors: []};
  79373. var concreteDim = visualMapModel.getDataDimension(data);
  79374. var dimInfo = data.getDimensionInfo(concreteDim);
  79375. if (dimInfo != null) {
  79376. // visualMeta.dimension should be dimension index, but not concrete dimension.
  79377. visualMeta.dimension = dimInfo.index;
  79378. visualMetaList.push(visualMeta);
  79379. }
  79380. }
  79381. });
  79382. // console.log(JSON.stringify(visualMetaList.map(a => a.stops)));
  79383. seriesModel.getData().setVisual('visualMeta', visualMetaList);
  79384. }
  79385. });
  79386. // FIXME
  79387. // performance and export for heatmap?
  79388. // value can be Infinity or -Infinity
  79389. function getColorVisual(seriesModel, visualMapModel, value, valueState) {
  79390. var mappings = visualMapModel.targetVisuals[valueState];
  79391. var visualTypes = VisualMapping.prepareVisualTypes(mappings);
  79392. var resultVisual = {
  79393. color: seriesModel.getData().getVisual('color') // default color.
  79394. };
  79395. for (var i = 0, len = visualTypes.length; i < len; i++) {
  79396. var type = visualTypes[i];
  79397. var mapping = mappings[
  79398. type === 'opacity' ? '__alphaForOpacity' : type
  79399. ];
  79400. mapping && mapping.applyVisual(value, getVisual, setVisual);
  79401. }
  79402. return resultVisual.color;
  79403. function getVisual(key) {
  79404. return resultVisual[key];
  79405. }
  79406. function setVisual(key, value) {
  79407. resultVisual[key] = value;
  79408. }
  79409. }
  79410. /*
  79411. * Licensed to the Apache Software Foundation (ASF) under one
  79412. * or more contributor license agreements. See the NOTICE file
  79413. * distributed with this work for additional information
  79414. * regarding copyright ownership. The ASF licenses this file
  79415. * to you under the Apache License, Version 2.0 (the
  79416. * "License"); you may not use this file except in compliance
  79417. * with the License. You may obtain a copy of the License at
  79418. *
  79419. * http://www.apache.org/licenses/LICENSE-2.0
  79420. *
  79421. * Unless required by applicable law or agreed to in writing,
  79422. * software distributed under the License is distributed on an
  79423. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  79424. * KIND, either express or implied. See the License for the
  79425. * specific language governing permissions and limitations
  79426. * under the License.
  79427. */
  79428. /**
  79429. * @file Visual mapping.
  79430. */
  79431. var visualDefault = {
  79432. /**
  79433. * @public
  79434. */
  79435. get: function (visualType, key, isCategory) {
  79436. var value = clone(
  79437. (defaultOption$3[visualType] || {})[key]
  79438. );
  79439. return isCategory
  79440. ? (isArray(value) ? value[value.length - 1] : value)
  79441. : value;
  79442. }
  79443. };
  79444. var defaultOption$3 = {
  79445. color: {
  79446. active: ['#006edd', '#e0ffff'],
  79447. inactive: ['rgba(0,0,0,0)']
  79448. },
  79449. colorHue: {
  79450. active: [0, 360],
  79451. inactive: [0, 0]
  79452. },
  79453. colorSaturation: {
  79454. active: [0.3, 1],
  79455. inactive: [0, 0]
  79456. },
  79457. colorLightness: {
  79458. active: [0.9, 0.5],
  79459. inactive: [0, 0]
  79460. },
  79461. colorAlpha: {
  79462. active: [0.3, 1],
  79463. inactive: [0, 0]
  79464. },
  79465. opacity: {
  79466. active: [0.3, 1],
  79467. inactive: [0, 0]
  79468. },
  79469. symbol: {
  79470. active: ['circle', 'roundRect', 'diamond'],
  79471. inactive: ['none']
  79472. },
  79473. symbolSize: {
  79474. active: [10, 50],
  79475. inactive: [0, 0]
  79476. }
  79477. };
  79478. /*
  79479. * Licensed to the Apache Software Foundation (ASF) under one
  79480. * or more contributor license agreements. See the NOTICE file
  79481. * distributed with this work for additional information
  79482. * regarding copyright ownership. The ASF licenses this file
  79483. * to you under the Apache License, Version 2.0 (the
  79484. * "License"); you may not use this file except in compliance
  79485. * with the License. You may obtain a copy of the License at
  79486. *
  79487. * http://www.apache.org/licenses/LICENSE-2.0
  79488. *
  79489. * Unless required by applicable law or agreed to in writing,
  79490. * software distributed under the License is distributed on an
  79491. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  79492. * KIND, either express or implied. See the License for the
  79493. * specific language governing permissions and limitations
  79494. * under the License.
  79495. */
  79496. var mapVisual$2 = VisualMapping.mapVisual;
  79497. var eachVisual = VisualMapping.eachVisual;
  79498. var isArray$3 = isArray;
  79499. var each$28 = each$1;
  79500. var asc$3 = asc;
  79501. var linearMap$2 = linearMap;
  79502. var noop$2 = noop;
  79503. var VisualMapModel = extendComponentModel({
  79504. type: 'visualMap',
  79505. dependencies: ['series'],
  79506. /**
  79507. * @readOnly
  79508. * @type {Array.<string>}
  79509. */
  79510. stateList: ['inRange', 'outOfRange'],
  79511. /**
  79512. * @readOnly
  79513. * @type {Array.<string>}
  79514. */
  79515. replacableOptionKeys: [
  79516. 'inRange', 'outOfRange', 'target', 'controller', 'color'
  79517. ],
  79518. /**
  79519. * [lowerBound, upperBound]
  79520. *
  79521. * @readOnly
  79522. * @type {Array.<number>}
  79523. */
  79524. dataBound: [-Infinity, Infinity],
  79525. /**
  79526. * @readOnly
  79527. * @type {string|Object}
  79528. */
  79529. layoutMode: {type: 'box', ignoreSize: true},
  79530. /**
  79531. * @protected
  79532. */
  79533. defaultOption: {
  79534. show: true,
  79535. zlevel: 0,
  79536. z: 4,
  79537. seriesIndex: 'all', // 'all' or null/undefined: all series.
  79538. // A number or an array of number: the specified series.
  79539. // set min: 0, max: 200, only for campatible with ec2.
  79540. // In fact min max should not have default value.
  79541. min: 0, // min value, must specified if pieces is not specified.
  79542. max: 200, // max value, must specified if pieces is not specified.
  79543. dimension: null,
  79544. inRange: null, // 'color', 'colorHue', 'colorSaturation', 'colorLightness', 'colorAlpha',
  79545. // 'symbol', 'symbolSize'
  79546. outOfRange: null, // 'color', 'colorHue', 'colorSaturation',
  79547. // 'colorLightness', 'colorAlpha',
  79548. // 'symbol', 'symbolSize'
  79549. left: 0, // 'center' ¦ 'left' ¦ 'right' ¦ {number} (px)
  79550. right: null, // The same as left.
  79551. top: null, // 'top' ¦ 'bottom' ¦ 'center' ¦ {number} (px)
  79552. bottom: 0, // The same as top.
  79553. itemWidth: null,
  79554. itemHeight: null,
  79555. inverse: false,
  79556. orient: 'vertical', // 'horizontal' ¦ 'vertical'
  79557. backgroundColor: 'rgba(0,0,0,0)',
  79558. borderColor: '#ccc', // 值域边框颜色
  79559. contentColor: '#5793f3',
  79560. inactiveColor: '#aaa',
  79561. borderWidth: 0, // 值域边框线宽,单位px,默认为0(无边框)
  79562. padding: 5, // 值域内边距,单位px,默认各方向内边距为5,
  79563. // 接受数组分别设定上右下左边距,同css
  79564. textGap: 10, //
  79565. precision: 0, // 小数精度,默认为0,无小数点
  79566. color: null, //颜色(deprecated,兼容ec2,顺序同pieces,不同于inRange/outOfRange)
  79567. formatter: null,
  79568. text: null, // 文本,如['高', '低'],兼容ec2,text[0]对应高值,text[1]对应低值
  79569. textStyle: {
  79570. color: '#333' // 值域文字颜色
  79571. }
  79572. },
  79573. /**
  79574. * @protected
  79575. */
  79576. init: function (option, parentModel, ecModel) {
  79577. /**
  79578. * @private
  79579. * @type {Array.<number>}
  79580. */
  79581. this._dataExtent;
  79582. /**
  79583. * @readOnly
  79584. */
  79585. this.targetVisuals = {};
  79586. /**
  79587. * @readOnly
  79588. */
  79589. this.controllerVisuals = {};
  79590. /**
  79591. * @readOnly
  79592. */
  79593. this.textStyleModel;
  79594. /**
  79595. * [width, height]
  79596. * @readOnly
  79597. * @type {Array.<number>}
  79598. */
  79599. this.itemSize;
  79600. this.mergeDefaultAndTheme(option, ecModel);
  79601. },
  79602. /**
  79603. * @protected
  79604. */
  79605. optionUpdated: function (newOption, isInit) {
  79606. var thisOption = this.option;
  79607. // FIXME
  79608. // necessary?
  79609. // Disable realtime view update if canvas is not supported.
  79610. if (!env$1.canvasSupported) {
  79611. thisOption.realtime = false;
  79612. }
  79613. !isInit && replaceVisualOption(
  79614. thisOption, newOption, this.replacableOptionKeys
  79615. );
  79616. this.textStyleModel = this.getModel('textStyle');
  79617. this.resetItemSize();
  79618. this.completeVisualOption();
  79619. },
  79620. /**
  79621. * @protected
  79622. */
  79623. resetVisual: function (supplementVisualOption) {
  79624. var stateList = this.stateList;
  79625. supplementVisualOption = bind(supplementVisualOption, this);
  79626. this.controllerVisuals = createVisualMappings(
  79627. this.option.controller, stateList, supplementVisualOption
  79628. );
  79629. this.targetVisuals = createVisualMappings(
  79630. this.option.target, stateList, supplementVisualOption
  79631. );
  79632. },
  79633. /**
  79634. * @protected
  79635. * @return {Array.<number>} An array of series indices.
  79636. */
  79637. getTargetSeriesIndices: function () {
  79638. var optionSeriesIndex = this.option.seriesIndex;
  79639. var seriesIndices = [];
  79640. if (optionSeriesIndex == null || optionSeriesIndex === 'all') {
  79641. this.ecModel.eachSeries(function (seriesModel, index) {
  79642. seriesIndices.push(index);
  79643. });
  79644. }
  79645. else {
  79646. seriesIndices = normalizeToArray(optionSeriesIndex);
  79647. }
  79648. return seriesIndices;
  79649. },
  79650. /**
  79651. * @public
  79652. */
  79653. eachTargetSeries: function (callback, context) {
  79654. each$1(this.getTargetSeriesIndices(), function (seriesIndex) {
  79655. callback.call(context, this.ecModel.getSeriesByIndex(seriesIndex));
  79656. }, this);
  79657. },
  79658. /**
  79659. * @pubilc
  79660. */
  79661. isTargetSeries: function (seriesModel) {
  79662. var is = false;
  79663. this.eachTargetSeries(function (model) {
  79664. model === seriesModel && (is = true);
  79665. });
  79666. return is;
  79667. },
  79668. /**
  79669. * @example
  79670. * this.formatValueText(someVal); // format single numeric value to text.
  79671. * this.formatValueText(someVal, true); // format single category value to text.
  79672. * this.formatValueText([min, max]); // format numeric min-max to text.
  79673. * this.formatValueText([this.dataBound[0], max]); // using data lower bound.
  79674. * this.formatValueText([min, this.dataBound[1]]); // using data upper bound.
  79675. *
  79676. * @param {number|Array.<number>} value Real value, or this.dataBound[0 or 1].
  79677. * @param {boolean} [isCategory=false] Only available when value is number.
  79678. * @param {Array.<string>} edgeSymbols Open-close symbol when value is interval.
  79679. * @return {string}
  79680. * @protected
  79681. */
  79682. formatValueText: function (value, isCategory, edgeSymbols) {
  79683. var option = this.option;
  79684. var precision = option.precision;
  79685. var dataBound = this.dataBound;
  79686. var formatter = option.formatter;
  79687. var isMinMax;
  79688. var textValue;
  79689. edgeSymbols = edgeSymbols || ['<', '>'];
  79690. if (isArray(value)) {
  79691. value = value.slice();
  79692. isMinMax = true;
  79693. }
  79694. textValue = isCategory
  79695. ? value
  79696. : (isMinMax
  79697. ? [toFixed(value[0]), toFixed(value[1])]
  79698. : toFixed(value)
  79699. );
  79700. if (isString(formatter)) {
  79701. return formatter
  79702. .replace('{value}', isMinMax ? textValue[0] : textValue)
  79703. .replace('{value2}', isMinMax ? textValue[1] : textValue);
  79704. }
  79705. else if (isFunction$1(formatter)) {
  79706. return isMinMax
  79707. ? formatter(value[0], value[1])
  79708. : formatter(value);
  79709. }
  79710. if (isMinMax) {
  79711. if (value[0] === dataBound[0]) {
  79712. return edgeSymbols[0] + ' ' + textValue[1];
  79713. }
  79714. else if (value[1] === dataBound[1]) {
  79715. return edgeSymbols[1] + ' ' + textValue[0];
  79716. }
  79717. else {
  79718. return textValue[0] + ' - ' + textValue[1];
  79719. }
  79720. }
  79721. else { // Format single value (includes category case).
  79722. return textValue;
  79723. }
  79724. function toFixed(val) {
  79725. return val === dataBound[0]
  79726. ? 'min'
  79727. : val === dataBound[1]
  79728. ? 'max'
  79729. : (+val).toFixed(Math.min(precision, 20));
  79730. }
  79731. },
  79732. /**
  79733. * @protected
  79734. */
  79735. resetExtent: function () {
  79736. var thisOption = this.option;
  79737. // Can not calculate data extent by data here.
  79738. // Because series and data may be modified in processing stage.
  79739. // So we do not support the feature "auto min/max".
  79740. var extent = asc$3([thisOption.min, thisOption.max]);
  79741. this._dataExtent = extent;
  79742. },
  79743. /**
  79744. * @public
  79745. * @param {module:echarts/data/List} list
  79746. * @return {string} Concrete dimention. If return null/undefined,
  79747. * no dimension used.
  79748. */
  79749. getDataDimension: function (list) {
  79750. var optDim = this.option.dimension;
  79751. var listDimensions = list.dimensions;
  79752. if (optDim == null && !listDimensions.length) {
  79753. return;
  79754. }
  79755. if (optDim != null) {
  79756. return list.getDimension(optDim);
  79757. }
  79758. var dimNames = list.dimensions;
  79759. for (var i = dimNames.length - 1; i >= 0; i--) {
  79760. var dimName = dimNames[i];
  79761. var dimInfo = list.getDimensionInfo(dimName);
  79762. if (!dimInfo.isCalculationCoord) {
  79763. return dimName;
  79764. }
  79765. }
  79766. },
  79767. /**
  79768. * @public
  79769. * @override
  79770. */
  79771. getExtent: function () {
  79772. return this._dataExtent.slice();
  79773. },
  79774. /**
  79775. * @protected
  79776. */
  79777. completeVisualOption: function () {
  79778. var ecModel = this.ecModel;
  79779. var thisOption = this.option;
  79780. var base = {inRange: thisOption.inRange, outOfRange: thisOption.outOfRange};
  79781. var target = thisOption.target || (thisOption.target = {});
  79782. var controller = thisOption.controller || (thisOption.controller = {});
  79783. merge(target, base); // Do not override
  79784. merge(controller, base); // Do not override
  79785. var isCategory = this.isCategory();
  79786. completeSingle.call(this, target);
  79787. completeSingle.call(this, controller);
  79788. completeInactive.call(this, target, 'inRange', 'outOfRange');
  79789. // completeInactive.call(this, target, 'outOfRange', 'inRange');
  79790. completeController.call(this, controller);
  79791. function completeSingle(base) {
  79792. // Compatible with ec2 dataRange.color.
  79793. // The mapping order of dataRange.color is: [high value, ..., low value]
  79794. // whereas inRange.color and outOfRange.color is [low value, ..., high value]
  79795. // Notice: ec2 has no inverse.
  79796. if (isArray$3(thisOption.color)
  79797. // If there has been inRange: {symbol: ...}, adding color is a mistake.
  79798. // So adding color only when no inRange defined.
  79799. && !base.inRange
  79800. ) {
  79801. base.inRange = {color: thisOption.color.slice().reverse()};
  79802. }
  79803. // Compatible with previous logic, always give a defautl color, otherwise
  79804. // simple config with no inRange and outOfRange will not work.
  79805. // Originally we use visualMap.color as the default color, but setOption at
  79806. // the second time the default color will be erased. So we change to use
  79807. // constant DEFAULT_COLOR.
  79808. // If user do not want the defualt color, set inRange: {color: null}.
  79809. base.inRange = base.inRange || {color: ecModel.get('gradientColor')};
  79810. // If using shortcut like: {inRange: 'symbol'}, complete default value.
  79811. each$28(this.stateList, function (state) {
  79812. var visualType = base[state];
  79813. if (isString(visualType)) {
  79814. var defa = visualDefault.get(visualType, 'active', isCategory);
  79815. if (defa) {
  79816. base[state] = {};
  79817. base[state][visualType] = defa;
  79818. }
  79819. else {
  79820. // Mark as not specified.
  79821. delete base[state];
  79822. }
  79823. }
  79824. }, this);
  79825. }
  79826. function completeInactive(base, stateExist, stateAbsent) {
  79827. var optExist = base[stateExist];
  79828. var optAbsent = base[stateAbsent];
  79829. if (optExist && !optAbsent) {
  79830. optAbsent = base[stateAbsent] = {};
  79831. each$28(optExist, function (visualData, visualType) {
  79832. if (!VisualMapping.isValidType(visualType)) {
  79833. return;
  79834. }
  79835. var defa = visualDefault.get(visualType, 'inactive', isCategory);
  79836. if (defa != null) {
  79837. optAbsent[visualType] = defa;
  79838. // Compatibable with ec2:
  79839. // Only inactive color to rgba(0,0,0,0) can not
  79840. // make label transparent, so use opacity also.
  79841. if (visualType === 'color'
  79842. && !optAbsent.hasOwnProperty('opacity')
  79843. && !optAbsent.hasOwnProperty('colorAlpha')
  79844. ) {
  79845. optAbsent.opacity = [0, 0];
  79846. }
  79847. }
  79848. });
  79849. }
  79850. }
  79851. function completeController(controller) {
  79852. var symbolExists = (controller.inRange || {}).symbol
  79853. || (controller.outOfRange || {}).symbol;
  79854. var symbolSizeExists = (controller.inRange || {}).symbolSize
  79855. || (controller.outOfRange || {}).symbolSize;
  79856. var inactiveColor = this.get('inactiveColor');
  79857. each$28(this.stateList, function (state) {
  79858. var itemSize = this.itemSize;
  79859. var visuals = controller[state];
  79860. // Set inactive color for controller if no other color
  79861. // attr (like colorAlpha) specified.
  79862. if (!visuals) {
  79863. visuals = controller[state] = {
  79864. color: isCategory ? inactiveColor : [inactiveColor]
  79865. };
  79866. }
  79867. // Consistent symbol and symbolSize if not specified.
  79868. if (visuals.symbol == null) {
  79869. visuals.symbol = symbolExists
  79870. && clone(symbolExists)
  79871. || (isCategory ? 'roundRect' : ['roundRect']);
  79872. }
  79873. if (visuals.symbolSize == null) {
  79874. visuals.symbolSize = symbolSizeExists
  79875. && clone(symbolSizeExists)
  79876. || (isCategory ? itemSize[0] : [itemSize[0], itemSize[0]]);
  79877. }
  79878. // Filter square and none.
  79879. visuals.symbol = mapVisual$2(visuals.symbol, function (symbol) {
  79880. return (symbol === 'none' || symbol === 'square') ? 'roundRect' : symbol;
  79881. });
  79882. // Normalize symbolSize
  79883. var symbolSize = visuals.symbolSize;
  79884. if (symbolSize != null) {
  79885. var max = -Infinity;
  79886. // symbolSize can be object when categories defined.
  79887. eachVisual(symbolSize, function (value) {
  79888. value > max && (max = value);
  79889. });
  79890. visuals.symbolSize = mapVisual$2(symbolSize, function (value) {
  79891. return linearMap$2(value, [0, max], [0, itemSize[0]], true);
  79892. });
  79893. }
  79894. }, this);
  79895. }
  79896. },
  79897. /**
  79898. * @protected
  79899. */
  79900. resetItemSize: function () {
  79901. this.itemSize = [
  79902. parseFloat(this.get('itemWidth')),
  79903. parseFloat(this.get('itemHeight'))
  79904. ];
  79905. },
  79906. /**
  79907. * @public
  79908. */
  79909. isCategory: function () {
  79910. return !!this.option.categories;
  79911. },
  79912. /**
  79913. * @public
  79914. * @abstract
  79915. */
  79916. setSelected: noop$2,
  79917. /**
  79918. * @public
  79919. * @abstract
  79920. * @param {*|module:echarts/data/List} valueOrData
  79921. * @param {number} dataIndex
  79922. * @return {string} state See this.stateList
  79923. */
  79924. getValueState: noop$2,
  79925. /**
  79926. * FIXME
  79927. * Do not publish to thirt-part-dev temporarily
  79928. * util the interface is stable. (Should it return
  79929. * a function but not visual meta?)
  79930. *
  79931. * @pubilc
  79932. * @abstract
  79933. * @param {Function} getColorVisual
  79934. * params: value, valueState
  79935. * return: color
  79936. * @return {Object} visualMeta
  79937. * should includes {stops, outerColors}
  79938. * outerColor means [colorBeyondMinValue, colorBeyondMaxValue]
  79939. */
  79940. getVisualMeta: noop$2
  79941. });
  79942. /*
  79943. * Licensed to the Apache Software Foundation (ASF) under one
  79944. * or more contributor license agreements. See the NOTICE file
  79945. * distributed with this work for additional information
  79946. * regarding copyright ownership. The ASF licenses this file
  79947. * to you under the Apache License, Version 2.0 (the
  79948. * "License"); you may not use this file except in compliance
  79949. * with the License. You may obtain a copy of the License at
  79950. *
  79951. * http://www.apache.org/licenses/LICENSE-2.0
  79952. *
  79953. * Unless required by applicable law or agreed to in writing,
  79954. * software distributed under the License is distributed on an
  79955. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  79956. * KIND, either express or implied. See the License for the
  79957. * specific language governing permissions and limitations
  79958. * under the License.
  79959. */
  79960. // Constant
  79961. var DEFAULT_BAR_BOUND = [20, 140];
  79962. var ContinuousModel = VisualMapModel.extend({
  79963. type: 'visualMap.continuous',
  79964. /**
  79965. * @protected
  79966. */
  79967. defaultOption: {
  79968. align: 'auto', // 'auto', 'left', 'right', 'top', 'bottom'
  79969. calculable: false, // This prop effect default component type determine,
  79970. // See echarts/component/visualMap/typeDefaulter.
  79971. range: null, // selected range. In default case `range` is [min, max]
  79972. // and can auto change along with modification of min max,
  79973. // util use specifid a range.
  79974. realtime: true, // Whether realtime update.
  79975. itemHeight: null, // The length of the range control edge.
  79976. itemWidth: null, // The length of the other side.
  79977. hoverLink: true, // Enable hover highlight.
  79978. hoverLinkDataSize: null, // The size of hovered data.
  79979. hoverLinkOnHandle: null // Whether trigger hoverLink when hover handle.
  79980. // If not specified, follow the value of `realtime`.
  79981. },
  79982. /**
  79983. * @override
  79984. */
  79985. optionUpdated: function (newOption, isInit) {
  79986. ContinuousModel.superApply(this, 'optionUpdated', arguments);
  79987. this.resetExtent();
  79988. this.resetVisual(function (mappingOption) {
  79989. mappingOption.mappingMethod = 'linear';
  79990. mappingOption.dataExtent = this.getExtent();
  79991. });
  79992. this._resetRange();
  79993. },
  79994. /**
  79995. * @protected
  79996. * @override
  79997. */
  79998. resetItemSize: function () {
  79999. ContinuousModel.superApply(this, 'resetItemSize', arguments);
  80000. var itemSize = this.itemSize;
  80001. this._orient === 'horizontal' && itemSize.reverse();
  80002. (itemSize[0] == null || isNaN(itemSize[0])) && (itemSize[0] = DEFAULT_BAR_BOUND[0]);
  80003. (itemSize[1] == null || isNaN(itemSize[1])) && (itemSize[1] = DEFAULT_BAR_BOUND[1]);
  80004. },
  80005. /**
  80006. * @private
  80007. */
  80008. _resetRange: function () {
  80009. var dataExtent = this.getExtent();
  80010. var range = this.option.range;
  80011. if (!range || range.auto) {
  80012. // `range` should always be array (so we dont use other
  80013. // value like 'auto') for user-friend. (consider getOption).
  80014. dataExtent.auto = 1;
  80015. this.option.range = dataExtent;
  80016. }
  80017. else if (isArray(range)) {
  80018. if (range[0] > range[1]) {
  80019. range.reverse();
  80020. }
  80021. range[0] = Math.max(range[0], dataExtent[0]);
  80022. range[1] = Math.min(range[1], dataExtent[1]);
  80023. }
  80024. },
  80025. /**
  80026. * @protected
  80027. * @override
  80028. */
  80029. completeVisualOption: function () {
  80030. VisualMapModel.prototype.completeVisualOption.apply(this, arguments);
  80031. each$1(this.stateList, function (state) {
  80032. var symbolSize = this.option.controller[state].symbolSize;
  80033. if (symbolSize && symbolSize[0] !== symbolSize[1]) {
  80034. symbolSize[0] = 0; // For good looking.
  80035. }
  80036. }, this);
  80037. },
  80038. /**
  80039. * @override
  80040. */
  80041. setSelected: function (selected) {
  80042. this.option.range = selected.slice();
  80043. this._resetRange();
  80044. },
  80045. /**
  80046. * @public
  80047. */
  80048. getSelected: function () {
  80049. var dataExtent = this.getExtent();
  80050. var dataInterval = asc(
  80051. (this.get('range') || []).slice()
  80052. );
  80053. // Clamp
  80054. dataInterval[0] > dataExtent[1] && (dataInterval[0] = dataExtent[1]);
  80055. dataInterval[1] > dataExtent[1] && (dataInterval[1] = dataExtent[1]);
  80056. dataInterval[0] < dataExtent[0] && (dataInterval[0] = dataExtent[0]);
  80057. dataInterval[1] < dataExtent[0] && (dataInterval[1] = dataExtent[0]);
  80058. return dataInterval;
  80059. },
  80060. /**
  80061. * @override
  80062. */
  80063. getValueState: function (value) {
  80064. var range = this.option.range;
  80065. var dataExtent = this.getExtent();
  80066. // When range[0] === dataExtent[0], any value larger than dataExtent[0] maps to 'inRange'.
  80067. // range[1] is processed likewise.
  80068. return (
  80069. (range[0] <= dataExtent[0] || range[0] <= value)
  80070. && (range[1] >= dataExtent[1] || value <= range[1])
  80071. ) ? 'inRange' : 'outOfRange';
  80072. },
  80073. /**
  80074. * @params {Array.<number>} range target value: range[0] <= value && value <= range[1]
  80075. * @return {Array.<Object>} [{seriesId, dataIndices: <Array.<number>>}, ...]
  80076. */
  80077. findTargetDataIndices: function (range) {
  80078. var result = [];
  80079. this.eachTargetSeries(function (seriesModel) {
  80080. var dataIndices = [];
  80081. var data = seriesModel.getData();
  80082. data.each(this.getDataDimension(data), function (value, dataIndex) {
  80083. range[0] <= value && value <= range[1] && dataIndices.push(dataIndex);
  80084. }, this);
  80085. result.push({seriesId: seriesModel.id, dataIndex: dataIndices});
  80086. }, this);
  80087. return result;
  80088. },
  80089. /**
  80090. * @implement
  80091. */
  80092. getVisualMeta: function (getColorVisual) {
  80093. var oVals = getColorStopValues(this, 'outOfRange', this.getExtent());
  80094. var iVals = getColorStopValues(this, 'inRange', this.option.range.slice());
  80095. var stops = [];
  80096. function setStop(value, valueState) {
  80097. stops.push({
  80098. value: value,
  80099. color: getColorVisual(value, valueState)
  80100. });
  80101. }
  80102. // Format to: outOfRange -- inRange -- outOfRange.
  80103. var iIdx = 0;
  80104. var oIdx = 0;
  80105. var iLen = iVals.length;
  80106. var oLen = oVals.length;
  80107. for (; oIdx < oLen && (!iVals.length || oVals[oIdx] <= iVals[0]); oIdx++) {
  80108. // If oVal[oIdx] === iVals[iIdx], oVal[oIdx] should be ignored.
  80109. if (oVals[oIdx] < iVals[iIdx]) {
  80110. setStop(oVals[oIdx], 'outOfRange');
  80111. }
  80112. }
  80113. for (var first = 1; iIdx < iLen; iIdx++, first = 0) {
  80114. // If range is full, value beyond min, max will be clamped.
  80115. // make a singularity
  80116. first && stops.length && setStop(iVals[iIdx], 'outOfRange');
  80117. setStop(iVals[iIdx], 'inRange');
  80118. }
  80119. for (var first = 1; oIdx < oLen; oIdx++) {
  80120. if (!iVals.length || iVals[iVals.length - 1] < oVals[oIdx]) {
  80121. // make a singularity
  80122. if (first) {
  80123. stops.length && setStop(stops[stops.length - 1].value, 'outOfRange');
  80124. first = 0;
  80125. }
  80126. setStop(oVals[oIdx], 'outOfRange');
  80127. }
  80128. }
  80129. var stopsLen = stops.length;
  80130. return {
  80131. stops: stops,
  80132. outerColors: [
  80133. stopsLen ? stops[0].color : 'transparent',
  80134. stopsLen ? stops[stopsLen - 1].color : 'transparent'
  80135. ]
  80136. };
  80137. }
  80138. });
  80139. function getColorStopValues(visualMapModel, valueState, dataExtent) {
  80140. if (dataExtent[0] === dataExtent[1]) {
  80141. return dataExtent.slice();
  80142. }
  80143. // When using colorHue mapping, it is not linear color any more.
  80144. // Moreover, canvas gradient seems not to be accurate linear.
  80145. // FIXME
  80146. // Should be arbitrary value 100? or based on pixel size?
  80147. var count = 200;
  80148. var step = (dataExtent[1] - dataExtent[0]) / count;
  80149. var value = dataExtent[0];
  80150. var stopValues = [];
  80151. for (var i = 0; i <= count && value < dataExtent[1]; i++) {
  80152. stopValues.push(value);
  80153. value += step;
  80154. }
  80155. stopValues.push(dataExtent[1]);
  80156. return stopValues;
  80157. }
  80158. /*
  80159. * Licensed to the Apache Software Foundation (ASF) under one
  80160. * or more contributor license agreements. See the NOTICE file
  80161. * distributed with this work for additional information
  80162. * regarding copyright ownership. The ASF licenses this file
  80163. * to you under the Apache License, Version 2.0 (the
  80164. * "License"); you may not use this file except in compliance
  80165. * with the License. You may obtain a copy of the License at
  80166. *
  80167. * http://www.apache.org/licenses/LICENSE-2.0
  80168. *
  80169. * Unless required by applicable law or agreed to in writing,
  80170. * software distributed under the License is distributed on an
  80171. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  80172. * KIND, either express or implied. See the License for the
  80173. * specific language governing permissions and limitations
  80174. * under the License.
  80175. */
  80176. var VisualMapView = extendComponentView({
  80177. type: 'visualMap',
  80178. /**
  80179. * @readOnly
  80180. * @type {Object}
  80181. */
  80182. autoPositionValues: {left: 1, right: 1, top: 1, bottom: 1},
  80183. init: function (ecModel, api) {
  80184. /**
  80185. * @readOnly
  80186. * @type {module:echarts/model/Global}
  80187. */
  80188. this.ecModel = ecModel;
  80189. /**
  80190. * @readOnly
  80191. * @type {module:echarts/ExtensionAPI}
  80192. */
  80193. this.api = api;
  80194. /**
  80195. * @readOnly
  80196. * @type {module:echarts/component/visualMap/visualMapModel}
  80197. */
  80198. this.visualMapModel;
  80199. },
  80200. /**
  80201. * @protected
  80202. */
  80203. render: function (visualMapModel, ecModel, api, payload) {
  80204. this.visualMapModel = visualMapModel;
  80205. if (visualMapModel.get('show') === false) {
  80206. this.group.removeAll();
  80207. return;
  80208. }
  80209. this.doRender.apply(this, arguments);
  80210. },
  80211. /**
  80212. * @protected
  80213. */
  80214. renderBackground: function (group) {
  80215. var visualMapModel = this.visualMapModel;
  80216. var padding = normalizeCssArray$1(visualMapModel.get('padding') || 0);
  80217. var rect = group.getBoundingRect();
  80218. group.add(new Rect({
  80219. z2: -1, // Lay background rect on the lowest layer.
  80220. silent: true,
  80221. shape: {
  80222. x: rect.x - padding[3],
  80223. y: rect.y - padding[0],
  80224. width: rect.width + padding[3] + padding[1],
  80225. height: rect.height + padding[0] + padding[2]
  80226. },
  80227. style: {
  80228. fill: visualMapModel.get('backgroundColor'),
  80229. stroke: visualMapModel.get('borderColor'),
  80230. lineWidth: visualMapModel.get('borderWidth')
  80231. }
  80232. }));
  80233. },
  80234. /**
  80235. * @protected
  80236. * @param {number} targetValue can be Infinity or -Infinity
  80237. * @param {string=} visualCluster Only can be 'color' 'opacity' 'symbol' 'symbolSize'
  80238. * @param {Object} [opts]
  80239. * @param {string=} [opts.forceState] Specify state, instead of using getValueState method.
  80240. * @param {string=} [opts.convertOpacityToAlpha=false] For color gradient in controller widget.
  80241. * @return {*} Visual value.
  80242. */
  80243. getControllerVisual: function (targetValue, visualCluster, opts) {
  80244. opts = opts || {};
  80245. var forceState = opts.forceState;
  80246. var visualMapModel = this.visualMapModel;
  80247. var visualObj = {};
  80248. // Default values.
  80249. if (visualCluster === 'symbol') {
  80250. visualObj.symbol = visualMapModel.get('itemSymbol');
  80251. }
  80252. if (visualCluster === 'color') {
  80253. var defaultColor = visualMapModel.get('contentColor');
  80254. visualObj.color = defaultColor;
  80255. }
  80256. function getter(key) {
  80257. return visualObj[key];
  80258. }
  80259. function setter(key, value) {
  80260. visualObj[key] = value;
  80261. }
  80262. var mappings = visualMapModel.controllerVisuals[
  80263. forceState || visualMapModel.getValueState(targetValue)
  80264. ];
  80265. var visualTypes = VisualMapping.prepareVisualTypes(mappings);
  80266. each$1(visualTypes, function (type) {
  80267. var visualMapping = mappings[type];
  80268. if (opts.convertOpacityToAlpha && type === 'opacity') {
  80269. type = 'colorAlpha';
  80270. visualMapping = mappings.__alphaForOpacity;
  80271. }
  80272. if (VisualMapping.dependsOn(type, visualCluster)) {
  80273. visualMapping && visualMapping.applyVisual(
  80274. targetValue, getter, setter
  80275. );
  80276. }
  80277. });
  80278. return visualObj[visualCluster];
  80279. },
  80280. /**
  80281. * @protected
  80282. */
  80283. positionGroup: function (group) {
  80284. var model = this.visualMapModel;
  80285. var api = this.api;
  80286. positionElement(
  80287. group,
  80288. model.getBoxLayoutParams(),
  80289. {width: api.getWidth(), height: api.getHeight()}
  80290. );
  80291. },
  80292. /**
  80293. * @protected
  80294. * @abstract
  80295. */
  80296. doRender: noop
  80297. });
  80298. /*
  80299. * Licensed to the Apache Software Foundation (ASF) under one
  80300. * or more contributor license agreements. See the NOTICE file
  80301. * distributed with this work for additional information
  80302. * regarding copyright ownership. The ASF licenses this file
  80303. * to you under the Apache License, Version 2.0 (the
  80304. * "License"); you may not use this file except in compliance
  80305. * with the License. You may obtain a copy of the License at
  80306. *
  80307. * http://www.apache.org/licenses/LICENSE-2.0
  80308. *
  80309. * Unless required by applicable law or agreed to in writing,
  80310. * software distributed under the License is distributed on an
  80311. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  80312. * KIND, either express or implied. See the License for the
  80313. * specific language governing permissions and limitations
  80314. * under the License.
  80315. */
  80316. /**
  80317. * @param {module:echarts/component/visualMap/VisualMapModel} visualMapModel\
  80318. * @param {module:echarts/ExtensionAPI} api
  80319. * @param {Array.<number>} itemSize always [short, long]
  80320. * @return {string} 'left' or 'right' or 'top' or 'bottom'
  80321. */
  80322. function getItemAlign(visualMapModel, api, itemSize) {
  80323. var modelOption = visualMapModel.option;
  80324. var itemAlign = modelOption.align;
  80325. if (itemAlign != null && itemAlign !== 'auto') {
  80326. return itemAlign;
  80327. }
  80328. // Auto decision align.
  80329. var ecSize = {width: api.getWidth(), height: api.getHeight()};
  80330. var realIndex = modelOption.orient === 'horizontal' ? 1 : 0;
  80331. var paramsSet = [
  80332. ['left', 'right', 'width'],
  80333. ['top', 'bottom', 'height']
  80334. ];
  80335. var reals = paramsSet[realIndex];
  80336. var fakeValue = [0, null, 10];
  80337. var layoutInput = {};
  80338. for (var i = 0; i < 3; i++) {
  80339. layoutInput[paramsSet[1 - realIndex][i]] = fakeValue[i];
  80340. layoutInput[reals[i]] = i === 2 ? itemSize[0] : modelOption[reals[i]];
  80341. }
  80342. var rParam = [['x', 'width', 3], ['y', 'height', 0]][realIndex];
  80343. var rect = getLayoutRect(layoutInput, ecSize, modelOption.padding);
  80344. return reals[
  80345. (rect.margin[rParam[2]] || 0) + rect[rParam[0]] + rect[rParam[1]] * 0.5
  80346. < ecSize[rParam[1]] * 0.5 ? 0 : 1
  80347. ];
  80348. }
  80349. /**
  80350. * Prepare dataIndex for outside usage, where dataIndex means rawIndex, and
  80351. * dataIndexInside means filtered index.
  80352. */
  80353. function makeHighDownBatch(batch, visualMapModel) {
  80354. each$1(batch || [], function (batchItem) {
  80355. if (batchItem.dataIndex != null) {
  80356. batchItem.dataIndexInside = batchItem.dataIndex;
  80357. batchItem.dataIndex = null;
  80358. }
  80359. batchItem.highlightKey = 'visualMap' + (visualMapModel ? visualMapModel.componentIndex : '');
  80360. });
  80361. return batch;
  80362. }
  80363. /*
  80364. * Licensed to the Apache Software Foundation (ASF) under one
  80365. * or more contributor license agreements. See the NOTICE file
  80366. * distributed with this work for additional information
  80367. * regarding copyright ownership. The ASF licenses this file
  80368. * to you under the Apache License, Version 2.0 (the
  80369. * "License"); you may not use this file except in compliance
  80370. * with the License. You may obtain a copy of the License at
  80371. *
  80372. * http://www.apache.org/licenses/LICENSE-2.0
  80373. *
  80374. * Unless required by applicable law or agreed to in writing,
  80375. * software distributed under the License is distributed on an
  80376. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  80377. * KIND, either express or implied. See the License for the
  80378. * specific language governing permissions and limitations
  80379. * under the License.
  80380. */
  80381. var linearMap$3 = linearMap;
  80382. var each$29 = each$1;
  80383. var mathMin$8 = Math.min;
  80384. var mathMax$8 = Math.max;
  80385. // Arbitrary value
  80386. var HOVER_LINK_SIZE = 12;
  80387. var HOVER_LINK_OUT = 6;
  80388. // Notice:
  80389. // Any "interval" should be by the order of [low, high].
  80390. // "handle0" (handleIndex === 0) maps to
  80391. // low data value: this._dataInterval[0] and has low coord.
  80392. // "handle1" (handleIndex === 1) maps to
  80393. // high data value: this._dataInterval[1] and has high coord.
  80394. // The logic of transform is implemented in this._createBarGroup.
  80395. var ContinuousView = VisualMapView.extend({
  80396. type: 'visualMap.continuous',
  80397. /**
  80398. * @override
  80399. */
  80400. init: function () {
  80401. ContinuousView.superApply(this, 'init', arguments);
  80402. /**
  80403. * @private
  80404. */
  80405. this._shapes = {};
  80406. /**
  80407. * @private
  80408. */
  80409. this._dataInterval = [];
  80410. /**
  80411. * @private
  80412. */
  80413. this._handleEnds = [];
  80414. /**
  80415. * @private
  80416. */
  80417. this._orient;
  80418. /**
  80419. * @private
  80420. */
  80421. this._useHandle;
  80422. /**
  80423. * @private
  80424. */
  80425. this._hoverLinkDataIndices = [];
  80426. /**
  80427. * @private
  80428. */
  80429. this._dragging;
  80430. /**
  80431. * @private
  80432. */
  80433. this._hovering;
  80434. },
  80435. /**
  80436. * @protected
  80437. * @override
  80438. */
  80439. doRender: function (visualMapModel, ecModel, api, payload) {
  80440. if (!payload || payload.type !== 'selectDataRange' || payload.from !== this.uid) {
  80441. this._buildView();
  80442. }
  80443. },
  80444. /**
  80445. * @private
  80446. */
  80447. _buildView: function () {
  80448. this.group.removeAll();
  80449. var visualMapModel = this.visualMapModel;
  80450. var thisGroup = this.group;
  80451. this._orient = visualMapModel.get('orient');
  80452. this._useHandle = visualMapModel.get('calculable');
  80453. this._resetInterval();
  80454. this._renderBar(thisGroup);
  80455. var dataRangeText = visualMapModel.get('text');
  80456. this._renderEndsText(thisGroup, dataRangeText, 0);
  80457. this._renderEndsText(thisGroup, dataRangeText, 1);
  80458. // Do this for background size calculation.
  80459. this._updateView(true);
  80460. // After updating view, inner shapes is built completely,
  80461. // and then background can be rendered.
  80462. this.renderBackground(thisGroup);
  80463. // Real update view
  80464. this._updateView();
  80465. this._enableHoverLinkToSeries();
  80466. this._enableHoverLinkFromSeries();
  80467. this.positionGroup(thisGroup);
  80468. },
  80469. /**
  80470. * @private
  80471. */
  80472. _renderEndsText: function (group, dataRangeText, endsIndex) {
  80473. if (!dataRangeText) {
  80474. return;
  80475. }
  80476. // Compatible with ec2, text[0] map to high value, text[1] map low value.
  80477. var text = dataRangeText[1 - endsIndex];
  80478. text = text != null ? text + '' : '';
  80479. var visualMapModel = this.visualMapModel;
  80480. var textGap = visualMapModel.get('textGap');
  80481. var itemSize = visualMapModel.itemSize;
  80482. var barGroup = this._shapes.barGroup;
  80483. var position = this._applyTransform(
  80484. [
  80485. itemSize[0] / 2,
  80486. endsIndex === 0 ? -textGap : itemSize[1] + textGap
  80487. ],
  80488. barGroup
  80489. );
  80490. var align = this._applyTransform(
  80491. endsIndex === 0 ? 'bottom' : 'top',
  80492. barGroup
  80493. );
  80494. var orient = this._orient;
  80495. var textStyleModel = this.visualMapModel.textStyleModel;
  80496. this.group.add(new Text({
  80497. style: {
  80498. x: position[0],
  80499. y: position[1],
  80500. textVerticalAlign: orient === 'horizontal' ? 'middle' : align,
  80501. textAlign: orient === 'horizontal' ? align : 'center',
  80502. text: text,
  80503. textFont: textStyleModel.getFont(),
  80504. textFill: textStyleModel.getTextColor()
  80505. }
  80506. }));
  80507. },
  80508. /**
  80509. * @private
  80510. */
  80511. _renderBar: function (targetGroup) {
  80512. var visualMapModel = this.visualMapModel;
  80513. var shapes = this._shapes;
  80514. var itemSize = visualMapModel.itemSize;
  80515. var orient = this._orient;
  80516. var useHandle = this._useHandle;
  80517. var itemAlign = getItemAlign(visualMapModel, this.api, itemSize);
  80518. var barGroup = shapes.barGroup = this._createBarGroup(itemAlign);
  80519. // Bar
  80520. barGroup.add(shapes.outOfRange = createPolygon());
  80521. barGroup.add(shapes.inRange = createPolygon(
  80522. null,
  80523. useHandle ? getCursor$1(this._orient) : null,
  80524. bind(this._dragHandle, this, 'all', false),
  80525. bind(this._dragHandle, this, 'all', true)
  80526. ));
  80527. var textRect = visualMapModel.textStyleModel.getTextRect('国');
  80528. var textSize = mathMax$8(textRect.width, textRect.height);
  80529. // Handle
  80530. if (useHandle) {
  80531. shapes.handleThumbs = [];
  80532. shapes.handleLabels = [];
  80533. shapes.handleLabelPoints = [];
  80534. this._createHandle(barGroup, 0, itemSize, textSize, orient, itemAlign);
  80535. this._createHandle(barGroup, 1, itemSize, textSize, orient, itemAlign);
  80536. }
  80537. this._createIndicator(barGroup, itemSize, textSize, orient);
  80538. targetGroup.add(barGroup);
  80539. },
  80540. /**
  80541. * @private
  80542. */
  80543. _createHandle: function (barGroup, handleIndex, itemSize, textSize, orient) {
  80544. var onDrift = bind(this._dragHandle, this, handleIndex, false);
  80545. var onDragEnd = bind(this._dragHandle, this, handleIndex, true);
  80546. var handleThumb = createPolygon(
  80547. createHandlePoints(handleIndex, textSize),
  80548. getCursor$1(this._orient),
  80549. onDrift,
  80550. onDragEnd
  80551. );
  80552. handleThumb.position[0] = itemSize[0];
  80553. barGroup.add(handleThumb);
  80554. // Text is always horizontal layout but should not be effected by
  80555. // transform (orient/inverse). So label is built separately but not
  80556. // use zrender/graphic/helper/RectText, and is located based on view
  80557. // group (according to handleLabelPoint) but not barGroup.
  80558. var textStyleModel = this.visualMapModel.textStyleModel;
  80559. var handleLabel = new Text({
  80560. draggable: true,
  80561. drift: onDrift,
  80562. onmousemove: function (e) {
  80563. // Fot mobile devicem, prevent screen slider on the button.
  80564. stop(e.event);
  80565. },
  80566. ondragend: onDragEnd,
  80567. style: {
  80568. x: 0, y: 0, text: '',
  80569. textFont: textStyleModel.getFont(),
  80570. textFill: textStyleModel.getTextColor()
  80571. }
  80572. });
  80573. this.group.add(handleLabel);
  80574. var handleLabelPoint = [
  80575. orient === 'horizontal'
  80576. ? textSize / 2
  80577. : textSize * 1.5,
  80578. orient === 'horizontal'
  80579. ? (handleIndex === 0 ? -(textSize * 1.5) : (textSize * 1.5))
  80580. : (handleIndex === 0 ? -textSize / 2 : textSize / 2)
  80581. ];
  80582. var shapes = this._shapes;
  80583. shapes.handleThumbs[handleIndex] = handleThumb;
  80584. shapes.handleLabelPoints[handleIndex] = handleLabelPoint;
  80585. shapes.handleLabels[handleIndex] = handleLabel;
  80586. },
  80587. /**
  80588. * @private
  80589. */
  80590. _createIndicator: function (barGroup, itemSize, textSize, orient) {
  80591. var indicator = createPolygon([[0, 0]], 'move');
  80592. indicator.position[0] = itemSize[0];
  80593. indicator.attr({invisible: true, silent: true});
  80594. barGroup.add(indicator);
  80595. var textStyleModel = this.visualMapModel.textStyleModel;
  80596. var indicatorLabel = new Text({
  80597. silent: true,
  80598. invisible: true,
  80599. style: {
  80600. x: 0, y: 0, text: '',
  80601. textFont: textStyleModel.getFont(),
  80602. textFill: textStyleModel.getTextColor()
  80603. }
  80604. });
  80605. this.group.add(indicatorLabel);
  80606. var indicatorLabelPoint = [
  80607. orient === 'horizontal' ? textSize / 2 : HOVER_LINK_OUT + 3,
  80608. 0
  80609. ];
  80610. var shapes = this._shapes;
  80611. shapes.indicator = indicator;
  80612. shapes.indicatorLabel = indicatorLabel;
  80613. shapes.indicatorLabelPoint = indicatorLabelPoint;
  80614. },
  80615. /**
  80616. * @private
  80617. */
  80618. _dragHandle: function (handleIndex, isEnd, dx, dy) {
  80619. if (!this._useHandle) {
  80620. return;
  80621. }
  80622. this._dragging = !isEnd;
  80623. if (!isEnd) {
  80624. // Transform dx, dy to bar coordination.
  80625. var vertex = this._applyTransform([dx, dy], this._shapes.barGroup, true);
  80626. this._updateInterval(handleIndex, vertex[1]);
  80627. // Considering realtime, update view should be executed
  80628. // before dispatch action.
  80629. this._updateView();
  80630. }
  80631. // dragEnd do not dispatch action when realtime.
  80632. if (isEnd === !this.visualMapModel.get('realtime')) { // jshint ignore:line
  80633. this.api.dispatchAction({
  80634. type: 'selectDataRange',
  80635. from: this.uid,
  80636. visualMapId: this.visualMapModel.id,
  80637. selected: this._dataInterval.slice()
  80638. });
  80639. }
  80640. if (isEnd) {
  80641. !this._hovering && this._clearHoverLinkToSeries();
  80642. }
  80643. else if (useHoverLinkOnHandle(this.visualMapModel)) {
  80644. this._doHoverLinkToSeries(this._handleEnds[handleIndex], false);
  80645. }
  80646. },
  80647. /**
  80648. * @private
  80649. */
  80650. _resetInterval: function () {
  80651. var visualMapModel = this.visualMapModel;
  80652. var dataInterval = this._dataInterval = visualMapModel.getSelected();
  80653. var dataExtent = visualMapModel.getExtent();
  80654. var sizeExtent = [0, visualMapModel.itemSize[1]];
  80655. this._handleEnds = [
  80656. linearMap$3(dataInterval[0], dataExtent, sizeExtent, true),
  80657. linearMap$3(dataInterval[1], dataExtent, sizeExtent, true)
  80658. ];
  80659. },
  80660. /**
  80661. * @private
  80662. * @param {(number|string)} handleIndex 0 or 1 or 'all'
  80663. * @param {number} dx
  80664. * @param {number} dy
  80665. */
  80666. _updateInterval: function (handleIndex, delta) {
  80667. delta = delta || 0;
  80668. var visualMapModel = this.visualMapModel;
  80669. var handleEnds = this._handleEnds;
  80670. var sizeExtent = [0, visualMapModel.itemSize[1]];
  80671. sliderMove(
  80672. delta,
  80673. handleEnds,
  80674. sizeExtent,
  80675. handleIndex,
  80676. // cross is forbiden
  80677. 0
  80678. );
  80679. var dataExtent = visualMapModel.getExtent();
  80680. // Update data interval.
  80681. this._dataInterval = [
  80682. linearMap$3(handleEnds[0], sizeExtent, dataExtent, true),
  80683. linearMap$3(handleEnds[1], sizeExtent, dataExtent, true)
  80684. ];
  80685. },
  80686. /**
  80687. * @private
  80688. */
  80689. _updateView: function (forSketch) {
  80690. var visualMapModel = this.visualMapModel;
  80691. var dataExtent = visualMapModel.getExtent();
  80692. var shapes = this._shapes;
  80693. var outOfRangeHandleEnds = [0, visualMapModel.itemSize[1]];
  80694. var inRangeHandleEnds = forSketch ? outOfRangeHandleEnds : this._handleEnds;
  80695. var visualInRange = this._createBarVisual(
  80696. this._dataInterval, dataExtent, inRangeHandleEnds, 'inRange'
  80697. );
  80698. var visualOutOfRange = this._createBarVisual(
  80699. dataExtent, dataExtent, outOfRangeHandleEnds, 'outOfRange'
  80700. );
  80701. shapes.inRange
  80702. .setStyle({
  80703. fill: visualInRange.barColor,
  80704. opacity: visualInRange.opacity
  80705. })
  80706. .setShape('points', visualInRange.barPoints);
  80707. shapes.outOfRange
  80708. .setStyle({
  80709. fill: visualOutOfRange.barColor,
  80710. opacity: visualOutOfRange.opacity
  80711. })
  80712. .setShape('points', visualOutOfRange.barPoints);
  80713. this._updateHandle(inRangeHandleEnds, visualInRange);
  80714. },
  80715. /**
  80716. * @private
  80717. */
  80718. _createBarVisual: function (dataInterval, dataExtent, handleEnds, forceState) {
  80719. var opts = {
  80720. forceState: forceState,
  80721. convertOpacityToAlpha: true
  80722. };
  80723. var colorStops = this._makeColorGradient(dataInterval, opts);
  80724. var symbolSizes = [
  80725. this.getControllerVisual(dataInterval[0], 'symbolSize', opts),
  80726. this.getControllerVisual(dataInterval[1], 'symbolSize', opts)
  80727. ];
  80728. var barPoints = this._createBarPoints(handleEnds, symbolSizes);
  80729. return {
  80730. barColor: new LinearGradient(0, 0, 0, 1, colorStops),
  80731. barPoints: barPoints,
  80732. handlesColor: [
  80733. colorStops[0].color,
  80734. colorStops[colorStops.length - 1].color
  80735. ]
  80736. };
  80737. },
  80738. /**
  80739. * @private
  80740. */
  80741. _makeColorGradient: function (dataInterval, opts) {
  80742. // Considering colorHue, which is not linear, so we have to sample
  80743. // to calculate gradient color stops, but not only caculate head
  80744. // and tail.
  80745. var sampleNumber = 100; // Arbitrary value.
  80746. var colorStops = [];
  80747. var step = (dataInterval[1] - dataInterval[0]) / sampleNumber;
  80748. colorStops.push({
  80749. color: this.getControllerVisual(dataInterval[0], 'color', opts),
  80750. offset: 0
  80751. });
  80752. for (var i = 1; i < sampleNumber; i++) {
  80753. var currValue = dataInterval[0] + step * i;
  80754. if (currValue > dataInterval[1]) {
  80755. break;
  80756. }
  80757. colorStops.push({
  80758. color: this.getControllerVisual(currValue, 'color', opts),
  80759. offset: i / sampleNumber
  80760. });
  80761. }
  80762. colorStops.push({
  80763. color: this.getControllerVisual(dataInterval[1], 'color', opts),
  80764. offset: 1
  80765. });
  80766. return colorStops;
  80767. },
  80768. /**
  80769. * @private
  80770. */
  80771. _createBarPoints: function (handleEnds, symbolSizes) {
  80772. var itemSize = this.visualMapModel.itemSize;
  80773. return [
  80774. [itemSize[0] - symbolSizes[0], handleEnds[0]],
  80775. [itemSize[0], handleEnds[0]],
  80776. [itemSize[0], handleEnds[1]],
  80777. [itemSize[0] - symbolSizes[1], handleEnds[1]]
  80778. ];
  80779. },
  80780. /**
  80781. * @private
  80782. */
  80783. _createBarGroup: function (itemAlign) {
  80784. var orient = this._orient;
  80785. var inverse = this.visualMapModel.get('inverse');
  80786. return new Group(
  80787. (orient === 'horizontal' && !inverse)
  80788. ? {scale: itemAlign === 'bottom' ? [1, 1] : [-1, 1], rotation: Math.PI / 2}
  80789. : (orient === 'horizontal' && inverse)
  80790. ? {scale: itemAlign === 'bottom' ? [-1, 1] : [1, 1], rotation: -Math.PI / 2}
  80791. : (orient === 'vertical' && !inverse)
  80792. ? {scale: itemAlign === 'left' ? [1, -1] : [-1, -1]}
  80793. : {scale: itemAlign === 'left' ? [1, 1] : [-1, 1]}
  80794. );
  80795. },
  80796. /**
  80797. * @private
  80798. */
  80799. _updateHandle: function (handleEnds, visualInRange) {
  80800. if (!this._useHandle) {
  80801. return;
  80802. }
  80803. var shapes = this._shapes;
  80804. var visualMapModel = this.visualMapModel;
  80805. var handleThumbs = shapes.handleThumbs;
  80806. var handleLabels = shapes.handleLabels;
  80807. each$29([0, 1], function (handleIndex) {
  80808. var handleThumb = handleThumbs[handleIndex];
  80809. handleThumb.setStyle('fill', visualInRange.handlesColor[handleIndex]);
  80810. handleThumb.position[1] = handleEnds[handleIndex];
  80811. // Update handle label position.
  80812. var textPoint = applyTransform$1(
  80813. shapes.handleLabelPoints[handleIndex],
  80814. getTransform(handleThumb, this.group)
  80815. );
  80816. handleLabels[handleIndex].setStyle({
  80817. x: textPoint[0],
  80818. y: textPoint[1],
  80819. text: visualMapModel.formatValueText(this._dataInterval[handleIndex]),
  80820. textVerticalAlign: 'middle',
  80821. textAlign: this._applyTransform(
  80822. this._orient === 'horizontal'
  80823. ? (handleIndex === 0 ? 'bottom' : 'top')
  80824. : 'left',
  80825. shapes.barGroup
  80826. )
  80827. });
  80828. }, this);
  80829. },
  80830. /**
  80831. * @private
  80832. * @param {number} cursorValue
  80833. * @param {number} textValue
  80834. * @param {string} [rangeSymbol]
  80835. * @param {number} [halfHoverLinkSize]
  80836. */
  80837. _showIndicator: function (cursorValue, textValue, rangeSymbol, halfHoverLinkSize) {
  80838. var visualMapModel = this.visualMapModel;
  80839. var dataExtent = visualMapModel.getExtent();
  80840. var itemSize = visualMapModel.itemSize;
  80841. var sizeExtent = [0, itemSize[1]];
  80842. var pos = linearMap$3(cursorValue, dataExtent, sizeExtent, true);
  80843. var shapes = this._shapes;
  80844. var indicator = shapes.indicator;
  80845. if (!indicator) {
  80846. return;
  80847. }
  80848. indicator.position[1] = pos;
  80849. indicator.attr('invisible', false);
  80850. indicator.setShape('points', createIndicatorPoints(
  80851. !!rangeSymbol, halfHoverLinkSize, pos, itemSize[1]
  80852. ));
  80853. var opts = {convertOpacityToAlpha: true};
  80854. var color = this.getControllerVisual(cursorValue, 'color', opts);
  80855. indicator.setStyle('fill', color);
  80856. // Update handle label position.
  80857. var textPoint = applyTransform$1(
  80858. shapes.indicatorLabelPoint,
  80859. getTransform(indicator, this.group)
  80860. );
  80861. var indicatorLabel = shapes.indicatorLabel;
  80862. indicatorLabel.attr('invisible', false);
  80863. var align = this._applyTransform('left', shapes.barGroup);
  80864. var orient = this._orient;
  80865. indicatorLabel.setStyle({
  80866. text: (rangeSymbol ? rangeSymbol : '') + visualMapModel.formatValueText(textValue),
  80867. textVerticalAlign: orient === 'horizontal' ? align : 'middle',
  80868. textAlign: orient === 'horizontal' ? 'center' : align,
  80869. x: textPoint[0],
  80870. y: textPoint[1]
  80871. });
  80872. },
  80873. /**
  80874. * @private
  80875. */
  80876. _enableHoverLinkToSeries: function () {
  80877. var self = this;
  80878. this._shapes.barGroup
  80879. .on('mousemove', function (e) {
  80880. self._hovering = true;
  80881. if (!self._dragging) {
  80882. var itemSize = self.visualMapModel.itemSize;
  80883. var pos = self._applyTransform(
  80884. [e.offsetX, e.offsetY], self._shapes.barGroup, true, true
  80885. );
  80886. // For hover link show when hover handle, which might be
  80887. // below or upper than sizeExtent.
  80888. pos[1] = mathMin$8(mathMax$8(0, pos[1]), itemSize[1]);
  80889. self._doHoverLinkToSeries(
  80890. pos[1],
  80891. 0 <= pos[0] && pos[0] <= itemSize[0]
  80892. );
  80893. }
  80894. })
  80895. .on('mouseout', function () {
  80896. // When mouse is out of handle, hoverLink still need
  80897. // to be displayed when realtime is set as false.
  80898. self._hovering = false;
  80899. !self._dragging && self._clearHoverLinkToSeries();
  80900. });
  80901. },
  80902. /**
  80903. * @private
  80904. */
  80905. _enableHoverLinkFromSeries: function () {
  80906. var zr = this.api.getZr();
  80907. if (this.visualMapModel.option.hoverLink) {
  80908. zr.on('mouseover', this._hoverLinkFromSeriesMouseOver, this);
  80909. zr.on('mouseout', this._hideIndicator, this);
  80910. }
  80911. else {
  80912. this._clearHoverLinkFromSeries();
  80913. }
  80914. },
  80915. /**
  80916. * @private
  80917. */
  80918. _doHoverLinkToSeries: function (cursorPos, hoverOnBar) {
  80919. var visualMapModel = this.visualMapModel;
  80920. var itemSize = visualMapModel.itemSize;
  80921. if (!visualMapModel.option.hoverLink) {
  80922. return;
  80923. }
  80924. var sizeExtent = [0, itemSize[1]];
  80925. var dataExtent = visualMapModel.getExtent();
  80926. // For hover link show when hover handle, which might be below or upper than sizeExtent.
  80927. cursorPos = mathMin$8(mathMax$8(sizeExtent[0], cursorPos), sizeExtent[1]);
  80928. var halfHoverLinkSize = getHalfHoverLinkSize(visualMapModel, dataExtent, sizeExtent);
  80929. var hoverRange = [cursorPos - halfHoverLinkSize, cursorPos + halfHoverLinkSize];
  80930. var cursorValue = linearMap$3(cursorPos, sizeExtent, dataExtent, true);
  80931. var valueRange = [
  80932. linearMap$3(hoverRange[0], sizeExtent, dataExtent, true),
  80933. linearMap$3(hoverRange[1], sizeExtent, dataExtent, true)
  80934. ];
  80935. // Consider data range is out of visualMap range, see test/visualMap-continuous.html,
  80936. // where china and india has very large population.
  80937. hoverRange[0] < sizeExtent[0] && (valueRange[0] = -Infinity);
  80938. hoverRange[1] > sizeExtent[1] && (valueRange[1] = Infinity);
  80939. // Do not show indicator when mouse is over handle,
  80940. // otherwise labels overlap, especially when dragging.
  80941. if (hoverOnBar) {
  80942. if (valueRange[0] === -Infinity) {
  80943. this._showIndicator(cursorValue, valueRange[1], '< ', halfHoverLinkSize);
  80944. }
  80945. else if (valueRange[1] === Infinity) {
  80946. this._showIndicator(cursorValue, valueRange[0], '> ', halfHoverLinkSize);
  80947. }
  80948. else {
  80949. this._showIndicator(cursorValue, cursorValue, '≈ ', halfHoverLinkSize);
  80950. }
  80951. }
  80952. // When realtime is set as false, handles, which are in barGroup,
  80953. // also trigger hoverLink, which help user to realize where they
  80954. // focus on when dragging. (see test/heatmap-large.html)
  80955. // When realtime is set as true, highlight will not show when hover
  80956. // handle, because the label on handle, which displays a exact value
  80957. // but not range, might mislead users.
  80958. var oldBatch = this._hoverLinkDataIndices;
  80959. var newBatch = [];
  80960. if (hoverOnBar || useHoverLinkOnHandle(visualMapModel)) {
  80961. newBatch = this._hoverLinkDataIndices = visualMapModel.findTargetDataIndices(valueRange);
  80962. }
  80963. var resultBatches = compressBatches(oldBatch, newBatch);
  80964. this._dispatchHighDown('downplay', makeHighDownBatch(resultBatches[0], visualMapModel));
  80965. this._dispatchHighDown('highlight', makeHighDownBatch(resultBatches[1], visualMapModel));
  80966. },
  80967. /**
  80968. * @private
  80969. */
  80970. _hoverLinkFromSeriesMouseOver: function (e) {
  80971. var el = e.target;
  80972. var visualMapModel = this.visualMapModel;
  80973. if (!el || el.dataIndex == null) {
  80974. return;
  80975. }
  80976. var dataModel = this.ecModel.getSeriesByIndex(el.seriesIndex);
  80977. if (!visualMapModel.isTargetSeries(dataModel)) {
  80978. return;
  80979. }
  80980. var data = dataModel.getData(el.dataType);
  80981. var value = data.get(visualMapModel.getDataDimension(data), el.dataIndex, true);
  80982. if (!isNaN(value)) {
  80983. this._showIndicator(value, value);
  80984. }
  80985. },
  80986. /**
  80987. * @private
  80988. */
  80989. _hideIndicator: function () {
  80990. var shapes = this._shapes;
  80991. shapes.indicator && shapes.indicator.attr('invisible', true);
  80992. shapes.indicatorLabel && shapes.indicatorLabel.attr('invisible', true);
  80993. },
  80994. /**
  80995. * @private
  80996. */
  80997. _clearHoverLinkToSeries: function () {
  80998. this._hideIndicator();
  80999. var indices = this._hoverLinkDataIndices;
  81000. this._dispatchHighDown('downplay', makeHighDownBatch(indices, this.visualMapModel));
  81001. indices.length = 0;
  81002. },
  81003. /**
  81004. * @private
  81005. */
  81006. _clearHoverLinkFromSeries: function () {
  81007. this._hideIndicator();
  81008. var zr = this.api.getZr();
  81009. zr.off('mouseover', this._hoverLinkFromSeriesMouseOver);
  81010. zr.off('mouseout', this._hideIndicator);
  81011. },
  81012. /**
  81013. * @private
  81014. */
  81015. _applyTransform: function (vertex, element, inverse, global) {
  81016. var transform = getTransform(element, global ? null : this.group);
  81017. return graphic[
  81018. isArray(vertex) ? 'applyTransform' : 'transformDirection'
  81019. ](vertex, transform, inverse);
  81020. },
  81021. /**
  81022. * @private
  81023. */
  81024. _dispatchHighDown: function (type, batch) {
  81025. batch && batch.length && this.api.dispatchAction({
  81026. type: type,
  81027. batch: batch
  81028. });
  81029. },
  81030. /**
  81031. * @override
  81032. */
  81033. dispose: function () {
  81034. this._clearHoverLinkFromSeries();
  81035. this._clearHoverLinkToSeries();
  81036. },
  81037. /**
  81038. * @override
  81039. */
  81040. remove: function () {
  81041. this._clearHoverLinkFromSeries();
  81042. this._clearHoverLinkToSeries();
  81043. }
  81044. });
  81045. function createPolygon(points, cursor, onDrift, onDragEnd) {
  81046. return new Polygon({
  81047. shape: {points: points},
  81048. draggable: !!onDrift,
  81049. cursor: cursor,
  81050. drift: onDrift,
  81051. onmousemove: function (e) {
  81052. // Fot mobile devicem, prevent screen slider on the button.
  81053. stop(e.event);
  81054. },
  81055. ondragend: onDragEnd
  81056. });
  81057. }
  81058. function createHandlePoints(handleIndex, textSize) {
  81059. return handleIndex === 0
  81060. ? [[0, 0], [textSize, 0], [textSize, -textSize]]
  81061. : [[0, 0], [textSize, 0], [textSize, textSize]];
  81062. }
  81063. function createIndicatorPoints(isRange, halfHoverLinkSize, pos, extentMax) {
  81064. return isRange
  81065. ? [ // indicate range
  81066. [0, -mathMin$8(halfHoverLinkSize, mathMax$8(pos, 0))],
  81067. [HOVER_LINK_OUT, 0],
  81068. [0, mathMin$8(halfHoverLinkSize, mathMax$8(extentMax - pos, 0))]
  81069. ]
  81070. : [ // indicate single value
  81071. [0, 0], [5, -5], [5, 5]
  81072. ];
  81073. }
  81074. function getHalfHoverLinkSize(visualMapModel, dataExtent, sizeExtent) {
  81075. var halfHoverLinkSize = HOVER_LINK_SIZE / 2;
  81076. var hoverLinkDataSize = visualMapModel.get('hoverLinkDataSize');
  81077. if (hoverLinkDataSize) {
  81078. halfHoverLinkSize = linearMap$3(hoverLinkDataSize, dataExtent, sizeExtent, true) / 2;
  81079. }
  81080. return halfHoverLinkSize;
  81081. }
  81082. function useHoverLinkOnHandle(visualMapModel) {
  81083. var hoverLinkOnHandle = visualMapModel.get('hoverLinkOnHandle');
  81084. return !!(hoverLinkOnHandle == null ? visualMapModel.get('realtime') : hoverLinkOnHandle);
  81085. }
  81086. function getCursor$1(orient) {
  81087. return orient === 'vertical' ? 'ns-resize' : 'ew-resize';
  81088. }
  81089. /*
  81090. * Licensed to the Apache Software Foundation (ASF) under one
  81091. * or more contributor license agreements. See the NOTICE file
  81092. * distributed with this work for additional information
  81093. * regarding copyright ownership. The ASF licenses this file
  81094. * to you under the Apache License, Version 2.0 (the
  81095. * "License"); you may not use this file except in compliance
  81096. * with the License. You may obtain a copy of the License at
  81097. *
  81098. * http://www.apache.org/licenses/LICENSE-2.0
  81099. *
  81100. * Unless required by applicable law or agreed to in writing,
  81101. * software distributed under the License is distributed on an
  81102. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  81103. * KIND, either express or implied. See the License for the
  81104. * specific language governing permissions and limitations
  81105. * under the License.
  81106. */
  81107. var actionInfo$2 = {
  81108. type: 'selectDataRange',
  81109. event: 'dataRangeSelected',
  81110. // FIXME use updateView appears wrong
  81111. update: 'update'
  81112. };
  81113. registerAction(actionInfo$2, function (payload, ecModel) {
  81114. ecModel.eachComponent({mainType: 'visualMap', query: payload}, function (model) {
  81115. model.setSelected(payload.selected);
  81116. });
  81117. });
  81118. /*
  81119. * Licensed to the Apache Software Foundation (ASF) under one
  81120. * or more contributor license agreements. See the NOTICE file
  81121. * distributed with this work for additional information
  81122. * regarding copyright ownership. The ASF licenses this file
  81123. * to you under the Apache License, Version 2.0 (the
  81124. * "License"); you may not use this file except in compliance
  81125. * with the License. You may obtain a copy of the License at
  81126. *
  81127. * http://www.apache.org/licenses/LICENSE-2.0
  81128. *
  81129. * Unless required by applicable law or agreed to in writing,
  81130. * software distributed under the License is distributed on an
  81131. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  81132. * KIND, either express or implied. See the License for the
  81133. * specific language governing permissions and limitations
  81134. * under the License.
  81135. */
  81136. /**
  81137. * DataZoom component entry
  81138. */
  81139. registerPreprocessor(preprocessor$3);
  81140. /*
  81141. * Licensed to the Apache Software Foundation (ASF) under one
  81142. * or more contributor license agreements. See the NOTICE file
  81143. * distributed with this work for additional information
  81144. * regarding copyright ownership. The ASF licenses this file
  81145. * to you under the Apache License, Version 2.0 (the
  81146. * "License"); you may not use this file except in compliance
  81147. * with the License. You may obtain a copy of the License at
  81148. *
  81149. * http://www.apache.org/licenses/LICENSE-2.0
  81150. *
  81151. * Unless required by applicable law or agreed to in writing,
  81152. * software distributed under the License is distributed on an
  81153. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  81154. * KIND, either express or implied. See the License for the
  81155. * specific language governing permissions and limitations
  81156. * under the License.
  81157. */
  81158. var PiecewiseModel = VisualMapModel.extend({
  81159. type: 'visualMap.piecewise',
  81160. /**
  81161. * Order Rule:
  81162. *
  81163. * option.categories / option.pieces / option.text / option.selected:
  81164. * If !option.inverse,
  81165. * Order when vertical: ['top', ..., 'bottom'].
  81166. * Order when horizontal: ['left', ..., 'right'].
  81167. * If option.inverse, the meaning of
  81168. * the order should be reversed.
  81169. *
  81170. * this._pieceList:
  81171. * The order is always [low, ..., high].
  81172. *
  81173. * Mapping from location to low-high:
  81174. * If !option.inverse
  81175. * When vertical, top is high.
  81176. * When horizontal, right is high.
  81177. * If option.inverse, reverse.
  81178. */
  81179. /**
  81180. * @protected
  81181. */
  81182. defaultOption: {
  81183. selected: null, // Object. If not specified, means selected.
  81184. // When pieces and splitNumber: {'0': true, '5': true}
  81185. // When categories: {'cate1': false, 'cate3': true}
  81186. // When selected === false, means all unselected.
  81187. minOpen: false, // Whether include values that smaller than `min`.
  81188. maxOpen: false, // Whether include values that bigger than `max`.
  81189. align: 'auto', // 'auto', 'left', 'right'
  81190. itemWidth: 20, // When put the controller vertically, it is the length of
  81191. // horizontal side of each item. Otherwise, vertical side.
  81192. itemHeight: 14, // When put the controller vertically, it is the length of
  81193. // vertical side of each item. Otherwise, horizontal side.
  81194. itemSymbol: 'roundRect',
  81195. pieceList: null, // Each item is Object, with some of those attrs:
  81196. // {min, max, lt, gt, lte, gte, value,
  81197. // color, colorSaturation, colorAlpha, opacity,
  81198. // symbol, symbolSize}, which customize the range or visual
  81199. // coding of the certain piece. Besides, see "Order Rule".
  81200. categories: null, // category names, like: ['some1', 'some2', 'some3'].
  81201. // Attr min/max are ignored when categories set. See "Order Rule"
  81202. splitNumber: 5, // If set to 5, auto split five pieces equally.
  81203. // If set to 0 and component type not set, component type will be
  81204. // determined as "continuous". (It is less reasonable but for ec2
  81205. // compatibility, see echarts/component/visualMap/typeDefaulter)
  81206. selectedMode: 'multiple', // Can be 'multiple' or 'single'.
  81207. itemGap: 10, // The gap between two items, in px.
  81208. hoverLink: true, // Enable hover highlight.
  81209. showLabel: null // By default, when text is used, label will hide (the logic
  81210. // is remained for compatibility reason)
  81211. },
  81212. /**
  81213. * @override
  81214. */
  81215. optionUpdated: function (newOption, isInit) {
  81216. PiecewiseModel.superApply(this, 'optionUpdated', arguments);
  81217. /**
  81218. * The order is always [low, ..., high].
  81219. * [{text: string, interval: Array.<number>}, ...]
  81220. * @private
  81221. * @type {Array.<Object>}
  81222. */
  81223. this._pieceList = [];
  81224. this.resetExtent();
  81225. /**
  81226. * 'pieces', 'categories', 'splitNumber'
  81227. * @type {string}
  81228. */
  81229. var mode = this._mode = this._determineMode();
  81230. resetMethods[this._mode].call(this);
  81231. this._resetSelected(newOption, isInit);
  81232. var categories = this.option.categories;
  81233. this.resetVisual(function (mappingOption, state) {
  81234. if (mode === 'categories') {
  81235. mappingOption.mappingMethod = 'category';
  81236. mappingOption.categories = clone(categories);
  81237. }
  81238. else {
  81239. mappingOption.dataExtent = this.getExtent();
  81240. mappingOption.mappingMethod = 'piecewise';
  81241. mappingOption.pieceList = map(this._pieceList, function (piece) {
  81242. var piece = clone(piece);
  81243. if (state !== 'inRange') {
  81244. // FIXME
  81245. // outOfRange do not support special visual in pieces.
  81246. piece.visual = null;
  81247. }
  81248. return piece;
  81249. });
  81250. }
  81251. });
  81252. },
  81253. /**
  81254. * @protected
  81255. * @override
  81256. */
  81257. completeVisualOption: function () {
  81258. // Consider this case:
  81259. // visualMap: {
  81260. // pieces: [{symbol: 'circle', lt: 0}, {symbol: 'rect', gte: 0}]
  81261. // }
  81262. // where no inRange/outOfRange set but only pieces. So we should make
  81263. // default inRange/outOfRange for this case, otherwise visuals that only
  81264. // appear in `pieces` will not be taken into account in visual encoding.
  81265. var option = this.option;
  81266. var visualTypesInPieces = {};
  81267. var visualTypes = VisualMapping.listVisualTypes();
  81268. var isCategory = this.isCategory();
  81269. each$1(option.pieces, function (piece) {
  81270. each$1(visualTypes, function (visualType) {
  81271. if (piece.hasOwnProperty(visualType)) {
  81272. visualTypesInPieces[visualType] = 1;
  81273. }
  81274. });
  81275. });
  81276. each$1(visualTypesInPieces, function (v, visualType) {
  81277. var exists = 0;
  81278. each$1(this.stateList, function (state) {
  81279. exists |= has(option, state, visualType)
  81280. || has(option.target, state, visualType);
  81281. }, this);
  81282. !exists && each$1(this.stateList, function (state) {
  81283. (option[state] || (option[state] = {}))[visualType] = visualDefault.get(
  81284. visualType, state === 'inRange' ? 'active' : 'inactive', isCategory
  81285. );
  81286. });
  81287. }, this);
  81288. function has(obj, state, visualType) {
  81289. return obj && obj[state] && (
  81290. isObject$1(obj[state])
  81291. ? obj[state].hasOwnProperty(visualType)
  81292. : obj[state] === visualType // e.g., inRange: 'symbol'
  81293. );
  81294. }
  81295. VisualMapModel.prototype.completeVisualOption.apply(this, arguments);
  81296. },
  81297. _resetSelected: function (newOption, isInit) {
  81298. var thisOption = this.option;
  81299. var pieceList = this._pieceList;
  81300. // Selected do not merge but all override.
  81301. var selected = (isInit ? thisOption : newOption).selected || {};
  81302. thisOption.selected = selected;
  81303. // Consider 'not specified' means true.
  81304. each$1(pieceList, function (piece, index) {
  81305. var key = this.getSelectedMapKey(piece);
  81306. if (!selected.hasOwnProperty(key)) {
  81307. selected[key] = true;
  81308. }
  81309. }, this);
  81310. if (thisOption.selectedMode === 'single') {
  81311. // Ensure there is only one selected.
  81312. var hasSel = false;
  81313. each$1(pieceList, function (piece, index) {
  81314. var key = this.getSelectedMapKey(piece);
  81315. if (selected[key]) {
  81316. hasSel
  81317. ? (selected[key] = false)
  81318. : (hasSel = true);
  81319. }
  81320. }, this);
  81321. }
  81322. // thisOption.selectedMode === 'multiple', default: all selected.
  81323. },
  81324. /**
  81325. * @public
  81326. */
  81327. getSelectedMapKey: function (piece) {
  81328. return this._mode === 'categories'
  81329. ? piece.value + '' : piece.index + '';
  81330. },
  81331. /**
  81332. * @public
  81333. */
  81334. getPieceList: function () {
  81335. return this._pieceList;
  81336. },
  81337. /**
  81338. * @private
  81339. * @return {string}
  81340. */
  81341. _determineMode: function () {
  81342. var option = this.option;
  81343. return option.pieces && option.pieces.length > 0
  81344. ? 'pieces'
  81345. : this.option.categories
  81346. ? 'categories'
  81347. : 'splitNumber';
  81348. },
  81349. /**
  81350. * @public
  81351. * @override
  81352. */
  81353. setSelected: function (selected) {
  81354. this.option.selected = clone(selected);
  81355. },
  81356. /**
  81357. * @public
  81358. * @override
  81359. */
  81360. getValueState: function (value) {
  81361. var index = VisualMapping.findPieceIndex(value, this._pieceList);
  81362. return index != null
  81363. ? (this.option.selected[this.getSelectedMapKey(this._pieceList[index])]
  81364. ? 'inRange' : 'outOfRange'
  81365. )
  81366. : 'outOfRange';
  81367. },
  81368. /**
  81369. * @public
  81370. * @params {number} pieceIndex piece index in visualMapModel.getPieceList()
  81371. * @return {Array.<Object>} [{seriesId, dataIndex: <Array.<number>>}, ...]
  81372. */
  81373. findTargetDataIndices: function (pieceIndex) {
  81374. var result = [];
  81375. this.eachTargetSeries(function (seriesModel) {
  81376. var dataIndices = [];
  81377. var data = seriesModel.getData();
  81378. data.each(this.getDataDimension(data), function (value, dataIndex) {
  81379. // Should always base on model pieceList, because it is order sensitive.
  81380. var pIdx = VisualMapping.findPieceIndex(value, this._pieceList);
  81381. pIdx === pieceIndex && dataIndices.push(dataIndex);
  81382. }, this);
  81383. result.push({seriesId: seriesModel.id, dataIndex: dataIndices});
  81384. }, this);
  81385. return result;
  81386. },
  81387. /**
  81388. * @private
  81389. * @param {Object} piece piece.value or piece.interval is required.
  81390. * @return {number} Can be Infinity or -Infinity
  81391. */
  81392. getRepresentValue: function (piece) {
  81393. var representValue;
  81394. if (this.isCategory()) {
  81395. representValue = piece.value;
  81396. }
  81397. else {
  81398. if (piece.value != null) {
  81399. representValue = piece.value;
  81400. }
  81401. else {
  81402. var pieceInterval = piece.interval || [];
  81403. representValue = (pieceInterval[0] === -Infinity && pieceInterval[1] === Infinity)
  81404. ? 0
  81405. : (pieceInterval[0] + pieceInterval[1]) / 2;
  81406. }
  81407. }
  81408. return representValue;
  81409. },
  81410. getVisualMeta: function (getColorVisual) {
  81411. // Do not support category. (category axis is ordinal, numerical)
  81412. if (this.isCategory()) {
  81413. return;
  81414. }
  81415. var stops = [];
  81416. var outerColors = [];
  81417. var visualMapModel = this;
  81418. function setStop(interval, valueState) {
  81419. var representValue = visualMapModel.getRepresentValue({interval: interval});
  81420. if (!valueState) {
  81421. valueState = visualMapModel.getValueState(representValue);
  81422. }
  81423. var color = getColorVisual(representValue, valueState);
  81424. if (interval[0] === -Infinity) {
  81425. outerColors[0] = color;
  81426. }
  81427. else if (interval[1] === Infinity) {
  81428. outerColors[1] = color;
  81429. }
  81430. else {
  81431. stops.push(
  81432. {value: interval[0], color: color},
  81433. {value: interval[1], color: color}
  81434. );
  81435. }
  81436. }
  81437. // Suplement
  81438. var pieceList = this._pieceList.slice();
  81439. if (!pieceList.length) {
  81440. pieceList.push({interval: [-Infinity, Infinity]});
  81441. }
  81442. else {
  81443. var edge = pieceList[0].interval[0];
  81444. edge !== -Infinity && pieceList.unshift({interval: [-Infinity, edge]});
  81445. edge = pieceList[pieceList.length - 1].interval[1];
  81446. edge !== Infinity && pieceList.push({interval: [edge, Infinity]});
  81447. }
  81448. var curr = -Infinity;
  81449. each$1(pieceList, function (piece) {
  81450. var interval = piece.interval;
  81451. if (interval) {
  81452. // Fulfill gap.
  81453. interval[0] > curr && setStop([curr, interval[0]], 'outOfRange');
  81454. setStop(interval.slice());
  81455. curr = interval[1];
  81456. }
  81457. }, this);
  81458. return {stops: stops, outerColors: outerColors};
  81459. }
  81460. });
  81461. /**
  81462. * Key is this._mode
  81463. * @type {Object}
  81464. * @this {module:echarts/component/viusalMap/PiecewiseMode}
  81465. */
  81466. var resetMethods = {
  81467. splitNumber: function () {
  81468. var thisOption = this.option;
  81469. var pieceList = this._pieceList;
  81470. var precision = Math.min(thisOption.precision, 20);
  81471. var dataExtent = this.getExtent();
  81472. var splitNumber = thisOption.splitNumber;
  81473. splitNumber = Math.max(parseInt(splitNumber, 10), 1);
  81474. thisOption.splitNumber = splitNumber;
  81475. var splitStep = (dataExtent[1] - dataExtent[0]) / splitNumber;
  81476. // Precision auto-adaption
  81477. while (+splitStep.toFixed(precision) !== splitStep && precision < 5) {
  81478. precision++;
  81479. }
  81480. thisOption.precision = precision;
  81481. splitStep = +splitStep.toFixed(precision);
  81482. if (thisOption.minOpen) {
  81483. pieceList.push({
  81484. interval: [-Infinity, dataExtent[0]],
  81485. close: [0, 0]
  81486. });
  81487. }
  81488. for (
  81489. var index = 0, curr = dataExtent[0];
  81490. index < splitNumber;
  81491. curr += splitStep, index++
  81492. ) {
  81493. var max = index === splitNumber - 1 ? dataExtent[1] : (curr + splitStep);
  81494. pieceList.push({
  81495. interval: [curr, max],
  81496. close: [1, 1]
  81497. });
  81498. }
  81499. if (thisOption.maxOpen) {
  81500. pieceList.push({
  81501. interval: [dataExtent[1], Infinity],
  81502. close: [0, 0]
  81503. });
  81504. }
  81505. reformIntervals(pieceList);
  81506. each$1(pieceList, function (piece, index) {
  81507. piece.index = index;
  81508. piece.text = this.formatValueText(piece.interval);
  81509. }, this);
  81510. },
  81511. categories: function () {
  81512. var thisOption = this.option;
  81513. each$1(thisOption.categories, function (cate) {
  81514. // FIXME category模式也使用pieceList,但在visualMapping中不是使用pieceList。
  81515. // 是否改一致。
  81516. this._pieceList.push({
  81517. text: this.formatValueText(cate, true),
  81518. value: cate
  81519. });
  81520. }, this);
  81521. // See "Order Rule".
  81522. normalizeReverse(thisOption, this._pieceList);
  81523. },
  81524. pieces: function () {
  81525. var thisOption = this.option;
  81526. var pieceList = this._pieceList;
  81527. each$1(thisOption.pieces, function (pieceListItem, index) {
  81528. if (!isObject$1(pieceListItem)) {
  81529. pieceListItem = {value: pieceListItem};
  81530. }
  81531. var item = {text: '', index: index};
  81532. if (pieceListItem.label != null) {
  81533. item.text = pieceListItem.label;
  81534. }
  81535. if (pieceListItem.hasOwnProperty('value')) {
  81536. var value = item.value = pieceListItem.value;
  81537. item.interval = [value, value];
  81538. item.close = [1, 1];
  81539. }
  81540. else {
  81541. // `min` `max` is legacy option.
  81542. // `lt` `gt` `lte` `gte` is recommanded.
  81543. var interval = item.interval = [];
  81544. var close = item.close = [0, 0];
  81545. var closeList = [1, 0, 1];
  81546. var infinityList = [-Infinity, Infinity];
  81547. var useMinMax = [];
  81548. for (var lg = 0; lg < 2; lg++) {
  81549. var names = [['gte', 'gt', 'min'], ['lte', 'lt', 'max']][lg];
  81550. for (var i = 0; i < 3 && interval[lg] == null; i++) {
  81551. interval[lg] = pieceListItem[names[i]];
  81552. close[lg] = closeList[i];
  81553. useMinMax[lg] = i === 2;
  81554. }
  81555. interval[lg] == null && (interval[lg] = infinityList[lg]);
  81556. }
  81557. useMinMax[0] && interval[1] === Infinity && (close[0] = 0);
  81558. useMinMax[1] && interval[0] === -Infinity && (close[1] = 0);
  81559. if (__DEV__) {
  81560. if (interval[0] > interval[1]) {
  81561. console.warn(
  81562. 'Piece ' + index + 'is illegal: ' + interval
  81563. + ' lower bound should not greater then uppper bound.'
  81564. );
  81565. }
  81566. }
  81567. if (interval[0] === interval[1] && close[0] && close[1]) {
  81568. // Consider: [{min: 5, max: 5, visual: {...}}, {min: 0, max: 5}],
  81569. // we use value to lift the priority when min === max
  81570. item.value = interval[0];
  81571. }
  81572. }
  81573. item.visual = VisualMapping.retrieveVisuals(pieceListItem);
  81574. pieceList.push(item);
  81575. }, this);
  81576. // See "Order Rule".
  81577. normalizeReverse(thisOption, pieceList);
  81578. // Only pieces
  81579. reformIntervals(pieceList);
  81580. each$1(pieceList, function (piece) {
  81581. var close = piece.close;
  81582. var edgeSymbols = [['<', '≤'][close[1]], ['>', '≥'][close[0]]];
  81583. piece.text = piece.text || this.formatValueText(
  81584. piece.value != null ? piece.value : piece.interval,
  81585. false,
  81586. edgeSymbols
  81587. );
  81588. }, this);
  81589. }
  81590. };
  81591. function normalizeReverse(thisOption, pieceList) {
  81592. var inverse = thisOption.inverse;
  81593. if (thisOption.orient === 'vertical' ? !inverse : inverse) {
  81594. pieceList.reverse();
  81595. }
  81596. }
  81597. /*
  81598. * Licensed to the Apache Software Foundation (ASF) under one
  81599. * or more contributor license agreements. See the NOTICE file
  81600. * distributed with this work for additional information
  81601. * regarding copyright ownership. The ASF licenses this file
  81602. * to you under the Apache License, Version 2.0 (the
  81603. * "License"); you may not use this file except in compliance
  81604. * with the License. You may obtain a copy of the License at
  81605. *
  81606. * http://www.apache.org/licenses/LICENSE-2.0
  81607. *
  81608. * Unless required by applicable law or agreed to in writing,
  81609. * software distributed under the License is distributed on an
  81610. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  81611. * KIND, either express or implied. See the License for the
  81612. * specific language governing permissions and limitations
  81613. * under the License.
  81614. */
  81615. var PiecewiseVisualMapView = VisualMapView.extend({
  81616. type: 'visualMap.piecewise',
  81617. /**
  81618. * @protected
  81619. * @override
  81620. */
  81621. doRender: function () {
  81622. var thisGroup = this.group;
  81623. thisGroup.removeAll();
  81624. var visualMapModel = this.visualMapModel;
  81625. var textGap = visualMapModel.get('textGap');
  81626. var textStyleModel = visualMapModel.textStyleModel;
  81627. var textFont = textStyleModel.getFont();
  81628. var textFill = textStyleModel.getTextColor();
  81629. var itemAlign = this._getItemAlign();
  81630. var itemSize = visualMapModel.itemSize;
  81631. var viewData = this._getViewData();
  81632. var endsText = viewData.endsText;
  81633. var showLabel = retrieve(visualMapModel.get('showLabel', true), !endsText);
  81634. endsText && this._renderEndsText(
  81635. thisGroup, endsText[0], itemSize, showLabel, itemAlign
  81636. );
  81637. each$1(viewData.viewPieceList, renderItem, this);
  81638. endsText && this._renderEndsText(
  81639. thisGroup, endsText[1], itemSize, showLabel, itemAlign
  81640. );
  81641. box(
  81642. visualMapModel.get('orient'), thisGroup, visualMapModel.get('itemGap')
  81643. );
  81644. this.renderBackground(thisGroup);
  81645. this.positionGroup(thisGroup);
  81646. function renderItem(item) {
  81647. var piece = item.piece;
  81648. var itemGroup = new Group();
  81649. itemGroup.onclick = bind(this._onItemClick, this, piece);
  81650. this._enableHoverLink(itemGroup, item.indexInModelPieceList);
  81651. var representValue = visualMapModel.getRepresentValue(piece);
  81652. this._createItemSymbol(
  81653. itemGroup, representValue, [0, 0, itemSize[0], itemSize[1]]
  81654. );
  81655. if (showLabel) {
  81656. var visualState = this.visualMapModel.getValueState(representValue);
  81657. itemGroup.add(new Text({
  81658. style: {
  81659. x: itemAlign === 'right' ? -textGap : itemSize[0] + textGap,
  81660. y: itemSize[1] / 2,
  81661. text: piece.text,
  81662. textVerticalAlign: 'middle',
  81663. textAlign: itemAlign,
  81664. textFont: textFont,
  81665. textFill: textFill,
  81666. opacity: visualState === 'outOfRange' ? 0.5 : 1
  81667. }
  81668. }));
  81669. }
  81670. thisGroup.add(itemGroup);
  81671. }
  81672. },
  81673. /**
  81674. * @private
  81675. */
  81676. _enableHoverLink: function (itemGroup, pieceIndex) {
  81677. itemGroup
  81678. .on('mouseover', bind(onHoverLink, this, 'highlight'))
  81679. .on('mouseout', bind(onHoverLink, this, 'downplay'));
  81680. function onHoverLink(method) {
  81681. var visualMapModel = this.visualMapModel;
  81682. visualMapModel.option.hoverLink && this.api.dispatchAction({
  81683. type: method,
  81684. batch: makeHighDownBatch(
  81685. visualMapModel.findTargetDataIndices(pieceIndex),
  81686. visualMapModel
  81687. )
  81688. });
  81689. }
  81690. },
  81691. /**
  81692. * @private
  81693. */
  81694. _getItemAlign: function () {
  81695. var visualMapModel = this.visualMapModel;
  81696. var modelOption = visualMapModel.option;
  81697. if (modelOption.orient === 'vertical') {
  81698. return getItemAlign(
  81699. visualMapModel, this.api, visualMapModel.itemSize
  81700. );
  81701. }
  81702. else { // horizontal, most case left unless specifying right.
  81703. var align = modelOption.align;
  81704. if (!align || align === 'auto') {
  81705. align = 'left';
  81706. }
  81707. return align;
  81708. }
  81709. },
  81710. /**
  81711. * @private
  81712. */
  81713. _renderEndsText: function (group, text, itemSize, showLabel, itemAlign) {
  81714. if (!text) {
  81715. return;
  81716. }
  81717. var itemGroup = new Group();
  81718. var textStyleModel = this.visualMapModel.textStyleModel;
  81719. itemGroup.add(new Text({
  81720. style: {
  81721. x: showLabel ? (itemAlign === 'right' ? itemSize[0] : 0) : itemSize[0] / 2,
  81722. y: itemSize[1] / 2,
  81723. textVerticalAlign: 'middle',
  81724. textAlign: showLabel ? itemAlign : 'center',
  81725. text: text,
  81726. textFont: textStyleModel.getFont(),
  81727. textFill: textStyleModel.getTextColor()
  81728. }
  81729. }));
  81730. group.add(itemGroup);
  81731. },
  81732. /**
  81733. * @private
  81734. * @return {Object} {peiceList, endsText} The order is the same as screen pixel order.
  81735. */
  81736. _getViewData: function () {
  81737. var visualMapModel = this.visualMapModel;
  81738. var viewPieceList = map(visualMapModel.getPieceList(), function (piece, index) {
  81739. return {piece: piece, indexInModelPieceList: index};
  81740. });
  81741. var endsText = visualMapModel.get('text');
  81742. // Consider orient and inverse.
  81743. var orient = visualMapModel.get('orient');
  81744. var inverse = visualMapModel.get('inverse');
  81745. // Order of model pieceList is always [low, ..., high]
  81746. if (orient === 'horizontal' ? inverse : !inverse) {
  81747. viewPieceList.reverse();
  81748. }
  81749. // Origin order of endsText is [high, low]
  81750. else if (endsText) {
  81751. endsText = endsText.slice().reverse();
  81752. }
  81753. return {viewPieceList: viewPieceList, endsText: endsText};
  81754. },
  81755. /**
  81756. * @private
  81757. */
  81758. _createItemSymbol: function (group, representValue, shapeParam) {
  81759. group.add(createSymbol(
  81760. this.getControllerVisual(representValue, 'symbol'),
  81761. shapeParam[0], shapeParam[1], shapeParam[2], shapeParam[3],
  81762. this.getControllerVisual(representValue, 'color')
  81763. ));
  81764. },
  81765. /**
  81766. * @private
  81767. */
  81768. _onItemClick: function (piece) {
  81769. var visualMapModel = this.visualMapModel;
  81770. var option = visualMapModel.option;
  81771. var selected = clone(option.selected);
  81772. var newKey = visualMapModel.getSelectedMapKey(piece);
  81773. if (option.selectedMode === 'single') {
  81774. selected[newKey] = true;
  81775. each$1(selected, function (o, key) {
  81776. selected[key] = key === newKey;
  81777. });
  81778. }
  81779. else {
  81780. selected[newKey] = !selected[newKey];
  81781. }
  81782. this.api.dispatchAction({
  81783. type: 'selectDataRange',
  81784. from: this.uid,
  81785. visualMapId: this.visualMapModel.id,
  81786. selected: selected
  81787. });
  81788. }
  81789. });
  81790. /*
  81791. * Licensed to the Apache Software Foundation (ASF) under one
  81792. * or more contributor license agreements. See the NOTICE file
  81793. * distributed with this work for additional information
  81794. * regarding copyright ownership. The ASF licenses this file
  81795. * to you under the Apache License, Version 2.0 (the
  81796. * "License"); you may not use this file except in compliance
  81797. * with the License. You may obtain a copy of the License at
  81798. *
  81799. * http://www.apache.org/licenses/LICENSE-2.0
  81800. *
  81801. * Unless required by applicable law or agreed to in writing,
  81802. * software distributed under the License is distributed on an
  81803. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  81804. * KIND, either express or implied. See the License for the
  81805. * specific language governing permissions and limitations
  81806. * under the License.
  81807. */
  81808. /**
  81809. * DataZoom component entry
  81810. */
  81811. registerPreprocessor(preprocessor$3);
  81812. /*
  81813. * Licensed to the Apache Software Foundation (ASF) under one
  81814. * or more contributor license agreements. See the NOTICE file
  81815. * distributed with this work for additional information
  81816. * regarding copyright ownership. The ASF licenses this file
  81817. * to you under the Apache License, Version 2.0 (the
  81818. * "License"); you may not use this file except in compliance
  81819. * with the License. You may obtain a copy of the License at
  81820. *
  81821. * http://www.apache.org/licenses/LICENSE-2.0
  81822. *
  81823. * Unless required by applicable law or agreed to in writing,
  81824. * software distributed under the License is distributed on an
  81825. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  81826. * KIND, either express or implied. See the License for the
  81827. * specific language governing permissions and limitations
  81828. * under the License.
  81829. */
  81830. /**
  81831. * visualMap component entry
  81832. */
  81833. var urn = 'urn:schemas-microsoft-com:vml';
  81834. var win = typeof window === 'undefined' ? null : window;
  81835. var vmlInited = false;
  81836. var doc = win && win.document;
  81837. function createNode(tagName) {
  81838. return doCreateNode(tagName);
  81839. }
  81840. // Avoid assign to an exported variable, for transforming to cjs.
  81841. var doCreateNode;
  81842. if (doc && !env$1.canvasSupported) {
  81843. try {
  81844. !doc.namespaces.zrvml && doc.namespaces.add('zrvml', urn);
  81845. doCreateNode = function (tagName) {
  81846. return doc.createElement('<zrvml:' + tagName + ' class="zrvml">');
  81847. };
  81848. }
  81849. catch (e) {
  81850. doCreateNode = function (tagName) {
  81851. return doc.createElement('<' + tagName + ' xmlns="' + urn + '" class="zrvml">');
  81852. };
  81853. }
  81854. }
  81855. // From raphael
  81856. function initVML() {
  81857. if (vmlInited || !doc) {
  81858. return;
  81859. }
  81860. vmlInited = true;
  81861. var styleSheets = doc.styleSheets;
  81862. if (styleSheets.length < 31) {
  81863. doc.createStyleSheet().addRule('.zrvml', 'behavior:url(#default#VML)');
  81864. }
  81865. else {
  81866. // http://msdn.microsoft.com/en-us/library/ms531194%28VS.85%29.aspx
  81867. styleSheets[0].addRule('.zrvml', 'behavior:url(#default#VML)');
  81868. }
  81869. }
  81870. // http://www.w3.org/TR/NOTE-VML
  81871. // TODO Use proxy like svg instead of overwrite brush methods
  81872. var CMD$3 = PathProxy.CMD;
  81873. var round$3 = Math.round;
  81874. var sqrt = Math.sqrt;
  81875. var abs$1 = Math.abs;
  81876. var cos = Math.cos;
  81877. var sin = Math.sin;
  81878. var mathMax$9 = Math.max;
  81879. if (!env$1.canvasSupported) {
  81880. var comma = ',';
  81881. var imageTransformPrefix = 'progid:DXImageTransform.Microsoft';
  81882. var Z = 21600;
  81883. var Z2 = Z / 2;
  81884. var ZLEVEL_BASE = 100000;
  81885. var Z_BASE$1 = 1000;
  81886. var initRootElStyle = function (el) {
  81887. el.style.cssText = 'position:absolute;left:0;top:0;width:1px;height:1px;';
  81888. el.coordsize = Z + ',' + Z;
  81889. el.coordorigin = '0,0';
  81890. };
  81891. var encodeHtmlAttribute = function (s) {
  81892. return String(s).replace(/&/g, '&amp;').replace(/"/g, '&quot;');
  81893. };
  81894. var rgb2Str = function (r, g, b) {
  81895. return 'rgb(' + [r, g, b].join(',') + ')';
  81896. };
  81897. var append = function (parent, child) {
  81898. if (child && parent && child.parentNode !== parent) {
  81899. parent.appendChild(child);
  81900. }
  81901. };
  81902. var remove = function (parent, child) {
  81903. if (child && parent && child.parentNode === parent) {
  81904. parent.removeChild(child);
  81905. }
  81906. };
  81907. var getZIndex = function (zlevel, z, z2) {
  81908. // z 的取值范围为 [0, 1000]
  81909. return (parseFloat(zlevel) || 0) * ZLEVEL_BASE + (parseFloat(z) || 0) * Z_BASE$1 + z2;
  81910. };
  81911. var parsePercent$3 = parsePercent;
  81912. /***************************************************
  81913. * PATH
  81914. **************************************************/
  81915. var setColorAndOpacity = function (el, color, opacity) {
  81916. var colorArr = parse(color);
  81917. opacity = +opacity;
  81918. if (isNaN(opacity)) {
  81919. opacity = 1;
  81920. }
  81921. if (colorArr) {
  81922. el.color = rgb2Str(colorArr[0], colorArr[1], colorArr[2]);
  81923. el.opacity = opacity * colorArr[3];
  81924. }
  81925. };
  81926. var getColorAndAlpha = function (color) {
  81927. var colorArr = parse(color);
  81928. return [
  81929. rgb2Str(colorArr[0], colorArr[1], colorArr[2]),
  81930. colorArr[3]
  81931. ];
  81932. };
  81933. var updateFillNode = function (el, style, zrEl) {
  81934. // TODO pattern
  81935. var fill = style.fill;
  81936. if (fill != null) {
  81937. // Modified from excanvas
  81938. if (fill instanceof Gradient) {
  81939. var gradientType;
  81940. var angle = 0;
  81941. var focus = [0, 0];
  81942. // additional offset
  81943. var shift = 0;
  81944. // scale factor for offset
  81945. var expansion = 1;
  81946. var rect = zrEl.getBoundingRect();
  81947. var rectWidth = rect.width;
  81948. var rectHeight = rect.height;
  81949. if (fill.type === 'linear') {
  81950. gradientType = 'gradient';
  81951. var transform = zrEl.transform;
  81952. var p0 = [fill.x * rectWidth, fill.y * rectHeight];
  81953. var p1 = [fill.x2 * rectWidth, fill.y2 * rectHeight];
  81954. if (transform) {
  81955. applyTransform(p0, p0, transform);
  81956. applyTransform(p1, p1, transform);
  81957. }
  81958. var dx = p1[0] - p0[0];
  81959. var dy = p1[1] - p0[1];
  81960. angle = Math.atan2(dx, dy) * 180 / Math.PI;
  81961. // The angle should be a non-negative number.
  81962. if (angle < 0) {
  81963. angle += 360;
  81964. }
  81965. // Very small angles produce an unexpected result because they are
  81966. // converted to a scientific notation string.
  81967. if (angle < 1e-6) {
  81968. angle = 0;
  81969. }
  81970. }
  81971. else {
  81972. gradientType = 'gradientradial';
  81973. var p0 = [fill.x * rectWidth, fill.y * rectHeight];
  81974. var transform = zrEl.transform;
  81975. var scale$$1 = zrEl.scale;
  81976. var width = rectWidth;
  81977. var height = rectHeight;
  81978. focus = [
  81979. // Percent in bounding rect
  81980. (p0[0] - rect.x) / width,
  81981. (p0[1] - rect.y) / height
  81982. ];
  81983. if (transform) {
  81984. applyTransform(p0, p0, transform);
  81985. }
  81986. width /= scale$$1[0] * Z;
  81987. height /= scale$$1[1] * Z;
  81988. var dimension = mathMax$9(width, height);
  81989. shift = 2 * 0 / dimension;
  81990. expansion = 2 * fill.r / dimension - shift;
  81991. }
  81992. // We need to sort the color stops in ascending order by offset,
  81993. // otherwise IE won't interpret it correctly.
  81994. var stops = fill.colorStops.slice();
  81995. stops.sort(function (cs1, cs2) {
  81996. return cs1.offset - cs2.offset;
  81997. });
  81998. var length$$1 = stops.length;
  81999. // Color and alpha list of first and last stop
  82000. var colorAndAlphaList = [];
  82001. var colors = [];
  82002. for (var i = 0; i < length$$1; i++) {
  82003. var stop = stops[i];
  82004. var colorAndAlpha = getColorAndAlpha(stop.color);
  82005. colors.push(stop.offset * expansion + shift + ' ' + colorAndAlpha[0]);
  82006. if (i === 0 || i === length$$1 - 1) {
  82007. colorAndAlphaList.push(colorAndAlpha);
  82008. }
  82009. }
  82010. if (length$$1 >= 2) {
  82011. var color1 = colorAndAlphaList[0][0];
  82012. var color2 = colorAndAlphaList[1][0];
  82013. var opacity1 = colorAndAlphaList[0][1] * style.opacity;
  82014. var opacity2 = colorAndAlphaList[1][1] * style.opacity;
  82015. el.type = gradientType;
  82016. el.method = 'none';
  82017. el.focus = '100%';
  82018. el.angle = angle;
  82019. el.color = color1;
  82020. el.color2 = color2;
  82021. el.colors = colors.join(',');
  82022. // When colors attribute is used, the meanings of opacity and o:opacity2
  82023. // are reversed.
  82024. el.opacity = opacity2;
  82025. // FIXME g_o_:opacity ?
  82026. el.opacity2 = opacity1;
  82027. }
  82028. if (gradientType === 'radial') {
  82029. el.focusposition = focus.join(',');
  82030. }
  82031. }
  82032. else {
  82033. // FIXME Change from Gradient fill to color fill
  82034. setColorAndOpacity(el, fill, style.opacity);
  82035. }
  82036. }
  82037. };
  82038. var updateStrokeNode = function (el, style) {
  82039. // if (style.lineJoin != null) {
  82040. // el.joinstyle = style.lineJoin;
  82041. // }
  82042. // if (style.miterLimit != null) {
  82043. // el.miterlimit = style.miterLimit * Z;
  82044. // }
  82045. // if (style.lineCap != null) {
  82046. // el.endcap = style.lineCap;
  82047. // }
  82048. if (style.lineDash) {
  82049. el.dashstyle = style.lineDash.join(' ');
  82050. }
  82051. if (style.stroke != null && !(style.stroke instanceof Gradient)) {
  82052. setColorAndOpacity(el, style.stroke, style.opacity);
  82053. }
  82054. };
  82055. var updateFillAndStroke = function (vmlEl, type, style, zrEl) {
  82056. var isFill = type === 'fill';
  82057. var el = vmlEl.getElementsByTagName(type)[0];
  82058. // Stroke must have lineWidth
  82059. if (style[type] != null && style[type] !== 'none' && (isFill || (!isFill && style.lineWidth))) {
  82060. vmlEl[isFill ? 'filled' : 'stroked'] = 'true';
  82061. // FIXME Remove before updating, or set `colors` will throw error
  82062. if (style[type] instanceof Gradient) {
  82063. remove(vmlEl, el);
  82064. }
  82065. if (!el) {
  82066. el = createNode(type);
  82067. }
  82068. isFill ? updateFillNode(el, style, zrEl) : updateStrokeNode(el, style);
  82069. append(vmlEl, el);
  82070. }
  82071. else {
  82072. vmlEl[isFill ? 'filled' : 'stroked'] = 'false';
  82073. remove(vmlEl, el);
  82074. }
  82075. };
  82076. var points$3 = [[], [], []];
  82077. var pathDataToString = function (path, m) {
  82078. var M = CMD$3.M;
  82079. var C = CMD$3.C;
  82080. var L = CMD$3.L;
  82081. var A = CMD$3.A;
  82082. var Q = CMD$3.Q;
  82083. var str = [];
  82084. var nPoint;
  82085. var cmdStr;
  82086. var cmd;
  82087. var i;
  82088. var xi;
  82089. var yi;
  82090. var data = path.data;
  82091. var dataLength = path.len();
  82092. for (i = 0; i < dataLength;) {
  82093. cmd = data[i++];
  82094. cmdStr = '';
  82095. nPoint = 0;
  82096. switch (cmd) {
  82097. case M:
  82098. cmdStr = ' m ';
  82099. nPoint = 1;
  82100. xi = data[i++];
  82101. yi = data[i++];
  82102. points$3[0][0] = xi;
  82103. points$3[0][1] = yi;
  82104. break;
  82105. case L:
  82106. cmdStr = ' l ';
  82107. nPoint = 1;
  82108. xi = data[i++];
  82109. yi = data[i++];
  82110. points$3[0][0] = xi;
  82111. points$3[0][1] = yi;
  82112. break;
  82113. case Q:
  82114. case C:
  82115. cmdStr = ' c ';
  82116. nPoint = 3;
  82117. var x1 = data[i++];
  82118. var y1 = data[i++];
  82119. var x2 = data[i++];
  82120. var y2 = data[i++];
  82121. var x3;
  82122. var y3;
  82123. if (cmd === Q) {
  82124. // Convert quadratic to cubic using degree elevation
  82125. x3 = x2;
  82126. y3 = y2;
  82127. x2 = (x2 + 2 * x1) / 3;
  82128. y2 = (y2 + 2 * y1) / 3;
  82129. x1 = (xi + 2 * x1) / 3;
  82130. y1 = (yi + 2 * y1) / 3;
  82131. }
  82132. else {
  82133. x3 = data[i++];
  82134. y3 = data[i++];
  82135. }
  82136. points$3[0][0] = x1;
  82137. points$3[0][1] = y1;
  82138. points$3[1][0] = x2;
  82139. points$3[1][1] = y2;
  82140. points$3[2][0] = x3;
  82141. points$3[2][1] = y3;
  82142. xi = x3;
  82143. yi = y3;
  82144. break;
  82145. case A:
  82146. var x = 0;
  82147. var y = 0;
  82148. var sx = 1;
  82149. var sy = 1;
  82150. var angle = 0;
  82151. if (m) {
  82152. // Extract SRT from matrix
  82153. x = m[4];
  82154. y = m[5];
  82155. sx = sqrt(m[0] * m[0] + m[1] * m[1]);
  82156. sy = sqrt(m[2] * m[2] + m[3] * m[3]);
  82157. angle = Math.atan2(-m[1] / sy, m[0] / sx);
  82158. }
  82159. var cx = data[i++];
  82160. var cy = data[i++];
  82161. var rx = data[i++];
  82162. var ry = data[i++];
  82163. var startAngle = data[i++] + angle;
  82164. var endAngle = data[i++] + startAngle + angle;
  82165. // FIXME
  82166. // var psi = data[i++];
  82167. i++;
  82168. var clockwise = data[i++];
  82169. var x0 = cx + cos(startAngle) * rx;
  82170. var y0 = cy + sin(startAngle) * ry;
  82171. var x1 = cx + cos(endAngle) * rx;
  82172. var y1 = cy + sin(endAngle) * ry;
  82173. var type = clockwise ? ' wa ' : ' at ';
  82174. if (Math.abs(x0 - x1) < 1e-4) {
  82175. // IE won't render arches drawn counter clockwise if x0 == x1.
  82176. if (Math.abs(endAngle - startAngle) > 1e-2) {
  82177. // Offset x0 by 1/80 of a pixel. Use something
  82178. // that can be represented in binary
  82179. if (clockwise) {
  82180. x0 += 270 / Z;
  82181. }
  82182. }
  82183. else {
  82184. // Avoid case draw full circle
  82185. if (Math.abs(y0 - cy) < 1e-4) {
  82186. if ((clockwise && x0 < cx) || (!clockwise && x0 > cx)) {
  82187. y1 -= 270 / Z;
  82188. }
  82189. else {
  82190. y1 += 270 / Z;
  82191. }
  82192. }
  82193. else if ((clockwise && y0 < cy) || (!clockwise && y0 > cy)) {
  82194. x1 += 270 / Z;
  82195. }
  82196. else {
  82197. x1 -= 270 / Z;
  82198. }
  82199. }
  82200. }
  82201. str.push(
  82202. type,
  82203. round$3(((cx - rx) * sx + x) * Z - Z2), comma,
  82204. round$3(((cy - ry) * sy + y) * Z - Z2), comma,
  82205. round$3(((cx + rx) * sx + x) * Z - Z2), comma,
  82206. round$3(((cy + ry) * sy + y) * Z - Z2), comma,
  82207. round$3((x0 * sx + x) * Z - Z2), comma,
  82208. round$3((y0 * sy + y) * Z - Z2), comma,
  82209. round$3((x1 * sx + x) * Z - Z2), comma,
  82210. round$3((y1 * sy + y) * Z - Z2)
  82211. );
  82212. xi = x1;
  82213. yi = y1;
  82214. break;
  82215. case CMD$3.R:
  82216. var p0 = points$3[0];
  82217. var p1 = points$3[1];
  82218. // x0, y0
  82219. p0[0] = data[i++];
  82220. p0[1] = data[i++];
  82221. // x1, y1
  82222. p1[0] = p0[0] + data[i++];
  82223. p1[1] = p0[1] + data[i++];
  82224. if (m) {
  82225. applyTransform(p0, p0, m);
  82226. applyTransform(p1, p1, m);
  82227. }
  82228. p0[0] = round$3(p0[0] * Z - Z2);
  82229. p1[0] = round$3(p1[0] * Z - Z2);
  82230. p0[1] = round$3(p0[1] * Z - Z2);
  82231. p1[1] = round$3(p1[1] * Z - Z2);
  82232. str.push(
  82233. // x0, y0
  82234. ' m ', p0[0], comma, p0[1],
  82235. // x1, y0
  82236. ' l ', p1[0], comma, p0[1],
  82237. // x1, y1
  82238. ' l ', p1[0], comma, p1[1],
  82239. // x0, y1
  82240. ' l ', p0[0], comma, p1[1]
  82241. );
  82242. break;
  82243. case CMD$3.Z:
  82244. // FIXME Update xi, yi
  82245. str.push(' x ');
  82246. }
  82247. if (nPoint > 0) {
  82248. str.push(cmdStr);
  82249. for (var k = 0; k < nPoint; k++) {
  82250. var p = points$3[k];
  82251. m && applyTransform(p, p, m);
  82252. // 不 round 会非常慢
  82253. str.push(
  82254. round$3(p[0] * Z - Z2), comma, round$3(p[1] * Z - Z2),
  82255. k < nPoint - 1 ? comma : ''
  82256. );
  82257. }
  82258. }
  82259. }
  82260. return str.join('');
  82261. };
  82262. // Rewrite the original path method
  82263. Path.prototype.brushVML = function (vmlRoot) {
  82264. var style = this.style;
  82265. var vmlEl = this._vmlEl;
  82266. if (!vmlEl) {
  82267. vmlEl = createNode('shape');
  82268. initRootElStyle(vmlEl);
  82269. this._vmlEl = vmlEl;
  82270. }
  82271. updateFillAndStroke(vmlEl, 'fill', style, this);
  82272. updateFillAndStroke(vmlEl, 'stroke', style, this);
  82273. var m = this.transform;
  82274. var needTransform = m != null;
  82275. var strokeEl = vmlEl.getElementsByTagName('stroke')[0];
  82276. if (strokeEl) {
  82277. var lineWidth = style.lineWidth;
  82278. // Get the line scale.
  82279. // Determinant of this.m_ means how much the area is enlarged by the
  82280. // transformation. So its square root can be used as a scale factor
  82281. // for width.
  82282. if (needTransform && !style.strokeNoScale) {
  82283. var det = m[0] * m[3] - m[1] * m[2];
  82284. lineWidth *= sqrt(abs$1(det));
  82285. }
  82286. strokeEl.weight = lineWidth + 'px';
  82287. }
  82288. var path = this.path || (this.path = new PathProxy());
  82289. if (this.__dirtyPath) {
  82290. path.beginPath();
  82291. path.subPixelOptimize = false;
  82292. this.buildPath(path, this.shape);
  82293. path.toStatic();
  82294. this.__dirtyPath = false;
  82295. }
  82296. vmlEl.path = pathDataToString(path, this.transform);
  82297. vmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  82298. // Append to root
  82299. append(vmlRoot, vmlEl);
  82300. // Text
  82301. if (style.text != null) {
  82302. this.drawRectText(vmlRoot, this.getBoundingRect());
  82303. }
  82304. else {
  82305. this.removeRectText(vmlRoot);
  82306. }
  82307. };
  82308. Path.prototype.onRemove = function (vmlRoot) {
  82309. remove(vmlRoot, this._vmlEl);
  82310. this.removeRectText(vmlRoot);
  82311. };
  82312. Path.prototype.onAdd = function (vmlRoot) {
  82313. append(vmlRoot, this._vmlEl);
  82314. this.appendRectText(vmlRoot);
  82315. };
  82316. /***************************************************
  82317. * IMAGE
  82318. **************************************************/
  82319. var isImage = function (img) {
  82320. // FIXME img instanceof Image 如果 img 是一个字符串的时候,IE8 下会报错
  82321. return (typeof img === 'object') && img.tagName && img.tagName.toUpperCase() === 'IMG';
  82322. // return img instanceof Image;
  82323. };
  82324. // Rewrite the original path method
  82325. ZImage.prototype.brushVML = function (vmlRoot) {
  82326. var style = this.style;
  82327. var image = style.image;
  82328. // Image original width, height
  82329. var ow;
  82330. var oh;
  82331. if (isImage(image)) {
  82332. var src = image.src;
  82333. if (src === this._imageSrc) {
  82334. ow = this._imageWidth;
  82335. oh = this._imageHeight;
  82336. }
  82337. else {
  82338. var imageRuntimeStyle = image.runtimeStyle;
  82339. var oldRuntimeWidth = imageRuntimeStyle.width;
  82340. var oldRuntimeHeight = imageRuntimeStyle.height;
  82341. imageRuntimeStyle.width = 'auto';
  82342. imageRuntimeStyle.height = 'auto';
  82343. // get the original size
  82344. ow = image.width;
  82345. oh = image.height;
  82346. // and remove overides
  82347. imageRuntimeStyle.width = oldRuntimeWidth;
  82348. imageRuntimeStyle.height = oldRuntimeHeight;
  82349. // Caching image original width, height and src
  82350. this._imageSrc = src;
  82351. this._imageWidth = ow;
  82352. this._imageHeight = oh;
  82353. }
  82354. image = src;
  82355. }
  82356. else {
  82357. if (image === this._imageSrc) {
  82358. ow = this._imageWidth;
  82359. oh = this._imageHeight;
  82360. }
  82361. }
  82362. if (!image) {
  82363. return;
  82364. }
  82365. var x = style.x || 0;
  82366. var y = style.y || 0;
  82367. var dw = style.width;
  82368. var dh = style.height;
  82369. var sw = style.sWidth;
  82370. var sh = style.sHeight;
  82371. var sx = style.sx || 0;
  82372. var sy = style.sy || 0;
  82373. var hasCrop = sw && sh;
  82374. var vmlEl = this._vmlEl;
  82375. if (!vmlEl) {
  82376. // FIXME 使用 group 在 left, top 都不是 0 的时候就无法显示了。
  82377. // vmlEl = vmlCore.createNode('group');
  82378. vmlEl = doc.createElement('div');
  82379. initRootElStyle(vmlEl);
  82380. this._vmlEl = vmlEl;
  82381. }
  82382. var vmlElStyle = vmlEl.style;
  82383. var hasRotation = false;
  82384. var m;
  82385. var scaleX = 1;
  82386. var scaleY = 1;
  82387. if (this.transform) {
  82388. m = this.transform;
  82389. scaleX = sqrt(m[0] * m[0] + m[1] * m[1]);
  82390. scaleY = sqrt(m[2] * m[2] + m[3] * m[3]);
  82391. hasRotation = m[1] || m[2];
  82392. }
  82393. if (hasRotation) {
  82394. // If filters are necessary (rotation exists), create them
  82395. // filters are bog-slow, so only create them if abbsolutely necessary
  82396. // The following check doesn't account for skews (which don't exist
  82397. // in the canvas spec (yet) anyway.
  82398. // From excanvas
  82399. var p0 = [x, y];
  82400. var p1 = [x + dw, y];
  82401. var p2 = [x, y + dh];
  82402. var p3 = [x + dw, y + dh];
  82403. applyTransform(p0, p0, m);
  82404. applyTransform(p1, p1, m);
  82405. applyTransform(p2, p2, m);
  82406. applyTransform(p3, p3, m);
  82407. var maxX = mathMax$9(p0[0], p1[0], p2[0], p3[0]);
  82408. var maxY = mathMax$9(p0[1], p1[1], p2[1], p3[1]);
  82409. var transformFilter = [];
  82410. transformFilter.push('M11=', m[0] / scaleX, comma,
  82411. 'M12=', m[2] / scaleY, comma,
  82412. 'M21=', m[1] / scaleX, comma,
  82413. 'M22=', m[3] / scaleY, comma,
  82414. 'Dx=', round$3(x * scaleX + m[4]), comma,
  82415. 'Dy=', round$3(y * scaleY + m[5]));
  82416. vmlElStyle.padding = '0 ' + round$3(maxX) + 'px ' + round$3(maxY) + 'px 0';
  82417. // FIXME DXImageTransform 在 IE11 的兼容模式下不起作用
  82418. vmlElStyle.filter = imageTransformPrefix + '.Matrix('
  82419. + transformFilter.join('') + ', SizingMethod=clip)';
  82420. }
  82421. else {
  82422. if (m) {
  82423. x = x * scaleX + m[4];
  82424. y = y * scaleY + m[5];
  82425. }
  82426. vmlElStyle.filter = '';
  82427. vmlElStyle.left = round$3(x) + 'px';
  82428. vmlElStyle.top = round$3(y) + 'px';
  82429. }
  82430. var imageEl = this._imageEl;
  82431. var cropEl = this._cropEl;
  82432. if (!imageEl) {
  82433. imageEl = doc.createElement('div');
  82434. this._imageEl = imageEl;
  82435. }
  82436. var imageELStyle = imageEl.style;
  82437. if (hasCrop) {
  82438. // Needs know image original width and height
  82439. if (!(ow && oh)) {
  82440. var tmpImage = new Image();
  82441. var self = this;
  82442. tmpImage.onload = function () {
  82443. tmpImage.onload = null;
  82444. ow = tmpImage.width;
  82445. oh = tmpImage.height;
  82446. // Adjust image width and height to fit the ratio destinationSize / sourceSize
  82447. imageELStyle.width = round$3(scaleX * ow * dw / sw) + 'px';
  82448. imageELStyle.height = round$3(scaleY * oh * dh / sh) + 'px';
  82449. // Caching image original width, height and src
  82450. self._imageWidth = ow;
  82451. self._imageHeight = oh;
  82452. self._imageSrc = image;
  82453. };
  82454. tmpImage.src = image;
  82455. }
  82456. else {
  82457. imageELStyle.width = round$3(scaleX * ow * dw / sw) + 'px';
  82458. imageELStyle.height = round$3(scaleY * oh * dh / sh) + 'px';
  82459. }
  82460. if (!cropEl) {
  82461. cropEl = doc.createElement('div');
  82462. cropEl.style.overflow = 'hidden';
  82463. this._cropEl = cropEl;
  82464. }
  82465. var cropElStyle = cropEl.style;
  82466. cropElStyle.width = round$3((dw + sx * dw / sw) * scaleX);
  82467. cropElStyle.height = round$3((dh + sy * dh / sh) * scaleY);
  82468. cropElStyle.filter = imageTransformPrefix + '.Matrix(Dx='
  82469. + (-sx * dw / sw * scaleX) + ',Dy=' + (-sy * dh / sh * scaleY) + ')';
  82470. if (!cropEl.parentNode) {
  82471. vmlEl.appendChild(cropEl);
  82472. }
  82473. if (imageEl.parentNode !== cropEl) {
  82474. cropEl.appendChild(imageEl);
  82475. }
  82476. }
  82477. else {
  82478. imageELStyle.width = round$3(scaleX * dw) + 'px';
  82479. imageELStyle.height = round$3(scaleY * dh) + 'px';
  82480. vmlEl.appendChild(imageEl);
  82481. if (cropEl && cropEl.parentNode) {
  82482. vmlEl.removeChild(cropEl);
  82483. this._cropEl = null;
  82484. }
  82485. }
  82486. var filterStr = '';
  82487. var alpha = style.opacity;
  82488. if (alpha < 1) {
  82489. filterStr += '.Alpha(opacity=' + round$3(alpha * 100) + ') ';
  82490. }
  82491. filterStr += imageTransformPrefix + '.AlphaImageLoader(src=' + image + ', SizingMethod=scale)';
  82492. imageELStyle.filter = filterStr;
  82493. vmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  82494. // Append to root
  82495. append(vmlRoot, vmlEl);
  82496. // Text
  82497. if (style.text != null) {
  82498. this.drawRectText(vmlRoot, this.getBoundingRect());
  82499. }
  82500. };
  82501. ZImage.prototype.onRemove = function (vmlRoot) {
  82502. remove(vmlRoot, this._vmlEl);
  82503. this._vmlEl = null;
  82504. this._cropEl = null;
  82505. this._imageEl = null;
  82506. this.removeRectText(vmlRoot);
  82507. };
  82508. ZImage.prototype.onAdd = function (vmlRoot) {
  82509. append(vmlRoot, this._vmlEl);
  82510. this.appendRectText(vmlRoot);
  82511. };
  82512. /***************************************************
  82513. * TEXT
  82514. **************************************************/
  82515. var DEFAULT_STYLE_NORMAL = 'normal';
  82516. var fontStyleCache = {};
  82517. var fontStyleCacheCount = 0;
  82518. var MAX_FONT_CACHE_SIZE = 100;
  82519. var fontEl = document.createElement('div');
  82520. var getFontStyle = function (fontString) {
  82521. var fontStyle = fontStyleCache[fontString];
  82522. if (!fontStyle) {
  82523. // Clear cache
  82524. if (fontStyleCacheCount > MAX_FONT_CACHE_SIZE) {
  82525. fontStyleCacheCount = 0;
  82526. fontStyleCache = {};
  82527. }
  82528. var style = fontEl.style;
  82529. var fontFamily;
  82530. try {
  82531. style.font = fontString;
  82532. fontFamily = style.fontFamily.split(',')[0];
  82533. }
  82534. catch (e) {
  82535. }
  82536. fontStyle = {
  82537. style: style.fontStyle || DEFAULT_STYLE_NORMAL,
  82538. variant: style.fontVariant || DEFAULT_STYLE_NORMAL,
  82539. weight: style.fontWeight || DEFAULT_STYLE_NORMAL,
  82540. size: parseFloat(style.fontSize || 12) | 0,
  82541. family: fontFamily || 'Microsoft YaHei'
  82542. };
  82543. fontStyleCache[fontString] = fontStyle;
  82544. fontStyleCacheCount++;
  82545. }
  82546. return fontStyle;
  82547. };
  82548. var textMeasureEl;
  82549. // Overwrite measure text method
  82550. $override$1('measureText', function (text, textFont) {
  82551. var doc$$1 = doc;
  82552. if (!textMeasureEl) {
  82553. textMeasureEl = doc$$1.createElement('div');
  82554. textMeasureEl.style.cssText = 'position:absolute;top:-20000px;left:0;'
  82555. + 'padding:0;margin:0;border:none;white-space:pre;';
  82556. doc.body.appendChild(textMeasureEl);
  82557. }
  82558. try {
  82559. textMeasureEl.style.font = textFont;
  82560. }
  82561. catch (ex) {
  82562. // Ignore failures to set to invalid font.
  82563. }
  82564. textMeasureEl.innerHTML = '';
  82565. // Don't use innerHTML or innerText because they allow markup/whitespace.
  82566. textMeasureEl.appendChild(doc$$1.createTextNode(text));
  82567. return {
  82568. width: textMeasureEl.offsetWidth
  82569. };
  82570. });
  82571. var tmpRect$2 = new BoundingRect();
  82572. var drawRectText = function (vmlRoot, rect, textRect, fromTextEl) {
  82573. var style = this.style;
  82574. // Optimize, avoid normalize every time.
  82575. this.__dirty && normalizeTextStyle(style, true);
  82576. var text = style.text;
  82577. // Convert to string
  82578. text != null && (text += '');
  82579. if (!text) {
  82580. return;
  82581. }
  82582. // Convert rich text to plain text. Rich text is not supported in
  82583. // IE8-, but tags in rich text template will be removed.
  82584. if (style.rich) {
  82585. var contentBlock = parseRichText(text, style);
  82586. text = [];
  82587. for (var i = 0; i < contentBlock.lines.length; i++) {
  82588. var tokens = contentBlock.lines[i].tokens;
  82589. var textLine = [];
  82590. for (var j = 0; j < tokens.length; j++) {
  82591. textLine.push(tokens[j].text);
  82592. }
  82593. text.push(textLine.join(''));
  82594. }
  82595. text = text.join('\n');
  82596. }
  82597. var x;
  82598. var y;
  82599. var align = style.textAlign;
  82600. var verticalAlign = style.textVerticalAlign;
  82601. var fontStyle = getFontStyle(style.font);
  82602. // FIXME encodeHtmlAttribute ?
  82603. var font = fontStyle.style + ' ' + fontStyle.variant + ' ' + fontStyle.weight + ' '
  82604. + fontStyle.size + 'px "' + fontStyle.family + '"';
  82605. textRect = textRect || getBoundingRect(
  82606. text, font, align, verticalAlign, style.textPadding, style.textLineHeight
  82607. );
  82608. // Transform rect to view space
  82609. var m = this.transform;
  82610. // Ignore transform for text in other element
  82611. if (m && !fromTextEl) {
  82612. tmpRect$2.copy(rect);
  82613. tmpRect$2.applyTransform(m);
  82614. rect = tmpRect$2;
  82615. }
  82616. if (!fromTextEl) {
  82617. var textPosition = style.textPosition;
  82618. // Text position represented by coord
  82619. if (textPosition instanceof Array) {
  82620. x = rect.x + parsePercent$3(textPosition[0], rect.width);
  82621. y = rect.y + parsePercent$3(textPosition[1], rect.height);
  82622. align = align || 'left';
  82623. }
  82624. else {
  82625. var res = this.calculateTextPosition
  82626. ? this.calculateTextPosition({}, style, rect)
  82627. : calculateTextPosition({}, style, rect);
  82628. x = res.x;
  82629. y = res.y;
  82630. // Default align and baseline when has textPosition
  82631. align = align || res.textAlign;
  82632. verticalAlign = verticalAlign || res.textVerticalAlign;
  82633. }
  82634. }
  82635. else {
  82636. x = rect.x;
  82637. y = rect.y;
  82638. }
  82639. x = adjustTextX(x, textRect.width, align);
  82640. y = adjustTextY(y, textRect.height, verticalAlign);
  82641. // Force baseline 'middle'
  82642. y += textRect.height / 2;
  82643. // var fontSize = fontStyle.size;
  82644. // 1.75 is an arbitrary number, as there is no info about the text baseline
  82645. // switch (baseline) {
  82646. // case 'hanging':
  82647. // case 'top':
  82648. // y += fontSize / 1.75;
  82649. // break;
  82650. // case 'middle':
  82651. // break;
  82652. // default:
  82653. // // case null:
  82654. // // case 'alphabetic':
  82655. // // case 'ideographic':
  82656. // // case 'bottom':
  82657. // y -= fontSize / 2.25;
  82658. // break;
  82659. // }
  82660. // switch (align) {
  82661. // case 'left':
  82662. // break;
  82663. // case 'center':
  82664. // x -= textRect.width / 2;
  82665. // break;
  82666. // case 'right':
  82667. // x -= textRect.width;
  82668. // break;
  82669. // case 'end':
  82670. // align = elementStyle.direction == 'ltr' ? 'right' : 'left';
  82671. // break;
  82672. // case 'start':
  82673. // align = elementStyle.direction == 'rtl' ? 'right' : 'left';
  82674. // break;
  82675. // default:
  82676. // align = 'left';
  82677. // }
  82678. var createNode$$1 = createNode;
  82679. var textVmlEl = this._textVmlEl;
  82680. var pathEl;
  82681. var textPathEl;
  82682. var skewEl;
  82683. if (!textVmlEl) {
  82684. textVmlEl = createNode$$1('line');
  82685. pathEl = createNode$$1('path');
  82686. textPathEl = createNode$$1('textpath');
  82687. skewEl = createNode$$1('skew');
  82688. // FIXME Why here is not cammel case
  82689. // Align 'center' seems wrong
  82690. textPathEl.style['v-text-align'] = 'left';
  82691. initRootElStyle(textVmlEl);
  82692. pathEl.textpathok = true;
  82693. textPathEl.on = true;
  82694. textVmlEl.from = '0 0';
  82695. textVmlEl.to = '1000 0.05';
  82696. append(textVmlEl, skewEl);
  82697. append(textVmlEl, pathEl);
  82698. append(textVmlEl, textPathEl);
  82699. this._textVmlEl = textVmlEl;
  82700. }
  82701. else {
  82702. // 这里是在前面 appendChild 保证顺序的前提下
  82703. skewEl = textVmlEl.firstChild;
  82704. pathEl = skewEl.nextSibling;
  82705. textPathEl = pathEl.nextSibling;
  82706. }
  82707. var coords = [x, y];
  82708. var textVmlElStyle = textVmlEl.style;
  82709. // Ignore transform for text in other element
  82710. if (m && fromTextEl) {
  82711. applyTransform(coords, coords, m);
  82712. skewEl.on = true;
  82713. skewEl.matrix = m[0].toFixed(3) + comma + m[2].toFixed(3) + comma
  82714. + m[1].toFixed(3) + comma + m[3].toFixed(3) + ',0,0';
  82715. // Text position
  82716. skewEl.offset = (round$3(coords[0]) || 0) + ',' + (round$3(coords[1]) || 0);
  82717. // Left top point as origin
  82718. skewEl.origin = '0 0';
  82719. textVmlElStyle.left = '0px';
  82720. textVmlElStyle.top = '0px';
  82721. }
  82722. else {
  82723. skewEl.on = false;
  82724. textVmlElStyle.left = round$3(x) + 'px';
  82725. textVmlElStyle.top = round$3(y) + 'px';
  82726. }
  82727. textPathEl.string = encodeHtmlAttribute(text);
  82728. // TODO
  82729. try {
  82730. textPathEl.style.font = font;
  82731. }
  82732. // Error font format
  82733. catch (e) {}
  82734. updateFillAndStroke(textVmlEl, 'fill', {
  82735. fill: style.textFill,
  82736. opacity: style.opacity
  82737. }, this);
  82738. updateFillAndStroke(textVmlEl, 'stroke', {
  82739. stroke: style.textStroke,
  82740. opacity: style.opacity,
  82741. lineDash: style.lineDash || null // style.lineDash can be `false`.
  82742. }, this);
  82743. textVmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  82744. // Attached to root
  82745. append(vmlRoot, textVmlEl);
  82746. };
  82747. var removeRectText = function (vmlRoot) {
  82748. remove(vmlRoot, this._textVmlEl);
  82749. this._textVmlEl = null;
  82750. };
  82751. var appendRectText = function (vmlRoot) {
  82752. append(vmlRoot, this._textVmlEl);
  82753. };
  82754. var list = [RectText, Displayable, ZImage, Path, Text];
  82755. // In case Displayable has been mixed in RectText
  82756. for (var i$3 = 0; i$3 < list.length; i$3++) {
  82757. var proto$8 = list[i$3].prototype;
  82758. proto$8.drawRectText = drawRectText;
  82759. proto$8.removeRectText = removeRectText;
  82760. proto$8.appendRectText = appendRectText;
  82761. }
  82762. Text.prototype.brushVML = function (vmlRoot) {
  82763. var style = this.style;
  82764. if (style.text != null) {
  82765. this.drawRectText(vmlRoot, {
  82766. x: style.x || 0, y: style.y || 0,
  82767. width: 0, height: 0
  82768. }, this.getBoundingRect(), true);
  82769. }
  82770. else {
  82771. this.removeRectText(vmlRoot);
  82772. }
  82773. };
  82774. Text.prototype.onRemove = function (vmlRoot) {
  82775. this.removeRectText(vmlRoot);
  82776. };
  82777. Text.prototype.onAdd = function (vmlRoot) {
  82778. this.appendRectText(vmlRoot);
  82779. };
  82780. }
  82781. /**
  82782. * VML Painter.
  82783. *
  82784. * @module zrender/vml/Painter
  82785. */
  82786. function parseInt10$1(val) {
  82787. return parseInt(val, 10);
  82788. }
  82789. /**
  82790. * @alias module:zrender/vml/Painter
  82791. */
  82792. function VMLPainter(root, storage) {
  82793. initVML();
  82794. this.root = root;
  82795. this.storage = storage;
  82796. var vmlViewport = document.createElement('div');
  82797. var vmlRoot = document.createElement('div');
  82798. vmlViewport.style.cssText = 'display:inline-block;overflow:hidden;position:relative;width:300px;height:150px;';
  82799. vmlRoot.style.cssText = 'position:absolute;left:0;top:0;';
  82800. root.appendChild(vmlViewport);
  82801. this._vmlRoot = vmlRoot;
  82802. this._vmlViewport = vmlViewport;
  82803. this.resize();
  82804. // Modify storage
  82805. var oldDelFromStorage = storage.delFromStorage;
  82806. var oldAddToStorage = storage.addToStorage;
  82807. storage.delFromStorage = function (el) {
  82808. oldDelFromStorage.call(storage, el);
  82809. if (el) {
  82810. el.onRemove && el.onRemove(vmlRoot);
  82811. }
  82812. };
  82813. storage.addToStorage = function (el) {
  82814. // Displayable already has a vml node
  82815. el.onAdd && el.onAdd(vmlRoot);
  82816. oldAddToStorage.call(storage, el);
  82817. };
  82818. this._firstPaint = true;
  82819. }
  82820. VMLPainter.prototype = {
  82821. constructor: VMLPainter,
  82822. getType: function () {
  82823. return 'vml';
  82824. },
  82825. /**
  82826. * @return {HTMLDivElement}
  82827. */
  82828. getViewportRoot: function () {
  82829. return this._vmlViewport;
  82830. },
  82831. getViewportRootOffset: function () {
  82832. var viewportRoot = this.getViewportRoot();
  82833. if (viewportRoot) {
  82834. return {
  82835. offsetLeft: viewportRoot.offsetLeft || 0,
  82836. offsetTop: viewportRoot.offsetTop || 0
  82837. };
  82838. }
  82839. },
  82840. /**
  82841. * 刷新
  82842. */
  82843. refresh: function () {
  82844. var list = this.storage.getDisplayList(true, true);
  82845. this._paintList(list);
  82846. },
  82847. _paintList: function (list) {
  82848. var vmlRoot = this._vmlRoot;
  82849. for (var i = 0; i < list.length; i++) {
  82850. var el = list[i];
  82851. if (el.invisible || el.ignore) {
  82852. if (!el.__alreadyNotVisible) {
  82853. el.onRemove(vmlRoot);
  82854. }
  82855. // Set as already invisible
  82856. el.__alreadyNotVisible = true;
  82857. }
  82858. else {
  82859. if (el.__alreadyNotVisible) {
  82860. el.onAdd(vmlRoot);
  82861. }
  82862. el.__alreadyNotVisible = false;
  82863. if (el.__dirty) {
  82864. el.beforeBrush && el.beforeBrush();
  82865. (el.brushVML || el.brush).call(el, vmlRoot);
  82866. el.afterBrush && el.afterBrush();
  82867. }
  82868. }
  82869. el.__dirty = false;
  82870. }
  82871. if (this._firstPaint) {
  82872. // Detached from document at first time
  82873. // to avoid page refreshing too many times
  82874. // FIXME 如果每次都先 removeChild 可能会导致一些填充和描边的效果改变
  82875. this._vmlViewport.appendChild(vmlRoot);
  82876. this._firstPaint = false;
  82877. }
  82878. },
  82879. resize: function (width, height) {
  82880. var width = width == null ? this._getWidth() : width;
  82881. var height = height == null ? this._getHeight() : height;
  82882. if (this._width !== width || this._height !== height) {
  82883. this._width = width;
  82884. this._height = height;
  82885. var vmlViewportStyle = this._vmlViewport.style;
  82886. vmlViewportStyle.width = width + 'px';
  82887. vmlViewportStyle.height = height + 'px';
  82888. }
  82889. },
  82890. dispose: function () {
  82891. this.root.innerHTML = '';
  82892. this._vmlRoot =
  82893. this._vmlViewport =
  82894. this.storage = null;
  82895. },
  82896. getWidth: function () {
  82897. return this._width;
  82898. },
  82899. getHeight: function () {
  82900. return this._height;
  82901. },
  82902. clear: function () {
  82903. if (this._vmlViewport) {
  82904. this.root.removeChild(this._vmlViewport);
  82905. }
  82906. },
  82907. _getWidth: function () {
  82908. var root = this.root;
  82909. var stl = root.currentStyle;
  82910. return ((root.clientWidth || parseInt10$1(stl.width))
  82911. - parseInt10$1(stl.paddingLeft)
  82912. - parseInt10$1(stl.paddingRight)) | 0;
  82913. },
  82914. _getHeight: function () {
  82915. var root = this.root;
  82916. var stl = root.currentStyle;
  82917. return ((root.clientHeight || parseInt10$1(stl.height))
  82918. - parseInt10$1(stl.paddingTop)
  82919. - parseInt10$1(stl.paddingBottom)) | 0;
  82920. }
  82921. };
  82922. // Not supported methods
  82923. function createMethodNotSupport(method) {
  82924. return function () {
  82925. logError$1('In IE8.0 VML mode painter not support method "' + method + '"');
  82926. };
  82927. }
  82928. // Unsupported methods
  82929. each$1([
  82930. 'getLayer', 'insertLayer', 'eachLayer', 'eachBuiltinLayer', 'eachOtherLayer', 'getLayers',
  82931. 'modLayer', 'delLayer', 'clearLayer', 'toDataURL', 'pathToImage'
  82932. ], function (name) {
  82933. VMLPainter.prototype[name] = createMethodNotSupport(name);
  82934. });
  82935. registerPainter('vml', VMLPainter);
  82936. var svgURI = 'http://www.w3.org/2000/svg';
  82937. function createElement(name) {
  82938. return document.createElementNS(svgURI, name);
  82939. }
  82940. // TODO
  82941. // 1. shadow
  82942. // 2. Image: sx, sy, sw, sh
  82943. var CMD$4 = PathProxy.CMD;
  82944. var arrayJoin = Array.prototype.join;
  82945. var NONE = 'none';
  82946. var mathRound = Math.round;
  82947. var mathSin$3 = Math.sin;
  82948. var mathCos$3 = Math.cos;
  82949. var PI$6 = Math.PI;
  82950. var PI2$6 = Math.PI * 2;
  82951. var degree = 180 / PI$6;
  82952. var EPSILON$4 = 1e-4;
  82953. function round4(val) {
  82954. return mathRound(val * 1e4) / 1e4;
  82955. }
  82956. function isAroundZero$1(val) {
  82957. return val < EPSILON$4 && val > -EPSILON$4;
  82958. }
  82959. function pathHasFill(style, isText) {
  82960. var fill = isText ? style.textFill : style.fill;
  82961. return fill != null && fill !== NONE;
  82962. }
  82963. function pathHasStroke(style, isText) {
  82964. var stroke = isText ? style.textStroke : style.stroke;
  82965. return stroke != null && stroke !== NONE;
  82966. }
  82967. function setTransform(svgEl, m) {
  82968. if (m) {
  82969. attr(svgEl, 'transform', 'matrix(' + arrayJoin.call(m, ',') + ')');
  82970. }
  82971. }
  82972. function attr(el, key, val) {
  82973. if (!val || val.type !== 'linear' && val.type !== 'radial') {
  82974. // Don't set attribute for gradient, since it need new dom nodes
  82975. el.setAttribute(key, val);
  82976. }
  82977. }
  82978. function attrXLink(el, key, val) {
  82979. el.setAttributeNS('http://www.w3.org/1999/xlink', key, val);
  82980. }
  82981. function bindStyle(svgEl, style, isText, el) {
  82982. if (pathHasFill(style, isText)) {
  82983. var fill = isText ? style.textFill : style.fill;
  82984. fill = fill === 'transparent' ? NONE : fill;
  82985. attr(svgEl, 'fill', fill);
  82986. attr(svgEl, 'fill-opacity', style.fillOpacity != null ? style.fillOpacity * style.opacity : style.opacity);
  82987. }
  82988. else {
  82989. attr(svgEl, 'fill', NONE);
  82990. }
  82991. if (pathHasStroke(style, isText)) {
  82992. var stroke = isText ? style.textStroke : style.stroke;
  82993. stroke = stroke === 'transparent' ? NONE : stroke;
  82994. attr(svgEl, 'stroke', stroke);
  82995. var strokeWidth = isText
  82996. ? style.textStrokeWidth
  82997. : style.lineWidth;
  82998. var strokeScale = !isText && style.strokeNoScale
  82999. ? el.getLineScale()
  83000. : 1;
  83001. attr(svgEl, 'stroke-width', strokeWidth / strokeScale);
  83002. // stroke then fill for text; fill then stroke for others
  83003. attr(svgEl, 'paint-order', isText ? 'stroke' : 'fill');
  83004. attr(svgEl, 'stroke-opacity', style.strokeOpacity != null ? style.strokeOpacity : style.opacity);
  83005. var lineDash = style.lineDash;
  83006. if (lineDash) {
  83007. attr(svgEl, 'stroke-dasharray', style.lineDash.join(','));
  83008. attr(svgEl, 'stroke-dashoffset', mathRound(style.lineDashOffset || 0));
  83009. }
  83010. else {
  83011. attr(svgEl, 'stroke-dasharray', '');
  83012. }
  83013. // PENDING
  83014. style.lineCap && attr(svgEl, 'stroke-linecap', style.lineCap);
  83015. style.lineJoin && attr(svgEl, 'stroke-linejoin', style.lineJoin);
  83016. style.miterLimit && attr(svgEl, 'stroke-miterlimit', style.miterLimit);
  83017. }
  83018. else {
  83019. attr(svgEl, 'stroke', NONE);
  83020. }
  83021. }
  83022. /***************************************************
  83023. * PATH
  83024. **************************************************/
  83025. function pathDataToString$1(path) {
  83026. var str = [];
  83027. var data = path.data;
  83028. var dataLength = path.len();
  83029. for (var i = 0; i < dataLength;) {
  83030. var cmd = data[i++];
  83031. var cmdStr = '';
  83032. var nData = 0;
  83033. switch (cmd) {
  83034. case CMD$4.M:
  83035. cmdStr = 'M';
  83036. nData = 2;
  83037. break;
  83038. case CMD$4.L:
  83039. cmdStr = 'L';
  83040. nData = 2;
  83041. break;
  83042. case CMD$4.Q:
  83043. cmdStr = 'Q';
  83044. nData = 4;
  83045. break;
  83046. case CMD$4.C:
  83047. cmdStr = 'C';
  83048. nData = 6;
  83049. break;
  83050. case CMD$4.A:
  83051. var cx = data[i++];
  83052. var cy = data[i++];
  83053. var rx = data[i++];
  83054. var ry = data[i++];
  83055. var theta = data[i++];
  83056. var dTheta = data[i++];
  83057. var psi = data[i++];
  83058. var clockwise = data[i++];
  83059. var dThetaPositive = Math.abs(dTheta);
  83060. var isCircle = isAroundZero$1(dThetaPositive - PI2$6)
  83061. || (clockwise ? dTheta >= PI2$6 : -dTheta >= PI2$6);
  83062. // Mapping to 0~2PI
  83063. var unifiedTheta = dTheta > 0 ? dTheta % PI2$6 : (dTheta % PI2$6 + PI2$6);
  83064. var large = false;
  83065. if (isCircle) {
  83066. large = true;
  83067. }
  83068. else if (isAroundZero$1(dThetaPositive)) {
  83069. large = false;
  83070. }
  83071. else {
  83072. large = (unifiedTheta >= PI$6) === !!clockwise;
  83073. }
  83074. var x0 = round4(cx + rx * mathCos$3(theta));
  83075. var y0 = round4(cy + ry * mathSin$3(theta));
  83076. // It will not draw if start point and end point are exactly the same
  83077. // We need to shift the end point with a small value
  83078. // FIXME A better way to draw circle ?
  83079. if (isCircle) {
  83080. if (clockwise) {
  83081. dTheta = PI2$6 - 1e-4;
  83082. }
  83083. else {
  83084. dTheta = -PI2$6 + 1e-4;
  83085. }
  83086. large = true;
  83087. if (i === 9) {
  83088. // Move to (x0, y0) only when CMD.A comes at the
  83089. // first position of a shape.
  83090. // For instance, when drawing a ring, CMD.A comes
  83091. // after CMD.M, so it's unnecessary to move to
  83092. // (x0, y0).
  83093. str.push('M', x0, y0);
  83094. }
  83095. }
  83096. var x = round4(cx + rx * mathCos$3(theta + dTheta));
  83097. var y = round4(cy + ry * mathSin$3(theta + dTheta));
  83098. // FIXME Ellipse
  83099. str.push('A', round4(rx), round4(ry),
  83100. mathRound(psi * degree), +large, +clockwise, x, y);
  83101. break;
  83102. case CMD$4.Z:
  83103. cmdStr = 'Z';
  83104. break;
  83105. case CMD$4.R:
  83106. var x = round4(data[i++]);
  83107. var y = round4(data[i++]);
  83108. var w = round4(data[i++]);
  83109. var h = round4(data[i++]);
  83110. str.push(
  83111. 'M', x, y,
  83112. 'L', x + w, y,
  83113. 'L', x + w, y + h,
  83114. 'L', x, y + h,
  83115. 'L', x, y
  83116. );
  83117. break;
  83118. }
  83119. cmdStr && str.push(cmdStr);
  83120. for (var j = 0; j < nData; j++) {
  83121. // PENDING With scale
  83122. str.push(round4(data[i++]));
  83123. }
  83124. }
  83125. return str.join(' ');
  83126. }
  83127. var svgPath = {};
  83128. svgPath.brush = function (el) {
  83129. var style = el.style;
  83130. var svgEl = el.__svgEl;
  83131. if (!svgEl) {
  83132. svgEl = createElement('path');
  83133. el.__svgEl = svgEl;
  83134. }
  83135. if (!el.path) {
  83136. el.createPathProxy();
  83137. }
  83138. var path = el.path;
  83139. if (el.__dirtyPath) {
  83140. path.beginPath();
  83141. path.subPixelOptimize = false;
  83142. el.buildPath(path, el.shape);
  83143. el.__dirtyPath = false;
  83144. var pathStr = pathDataToString$1(path);
  83145. if (pathStr.indexOf('NaN') < 0) {
  83146. // Ignore illegal path, which may happen such in out-of-range
  83147. // data in Calendar series.
  83148. attr(svgEl, 'd', pathStr);
  83149. }
  83150. }
  83151. bindStyle(svgEl, style, false, el);
  83152. setTransform(svgEl, el.transform);
  83153. if (style.text != null) {
  83154. svgTextDrawRectText(el, el.getBoundingRect());
  83155. }
  83156. else {
  83157. removeOldTextNode(el);
  83158. }
  83159. };
  83160. /***************************************************
  83161. * IMAGE
  83162. **************************************************/
  83163. var svgImage = {};
  83164. svgImage.brush = function (el) {
  83165. var style = el.style;
  83166. var image = style.image;
  83167. if (image instanceof HTMLImageElement) {
  83168. var src = image.src;
  83169. image = src;
  83170. }
  83171. if (!image) {
  83172. return;
  83173. }
  83174. var x = style.x || 0;
  83175. var y = style.y || 0;
  83176. var dw = style.width;
  83177. var dh = style.height;
  83178. var svgEl = el.__svgEl;
  83179. if (!svgEl) {
  83180. svgEl = createElement('image');
  83181. el.__svgEl = svgEl;
  83182. }
  83183. if (image !== el.__imageSrc) {
  83184. attrXLink(svgEl, 'href', image);
  83185. // Caching image src
  83186. el.__imageSrc = image;
  83187. }
  83188. attr(svgEl, 'width', dw);
  83189. attr(svgEl, 'height', dh);
  83190. attr(svgEl, 'x', x);
  83191. attr(svgEl, 'y', y);
  83192. setTransform(svgEl, el.transform);
  83193. if (style.text != null) {
  83194. svgTextDrawRectText(el, el.getBoundingRect());
  83195. }
  83196. else {
  83197. removeOldTextNode(el);
  83198. }
  83199. };
  83200. /***************************************************
  83201. * TEXT
  83202. **************************************************/
  83203. var svgText = {};
  83204. var _tmpTextHostRect = new BoundingRect();
  83205. var _tmpTextBoxPos = {};
  83206. var _tmpTextTransform = [];
  83207. var TEXT_ALIGN_TO_ANCHRO = {
  83208. left: 'start',
  83209. right: 'end',
  83210. center: 'middle',
  83211. middle: 'middle'
  83212. };
  83213. /**
  83214. * @param {module:zrender/Element} el
  83215. * @param {Object|boolean} [hostRect] {x, y, width, height}
  83216. * If set false, rect text is not used.
  83217. */
  83218. var svgTextDrawRectText = function (el, hostRect) {
  83219. var style = el.style;
  83220. var elTransform = el.transform;
  83221. var needTransformTextByHostEl = el instanceof Text || style.transformText;
  83222. el.__dirty && normalizeTextStyle(style, true);
  83223. var text = style.text;
  83224. // Convert to string
  83225. text != null && (text += '');
  83226. if (!needDrawText(text, style)) {
  83227. return;
  83228. }
  83229. // render empty text for svg if no text but need draw text.
  83230. text == null && (text = '');
  83231. // Follow the setting in the canvas renderer, if not transform the
  83232. // text, transform the hostRect, by which the text is located.
  83233. if (!needTransformTextByHostEl && elTransform) {
  83234. _tmpTextHostRect.copy(hostRect);
  83235. _tmpTextHostRect.applyTransform(elTransform);
  83236. hostRect = _tmpTextHostRect;
  83237. }
  83238. var textSvgEl = el.__textSvgEl;
  83239. if (!textSvgEl) {
  83240. textSvgEl = createElement('text');
  83241. el.__textSvgEl = textSvgEl;
  83242. }
  83243. // style.font has been normalized by `normalizeTextStyle`.
  83244. var textSvgElStyle = textSvgEl.style;
  83245. var font = style.font || DEFAULT_FONT$1;
  83246. var computedFont = textSvgEl.__computedFont;
  83247. if (font !== textSvgEl.__styleFont) {
  83248. textSvgElStyle.font = textSvgEl.__styleFont = font;
  83249. // The computedFont might not be the orginal font if it is illegal font.
  83250. computedFont = textSvgEl.__computedFont = textSvgElStyle.font;
  83251. }
  83252. var textPadding = style.textPadding;
  83253. var textLineHeight = style.textLineHeight;
  83254. var contentBlock = el.__textCotentBlock;
  83255. if (!contentBlock || el.__dirtyText) {
  83256. contentBlock = el.__textCotentBlock = parsePlainText(
  83257. text, computedFont, textPadding, textLineHeight, style.truncate
  83258. );
  83259. }
  83260. var outerHeight = contentBlock.outerHeight;
  83261. var lineHeight = contentBlock.lineHeight;
  83262. getBoxPosition(_tmpTextBoxPos, el, style, hostRect);
  83263. var baseX = _tmpTextBoxPos.baseX;
  83264. var baseY = _tmpTextBoxPos.baseY;
  83265. var textAlign = _tmpTextBoxPos.textAlign || 'left';
  83266. var textVerticalAlign = _tmpTextBoxPos.textVerticalAlign;
  83267. setTextTransform(
  83268. textSvgEl, needTransformTextByHostEl, elTransform, style, hostRect, baseX, baseY
  83269. );
  83270. var boxY = adjustTextY(baseY, outerHeight, textVerticalAlign);
  83271. var textX = baseX;
  83272. var textY = boxY;
  83273. // TODO needDrawBg
  83274. if (textPadding) {
  83275. textX = getTextXForPadding$1(baseX, textAlign, textPadding);
  83276. textY += textPadding[0];
  83277. }
  83278. // `textBaseline` is set as 'middle'.
  83279. textY += lineHeight / 2;
  83280. bindStyle(textSvgEl, style, true, el);
  83281. // FIXME
  83282. // Add a <style> to reset all of the text font as inherit?
  83283. // otherwise the outer <style> may set the unexpected style.
  83284. // Font may affect position of each tspan elements
  83285. var canCacheByTextString = contentBlock.canCacheByTextString;
  83286. var tspanList = el.__tspanList || (el.__tspanList = []);
  83287. var tspanOriginLen = tspanList.length;
  83288. // Optimize for most cases, just compare text string to determine change.
  83289. if (canCacheByTextString && el.__canCacheByTextString && el.__text === text) {
  83290. if (el.__dirtyText && tspanOriginLen) {
  83291. for (var idx = 0; idx < tspanOriginLen; ++idx) {
  83292. updateTextLocation(tspanList[idx], textAlign, textX, textY + idx * lineHeight);
  83293. }
  83294. }
  83295. }
  83296. else {
  83297. el.__text = text;
  83298. el.__canCacheByTextString = canCacheByTextString;
  83299. var textLines = contentBlock.lines;
  83300. var nTextLines = textLines.length;
  83301. var idx = 0;
  83302. for (; idx < nTextLines; idx++) {
  83303. // Using cached tspan elements
  83304. var tspan = tspanList[idx];
  83305. var singleLineText = textLines[idx];
  83306. if (!tspan) {
  83307. tspan = tspanList[idx] = createElement('tspan');
  83308. textSvgEl.appendChild(tspan);
  83309. tspan.appendChild(document.createTextNode(singleLineText));
  83310. }
  83311. else if (tspan.__zrText !== singleLineText) {
  83312. tspan.innerHTML = '';
  83313. tspan.appendChild(document.createTextNode(singleLineText));
  83314. }
  83315. updateTextLocation(tspan, textAlign, textX, textY + idx * lineHeight);
  83316. }
  83317. // Remove unused tspan elements
  83318. if (tspanOriginLen > nTextLines) {
  83319. for (; idx < tspanOriginLen; idx++) {
  83320. textSvgEl.removeChild(tspanList[idx]);
  83321. }
  83322. tspanList.length = nTextLines;
  83323. }
  83324. }
  83325. };
  83326. function setTextTransform(textSvgEl, needTransformTextByHostEl, elTransform, style, hostRect, baseX, baseY) {
  83327. identity(_tmpTextTransform);
  83328. if (needTransformTextByHostEl && elTransform) {
  83329. copy$1(_tmpTextTransform, elTransform);
  83330. }
  83331. // textRotation only apply in RectText.
  83332. var textRotation = style.textRotation;
  83333. if (hostRect && textRotation) {
  83334. var origin = style.textOrigin;
  83335. if (origin === 'center') {
  83336. baseX = hostRect.width / 2 + hostRect.x;
  83337. baseY = hostRect.height / 2 + hostRect.y;
  83338. }
  83339. else if (origin) {
  83340. baseX = origin[0] + hostRect.x;
  83341. baseY = origin[1] + hostRect.y;
  83342. }
  83343. _tmpTextTransform[4] -= baseX;
  83344. _tmpTextTransform[5] -= baseY;
  83345. // Positive: anticlockwise
  83346. rotate(_tmpTextTransform, _tmpTextTransform, textRotation);
  83347. _tmpTextTransform[4] += baseX;
  83348. _tmpTextTransform[5] += baseY;
  83349. }
  83350. // See the definition in `Style.js#textOrigin`, the default
  83351. // origin is from the result of `getBoxPosition`.
  83352. setTransform(textSvgEl, _tmpTextTransform);
  83353. }
  83354. // FIXME merge the same code with `helper/text.js#getTextXForPadding`;
  83355. function getTextXForPadding$1(x, textAlign, textPadding) {
  83356. return textAlign === 'right'
  83357. ? (x - textPadding[1])
  83358. : textAlign === 'center'
  83359. ? (x + textPadding[3] / 2 - textPadding[1] / 2)
  83360. : (x + textPadding[3]);
  83361. }
  83362. function updateTextLocation(tspan, textAlign, x, y) {
  83363. // Consider different font display differently in vertial align, we always
  83364. // set vertialAlign as 'middle', and use 'y' to locate text vertically.
  83365. attr(tspan, 'dominant-baseline', 'middle');
  83366. attr(tspan, 'text-anchor', TEXT_ALIGN_TO_ANCHRO[textAlign]);
  83367. attr(tspan, 'x', x);
  83368. attr(tspan, 'y', y);
  83369. }
  83370. function removeOldTextNode(el) {
  83371. if (el && el.__textSvgEl) {
  83372. // textSvgEl may has no parentNode if el has been removed temporary.
  83373. if (el.__textSvgEl.parentNode) {
  83374. el.__textSvgEl.parentNode.removeChild(el.__textSvgEl);
  83375. }
  83376. el.__textSvgEl = null;
  83377. el.__tspanList = [];
  83378. el.__text = null;
  83379. }
  83380. }
  83381. svgText.drawRectText = svgTextDrawRectText;
  83382. svgText.brush = function (el) {
  83383. var style = el.style;
  83384. if (style.text != null) {
  83385. svgTextDrawRectText(el, false);
  83386. }
  83387. else {
  83388. removeOldTextNode(el);
  83389. }
  83390. };
  83391. // Myers' Diff Algorithm
  83392. // Modified from https://github.com/kpdecker/jsdiff/blob/master/src/diff/base.js
  83393. function Diff() {}
  83394. Diff.prototype = {
  83395. diff: function (oldArr, newArr, equals) {
  83396. if (!equals) {
  83397. equals = function (a, b) {
  83398. return a === b;
  83399. };
  83400. }
  83401. this.equals = equals;
  83402. var self = this;
  83403. oldArr = oldArr.slice();
  83404. newArr = newArr.slice();
  83405. // Allow subclasses to massage the input prior to running
  83406. var newLen = newArr.length;
  83407. var oldLen = oldArr.length;
  83408. var editLength = 1;
  83409. var maxEditLength = newLen + oldLen;
  83410. var bestPath = [{ newPos: -1, components: [] }];
  83411. // Seed editLength = 0, i.e. the content starts with the same values
  83412. var oldPos = this.extractCommon(bestPath[0], newArr, oldArr, 0);
  83413. if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
  83414. var indices = [];
  83415. for (var i = 0; i < newArr.length; i++) {
  83416. indices.push(i);
  83417. }
  83418. // Identity per the equality and tokenizer
  83419. return [{
  83420. indices: indices, count: newArr.length
  83421. }];
  83422. }
  83423. // Main worker method. checks all permutations of a given edit length for acceptance.
  83424. function execEditLength() {
  83425. for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
  83426. var basePath;
  83427. var addPath = bestPath[diagonalPath - 1];
  83428. var removePath = bestPath[diagonalPath + 1];
  83429. var oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
  83430. if (addPath) {
  83431. // No one else is going to attempt to use this value, clear it
  83432. bestPath[diagonalPath - 1] = undefined;
  83433. }
  83434. var canAdd = addPath && addPath.newPos + 1 < newLen;
  83435. var canRemove = removePath && 0 <= oldPos && oldPos < oldLen;
  83436. if (!canAdd && !canRemove) {
  83437. // If this path is a terminal then prune
  83438. bestPath[diagonalPath] = undefined;
  83439. continue;
  83440. }
  83441. // Select the diagonal that we want to branch from. We select the prior
  83442. // path whose position in the new string is the farthest from the origin
  83443. // and does not pass the bounds of the diff graph
  83444. if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) {
  83445. basePath = clonePath(removePath);
  83446. self.pushComponent(basePath.components, undefined, true);
  83447. }
  83448. else {
  83449. basePath = addPath; // No need to clone, we've pulled it from the list
  83450. basePath.newPos++;
  83451. self.pushComponent(basePath.components, true, undefined);
  83452. }
  83453. oldPos = self.extractCommon(basePath, newArr, oldArr, diagonalPath);
  83454. // If we have hit the end of both strings, then we are done
  83455. if (basePath.newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
  83456. return buildValues(self, basePath.components, newArr, oldArr);
  83457. }
  83458. else {
  83459. // Otherwise track this path as a potential candidate and continue.
  83460. bestPath[diagonalPath] = basePath;
  83461. }
  83462. }
  83463. editLength++;
  83464. }
  83465. while (editLength <= maxEditLength) {
  83466. var ret = execEditLength();
  83467. if (ret) {
  83468. return ret;
  83469. }
  83470. }
  83471. },
  83472. pushComponent: function (components, added, removed) {
  83473. var last = components[components.length - 1];
  83474. if (last && last.added === added && last.removed === removed) {
  83475. // We need to clone here as the component clone operation is just
  83476. // as shallow array clone
  83477. components[components.length - 1] = {count: last.count + 1, added: added, removed: removed };
  83478. }
  83479. else {
  83480. components.push({count: 1, added: added, removed: removed });
  83481. }
  83482. },
  83483. extractCommon: function (basePath, newArr, oldArr, diagonalPath) {
  83484. var newLen = newArr.length;
  83485. var oldLen = oldArr.length;
  83486. var newPos = basePath.newPos;
  83487. var oldPos = newPos - diagonalPath;
  83488. var commonCount = 0;
  83489. while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newArr[newPos + 1], oldArr[oldPos + 1])) {
  83490. newPos++;
  83491. oldPos++;
  83492. commonCount++;
  83493. }
  83494. if (commonCount) {
  83495. basePath.components.push({count: commonCount});
  83496. }
  83497. basePath.newPos = newPos;
  83498. return oldPos;
  83499. },
  83500. tokenize: function (value) {
  83501. return value.slice();
  83502. },
  83503. join: function (value) {
  83504. return value.slice();
  83505. }
  83506. };
  83507. function buildValues(diff, components, newArr, oldArr) {
  83508. var componentPos = 0;
  83509. var componentLen = components.length;
  83510. var newPos = 0;
  83511. var oldPos = 0;
  83512. for (; componentPos < componentLen; componentPos++) {
  83513. var component = components[componentPos];
  83514. if (!component.removed) {
  83515. var indices = [];
  83516. for (var i = newPos; i < newPos + component.count; i++) {
  83517. indices.push(i);
  83518. }
  83519. component.indices = indices;
  83520. newPos += component.count;
  83521. // Common case
  83522. if (!component.added) {
  83523. oldPos += component.count;
  83524. }
  83525. }
  83526. else {
  83527. var indices = [];
  83528. for (var i = oldPos; i < oldPos + component.count; i++) {
  83529. indices.push(i);
  83530. }
  83531. component.indices = indices;
  83532. oldPos += component.count;
  83533. }
  83534. }
  83535. return components;
  83536. }
  83537. function clonePath(path) {
  83538. return { newPos: path.newPos, components: path.components.slice(0) };
  83539. }
  83540. var arrayDiff = new Diff();
  83541. var arrayDiff$1 = function (oldArr, newArr, callback) {
  83542. return arrayDiff.diff(oldArr, newArr, callback);
  83543. };
  83544. /**
  83545. * @file Manages elements that can be defined in <defs> in SVG,
  83546. * e.g., gradients, clip path, etc.
  83547. * @author Zhang Wenli
  83548. */
  83549. var MARK_UNUSED = '0';
  83550. var MARK_USED = '1';
  83551. /**
  83552. * Manages elements that can be defined in <defs> in SVG,
  83553. * e.g., gradients, clip path, etc.
  83554. *
  83555. * @class
  83556. * @param {number} zrId zrender instance id
  83557. * @param {SVGElement} svgRoot root of SVG document
  83558. * @param {string|string[]} tagNames possible tag names
  83559. * @param {string} markLabel label name to make if the element
  83560. * is used
  83561. */
  83562. function Definable(
  83563. zrId,
  83564. svgRoot,
  83565. tagNames,
  83566. markLabel,
  83567. domName
  83568. ) {
  83569. this._zrId = zrId;
  83570. this._svgRoot = svgRoot;
  83571. this._tagNames = typeof tagNames === 'string' ? [tagNames] : tagNames;
  83572. this._markLabel = markLabel;
  83573. this._domName = domName || '_dom';
  83574. this.nextId = 0;
  83575. }
  83576. Definable.prototype.createElement = createElement;
  83577. /**
  83578. * Get the <defs> tag for svgRoot; optionally creates one if not exists.
  83579. *
  83580. * @param {boolean} isForceCreating if need to create when not exists
  83581. * @return {SVGDefsElement} SVG <defs> element, null if it doesn't
  83582. * exist and isForceCreating is false
  83583. */
  83584. Definable.prototype.getDefs = function (isForceCreating) {
  83585. var svgRoot = this._svgRoot;
  83586. var defs = this._svgRoot.getElementsByTagName('defs');
  83587. if (defs.length === 0) {
  83588. // Not exist
  83589. if (isForceCreating) {
  83590. defs = svgRoot.insertBefore(
  83591. this.createElement('defs'), // Create new tag
  83592. svgRoot.firstChild // Insert in the front of svg
  83593. );
  83594. if (!defs.contains) {
  83595. // IE doesn't support contains method
  83596. defs.contains = function (el) {
  83597. var children = defs.children;
  83598. if (!children) {
  83599. return false;
  83600. }
  83601. for (var i = children.length - 1; i >= 0; --i) {
  83602. if (children[i] === el) {
  83603. return true;
  83604. }
  83605. }
  83606. return false;
  83607. };
  83608. }
  83609. return defs;
  83610. }
  83611. else {
  83612. return null;
  83613. }
  83614. }
  83615. else {
  83616. return defs[0];
  83617. }
  83618. };
  83619. /**
  83620. * Update DOM element if necessary.
  83621. *
  83622. * @param {Object|string} element style element. e.g., for gradient,
  83623. * it may be '#ccc' or {type: 'linear', ...}
  83624. * @param {Function|undefined} onUpdate update callback
  83625. */
  83626. Definable.prototype.update = function (element, onUpdate) {
  83627. if (!element) {
  83628. return;
  83629. }
  83630. var defs = this.getDefs(false);
  83631. if (element[this._domName] && defs.contains(element[this._domName])) {
  83632. // Update DOM
  83633. if (typeof onUpdate === 'function') {
  83634. onUpdate(element);
  83635. }
  83636. }
  83637. else {
  83638. // No previous dom, create new
  83639. var dom = this.add(element);
  83640. if (dom) {
  83641. element[this._domName] = dom;
  83642. }
  83643. }
  83644. };
  83645. /**
  83646. * Add gradient dom to defs
  83647. *
  83648. * @param {SVGElement} dom DOM to be added to <defs>
  83649. */
  83650. Definable.prototype.addDom = function (dom) {
  83651. var defs = this.getDefs(true);
  83652. defs.appendChild(dom);
  83653. };
  83654. /**
  83655. * Remove DOM of a given element.
  83656. *
  83657. * @param {SVGElement} element element to remove dom
  83658. */
  83659. Definable.prototype.removeDom = function (element) {
  83660. var defs = this.getDefs(false);
  83661. if (defs && element[this._domName]) {
  83662. defs.removeChild(element[this._domName]);
  83663. element[this._domName] = null;
  83664. }
  83665. };
  83666. /**
  83667. * Get DOMs of this element.
  83668. *
  83669. * @return {HTMLDomElement} doms of this defineable elements in <defs>
  83670. */
  83671. Definable.prototype.getDoms = function () {
  83672. var defs = this.getDefs(false);
  83673. if (!defs) {
  83674. // No dom when defs is not defined
  83675. return [];
  83676. }
  83677. var doms = [];
  83678. each$1(this._tagNames, function (tagName) {
  83679. var tags = defs.getElementsByTagName(tagName);
  83680. // Note that tags is HTMLCollection, which is array-like
  83681. // rather than real array.
  83682. // So `doms.concat(tags)` add tags as one object.
  83683. doms = doms.concat([].slice.call(tags));
  83684. });
  83685. return doms;
  83686. };
  83687. /**
  83688. * Mark DOMs to be unused before painting, and clear unused ones at the end
  83689. * of the painting.
  83690. */
  83691. Definable.prototype.markAllUnused = function () {
  83692. var doms = this.getDoms();
  83693. var that = this;
  83694. each$1(doms, function (dom) {
  83695. dom[that._markLabel] = MARK_UNUSED;
  83696. });
  83697. };
  83698. /**
  83699. * Mark a single DOM to be used.
  83700. *
  83701. * @param {SVGElement} dom DOM to mark
  83702. */
  83703. Definable.prototype.markUsed = function (dom) {
  83704. if (dom) {
  83705. dom[this._markLabel] = MARK_USED;
  83706. }
  83707. };
  83708. /**
  83709. * Remove unused DOMs defined in <defs>
  83710. */
  83711. Definable.prototype.removeUnused = function () {
  83712. var defs = this.getDefs(false);
  83713. if (!defs) {
  83714. // Nothing to remove
  83715. return;
  83716. }
  83717. var doms = this.getDoms();
  83718. var that = this;
  83719. each$1(doms, function (dom) {
  83720. if (dom[that._markLabel] !== MARK_USED) {
  83721. // Remove gradient
  83722. defs.removeChild(dom);
  83723. }
  83724. });
  83725. };
  83726. /**
  83727. * Get SVG proxy.
  83728. *
  83729. * @param {Displayable} displayable displayable element
  83730. * @return {Path|Image|Text} svg proxy of given element
  83731. */
  83732. Definable.prototype.getSvgProxy = function (displayable) {
  83733. if (displayable instanceof Path) {
  83734. return svgPath;
  83735. }
  83736. else if (displayable instanceof ZImage) {
  83737. return svgImage;
  83738. }
  83739. else if (displayable instanceof Text) {
  83740. return svgText;
  83741. }
  83742. else {
  83743. return svgPath;
  83744. }
  83745. };
  83746. /**
  83747. * Get text SVG element.
  83748. *
  83749. * @param {Displayable} displayable displayable element
  83750. * @return {SVGElement} SVG element of text
  83751. */
  83752. Definable.prototype.getTextSvgElement = function (displayable) {
  83753. return displayable.__textSvgEl;
  83754. };
  83755. /**
  83756. * Get SVG element.
  83757. *
  83758. * @param {Displayable} displayable displayable element
  83759. * @return {SVGElement} SVG element
  83760. */
  83761. Definable.prototype.getSvgElement = function (displayable) {
  83762. return displayable.__svgEl;
  83763. };
  83764. /**
  83765. * @file Manages SVG gradient elements.
  83766. * @author Zhang Wenli
  83767. */
  83768. /**
  83769. * Manages SVG gradient elements.
  83770. *
  83771. * @class
  83772. * @extends Definable
  83773. * @param {number} zrId zrender instance id
  83774. * @param {SVGElement} svgRoot root of SVG document
  83775. */
  83776. function GradientManager(zrId, svgRoot) {
  83777. Definable.call(
  83778. this,
  83779. zrId,
  83780. svgRoot,
  83781. ['linearGradient', 'radialGradient'],
  83782. '__gradient_in_use__'
  83783. );
  83784. }
  83785. inherits(GradientManager, Definable);
  83786. /**
  83787. * Create new gradient DOM for fill or stroke if not exist,
  83788. * but will not update gradient if exists.
  83789. *
  83790. * @param {SvgElement} svgElement SVG element to paint
  83791. * @param {Displayable} displayable zrender displayable element
  83792. */
  83793. GradientManager.prototype.addWithoutUpdate = function (
  83794. svgElement,
  83795. displayable
  83796. ) {
  83797. if (displayable && displayable.style) {
  83798. var that = this;
  83799. each$1(['fill', 'stroke'], function (fillOrStroke) {
  83800. if (displayable.style[fillOrStroke]
  83801. && (displayable.style[fillOrStroke].type === 'linear'
  83802. || displayable.style[fillOrStroke].type === 'radial')
  83803. ) {
  83804. var gradient = displayable.style[fillOrStroke];
  83805. var defs = that.getDefs(true);
  83806. // Create dom in <defs> if not exists
  83807. var dom;
  83808. if (gradient._dom) {
  83809. // Gradient exists
  83810. dom = gradient._dom;
  83811. if (!defs.contains(gradient._dom)) {
  83812. // _dom is no longer in defs, recreate
  83813. that.addDom(dom);
  83814. }
  83815. }
  83816. else {
  83817. // New dom
  83818. dom = that.add(gradient);
  83819. }
  83820. that.markUsed(displayable);
  83821. var id = dom.getAttribute('id');
  83822. svgElement.setAttribute(fillOrStroke, 'url(#' + id + ')');
  83823. }
  83824. });
  83825. }
  83826. };
  83827. /**
  83828. * Add a new gradient tag in <defs>
  83829. *
  83830. * @param {Gradient} gradient zr gradient instance
  83831. * @return {SVGLinearGradientElement | SVGRadialGradientElement}
  83832. * created DOM
  83833. */
  83834. GradientManager.prototype.add = function (gradient) {
  83835. var dom;
  83836. if (gradient.type === 'linear') {
  83837. dom = this.createElement('linearGradient');
  83838. }
  83839. else if (gradient.type === 'radial') {
  83840. dom = this.createElement('radialGradient');
  83841. }
  83842. else {
  83843. logError$1('Illegal gradient type.');
  83844. return null;
  83845. }
  83846. // Set dom id with gradient id, since each gradient instance
  83847. // will have no more than one dom element.
  83848. // id may exists before for those dirty elements, in which case
  83849. // id should remain the same, and other attributes should be
  83850. // updated.
  83851. gradient.id = gradient.id || this.nextId++;
  83852. dom.setAttribute('id', 'zr' + this._zrId
  83853. + '-gradient-' + gradient.id);
  83854. this.updateDom(gradient, dom);
  83855. this.addDom(dom);
  83856. return dom;
  83857. };
  83858. /**
  83859. * Update gradient.
  83860. *
  83861. * @param {Gradient} gradient zr gradient instance
  83862. */
  83863. GradientManager.prototype.update = function (gradient) {
  83864. var that = this;
  83865. Definable.prototype.update.call(this, gradient, function () {
  83866. var type = gradient.type;
  83867. var tagName = gradient._dom.tagName;
  83868. if (type === 'linear' && tagName === 'linearGradient'
  83869. || type === 'radial' && tagName === 'radialGradient'
  83870. ) {
  83871. // Gradient type is not changed, update gradient
  83872. that.updateDom(gradient, gradient._dom);
  83873. }
  83874. else {
  83875. // Remove and re-create if type is changed
  83876. that.removeDom(gradient);
  83877. that.add(gradient);
  83878. }
  83879. });
  83880. };
  83881. /**
  83882. * Update gradient dom
  83883. *
  83884. * @param {Gradient} gradient zr gradient instance
  83885. * @param {SVGLinearGradientElement | SVGRadialGradientElement} dom
  83886. * DOM to update
  83887. */
  83888. GradientManager.prototype.updateDom = function (gradient, dom) {
  83889. if (gradient.type === 'linear') {
  83890. dom.setAttribute('x1', gradient.x);
  83891. dom.setAttribute('y1', gradient.y);
  83892. dom.setAttribute('x2', gradient.x2);
  83893. dom.setAttribute('y2', gradient.y2);
  83894. }
  83895. else if (gradient.type === 'radial') {
  83896. dom.setAttribute('cx', gradient.x);
  83897. dom.setAttribute('cy', gradient.y);
  83898. dom.setAttribute('r', gradient.r);
  83899. }
  83900. else {
  83901. logError$1('Illegal gradient type.');
  83902. return;
  83903. }
  83904. if (gradient.global) {
  83905. // x1, x2, y1, y2 in range of 0 to canvas width or height
  83906. dom.setAttribute('gradientUnits', 'userSpaceOnUse');
  83907. }
  83908. else {
  83909. // x1, x2, y1, y2 in range of 0 to 1
  83910. dom.setAttribute('gradientUnits', 'objectBoundingBox');
  83911. }
  83912. // Remove color stops if exists
  83913. dom.innerHTML = '';
  83914. // Add color stops
  83915. var colors = gradient.colorStops;
  83916. for (var i = 0, len = colors.length; i < len; ++i) {
  83917. var stop = this.createElement('stop');
  83918. stop.setAttribute('offset', colors[i].offset * 100 + '%');
  83919. var color = colors[i].color;
  83920. if (color.indexOf('rgba' > -1)) {
  83921. // Fix Safari bug that stop-color not recognizing alpha #9014
  83922. var opacity = parse(color)[3];
  83923. var hex = toHex(color);
  83924. // stop-color cannot be color, since:
  83925. // The opacity value used for the gradient calculation is the
  83926. // *product* of the value of stop-opacity and the opacity of the
  83927. // value of stop-color.
  83928. // See https://www.w3.org/TR/SVG2/pservers.html#StopOpacityProperty
  83929. stop.setAttribute('stop-color', '#' + hex);
  83930. stop.setAttribute('stop-opacity', opacity);
  83931. }
  83932. else {
  83933. stop.setAttribute('stop-color', colors[i].color);
  83934. }
  83935. dom.appendChild(stop);
  83936. }
  83937. // Store dom element in gradient, to avoid creating multiple
  83938. // dom instances for the same gradient element
  83939. gradient._dom = dom;
  83940. };
  83941. /**
  83942. * Mark a single gradient to be used
  83943. *
  83944. * @param {Displayable} displayable displayable element
  83945. */
  83946. GradientManager.prototype.markUsed = function (displayable) {
  83947. if (displayable.style) {
  83948. var gradient = displayable.style.fill;
  83949. if (gradient && gradient._dom) {
  83950. Definable.prototype.markUsed.call(this, gradient._dom);
  83951. }
  83952. gradient = displayable.style.stroke;
  83953. if (gradient && gradient._dom) {
  83954. Definable.prototype.markUsed.call(this, gradient._dom);
  83955. }
  83956. }
  83957. };
  83958. /**
  83959. * @file Manages SVG clipPath elements.
  83960. * @author Zhang Wenli
  83961. */
  83962. /**
  83963. * Manages SVG clipPath elements.
  83964. *
  83965. * @class
  83966. * @extends Definable
  83967. * @param {number} zrId zrender instance id
  83968. * @param {SVGElement} svgRoot root of SVG document
  83969. */
  83970. function ClippathManager(zrId, svgRoot) {
  83971. Definable.call(this, zrId, svgRoot, 'clipPath', '__clippath_in_use__');
  83972. }
  83973. inherits(ClippathManager, Definable);
  83974. /**
  83975. * Update clipPath.
  83976. *
  83977. * @param {Displayable} displayable displayable element
  83978. */
  83979. ClippathManager.prototype.update = function (displayable) {
  83980. var svgEl = this.getSvgElement(displayable);
  83981. if (svgEl) {
  83982. this.updateDom(svgEl, displayable.__clipPaths, false);
  83983. }
  83984. var textEl = this.getTextSvgElement(displayable);
  83985. if (textEl) {
  83986. // Make another clipPath for text, since it's transform
  83987. // matrix is not the same with svgElement
  83988. this.updateDom(textEl, displayable.__clipPaths, true);
  83989. }
  83990. this.markUsed(displayable);
  83991. };
  83992. /**
  83993. * Create an SVGElement of displayable and create a <clipPath> of its
  83994. * clipPath
  83995. *
  83996. * @param {Displayable} parentEl parent element
  83997. * @param {ClipPath[]} clipPaths clipPaths of parent element
  83998. * @param {boolean} isText if parent element is Text
  83999. */
  84000. ClippathManager.prototype.updateDom = function (
  84001. parentEl,
  84002. clipPaths,
  84003. isText
  84004. ) {
  84005. if (clipPaths && clipPaths.length > 0) {
  84006. // Has clipPath, create <clipPath> with the first clipPath
  84007. var defs = this.getDefs(true);
  84008. var clipPath = clipPaths[0];
  84009. var clipPathEl;
  84010. var id;
  84011. var dom = isText ? '_textDom' : '_dom';
  84012. if (clipPath[dom]) {
  84013. // Use a dom that is already in <defs>
  84014. id = clipPath[dom].getAttribute('id');
  84015. clipPathEl = clipPath[dom];
  84016. // Use a dom that is already in <defs>
  84017. if (!defs.contains(clipPathEl)) {
  84018. // This happens when set old clipPath that has
  84019. // been previously removed
  84020. defs.appendChild(clipPathEl);
  84021. }
  84022. }
  84023. else {
  84024. // New <clipPath>
  84025. id = 'zr' + this._zrId + '-clip-' + this.nextId;
  84026. ++this.nextId;
  84027. clipPathEl = this.createElement('clipPath');
  84028. clipPathEl.setAttribute('id', id);
  84029. defs.appendChild(clipPathEl);
  84030. clipPath[dom] = clipPathEl;
  84031. }
  84032. // Build path and add to <clipPath>
  84033. var svgProxy = this.getSvgProxy(clipPath);
  84034. if (clipPath.transform
  84035. && clipPath.parent.invTransform
  84036. && !isText
  84037. ) {
  84038. /**
  84039. * If a clipPath has a parent with transform, the transform
  84040. * of parent should not be considered when setting transform
  84041. * of clipPath. So we need to transform back from parent's
  84042. * transform, which is done by multiplying parent's inverse
  84043. * transform.
  84044. */
  84045. // Store old transform
  84046. var transform = Array.prototype.slice.call(
  84047. clipPath.transform
  84048. );
  84049. // Transform back from parent, and brush path
  84050. mul$1(
  84051. clipPath.transform,
  84052. clipPath.parent.invTransform,
  84053. clipPath.transform
  84054. );
  84055. svgProxy.brush(clipPath);
  84056. // Set back transform of clipPath
  84057. clipPath.transform = transform;
  84058. }
  84059. else {
  84060. svgProxy.brush(clipPath);
  84061. }
  84062. var pathEl = this.getSvgElement(clipPath);
  84063. clipPathEl.innerHTML = '';
  84064. /**
  84065. * Use `cloneNode()` here to appendChild to multiple parents,
  84066. * which may happend when Text and other shapes are using the same
  84067. * clipPath. Since Text will create an extra clipPath DOM due to
  84068. * different transform rules.
  84069. */
  84070. clipPathEl.appendChild(pathEl.cloneNode());
  84071. parentEl.setAttribute('clip-path', 'url(#' + id + ')');
  84072. if (clipPaths.length > 1) {
  84073. // Make the other clipPaths recursively
  84074. this.updateDom(clipPathEl, clipPaths.slice(1), isText);
  84075. }
  84076. }
  84077. else {
  84078. // No clipPath
  84079. if (parentEl) {
  84080. parentEl.setAttribute('clip-path', 'none');
  84081. }
  84082. }
  84083. };
  84084. /**
  84085. * Mark a single clipPath to be used
  84086. *
  84087. * @param {Displayable} displayable displayable element
  84088. */
  84089. ClippathManager.prototype.markUsed = function (displayable) {
  84090. var that = this;
  84091. // displayable.__clipPaths can only be `null`/`undefined` or an non-empty array.
  84092. if (displayable.__clipPaths) {
  84093. each$1(displayable.__clipPaths, function (clipPath) {
  84094. if (clipPath._dom) {
  84095. Definable.prototype.markUsed.call(that, clipPath._dom);
  84096. }
  84097. if (clipPath._textDom) {
  84098. Definable.prototype.markUsed.call(that, clipPath._textDom);
  84099. }
  84100. });
  84101. }
  84102. };
  84103. /**
  84104. * @file Manages SVG shadow elements.
  84105. * @author Zhang Wenli
  84106. */
  84107. /**
  84108. * Manages SVG shadow elements.
  84109. *
  84110. * @class
  84111. * @extends Definable
  84112. * @param {number} zrId zrender instance id
  84113. * @param {SVGElement} svgRoot root of SVG document
  84114. */
  84115. function ShadowManager(zrId, svgRoot) {
  84116. Definable.call(
  84117. this,
  84118. zrId,
  84119. svgRoot,
  84120. ['filter'],
  84121. '__filter_in_use__',
  84122. '_shadowDom'
  84123. );
  84124. }
  84125. inherits(ShadowManager, Definable);
  84126. /**
  84127. * Create new shadow DOM for fill or stroke if not exist,
  84128. * but will not update shadow if exists.
  84129. *
  84130. * @param {SvgElement} svgElement SVG element to paint
  84131. * @param {Displayable} displayable zrender displayable element
  84132. */
  84133. ShadowManager.prototype.addWithoutUpdate = function (
  84134. svgElement,
  84135. displayable
  84136. ) {
  84137. if (displayable && hasShadow(displayable.style)) {
  84138. // Create dom in <defs> if not exists
  84139. var dom;
  84140. if (displayable._shadowDom) {
  84141. // Gradient exists
  84142. dom = displayable._shadowDom;
  84143. var defs = this.getDefs(true);
  84144. if (!defs.contains(displayable._shadowDom)) {
  84145. // _shadowDom is no longer in defs, recreate
  84146. this.addDom(dom);
  84147. }
  84148. }
  84149. else {
  84150. // New dom
  84151. dom = this.add(displayable);
  84152. }
  84153. this.markUsed(displayable);
  84154. var id = dom.getAttribute('id');
  84155. svgElement.style.filter = 'url(#' + id + ')';
  84156. }
  84157. };
  84158. /**
  84159. * Add a new shadow tag in <defs>
  84160. *
  84161. * @param {Displayable} displayable zrender displayable element
  84162. * @return {SVGFilterElement} created DOM
  84163. */
  84164. ShadowManager.prototype.add = function (displayable) {
  84165. var dom = this.createElement('filter');
  84166. // Set dom id with shadow id, since each shadow instance
  84167. // will have no more than one dom element.
  84168. // id may exists before for those dirty elements, in which case
  84169. // id should remain the same, and other attributes should be
  84170. // updated.
  84171. displayable._shadowDomId = displayable._shadowDomId || this.nextId++;
  84172. dom.setAttribute('id', 'zr' + this._zrId
  84173. + '-shadow-' + displayable._shadowDomId);
  84174. this.updateDom(displayable, dom);
  84175. this.addDom(dom);
  84176. return dom;
  84177. };
  84178. /**
  84179. * Update shadow.
  84180. *
  84181. * @param {Displayable} displayable zrender displayable element
  84182. */
  84183. ShadowManager.prototype.update = function (svgElement, displayable) {
  84184. var style = displayable.style;
  84185. if (hasShadow(style)) {
  84186. var that = this;
  84187. Definable.prototype.update.call(this, displayable, function () {
  84188. that.updateDom(displayable, displayable._shadowDom);
  84189. });
  84190. }
  84191. else {
  84192. // Remove shadow
  84193. this.remove(svgElement, displayable);
  84194. }
  84195. };
  84196. /**
  84197. * Remove DOM and clear parent filter
  84198. */
  84199. ShadowManager.prototype.remove = function (svgElement, displayable) {
  84200. if (displayable._shadowDomId != null) {
  84201. this.removeDom(svgElement);
  84202. svgElement.style.filter = '';
  84203. }
  84204. };
  84205. /**
  84206. * Update shadow dom
  84207. *
  84208. * @param {Displayable} displayable zrender displayable element
  84209. * @param {SVGFilterElement} dom DOM to update
  84210. */
  84211. ShadowManager.prototype.updateDom = function (displayable, dom) {
  84212. var domChild = dom.getElementsByTagName('feDropShadow');
  84213. if (domChild.length === 0) {
  84214. domChild = this.createElement('feDropShadow');
  84215. }
  84216. else {
  84217. domChild = domChild[0];
  84218. }
  84219. var style = displayable.style;
  84220. var scaleX = displayable.scale ? (displayable.scale[0] || 1) : 1;
  84221. var scaleY = displayable.scale ? (displayable.scale[1] || 1) : 1;
  84222. // TODO: textBoxShadowBlur is not supported yet
  84223. var offsetX;
  84224. var offsetY;
  84225. var blur;
  84226. var color;
  84227. if (style.shadowBlur || style.shadowOffsetX || style.shadowOffsetY) {
  84228. offsetX = style.shadowOffsetX || 0;
  84229. offsetY = style.shadowOffsetY || 0;
  84230. blur = style.shadowBlur;
  84231. color = style.shadowColor;
  84232. }
  84233. else if (style.textShadowBlur) {
  84234. offsetX = style.textShadowOffsetX || 0;
  84235. offsetY = style.textShadowOffsetY || 0;
  84236. blur = style.textShadowBlur;
  84237. color = style.textShadowColor;
  84238. }
  84239. else {
  84240. // Remove shadow
  84241. this.removeDom(dom, style);
  84242. return;
  84243. }
  84244. domChild.setAttribute('dx', offsetX / scaleX);
  84245. domChild.setAttribute('dy', offsetY / scaleY);
  84246. domChild.setAttribute('flood-color', color);
  84247. // Divide by two here so that it looks the same as in canvas
  84248. // See: https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-shadowblur
  84249. var stdDx = blur / 2 / scaleX;
  84250. var stdDy = blur / 2 / scaleY;
  84251. var stdDeviation = stdDx + ' ' + stdDy;
  84252. domChild.setAttribute('stdDeviation', stdDeviation);
  84253. // Fix filter clipping problem
  84254. dom.setAttribute('x', '-100%');
  84255. dom.setAttribute('y', '-100%');
  84256. dom.setAttribute('width', Math.ceil(blur / 2 * 200) + '%');
  84257. dom.setAttribute('height', Math.ceil(blur / 2 * 200) + '%');
  84258. dom.appendChild(domChild);
  84259. // Store dom element in shadow, to avoid creating multiple
  84260. // dom instances for the same shadow element
  84261. displayable._shadowDom = dom;
  84262. };
  84263. /**
  84264. * Mark a single shadow to be used
  84265. *
  84266. * @param {Displayable} displayable displayable element
  84267. */
  84268. ShadowManager.prototype.markUsed = function (displayable) {
  84269. if (displayable._shadowDom) {
  84270. Definable.prototype.markUsed.call(this, displayable._shadowDom);
  84271. }
  84272. };
  84273. function hasShadow(style) {
  84274. // TODO: textBoxShadowBlur is not supported yet
  84275. return style
  84276. && (style.shadowBlur || style.shadowOffsetX || style.shadowOffsetY
  84277. || style.textShadowBlur || style.textShadowOffsetX
  84278. || style.textShadowOffsetY);
  84279. }
  84280. /**
  84281. * SVG Painter
  84282. * @module zrender/svg/Painter
  84283. */
  84284. function parseInt10$2(val) {
  84285. return parseInt(val, 10);
  84286. }
  84287. function getSvgProxy(el) {
  84288. if (el instanceof Path) {
  84289. return svgPath;
  84290. }
  84291. else if (el instanceof ZImage) {
  84292. return svgImage;
  84293. }
  84294. else if (el instanceof Text) {
  84295. return svgText;
  84296. }
  84297. else {
  84298. return svgPath;
  84299. }
  84300. }
  84301. function checkParentAvailable(parent, child) {
  84302. return child && parent && child.parentNode !== parent;
  84303. }
  84304. function insertAfter(parent, child, prevSibling) {
  84305. if (checkParentAvailable(parent, child) && prevSibling) {
  84306. var nextSibling = prevSibling.nextSibling;
  84307. nextSibling ? parent.insertBefore(child, nextSibling)
  84308. : parent.appendChild(child);
  84309. }
  84310. }
  84311. function prepend(parent, child) {
  84312. if (checkParentAvailable(parent, child)) {
  84313. var firstChild = parent.firstChild;
  84314. firstChild ? parent.insertBefore(child, firstChild)
  84315. : parent.appendChild(child);
  84316. }
  84317. }
  84318. // function append(parent, child) {
  84319. // if (checkParentAvailable(parent, child)) {
  84320. // parent.appendChild(child);
  84321. // }
  84322. // }
  84323. function remove$1(parent, child) {
  84324. if (child && parent && child.parentNode === parent) {
  84325. parent.removeChild(child);
  84326. }
  84327. }
  84328. function getTextSvgElement(displayable) {
  84329. return displayable.__textSvgEl;
  84330. }
  84331. function getSvgElement(displayable) {
  84332. return displayable.__svgEl;
  84333. }
  84334. /**
  84335. * @alias module:zrender/svg/Painter
  84336. * @constructor
  84337. * @param {HTMLElement} root 绘图容器
  84338. * @param {module:zrender/Storage} storage
  84339. * @param {Object} opts
  84340. */
  84341. var SVGPainter = function (root, storage, opts, zrId) {
  84342. this.root = root;
  84343. this.storage = storage;
  84344. this._opts = opts = extend({}, opts || {});
  84345. var svgDom = createElement('svg');
  84346. svgDom.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
  84347. svgDom.setAttribute('version', '1.1');
  84348. svgDom.setAttribute('baseProfile', 'full');
  84349. svgDom.style.cssText = 'user-select:none;position:absolute;left:0;top:0;';
  84350. var bgRoot = createElement('g');
  84351. svgDom.appendChild(bgRoot);
  84352. var svgRoot = createElement('g');
  84353. svgDom.appendChild(svgRoot);
  84354. this.gradientManager = new GradientManager(zrId, svgRoot);
  84355. this.clipPathManager = new ClippathManager(zrId, svgRoot);
  84356. this.shadowManager = new ShadowManager(zrId, svgRoot);
  84357. var viewport = document.createElement('div');
  84358. viewport.style.cssText = 'overflow:hidden;position:relative';
  84359. this._svgDom = svgDom;
  84360. this._svgRoot = svgRoot;
  84361. this._backgroundRoot = bgRoot;
  84362. this._viewport = viewport;
  84363. root.appendChild(viewport);
  84364. viewport.appendChild(svgDom);
  84365. this.resize(opts.width, opts.height);
  84366. this._visibleList = [];
  84367. };
  84368. SVGPainter.prototype = {
  84369. constructor: SVGPainter,
  84370. getType: function () {
  84371. return 'svg';
  84372. },
  84373. getViewportRoot: function () {
  84374. return this._viewport;
  84375. },
  84376. getSvgDom: function () {
  84377. return this._svgDom;
  84378. },
  84379. getSvgRoot: function () {
  84380. return this._svgRoot;
  84381. },
  84382. getViewportRootOffset: function () {
  84383. var viewportRoot = this.getViewportRoot();
  84384. if (viewportRoot) {
  84385. return {
  84386. offsetLeft: viewportRoot.offsetLeft || 0,
  84387. offsetTop: viewportRoot.offsetTop || 0
  84388. };
  84389. }
  84390. },
  84391. refresh: function () {
  84392. var list = this.storage.getDisplayList(true);
  84393. this._paintList(list);
  84394. },
  84395. setBackgroundColor: function (backgroundColor) {
  84396. // TODO gradient
  84397. // Insert a bg rect instead of setting background to viewport.
  84398. // Otherwise, the exported SVG don't have background.
  84399. if (this._backgroundRoot && this._backgroundNode) {
  84400. this._backgroundRoot.removeChild(this._backgroundNode);
  84401. }
  84402. var bgNode = createElement('rect');
  84403. bgNode.setAttribute('width', this.getWidth());
  84404. bgNode.setAttribute('height', this.getHeight());
  84405. bgNode.setAttribute('x', 0);
  84406. bgNode.setAttribute('y', 0);
  84407. bgNode.setAttribute('id', 0);
  84408. bgNode.style.fill = backgroundColor;
  84409. this._backgroundRoot.appendChild(bgNode);
  84410. this._backgroundNode = bgNode;
  84411. },
  84412. _paintList: function (list) {
  84413. this.gradientManager.markAllUnused();
  84414. this.clipPathManager.markAllUnused();
  84415. this.shadowManager.markAllUnused();
  84416. var svgRoot = this._svgRoot;
  84417. var visibleList = this._visibleList;
  84418. var listLen = list.length;
  84419. var newVisibleList = [];
  84420. var i;
  84421. for (i = 0; i < listLen; i++) {
  84422. var displayable = list[i];
  84423. var svgProxy = getSvgProxy(displayable);
  84424. var svgElement = getSvgElement(displayable)
  84425. || getTextSvgElement(displayable);
  84426. if (!displayable.invisible) {
  84427. if (displayable.__dirty) {
  84428. svgProxy && svgProxy.brush(displayable);
  84429. // Update clipPath
  84430. this.clipPathManager.update(displayable);
  84431. // Update gradient and shadow
  84432. if (displayable.style) {
  84433. this.gradientManager
  84434. .update(displayable.style.fill);
  84435. this.gradientManager
  84436. .update(displayable.style.stroke);
  84437. this.shadowManager
  84438. .update(svgElement, displayable);
  84439. }
  84440. displayable.__dirty = false;
  84441. }
  84442. newVisibleList.push(displayable);
  84443. }
  84444. }
  84445. var diff = arrayDiff$1(visibleList, newVisibleList);
  84446. var prevSvgElement;
  84447. // First do remove, in case element moved to the head and do remove
  84448. // after add
  84449. for (i = 0; i < diff.length; i++) {
  84450. var item = diff[i];
  84451. if (item.removed) {
  84452. for (var k = 0; k < item.count; k++) {
  84453. var displayable = visibleList[item.indices[k]];
  84454. var svgElement = getSvgElement(displayable);
  84455. var textSvgElement = getTextSvgElement(displayable);
  84456. remove$1(svgRoot, svgElement);
  84457. remove$1(svgRoot, textSvgElement);
  84458. }
  84459. }
  84460. }
  84461. for (i = 0; i < diff.length; i++) {
  84462. var item = diff[i];
  84463. if (item.added) {
  84464. for (var k = 0; k < item.count; k++) {
  84465. var displayable = newVisibleList[item.indices[k]];
  84466. var svgElement = getSvgElement(displayable);
  84467. var textSvgElement = getTextSvgElement(displayable);
  84468. prevSvgElement
  84469. ? insertAfter(svgRoot, svgElement, prevSvgElement)
  84470. : prepend(svgRoot, svgElement);
  84471. if (svgElement) {
  84472. insertAfter(svgRoot, textSvgElement, svgElement);
  84473. }
  84474. else if (prevSvgElement) {
  84475. insertAfter(
  84476. svgRoot, textSvgElement, prevSvgElement
  84477. );
  84478. }
  84479. else {
  84480. prepend(svgRoot, textSvgElement);
  84481. }
  84482. // Insert text
  84483. insertAfter(svgRoot, textSvgElement, svgElement);
  84484. prevSvgElement = textSvgElement || svgElement
  84485. || prevSvgElement;
  84486. // zrender.Text only create textSvgElement.
  84487. this.gradientManager
  84488. .addWithoutUpdate(svgElement || textSvgElement, displayable);
  84489. this.shadowManager
  84490. .addWithoutUpdate(svgElement || textSvgElement, displayable);
  84491. this.clipPathManager.markUsed(displayable);
  84492. }
  84493. }
  84494. else if (!item.removed) {
  84495. for (var k = 0; k < item.count; k++) {
  84496. var displayable = newVisibleList[item.indices[k]];
  84497. var svgElement = getSvgElement(displayable);
  84498. var textSvgElement = getTextSvgElement(displayable);
  84499. var svgElement = getSvgElement(displayable);
  84500. var textSvgElement = getTextSvgElement(displayable);
  84501. this.gradientManager.markUsed(displayable);
  84502. this.gradientManager
  84503. .addWithoutUpdate(svgElement || textSvgElement, displayable);
  84504. this.shadowManager.markUsed(displayable);
  84505. this.shadowManager
  84506. .addWithoutUpdate(svgElement || textSvgElement, displayable);
  84507. this.clipPathManager.markUsed(displayable);
  84508. if (textSvgElement) { // Insert text.
  84509. insertAfter(svgRoot, textSvgElement, svgElement);
  84510. }
  84511. prevSvgElement = svgElement
  84512. || textSvgElement || prevSvgElement;
  84513. }
  84514. }
  84515. }
  84516. this.gradientManager.removeUnused();
  84517. this.clipPathManager.removeUnused();
  84518. this.shadowManager.removeUnused();
  84519. this._visibleList = newVisibleList;
  84520. },
  84521. _getDefs: function (isForceCreating) {
  84522. var svgRoot = this._svgDom;
  84523. var defs = svgRoot.getElementsByTagName('defs');
  84524. if (defs.length === 0) {
  84525. // Not exist
  84526. if (isForceCreating) {
  84527. var defs = svgRoot.insertBefore(
  84528. createElement('defs'), // Create new tag
  84529. svgRoot.firstChild // Insert in the front of svg
  84530. );
  84531. if (!defs.contains) {
  84532. // IE doesn't support contains method
  84533. defs.contains = function (el) {
  84534. var children = defs.children;
  84535. if (!children) {
  84536. return false;
  84537. }
  84538. for (var i = children.length - 1; i >= 0; --i) {
  84539. if (children[i] === el) {
  84540. return true;
  84541. }
  84542. }
  84543. return false;
  84544. };
  84545. }
  84546. return defs;
  84547. }
  84548. else {
  84549. return null;
  84550. }
  84551. }
  84552. else {
  84553. return defs[0];
  84554. }
  84555. },
  84556. resize: function (width, height) {
  84557. var viewport = this._viewport;
  84558. // FIXME Why ?
  84559. viewport.style.display = 'none';
  84560. // Save input w/h
  84561. var opts = this._opts;
  84562. width != null && (opts.width = width);
  84563. height != null && (opts.height = height);
  84564. width = this._getSize(0);
  84565. height = this._getSize(1);
  84566. viewport.style.display = '';
  84567. if (this._width !== width || this._height !== height) {
  84568. this._width = width;
  84569. this._height = height;
  84570. var viewportStyle = viewport.style;
  84571. viewportStyle.width = width + 'px';
  84572. viewportStyle.height = height + 'px';
  84573. var svgRoot = this._svgDom;
  84574. // Set width by 'svgRoot.width = width' is invalid
  84575. svgRoot.setAttribute('width', width);
  84576. svgRoot.setAttribute('height', height);
  84577. }
  84578. if (this._backgroundNode) {
  84579. this._backgroundNode.setAttribute('width', width);
  84580. this._backgroundNode.setAttribute('height', height);
  84581. }
  84582. },
  84583. /**
  84584. * 获取绘图区域宽度
  84585. */
  84586. getWidth: function () {
  84587. return this._width;
  84588. },
  84589. /**
  84590. * 获取绘图区域高度
  84591. */
  84592. getHeight: function () {
  84593. return this._height;
  84594. },
  84595. _getSize: function (whIdx) {
  84596. var opts = this._opts;
  84597. var wh = ['width', 'height'][whIdx];
  84598. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  84599. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  84600. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  84601. if (opts[wh] != null && opts[wh] !== 'auto') {
  84602. return parseFloat(opts[wh]);
  84603. }
  84604. var root = this.root;
  84605. // IE8 does not support getComputedStyle, but it use VML.
  84606. var stl = document.defaultView.getComputedStyle(root);
  84607. return (
  84608. (root[cwh] || parseInt10$2(stl[wh]) || parseInt10$2(root.style[wh]))
  84609. - (parseInt10$2(stl[plt]) || 0)
  84610. - (parseInt10$2(stl[prb]) || 0)
  84611. ) | 0;
  84612. },
  84613. dispose: function () {
  84614. this.root.innerHTML = '';
  84615. this._svgRoot
  84616. = this._backgroundRoot
  84617. = this._svgDom
  84618. = this._backgroundNode
  84619. = this._viewport
  84620. = this.storage
  84621. = null;
  84622. },
  84623. clear: function () {
  84624. if (this._viewport) {
  84625. this.root.removeChild(this._viewport);
  84626. }
  84627. },
  84628. toDataURL: function () {
  84629. this.refresh();
  84630. var html = encodeURIComponent(this._svgDom.outerHTML.replace(/></g, '>\n\r<'));
  84631. return 'data:image/svg+xml;charset=UTF-8,' + html;
  84632. }
  84633. };
  84634. // Not supported methods
  84635. function createMethodNotSupport$1(method) {
  84636. return function () {
  84637. logError$1('In SVG mode painter not support method "' + method + '"');
  84638. };
  84639. }
  84640. // Unsuppoted methods
  84641. each$1([
  84642. 'getLayer', 'insertLayer', 'eachLayer', 'eachBuiltinLayer',
  84643. 'eachOtherLayer', 'getLayers', 'modLayer', 'delLayer', 'clearLayer',
  84644. 'pathToImage'
  84645. ], function (name) {
  84646. SVGPainter.prototype[name] = createMethodNotSupport$1(name);
  84647. });
  84648. registerPainter('svg', SVGPainter);
  84649. /*
  84650. * Licensed to the Apache Software Foundation (ASF) under one
  84651. * or more contributor license agreements. See the NOTICE file
  84652. * distributed with this work for additional information
  84653. * regarding copyright ownership. The ASF licenses this file
  84654. * to you under the Apache License, Version 2.0 (the
  84655. * "License"); you may not use this file except in compliance
  84656. * with the License. You may obtain a copy of the License at
  84657. *
  84658. * http://www.apache.org/licenses/LICENSE-2.0
  84659. *
  84660. * Unless required by applicable law or agreed to in writing,
  84661. * software distributed under the License is distributed on an
  84662. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  84663. * KIND, either express or implied. See the License for the
  84664. * specific language governing permissions and limitations
  84665. * under the License.
  84666. */
  84667. // ----------------------------------------------
  84668. // All of the modules that are allowed to be
  84669. // imported are listed below.
  84670. //
  84671. // Users MUST NOT import other modules that are
  84672. // not included in this list.
  84673. // ----------------------------------------------
  84674. // ----------------
  84675. // Charts (series)
  84676. // ----------------
  84677. // All of the series types, for example:
  84678. // chart.setOption({
  84679. // series: [{
  84680. // type: 'line' // or 'bar', 'pie', ...
  84681. // }]
  84682. // });
  84683. // -------------------
  84684. // Coordinate systems
  84685. // -------------------
  84686. // All of the axis modules have been included in the
  84687. // coordinate system module below, do not need to
  84688. // make extra import.
  84689. // `cartesian` coordinate system. For some historical
  84690. // reasons, it is named as grid, for example:
  84691. // chart.setOption({
  84692. // grid: {...},
  84693. // xAxis: {...},
  84694. // yAxis: {...},
  84695. // series: [{...}]
  84696. // });
  84697. // `polar` coordinate system, for example:
  84698. // chart.setOption({
  84699. // polar: {...},
  84700. // radiusAxis: {...},
  84701. // angleAxis: {...},
  84702. // series: [{
  84703. // coordinateSystem: 'polar'
  84704. // }]
  84705. // });
  84706. // `geo` coordinate system, for example:
  84707. // chart.setOption({
  84708. // geo: {...},
  84709. // series: [{
  84710. // coordinateSystem: 'geo'
  84711. // }]
  84712. // });
  84713. // `singleAxis` coordinate system (notice, it is a coordinate system
  84714. // with only one axis, work for chart like theme river), for example:
  84715. // chart.setOption({
  84716. // singleAxis: {...}
  84717. // series: [{type: 'themeRiver', ...}]
  84718. // });
  84719. // `parallel` coordinate system, only work for parallel series, for example:
  84720. // chart.setOption({
  84721. // parallel: {...},
  84722. // parallelAxis: [{...}, ...],
  84723. // series: [{
  84724. // type: 'parallel'
  84725. // }]
  84726. // });
  84727. // `calendar` coordinate system. for example,
  84728. // chart.setOptionp({
  84729. // calendar: {...},
  84730. // series: [{
  84731. // coordinateSystem: 'calendar'
  84732. // }]
  84733. // );
  84734. // ------------------
  84735. // Other components
  84736. // ------------------
  84737. // `graphic` component, for example:
  84738. // chart.setOption({
  84739. // graphic: {...}
  84740. // });
  84741. // `toolbox` component, for example:
  84742. // chart.setOption({
  84743. // toolbox: {...}
  84744. // });
  84745. // `tooltip` component, for example:
  84746. // chart.setOption({
  84747. // tooltip: {...}
  84748. // });
  84749. // `axisPointer` component, for example:
  84750. // chart.setOption({
  84751. // tooltip: {axisPointer: {...}, ...}
  84752. // });
  84753. // Or
  84754. // chart.setOption({
  84755. // axisPointer: {...}
  84756. // });
  84757. // `brush` component, for example:
  84758. // chart.setOption({
  84759. // brush: {...}
  84760. // });
  84761. // Or
  84762. // chart.setOption({
  84763. // tooltip: {feature: {brush: {...}}
  84764. // })
  84765. // `title` component, for example:
  84766. // chart.setOption({
  84767. // title: {...}
  84768. // });
  84769. // `timeline` component, for example:
  84770. // chart.setOption({
  84771. // timeline: {...}
  84772. // });
  84773. // `markPoint` component, for example:
  84774. // chart.setOption({
  84775. // series: [{markPoint: {...}}]
  84776. // });
  84777. // `markLine` component, for example:
  84778. // chart.setOption({
  84779. // series: [{markLine: {...}}]
  84780. // });
  84781. // `markArea` component, for example:
  84782. // chart.setOption({
  84783. // series: [{markArea: {...}}]
  84784. // });
  84785. // `legend` component scrollable, for example:
  84786. // chart.setOption({
  84787. // legend: {type: 'scroll'}
  84788. // });
  84789. // `legend` component not scrollable. for example:
  84790. // chart.setOption({
  84791. // legend: {...}
  84792. // });
  84793. // `dataZoom` component including both `dataZoomInside` and `dataZoomSlider`.
  84794. // `dataZoom` component providing drag, pinch, wheel behaviors
  84795. // inside coodinate system, for example:
  84796. // chart.setOption({
  84797. // dataZoom: {type: 'inside'}
  84798. // });
  84799. // `dataZoom` component providing a slider bar, for example:
  84800. // chart.setOption({
  84801. // dataZoom: {type: 'slider'}
  84802. // });
  84803. // `dataZoom` component including both `visualMapContinuous` and `visualMapPiecewise`.
  84804. // `visualMap` component providing continuous bar, for example:
  84805. // chart.setOption({
  84806. // visualMap: {type: 'continuous'}
  84807. // });
  84808. // `visualMap` component providing pieces bar, for example:
  84809. // chart.setOption({
  84810. // visualMap: {type: 'piecewise'}
  84811. // });
  84812. // -----------------
  84813. // Render engines
  84814. // -----------------
  84815. // Provide IE 6,7,8 compatibility.
  84816. // Render via SVG rather than canvas.
  84817. exports.version = version;
  84818. exports.dependencies = dependencies;
  84819. exports.PRIORITY = PRIORITY;
  84820. exports.init = init;
  84821. exports.connect = connect;
  84822. exports.disConnect = disConnect;
  84823. exports.disconnect = disconnect;
  84824. exports.dispose = dispose;
  84825. exports.getInstanceByDom = getInstanceByDom;
  84826. exports.getInstanceById = getInstanceById;
  84827. exports.registerTheme = registerTheme;
  84828. exports.registerPreprocessor = registerPreprocessor;
  84829. exports.registerProcessor = registerProcessor;
  84830. exports.registerPostUpdate = registerPostUpdate;
  84831. exports.registerAction = registerAction;
  84832. exports.registerCoordinateSystem = registerCoordinateSystem;
  84833. exports.getCoordinateSystemDimensions = getCoordinateSystemDimensions;
  84834. exports.registerLayout = registerLayout;
  84835. exports.registerVisual = registerVisual;
  84836. exports.registerLoading = registerLoading;
  84837. exports.extendComponentModel = extendComponentModel;
  84838. exports.extendComponentView = extendComponentView;
  84839. exports.extendSeriesModel = extendSeriesModel;
  84840. exports.extendChartView = extendChartView;
  84841. exports.setCanvasCreator = setCanvasCreator;
  84842. exports.registerMap = registerMap;
  84843. exports.getMap = getMap;
  84844. exports.dataTool = dataTool;
  84845. exports.zrender = zrender;
  84846. exports.number = number;
  84847. exports.format = format;
  84848. exports.throttle = throttle;
  84849. exports.helper = helper;
  84850. exports.matrix = matrix;
  84851. exports.vector = vector;
  84852. exports.color = color;
  84853. exports.parseGeoJSON = parseGeoJson$1;
  84854. exports.parseGeoJson = parseGeoJson;
  84855. exports.util = ecUtil;
  84856. exports.graphic = graphic$1;
  84857. exports.List = List;
  84858. exports.Model = Model;
  84859. exports.Axis = Axis;
  84860. exports.env = env$1;
  84861. })));
  84862. //# sourceMappingURL=echarts.js.map