echarts.js 2.6 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246
  1. /*!
  2. * Copyright (c) https://github.com/apache/incubator-echarts
  3. * github: https://github.com/apache/incubator-echarts
  4. * license: Apachelicence 2.0
  5. * version: 4.1.0
  6. */
  7. (function (global, factory) {
  8. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  9. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  10. (factory((global.echarts = {})));
  11. }(this, (function (exports) { 'use strict';
  12. /*
  13. * Licensed to the Apache Software Foundation (ASF) under one
  14. * or more contributor license agreements. See the NOTICE file
  15. * distributed with this work for additional information
  16. * regarding copyright ownership. The ASF licenses this file
  17. * to you under the Apache License, Version 2.0 (the
  18. * "License"); you may not use this file except in compliance
  19. * with the License. You may obtain a copy of the License at
  20. *
  21. * http://www.apache.org/licenses/LICENSE-2.0
  22. *
  23. * Unless required by applicable law or agreed to in writing,
  24. * software distributed under the License is distributed on an
  25. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26. * KIND, either express or implied. See the License for the
  27. * specific language governing permissions and limitations
  28. * under the License.
  29. */
  30. // (1) The code `if (__DEV__) ...` can be removed by build tool.
  31. // (2) If intend to use `__DEV__`, this module should be imported. Use a global
  32. // variable `__DEV__` may cause that miss the declaration (see #6535), or the
  33. // declaration is behind of the using position (for example in `Model.extent`,
  34. // And tools like rollup can not analysis the dependency if not import).
  35. var dev;
  36. // In browser
  37. if (typeof window !== 'undefined') {
  38. dev = window.__DEV__;
  39. }
  40. // In node
  41. else if (typeof global !== 'undefined') {
  42. dev = global.__DEV__;
  43. }
  44. if (typeof dev === 'undefined') {
  45. dev = true;
  46. }
  47. var __DEV__ = dev;
  48. /**
  49. * zrender: 生成唯一id
  50. *
  51. * @author errorrik (errorrik@gmail.com)
  52. */
  53. var idStart = 0x0907;
  54. var guid = function () {
  55. return idStart++;
  56. };
  57. /**
  58. * echarts设备环境识别
  59. *
  60. * @desc echarts基于Canvas,纯Javascript图表库,提供直观,生动,可交互,可个性化定制的数据统计图表。
  61. * @author firede[firede@firede.us]
  62. * @desc thanks zepto.
  63. */
  64. var env = {};
  65. if (typeof wx === 'object' && typeof wx.getSystemInfoSync === 'function') {
  66. // In Weixin Application
  67. env = {
  68. browser: {},
  69. os: {},
  70. node: false,
  71. wxa: true, // Weixin Application
  72. canvasSupported: true,
  73. svgSupported: false,
  74. touchEventsSupported: true
  75. };
  76. }
  77. else if (typeof document === 'undefined' && typeof self !== 'undefined') {
  78. // In worker
  79. env = {
  80. browser: {},
  81. os: {},
  82. node: false,
  83. worker: true,
  84. canvasSupported: true
  85. };
  86. }
  87. else if (typeof navigator === 'undefined') {
  88. // In node
  89. env = {
  90. browser: {},
  91. os: {},
  92. node: true,
  93. worker: false,
  94. // Assume canvas is supported
  95. canvasSupported: true,
  96. svgSupported: true
  97. };
  98. }
  99. else {
  100. env = detect(navigator.userAgent);
  101. }
  102. var env$1 = env;
  103. // Zepto.js
  104. // (c) 2010-2013 Thomas Fuchs
  105. // Zepto.js may be freely distributed under the MIT license.
  106. function detect(ua) {
  107. var os = {};
  108. var browser = {};
  109. // var webkit = ua.match(/Web[kK]it[\/]{0,1}([\d.]+)/);
  110. // var android = ua.match(/(Android);?[\s\/]+([\d.]+)?/);
  111. // var ipad = ua.match(/(iPad).*OS\s([\d_]+)/);
  112. // var ipod = ua.match(/(iPod)(.*OS\s([\d_]+))?/);
  113. // var iphone = !ipad && ua.match(/(iPhone\sOS)\s([\d_]+)/);
  114. // var webos = ua.match(/(webOS|hpwOS)[\s\/]([\d.]+)/);
  115. // var touchpad = webos && ua.match(/TouchPad/);
  116. // var kindle = ua.match(/Kindle\/([\d.]+)/);
  117. // var silk = ua.match(/Silk\/([\d._]+)/);
  118. // var blackberry = ua.match(/(BlackBerry).*Version\/([\d.]+)/);
  119. // var bb10 = ua.match(/(BB10).*Version\/([\d.]+)/);
  120. // var rimtabletos = ua.match(/(RIM\sTablet\sOS)\s([\d.]+)/);
  121. // var playbook = ua.match(/PlayBook/);
  122. // var chrome = ua.match(/Chrome\/([\d.]+)/) || ua.match(/CriOS\/([\d.]+)/);
  123. var firefox = ua.match(/Firefox\/([\d.]+)/);
  124. // var safari = webkit && ua.match(/Mobile\//) && !chrome;
  125. // var webview = ua.match(/(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/) && !chrome;
  126. var ie = ua.match(/MSIE\s([\d.]+)/)
  127. // IE 11 Trident/7.0; rv:11.0
  128. || ua.match(/Trident\/.+?rv:(([\d.]+))/);
  129. var edge = ua.match(/Edge\/([\d.]+)/); // IE 12 and 12+
  130. var weChat = (/micromessenger/i).test(ua);
  131. // Todo: clean this up with a better OS/browser seperation:
  132. // - discern (more) between multiple browsers on android
  133. // - decide if kindle fire in silk mode is android or not
  134. // - Firefox on Android doesn't specify the Android version
  135. // - possibly devide in os, device and browser hashes
  136. // if (browser.webkit = !!webkit) browser.version = webkit[1];
  137. // if (android) os.android = true, os.version = android[2];
  138. // if (iphone && !ipod) os.ios = os.iphone = true, os.version = iphone[2].replace(/_/g, '.');
  139. // if (ipad) os.ios = os.ipad = true, os.version = ipad[2].replace(/_/g, '.');
  140. // if (ipod) os.ios = os.ipod = true, os.version = ipod[3] ? ipod[3].replace(/_/g, '.') : null;
  141. // if (webos) os.webos = true, os.version = webos[2];
  142. // if (touchpad) os.touchpad = true;
  143. // if (blackberry) os.blackberry = true, os.version = blackberry[2];
  144. // if (bb10) os.bb10 = true, os.version = bb10[2];
  145. // if (rimtabletos) os.rimtabletos = true, os.version = rimtabletos[2];
  146. // if (playbook) browser.playbook = true;
  147. // if (kindle) os.kindle = true, os.version = kindle[1];
  148. // if (silk) browser.silk = true, browser.version = silk[1];
  149. // if (!silk && os.android && ua.match(/Kindle Fire/)) browser.silk = true;
  150. // if (chrome) browser.chrome = true, browser.version = chrome[1];
  151. if (firefox) {
  152. browser.firefox = true;
  153. browser.version = firefox[1];
  154. }
  155. // if (safari && (ua.match(/Safari/) || !!os.ios)) browser.safari = true;
  156. // if (webview) browser.webview = true;
  157. if (ie) {
  158. browser.ie = true;
  159. browser.version = ie[1];
  160. }
  161. if (edge) {
  162. browser.edge = true;
  163. browser.version = edge[1];
  164. }
  165. // It is difficult to detect WeChat in Win Phone precisely, because ua can
  166. // not be set on win phone. So we do not consider Win Phone.
  167. if (weChat) {
  168. browser.weChat = true;
  169. }
  170. // os.tablet = !!(ipad || playbook || (android && !ua.match(/Mobile/)) ||
  171. // (firefox && ua.match(/Tablet/)) || (ie && !ua.match(/Phone/) && ua.match(/Touch/)));
  172. // os.phone = !!(!os.tablet && !os.ipod && (android || iphone || webos ||
  173. // (chrome && ua.match(/Android/)) || (chrome && ua.match(/CriOS\/([\d.]+)/)) ||
  174. // (firefox && ua.match(/Mobile/)) || (ie && ua.match(/Touch/))));
  175. return {
  176. browser: browser,
  177. os: os,
  178. node: false,
  179. // 原生canvas支持,改极端点了
  180. // canvasSupported : !(browser.ie && parseFloat(browser.version) < 9)
  181. canvasSupported: !!document.createElement('canvas').getContext,
  182. svgSupported: typeof SVGRect !== 'undefined',
  183. // works on most browsers
  184. // IE10/11 does not support touch event, and MS Edge supports them but not by
  185. // default, so we dont check navigator.maxTouchPoints for them here.
  186. touchEventsSupported: 'ontouchstart' in window && !browser.ie && !browser.edge,
  187. // <http://caniuse.com/#search=pointer%20event>.
  188. pointerEventsSupported: 'onpointerdown' in window
  189. // Firefox supports pointer but not by default, only MS browsers are reliable on pointer
  190. // events currently. So we dont use that on other browsers unless tested sufficiently.
  191. // Although IE 10 supports pointer event, it use old style and is different from the
  192. // standard. So we exclude that. (IE 10 is hardly used on touch device)
  193. && (browser.edge || (browser.ie && browser.version >= 11))
  194. // passiveSupported: detectPassiveSupport()
  195. };
  196. }
  197. // See https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md#feature-detection
  198. // function detectPassiveSupport() {
  199. // // Test via a getter in the options object to see if the passive property is accessed
  200. // var supportsPassive = false;
  201. // try {
  202. // var opts = Object.defineProperty({}, 'passive', {
  203. // get: function() {
  204. // supportsPassive = true;
  205. // }
  206. // });
  207. // window.addEventListener('testPassive', function() {}, opts);
  208. // } catch (e) {
  209. // }
  210. // return supportsPassive;
  211. // }
  212. /**
  213. * @module zrender/core/util
  214. */
  215. // 用于处理merge时无法遍历Date等对象的问题
  216. var BUILTIN_OBJECT = {
  217. '[object Function]': 1,
  218. '[object RegExp]': 1,
  219. '[object Date]': 1,
  220. '[object Error]': 1,
  221. '[object CanvasGradient]': 1,
  222. '[object CanvasPattern]': 1,
  223. // For node-canvas
  224. '[object Image]': 1,
  225. '[object Canvas]': 1
  226. };
  227. var TYPED_ARRAY = {
  228. '[object Int8Array]': 1,
  229. '[object Uint8Array]': 1,
  230. '[object Uint8ClampedArray]': 1,
  231. '[object Int16Array]': 1,
  232. '[object Uint16Array]': 1,
  233. '[object Int32Array]': 1,
  234. '[object Uint32Array]': 1,
  235. '[object Float32Array]': 1,
  236. '[object Float64Array]': 1
  237. };
  238. var objToString = Object.prototype.toString;
  239. var arrayProto = Array.prototype;
  240. var nativeForEach = arrayProto.forEach;
  241. var nativeFilter = arrayProto.filter;
  242. var nativeSlice = arrayProto.slice;
  243. var nativeMap = arrayProto.map;
  244. var nativeReduce = arrayProto.reduce;
  245. // Avoid assign to an exported variable, for transforming to cjs.
  246. var methods = {};
  247. function $override(name, fn) {
  248. // Clear ctx instance for different environment
  249. if (name === 'createCanvas') {
  250. _ctx = null;
  251. }
  252. methods[name] = fn;
  253. }
  254. /**
  255. * Those data types can be cloned:
  256. * Plain object, Array, TypedArray, number, string, null, undefined.
  257. * Those data types will be assgined using the orginal data:
  258. * BUILTIN_OBJECT
  259. * Instance of user defined class will be cloned to a plain object, without
  260. * properties in prototype.
  261. * Other data types is not supported (not sure what will happen).
  262. *
  263. * Caution: do not support clone Date, for performance consideration.
  264. * (There might be a large number of date in `series.data`).
  265. * So date should not be modified in and out of echarts.
  266. *
  267. * @param {*} source
  268. * @return {*} new
  269. */
  270. function clone(source) {
  271. if (source == null || typeof source != 'object') {
  272. return source;
  273. }
  274. var result = source;
  275. var typeStr = objToString.call(source);
  276. if (typeStr === '[object Array]') {
  277. if (!isPrimitive(source)) {
  278. result = [];
  279. for (var i = 0, len = source.length; i < len; i++) {
  280. result[i] = clone(source[i]);
  281. }
  282. }
  283. }
  284. else if (TYPED_ARRAY[typeStr]) {
  285. if (!isPrimitive(source)) {
  286. var Ctor = source.constructor;
  287. if (source.constructor.from) {
  288. result = Ctor.from(source);
  289. }
  290. else {
  291. result = new Ctor(source.length);
  292. for (var i = 0, len = source.length; i < len; i++) {
  293. result[i] = clone(source[i]);
  294. }
  295. }
  296. }
  297. }
  298. else if (!BUILTIN_OBJECT[typeStr] && !isPrimitive(source) && !isDom(source)) {
  299. result = {};
  300. for (var key in source) {
  301. if (source.hasOwnProperty(key)) {
  302. result[key] = clone(source[key]);
  303. }
  304. }
  305. }
  306. return result;
  307. }
  308. /**
  309. * @memberOf module:zrender/core/util
  310. * @param {*} target
  311. * @param {*} source
  312. * @param {boolean} [overwrite=false]
  313. */
  314. function merge(target, source, overwrite) {
  315. // We should escapse that source is string
  316. // and enter for ... in ...
  317. if (!isObject$1(source) || !isObject$1(target)) {
  318. return overwrite ? clone(source) : target;
  319. }
  320. for (var key in source) {
  321. if (source.hasOwnProperty(key)) {
  322. var targetProp = target[key];
  323. var sourceProp = source[key];
  324. if (isObject$1(sourceProp)
  325. && isObject$1(targetProp)
  326. && !isArray(sourceProp)
  327. && !isArray(targetProp)
  328. && !isDom(sourceProp)
  329. && !isDom(targetProp)
  330. && !isBuiltInObject(sourceProp)
  331. && !isBuiltInObject(targetProp)
  332. && !isPrimitive(sourceProp)
  333. && !isPrimitive(targetProp)
  334. ) {
  335. // 如果需要递归覆盖,就递归调用merge
  336. merge(targetProp, sourceProp, overwrite);
  337. }
  338. else if (overwrite || !(key in target)) {
  339. // 否则只处理overwrite为true,或者在目标对象中没有此属性的情况
  340. // NOTE,在 target[key] 不存在的时候也是直接覆盖
  341. target[key] = clone(source[key], true);
  342. }
  343. }
  344. }
  345. return target;
  346. }
  347. /**
  348. * @param {Array} targetAndSources The first item is target, and the rests are source.
  349. * @param {boolean} [overwrite=false]
  350. * @return {*} target
  351. */
  352. function mergeAll(targetAndSources, overwrite) {
  353. var result = targetAndSources[0];
  354. for (var i = 1, len = targetAndSources.length; i < len; i++) {
  355. result = merge(result, targetAndSources[i], overwrite);
  356. }
  357. return result;
  358. }
  359. /**
  360. * @param {*} target
  361. * @param {*} source
  362. * @memberOf module:zrender/core/util
  363. */
  364. function extend(target, source) {
  365. for (var key in source) {
  366. if (source.hasOwnProperty(key)) {
  367. target[key] = source[key];
  368. }
  369. }
  370. return target;
  371. }
  372. /**
  373. * @param {*} target
  374. * @param {*} source
  375. * @param {boolean} [overlay=false]
  376. * @memberOf module:zrender/core/util
  377. */
  378. function defaults(target, source, overlay) {
  379. for (var key in source) {
  380. if (source.hasOwnProperty(key)
  381. && (overlay ? source[key] != null : target[key] == null)
  382. ) {
  383. target[key] = source[key];
  384. }
  385. }
  386. return target;
  387. }
  388. var createCanvas = function () {
  389. return methods.createCanvas();
  390. };
  391. methods.createCanvas = function () {
  392. return document.createElement('canvas');
  393. };
  394. // FIXME
  395. var _ctx;
  396. function getContext() {
  397. if (!_ctx) {
  398. // Use util.createCanvas instead of createCanvas
  399. // because createCanvas may be overwritten in different environment
  400. _ctx = createCanvas().getContext('2d');
  401. }
  402. return _ctx;
  403. }
  404. /**
  405. * 查询数组中元素的index
  406. * @memberOf module:zrender/core/util
  407. */
  408. function indexOf(array, value) {
  409. if (array) {
  410. if (array.indexOf) {
  411. return array.indexOf(value);
  412. }
  413. for (var i = 0, len = array.length; i < len; i++) {
  414. if (array[i] === value) {
  415. return i;
  416. }
  417. }
  418. }
  419. return -1;
  420. }
  421. /**
  422. * 构造类继承关系
  423. *
  424. * @memberOf module:zrender/core/util
  425. * @param {Function} clazz 源类
  426. * @param {Function} baseClazz 基类
  427. */
  428. function inherits(clazz, baseClazz) {
  429. var clazzPrototype = clazz.prototype;
  430. function F() {}
  431. F.prototype = baseClazz.prototype;
  432. clazz.prototype = new F();
  433. for (var prop in clazzPrototype) {
  434. clazz.prototype[prop] = clazzPrototype[prop];
  435. }
  436. clazz.prototype.constructor = clazz;
  437. clazz.superClass = baseClazz;
  438. }
  439. /**
  440. * @memberOf module:zrender/core/util
  441. * @param {Object|Function} target
  442. * @param {Object|Function} sorce
  443. * @param {boolean} overlay
  444. */
  445. function mixin(target, source, overlay) {
  446. target = 'prototype' in target ? target.prototype : target;
  447. source = 'prototype' in source ? source.prototype : source;
  448. defaults(target, source, overlay);
  449. }
  450. /**
  451. * Consider typed array.
  452. * @param {Array|TypedArray} data
  453. */
  454. function isArrayLike(data) {
  455. if (! data) {
  456. return;
  457. }
  458. if (typeof data == 'string') {
  459. return false;
  460. }
  461. return typeof data.length == 'number';
  462. }
  463. /**
  464. * 数组或对象遍历
  465. * @memberOf module:zrender/core/util
  466. * @param {Object|Array} obj
  467. * @param {Function} cb
  468. * @param {*} [context]
  469. */
  470. function each$1(obj, cb, context) {
  471. if (!(obj && cb)) {
  472. return;
  473. }
  474. if (obj.forEach && obj.forEach === nativeForEach) {
  475. obj.forEach(cb, context);
  476. }
  477. else if (obj.length === +obj.length) {
  478. for (var i = 0, len = obj.length; i < len; i++) {
  479. cb.call(context, obj[i], i, obj);
  480. }
  481. }
  482. else {
  483. for (var key in obj) {
  484. if (obj.hasOwnProperty(key)) {
  485. cb.call(context, obj[key], key, obj);
  486. }
  487. }
  488. }
  489. }
  490. /**
  491. * 数组映射
  492. * @memberOf module:zrender/core/util
  493. * @param {Array} obj
  494. * @param {Function} cb
  495. * @param {*} [context]
  496. * @return {Array}
  497. */
  498. function map(obj, cb, context) {
  499. if (!(obj && cb)) {
  500. return;
  501. }
  502. if (obj.map && obj.map === nativeMap) {
  503. return obj.map(cb, context);
  504. }
  505. else {
  506. var result = [];
  507. for (var i = 0, len = obj.length; i < len; i++) {
  508. result.push(cb.call(context, obj[i], i, obj));
  509. }
  510. return result;
  511. }
  512. }
  513. /**
  514. * @memberOf module:zrender/core/util
  515. * @param {Array} obj
  516. * @param {Function} cb
  517. * @param {Object} [memo]
  518. * @param {*} [context]
  519. * @return {Array}
  520. */
  521. function reduce(obj, cb, memo, context) {
  522. if (!(obj && cb)) {
  523. return;
  524. }
  525. if (obj.reduce && obj.reduce === nativeReduce) {
  526. return obj.reduce(cb, memo, context);
  527. }
  528. else {
  529. for (var i = 0, len = obj.length; i < len; i++) {
  530. memo = cb.call(context, memo, obj[i], i, obj);
  531. }
  532. return memo;
  533. }
  534. }
  535. /**
  536. * 数组过滤
  537. * @memberOf module:zrender/core/util
  538. * @param {Array} obj
  539. * @param {Function} cb
  540. * @param {*} [context]
  541. * @return {Array}
  542. */
  543. function filter(obj, cb, context) {
  544. if (!(obj && cb)) {
  545. return;
  546. }
  547. if (obj.filter && obj.filter === nativeFilter) {
  548. return obj.filter(cb, context);
  549. }
  550. else {
  551. var result = [];
  552. for (var i = 0, len = obj.length; i < len; i++) {
  553. if (cb.call(context, obj[i], i, obj)) {
  554. result.push(obj[i]);
  555. }
  556. }
  557. return result;
  558. }
  559. }
  560. /**
  561. * 数组项查找
  562. * @memberOf module:zrender/core/util
  563. * @param {Array} obj
  564. * @param {Function} cb
  565. * @param {*} [context]
  566. * @return {*}
  567. */
  568. function find(obj, cb, context) {
  569. if (!(obj && cb)) {
  570. return;
  571. }
  572. for (var i = 0, len = obj.length; i < len; i++) {
  573. if (cb.call(context, obj[i], i, obj)) {
  574. return obj[i];
  575. }
  576. }
  577. }
  578. /**
  579. * @memberOf module:zrender/core/util
  580. * @param {Function} func
  581. * @param {*} context
  582. * @return {Function}
  583. */
  584. function bind(func, context) {
  585. var args = nativeSlice.call(arguments, 2);
  586. return function () {
  587. return func.apply(context, args.concat(nativeSlice.call(arguments)));
  588. };
  589. }
  590. /**
  591. * @memberOf module:zrender/core/util
  592. * @param {Function} func
  593. * @return {Function}
  594. */
  595. function curry(func) {
  596. var args = nativeSlice.call(arguments, 1);
  597. return function () {
  598. return func.apply(this, args.concat(nativeSlice.call(arguments)));
  599. };
  600. }
  601. /**
  602. * @memberOf module:zrender/core/util
  603. * @param {*} value
  604. * @return {boolean}
  605. */
  606. function isArray(value) {
  607. return objToString.call(value) === '[object Array]';
  608. }
  609. /**
  610. * @memberOf module:zrender/core/util
  611. * @param {*} value
  612. * @return {boolean}
  613. */
  614. function isFunction$1(value) {
  615. return typeof value === 'function';
  616. }
  617. /**
  618. * @memberOf module:zrender/core/util
  619. * @param {*} value
  620. * @return {boolean}
  621. */
  622. function isString(value) {
  623. return objToString.call(value) === '[object String]';
  624. }
  625. /**
  626. * @memberOf module:zrender/core/util
  627. * @param {*} value
  628. * @return {boolean}
  629. */
  630. function isObject$1(value) {
  631. // Avoid a V8 JIT bug in Chrome 19-20.
  632. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
  633. var type = typeof value;
  634. return type === 'function' || (!!value && type == 'object');
  635. }
  636. /**
  637. * @memberOf module:zrender/core/util
  638. * @param {*} value
  639. * @return {boolean}
  640. */
  641. function isBuiltInObject(value) {
  642. return !!BUILTIN_OBJECT[objToString.call(value)];
  643. }
  644. /**
  645. * @memberOf module:zrender/core/util
  646. * @param {*} value
  647. * @return {boolean}
  648. */
  649. function isTypedArray(value) {
  650. return !!TYPED_ARRAY[objToString.call(value)];
  651. }
  652. /**
  653. * @memberOf module:zrender/core/util
  654. * @param {*} value
  655. * @return {boolean}
  656. */
  657. function isDom(value) {
  658. return typeof value === 'object'
  659. && typeof value.nodeType === 'number'
  660. && typeof value.ownerDocument === 'object';
  661. }
  662. /**
  663. * Whether is exactly NaN. Notice isNaN('a') returns true.
  664. * @param {*} value
  665. * @return {boolean}
  666. */
  667. function eqNaN(value) {
  668. return value !== value;
  669. }
  670. /**
  671. * If value1 is not null, then return value1, otherwise judget rest of values.
  672. * Low performance.
  673. * @memberOf module:zrender/core/util
  674. * @return {*} Final value
  675. */
  676. function retrieve(values) {
  677. for (var i = 0, len = arguments.length; i < len; i++) {
  678. if (arguments[i] != null) {
  679. return arguments[i];
  680. }
  681. }
  682. }
  683. function retrieve2(value0, value1) {
  684. return value0 != null
  685. ? value0
  686. : value1;
  687. }
  688. function retrieve3(value0, value1, value2) {
  689. return value0 != null
  690. ? value0
  691. : value1 != null
  692. ? value1
  693. : value2;
  694. }
  695. /**
  696. * @memberOf module:zrender/core/util
  697. * @param {Array} arr
  698. * @param {number} startIndex
  699. * @param {number} endIndex
  700. * @return {Array}
  701. */
  702. function slice() {
  703. return Function.call.apply(nativeSlice, arguments);
  704. }
  705. /**
  706. * Normalize css liked array configuration
  707. * e.g.
  708. * 3 => [3, 3, 3, 3]
  709. * [4, 2] => [4, 2, 4, 2]
  710. * [4, 3, 2] => [4, 3, 2, 3]
  711. * @param {number|Array.<number>} val
  712. * @return {Array.<number>}
  713. */
  714. function normalizeCssArray(val) {
  715. if (typeof (val) === 'number') {
  716. return [val, val, val, val];
  717. }
  718. var len = val.length;
  719. if (len === 2) {
  720. // vertical | horizontal
  721. return [val[0], val[1], val[0], val[1]];
  722. }
  723. else if (len === 3) {
  724. // top | horizontal | bottom
  725. return [val[0], val[1], val[2], val[1]];
  726. }
  727. return val;
  728. }
  729. /**
  730. * @memberOf module:zrender/core/util
  731. * @param {boolean} condition
  732. * @param {string} message
  733. */
  734. function assert$1(condition, message) {
  735. if (!condition) {
  736. throw new Error(message);
  737. }
  738. }
  739. /**
  740. * @memberOf module:zrender/core/util
  741. * @param {string} str string to be trimed
  742. * @return {string} trimed string
  743. */
  744. function trim(str) {
  745. if (str == null) {
  746. return null;
  747. }
  748. else if (typeof str.trim === 'function') {
  749. return str.trim();
  750. }
  751. else {
  752. return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  753. }
  754. }
  755. var primitiveKey = '__ec_primitive__';
  756. /**
  757. * Set an object as primitive to be ignored traversing children in clone or merge
  758. */
  759. function setAsPrimitive(obj) {
  760. obj[primitiveKey] = true;
  761. }
  762. function isPrimitive(obj) {
  763. return obj[primitiveKey];
  764. }
  765. /**
  766. * @constructor
  767. * @param {Object} obj Only apply `ownProperty`.
  768. */
  769. function HashMap(obj) {
  770. var isArr = isArray(obj);
  771. var thisMap = this;
  772. (obj instanceof HashMap)
  773. ? obj.each(visit)
  774. : (obj && each$1(obj, visit));
  775. function visit(value, key) {
  776. isArr ? thisMap.set(value, key) : thisMap.set(key, value);
  777. }
  778. }
  779. // Add prefix to avoid conflict with Object.prototype.
  780. HashMap.prototype = {
  781. constructor: HashMap,
  782. // Do not provide `has` method to avoid defining what is `has`.
  783. // (We usually treat `null` and `undefined` as the same, different
  784. // from ES6 Map).
  785. get: function (key) {
  786. return this.hasOwnProperty(key) ? this[key] : null;
  787. },
  788. set: function (key, value) {
  789. // Comparing with invocation chaining, `return value` is more commonly
  790. // used in this case: `var someVal = map.set('a', genVal());`
  791. return (this[key] = value);
  792. },
  793. // Although util.each can be performed on this hashMap directly, user
  794. // should not use the exposed keys, who are prefixed.
  795. each: function (cb, context) {
  796. context !== void 0 && (cb = bind(cb, context));
  797. for (var key in this) {
  798. this.hasOwnProperty(key) && cb(this[key], key);
  799. }
  800. },
  801. // Do not use this method if performance sensitive.
  802. removeKey: function (key) {
  803. delete this[key];
  804. }
  805. };
  806. function createHashMap(obj) {
  807. return new HashMap(obj);
  808. }
  809. function concatArray(a, b) {
  810. var newArray = new a.constructor(a.length + b.length);
  811. for (var i = 0; i < a.length; i++) {
  812. newArray[i] = a[i];
  813. }
  814. var offset = a.length;
  815. for (i = 0; i < b.length; i++) {
  816. newArray[i + offset] = b[i];
  817. }
  818. return newArray;
  819. }
  820. function noop() {}
  821. var zrUtil = (Object.freeze || Object)({
  822. $override: $override,
  823. clone: clone,
  824. merge: merge,
  825. mergeAll: mergeAll,
  826. extend: extend,
  827. defaults: defaults,
  828. createCanvas: createCanvas,
  829. getContext: getContext,
  830. indexOf: indexOf,
  831. inherits: inherits,
  832. mixin: mixin,
  833. isArrayLike: isArrayLike,
  834. each: each$1,
  835. map: map,
  836. reduce: reduce,
  837. filter: filter,
  838. find: find,
  839. bind: bind,
  840. curry: curry,
  841. isArray: isArray,
  842. isFunction: isFunction$1,
  843. isString: isString,
  844. isObject: isObject$1,
  845. isBuiltInObject: isBuiltInObject,
  846. isTypedArray: isTypedArray,
  847. isDom: isDom,
  848. eqNaN: eqNaN,
  849. retrieve: retrieve,
  850. retrieve2: retrieve2,
  851. retrieve3: retrieve3,
  852. slice: slice,
  853. normalizeCssArray: normalizeCssArray,
  854. assert: assert$1,
  855. trim: trim,
  856. setAsPrimitive: setAsPrimitive,
  857. isPrimitive: isPrimitive,
  858. createHashMap: createHashMap,
  859. concatArray: concatArray,
  860. noop: noop
  861. });
  862. var ArrayCtor = typeof Float32Array === 'undefined'
  863. ? Array
  864. : Float32Array;
  865. /**
  866. * 创建一个向量
  867. * @param {number} [x=0]
  868. * @param {number} [y=0]
  869. * @return {Vector2}
  870. */
  871. function create(x, y) {
  872. var out = new ArrayCtor(2);
  873. if (x == null) {
  874. x = 0;
  875. }
  876. if (y == null) {
  877. y = 0;
  878. }
  879. out[0] = x;
  880. out[1] = y;
  881. return out;
  882. }
  883. /**
  884. * 复制向量数据
  885. * @param {Vector2} out
  886. * @param {Vector2} v
  887. * @return {Vector2}
  888. */
  889. function copy(out, v) {
  890. out[0] = v[0];
  891. out[1] = v[1];
  892. return out;
  893. }
  894. /**
  895. * 克隆一个向量
  896. * @param {Vector2} v
  897. * @return {Vector2}
  898. */
  899. function clone$1(v) {
  900. var out = new ArrayCtor(2);
  901. out[0] = v[0];
  902. out[1] = v[1];
  903. return out;
  904. }
  905. /**
  906. * 设置向量的两个项
  907. * @param {Vector2} out
  908. * @param {number} a
  909. * @param {number} b
  910. * @return {Vector2} 结果
  911. */
  912. function set(out, a, b) {
  913. out[0] = a;
  914. out[1] = b;
  915. return out;
  916. }
  917. /**
  918. * 向量相加
  919. * @param {Vector2} out
  920. * @param {Vector2} v1
  921. * @param {Vector2} v2
  922. */
  923. function add(out, v1, v2) {
  924. out[0] = v1[0] + v2[0];
  925. out[1] = v1[1] + v2[1];
  926. return out;
  927. }
  928. /**
  929. * 向量缩放后相加
  930. * @param {Vector2} out
  931. * @param {Vector2} v1
  932. * @param {Vector2} v2
  933. * @param {number} a
  934. */
  935. function scaleAndAdd(out, v1, v2, a) {
  936. out[0] = v1[0] + v2[0] * a;
  937. out[1] = v1[1] + v2[1] * a;
  938. return out;
  939. }
  940. /**
  941. * 向量相减
  942. * @param {Vector2} out
  943. * @param {Vector2} v1
  944. * @param {Vector2} v2
  945. */
  946. function sub(out, v1, v2) {
  947. out[0] = v1[0] - v2[0];
  948. out[1] = v1[1] - v2[1];
  949. return out;
  950. }
  951. /**
  952. * 向量长度
  953. * @param {Vector2} v
  954. * @return {number}
  955. */
  956. function len(v) {
  957. return Math.sqrt(lenSquare(v));
  958. }
  959. var length = len; // jshint ignore:line
  960. /**
  961. * 向量长度平方
  962. * @param {Vector2} v
  963. * @return {number}
  964. */
  965. function lenSquare(v) {
  966. return v[0] * v[0] + v[1] * v[1];
  967. }
  968. var lengthSquare = lenSquare;
  969. /**
  970. * 向量乘法
  971. * @param {Vector2} out
  972. * @param {Vector2} v1
  973. * @param {Vector2} v2
  974. */
  975. function mul(out, v1, v2) {
  976. out[0] = v1[0] * v2[0];
  977. out[1] = v1[1] * v2[1];
  978. return out;
  979. }
  980. /**
  981. * 向量除法
  982. * @param {Vector2} out
  983. * @param {Vector2} v1
  984. * @param {Vector2} v2
  985. */
  986. function div(out, v1, v2) {
  987. out[0] = v1[0] / v2[0];
  988. out[1] = v1[1] / v2[1];
  989. return out;
  990. }
  991. /**
  992. * 向量点乘
  993. * @param {Vector2} v1
  994. * @param {Vector2} v2
  995. * @return {number}
  996. */
  997. function dot(v1, v2) {
  998. return v1[0] * v2[0] + v1[1] * v2[1];
  999. }
  1000. /**
  1001. * 向量缩放
  1002. * @param {Vector2} out
  1003. * @param {Vector2} v
  1004. * @param {number} s
  1005. */
  1006. function scale(out, v, s) {
  1007. out[0] = v[0] * s;
  1008. out[1] = v[1] * s;
  1009. return out;
  1010. }
  1011. /**
  1012. * 向量归一化
  1013. * @param {Vector2} out
  1014. * @param {Vector2} v
  1015. */
  1016. function normalize(out, v) {
  1017. var d = len(v);
  1018. if (d === 0) {
  1019. out[0] = 0;
  1020. out[1] = 0;
  1021. }
  1022. else {
  1023. out[0] = v[0] / d;
  1024. out[1] = v[1] / d;
  1025. }
  1026. return out;
  1027. }
  1028. /**
  1029. * 计算向量间距离
  1030. * @param {Vector2} v1
  1031. * @param {Vector2} v2
  1032. * @return {number}
  1033. */
  1034. function distance(v1, v2) {
  1035. return Math.sqrt(
  1036. (v1[0] - v2[0]) * (v1[0] - v2[0])
  1037. + (v1[1] - v2[1]) * (v1[1] - v2[1])
  1038. );
  1039. }
  1040. var dist = distance;
  1041. /**
  1042. * 向量距离平方
  1043. * @param {Vector2} v1
  1044. * @param {Vector2} v2
  1045. * @return {number}
  1046. */
  1047. function distanceSquare(v1, v2) {
  1048. return (v1[0] - v2[0]) * (v1[0] - v2[0])
  1049. + (v1[1] - v2[1]) * (v1[1] - v2[1]);
  1050. }
  1051. var distSquare = distanceSquare;
  1052. /**
  1053. * 求负向量
  1054. * @param {Vector2} out
  1055. * @param {Vector2} v
  1056. */
  1057. function negate(out, v) {
  1058. out[0] = -v[0];
  1059. out[1] = -v[1];
  1060. return out;
  1061. }
  1062. /**
  1063. * 插值两个点
  1064. * @param {Vector2} out
  1065. * @param {Vector2} v1
  1066. * @param {Vector2} v2
  1067. * @param {number} t
  1068. */
  1069. function lerp(out, v1, v2, t) {
  1070. out[0] = v1[0] + t * (v2[0] - v1[0]);
  1071. out[1] = v1[1] + t * (v2[1] - v1[1]);
  1072. return out;
  1073. }
  1074. /**
  1075. * 矩阵左乘向量
  1076. * @param {Vector2} out
  1077. * @param {Vector2} v
  1078. * @param {Vector2} m
  1079. */
  1080. function applyTransform(out, v, m) {
  1081. var x = v[0];
  1082. var y = v[1];
  1083. out[0] = m[0] * x + m[2] * y + m[4];
  1084. out[1] = m[1] * x + m[3] * y + m[5];
  1085. return out;
  1086. }
  1087. /**
  1088. * 求两个向量最小值
  1089. * @param {Vector2} out
  1090. * @param {Vector2} v1
  1091. * @param {Vector2} v2
  1092. */
  1093. function min(out, v1, v2) {
  1094. out[0] = Math.min(v1[0], v2[0]);
  1095. out[1] = Math.min(v1[1], v2[1]);
  1096. return out;
  1097. }
  1098. /**
  1099. * 求两个向量最大值
  1100. * @param {Vector2} out
  1101. * @param {Vector2} v1
  1102. * @param {Vector2} v2
  1103. */
  1104. function max(out, v1, v2) {
  1105. out[0] = Math.max(v1[0], v2[0]);
  1106. out[1] = Math.max(v1[1], v2[1]);
  1107. return out;
  1108. }
  1109. var vector = (Object.freeze || Object)({
  1110. create: create,
  1111. copy: copy,
  1112. clone: clone$1,
  1113. set: set,
  1114. add: add,
  1115. scaleAndAdd: scaleAndAdd,
  1116. sub: sub,
  1117. len: len,
  1118. length: length,
  1119. lenSquare: lenSquare,
  1120. lengthSquare: lengthSquare,
  1121. mul: mul,
  1122. div: div,
  1123. dot: dot,
  1124. scale: scale,
  1125. normalize: normalize,
  1126. distance: distance,
  1127. dist: dist,
  1128. distanceSquare: distanceSquare,
  1129. distSquare: distSquare,
  1130. negate: negate,
  1131. lerp: lerp,
  1132. applyTransform: applyTransform,
  1133. min: min,
  1134. max: max
  1135. });
  1136. // TODO Draggable for group
  1137. // FIXME Draggable on element which has parent rotation or scale
  1138. function Draggable() {
  1139. this.on('mousedown', this._dragStart, this);
  1140. this.on('mousemove', this._drag, this);
  1141. this.on('mouseup', this._dragEnd, this);
  1142. this.on('globalout', this._dragEnd, this);
  1143. // this._dropTarget = null;
  1144. // this._draggingTarget = null;
  1145. // this._x = 0;
  1146. // this._y = 0;
  1147. }
  1148. Draggable.prototype = {
  1149. constructor: Draggable,
  1150. _dragStart: function (e) {
  1151. var draggingTarget = e.target;
  1152. if (draggingTarget && draggingTarget.draggable) {
  1153. this._draggingTarget = draggingTarget;
  1154. draggingTarget.dragging = true;
  1155. this._x = e.offsetX;
  1156. this._y = e.offsetY;
  1157. this.dispatchToElement(param(draggingTarget, e), 'dragstart', e.event);
  1158. }
  1159. },
  1160. _drag: function (e) {
  1161. var draggingTarget = this._draggingTarget;
  1162. if (draggingTarget) {
  1163. var x = e.offsetX;
  1164. var y = e.offsetY;
  1165. var dx = x - this._x;
  1166. var dy = y - this._y;
  1167. this._x = x;
  1168. this._y = y;
  1169. draggingTarget.drift(dx, dy, e);
  1170. this.dispatchToElement(param(draggingTarget, e), 'drag', e.event);
  1171. var dropTarget = this.findHover(x, y, draggingTarget).target;
  1172. var lastDropTarget = this._dropTarget;
  1173. this._dropTarget = dropTarget;
  1174. if (draggingTarget !== dropTarget) {
  1175. if (lastDropTarget && dropTarget !== lastDropTarget) {
  1176. this.dispatchToElement(param(lastDropTarget, e), 'dragleave', e.event);
  1177. }
  1178. if (dropTarget && dropTarget !== lastDropTarget) {
  1179. this.dispatchToElement(param(dropTarget, e), 'dragenter', e.event);
  1180. }
  1181. }
  1182. }
  1183. },
  1184. _dragEnd: function (e) {
  1185. var draggingTarget = this._draggingTarget;
  1186. if (draggingTarget) {
  1187. draggingTarget.dragging = false;
  1188. }
  1189. this.dispatchToElement(param(draggingTarget, e), 'dragend', e.event);
  1190. if (this._dropTarget) {
  1191. this.dispatchToElement(param(this._dropTarget, e), 'drop', e.event);
  1192. }
  1193. this._draggingTarget = null;
  1194. this._dropTarget = null;
  1195. }
  1196. };
  1197. function param(target, e) {
  1198. return {target: target, topTarget: e && e.topTarget};
  1199. }
  1200. /**
  1201. * 事件扩展
  1202. * @module zrender/mixin/Eventful
  1203. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  1204. * pissang (https://www.github.com/pissang)
  1205. */
  1206. var arrySlice = Array.prototype.slice;
  1207. /**
  1208. * 事件分发器
  1209. * @alias module:zrender/mixin/Eventful
  1210. * @constructor
  1211. */
  1212. var Eventful = function () {
  1213. this._$handlers = {};
  1214. };
  1215. Eventful.prototype = {
  1216. constructor: Eventful,
  1217. /**
  1218. * 单次触发绑定,trigger后销毁
  1219. *
  1220. * @param {string} event 事件名
  1221. * @param {Function} handler 响应函数
  1222. * @param {Object} context
  1223. */
  1224. one: function (event, handler, context) {
  1225. var _h = this._$handlers;
  1226. if (!handler || !event) {
  1227. return this;
  1228. }
  1229. if (!_h[event]) {
  1230. _h[event] = [];
  1231. }
  1232. for (var i = 0; i < _h[event].length; i++) {
  1233. if (_h[event][i].h === handler) {
  1234. return this;
  1235. }
  1236. }
  1237. _h[event].push({
  1238. h: handler,
  1239. one: true,
  1240. ctx: context || this
  1241. });
  1242. return this;
  1243. },
  1244. /**
  1245. * 绑定事件
  1246. * @param {string} event 事件名
  1247. * @param {Function} handler 事件处理函数
  1248. * @param {Object} [context]
  1249. */
  1250. on: function (event, handler, context) {
  1251. var _h = this._$handlers;
  1252. if (!handler || !event) {
  1253. return this;
  1254. }
  1255. if (!_h[event]) {
  1256. _h[event] = [];
  1257. }
  1258. for (var i = 0; i < _h[event].length; i++) {
  1259. if (_h[event][i].h === handler) {
  1260. return this;
  1261. }
  1262. }
  1263. _h[event].push({
  1264. h: handler,
  1265. one: false,
  1266. ctx: context || this
  1267. });
  1268. return this;
  1269. },
  1270. /**
  1271. * 是否绑定了事件
  1272. * @param {string} event
  1273. * @return {boolean}
  1274. */
  1275. isSilent: function (event) {
  1276. var _h = this._$handlers;
  1277. return _h[event] && _h[event].length;
  1278. },
  1279. /**
  1280. * 解绑事件
  1281. * @param {string} event 事件名
  1282. * @param {Function} [handler] 事件处理函数
  1283. */
  1284. off: function (event, handler) {
  1285. var _h = this._$handlers;
  1286. if (!event) {
  1287. this._$handlers = {};
  1288. return this;
  1289. }
  1290. if (handler) {
  1291. if (_h[event]) {
  1292. var newList = [];
  1293. for (var i = 0, l = _h[event].length; i < l; i++) {
  1294. if (_h[event][i]['h'] != handler) {
  1295. newList.push(_h[event][i]);
  1296. }
  1297. }
  1298. _h[event] = newList;
  1299. }
  1300. if (_h[event] && _h[event].length === 0) {
  1301. delete _h[event];
  1302. }
  1303. }
  1304. else {
  1305. delete _h[event];
  1306. }
  1307. return this;
  1308. },
  1309. /**
  1310. * 事件分发
  1311. *
  1312. * @param {string} type 事件类型
  1313. */
  1314. trigger: function (type) {
  1315. if (this._$handlers[type]) {
  1316. var args = arguments;
  1317. var argLen = args.length;
  1318. if (argLen > 3) {
  1319. args = arrySlice.call(args, 1);
  1320. }
  1321. var _h = this._$handlers[type];
  1322. var len = _h.length;
  1323. for (var i = 0; i < len;) {
  1324. // Optimize advise from backbone
  1325. switch (argLen) {
  1326. case 1:
  1327. _h[i]['h'].call(_h[i]['ctx']);
  1328. break;
  1329. case 2:
  1330. _h[i]['h'].call(_h[i]['ctx'], args[1]);
  1331. break;
  1332. case 3:
  1333. _h[i]['h'].call(_h[i]['ctx'], args[1], args[2]);
  1334. break;
  1335. default:
  1336. // have more than 2 given arguments
  1337. _h[i]['h'].apply(_h[i]['ctx'], args);
  1338. break;
  1339. }
  1340. if (_h[i]['one']) {
  1341. _h.splice(i, 1);
  1342. len--;
  1343. }
  1344. else {
  1345. i++;
  1346. }
  1347. }
  1348. }
  1349. return this;
  1350. },
  1351. /**
  1352. * 带有context的事件分发, 最后一个参数是事件回调的context
  1353. * @param {string} type 事件类型
  1354. */
  1355. triggerWithContext: function (type) {
  1356. if (this._$handlers[type]) {
  1357. var args = arguments;
  1358. var argLen = args.length;
  1359. if (argLen > 4) {
  1360. args = arrySlice.call(args, 1, args.length - 1);
  1361. }
  1362. var ctx = args[args.length - 1];
  1363. var _h = this._$handlers[type];
  1364. var len = _h.length;
  1365. for (var i = 0; i < len;) {
  1366. // Optimize advise from backbone
  1367. switch (argLen) {
  1368. case 1:
  1369. _h[i]['h'].call(ctx);
  1370. break;
  1371. case 2:
  1372. _h[i]['h'].call(ctx, args[1]);
  1373. break;
  1374. case 3:
  1375. _h[i]['h'].call(ctx, args[1], args[2]);
  1376. break;
  1377. default:
  1378. // have more than 2 given arguments
  1379. _h[i]['h'].apply(ctx, args);
  1380. break;
  1381. }
  1382. if (_h[i]['one']) {
  1383. _h.splice(i, 1);
  1384. len--;
  1385. }
  1386. else {
  1387. i++;
  1388. }
  1389. }
  1390. }
  1391. return this;
  1392. }
  1393. };
  1394. var SILENT = 'silent';
  1395. function makeEventPacket(eveType, targetInfo, event) {
  1396. return {
  1397. type: eveType,
  1398. event: event,
  1399. // target can only be an element that is not silent.
  1400. target: targetInfo.target,
  1401. // topTarget can be a silent element.
  1402. topTarget: targetInfo.topTarget,
  1403. cancelBubble: false,
  1404. offsetX: event.zrX,
  1405. offsetY: event.zrY,
  1406. gestureEvent: event.gestureEvent,
  1407. pinchX: event.pinchX,
  1408. pinchY: event.pinchY,
  1409. pinchScale: event.pinchScale,
  1410. wheelDelta: event.zrDelta,
  1411. zrByTouch: event.zrByTouch,
  1412. which: event.which
  1413. };
  1414. }
  1415. function EmptyProxy () {}
  1416. EmptyProxy.prototype.dispose = function () {};
  1417. var handlerNames = [
  1418. 'click', 'dblclick', 'mousewheel', 'mouseout',
  1419. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  1420. ];
  1421. /**
  1422. * @alias module:zrender/Handler
  1423. * @constructor
  1424. * @extends module:zrender/mixin/Eventful
  1425. * @param {module:zrender/Storage} storage Storage instance.
  1426. * @param {module:zrender/Painter} painter Painter instance.
  1427. * @param {module:zrender/dom/HandlerProxy} proxy HandlerProxy instance.
  1428. * @param {HTMLElement} painterRoot painter.root (not painter.getViewportRoot()).
  1429. */
  1430. var Handler = function(storage, painter, proxy, painterRoot) {
  1431. Eventful.call(this);
  1432. this.storage = storage;
  1433. this.painter = painter;
  1434. this.painterRoot = painterRoot;
  1435. proxy = proxy || new EmptyProxy();
  1436. /**
  1437. * Proxy of event. can be Dom, WebGLSurface, etc.
  1438. */
  1439. this.proxy = null;
  1440. /**
  1441. * {target, topTarget, x, y}
  1442. * @private
  1443. * @type {Object}
  1444. */
  1445. this._hovered = {};
  1446. /**
  1447. * @private
  1448. * @type {Date}
  1449. */
  1450. this._lastTouchMoment;
  1451. /**
  1452. * @private
  1453. * @type {number}
  1454. */
  1455. this._lastX;
  1456. /**
  1457. * @private
  1458. * @type {number}
  1459. */
  1460. this._lastY;
  1461. Draggable.call(this);
  1462. this.setHandlerProxy(proxy);
  1463. };
  1464. Handler.prototype = {
  1465. constructor: Handler,
  1466. setHandlerProxy: function (proxy) {
  1467. if (this.proxy) {
  1468. this.proxy.dispose();
  1469. }
  1470. if (proxy) {
  1471. each$1(handlerNames, function (name) {
  1472. proxy.on && proxy.on(name, this[name], this);
  1473. }, this);
  1474. // Attach handler
  1475. proxy.handler = this;
  1476. }
  1477. this.proxy = proxy;
  1478. },
  1479. mousemove: function (event) {
  1480. var x = event.zrX;
  1481. var y = event.zrY;
  1482. var lastHovered = this._hovered;
  1483. var lastHoveredTarget = lastHovered.target;
  1484. // If lastHoveredTarget is removed from zr (detected by '__zr') by some API call
  1485. // (like 'setOption' or 'dispatchAction') in event handlers, we should find
  1486. // lastHovered again here. Otherwise 'mouseout' can not be triggered normally.
  1487. // See #6198.
  1488. if (lastHoveredTarget && !lastHoveredTarget.__zr) {
  1489. lastHovered = this.findHover(lastHovered.x, lastHovered.y);
  1490. lastHoveredTarget = lastHovered.target;
  1491. }
  1492. var hovered = this._hovered = this.findHover(x, y);
  1493. var hoveredTarget = hovered.target;
  1494. var proxy = this.proxy;
  1495. proxy.setCursor && proxy.setCursor(hoveredTarget ? hoveredTarget.cursor : 'default');
  1496. // Mouse out on previous hovered element
  1497. if (lastHoveredTarget && hoveredTarget !== lastHoveredTarget) {
  1498. this.dispatchToElement(lastHovered, 'mouseout', event);
  1499. }
  1500. // Mouse moving on one element
  1501. this.dispatchToElement(hovered, 'mousemove', event);
  1502. // Mouse over on a new element
  1503. if (hoveredTarget && hoveredTarget !== lastHoveredTarget) {
  1504. this.dispatchToElement(hovered, 'mouseover', event);
  1505. }
  1506. },
  1507. mouseout: function (event) {
  1508. this.dispatchToElement(this._hovered, 'mouseout', event);
  1509. // There might be some doms created by upper layer application
  1510. // at the same level of painter.getViewportRoot() (e.g., tooltip
  1511. // dom created by echarts), where 'globalout' event should not
  1512. // be triggered when mouse enters these doms. (But 'mouseout'
  1513. // should be triggered at the original hovered element as usual).
  1514. var element = event.toElement || event.relatedTarget;
  1515. var innerDom;
  1516. do {
  1517. element = element && element.parentNode;
  1518. }
  1519. while (element && element.nodeType != 9 && !(
  1520. innerDom = element === this.painterRoot
  1521. ));
  1522. !innerDom && this.trigger('globalout', {event: event});
  1523. },
  1524. /**
  1525. * Resize
  1526. */
  1527. resize: function (event) {
  1528. this._hovered = {};
  1529. },
  1530. /**
  1531. * Dispatch event
  1532. * @param {string} eventName
  1533. * @param {event=} eventArgs
  1534. */
  1535. dispatch: function (eventName, eventArgs) {
  1536. var handler = this[eventName];
  1537. handler && handler.call(this, eventArgs);
  1538. },
  1539. /**
  1540. * Dispose
  1541. */
  1542. dispose: function () {
  1543. this.proxy.dispose();
  1544. this.storage =
  1545. this.proxy =
  1546. this.painter = null;
  1547. },
  1548. /**
  1549. * 设置默认的cursor style
  1550. * @param {string} [cursorStyle='default'] 例如 crosshair
  1551. */
  1552. setCursorStyle: function (cursorStyle) {
  1553. var proxy = this.proxy;
  1554. proxy.setCursor && proxy.setCursor(cursorStyle);
  1555. },
  1556. /**
  1557. * 事件分发代理
  1558. *
  1559. * @private
  1560. * @param {Object} targetInfo {target, topTarget} 目标图形元素
  1561. * @param {string} eventName 事件名称
  1562. * @param {Object} event 事件对象
  1563. */
  1564. dispatchToElement: function (targetInfo, eventName, event) {
  1565. targetInfo = targetInfo || {};
  1566. var el = targetInfo.target;
  1567. if (el && el.silent) {
  1568. return;
  1569. }
  1570. var eventHandler = 'on' + eventName;
  1571. var eventPacket = makeEventPacket(eventName, targetInfo, event);
  1572. while (el) {
  1573. el[eventHandler]
  1574. && (eventPacket.cancelBubble = el[eventHandler].call(el, eventPacket));
  1575. el.trigger(eventName, eventPacket);
  1576. el = el.parent;
  1577. if (eventPacket.cancelBubble) {
  1578. break;
  1579. }
  1580. }
  1581. if (!eventPacket.cancelBubble) {
  1582. // 冒泡到顶级 zrender 对象
  1583. this.trigger(eventName, eventPacket);
  1584. // 分发事件到用户自定义层
  1585. // 用户有可能在全局 click 事件中 dispose,所以需要判断下 painter 是否存在
  1586. this.painter && this.painter.eachOtherLayer(function (layer) {
  1587. if (typeof(layer[eventHandler]) == 'function') {
  1588. layer[eventHandler].call(layer, eventPacket);
  1589. }
  1590. if (layer.trigger) {
  1591. layer.trigger(eventName, eventPacket);
  1592. }
  1593. });
  1594. }
  1595. },
  1596. /**
  1597. * @private
  1598. * @param {number} x
  1599. * @param {number} y
  1600. * @param {module:zrender/graphic/Displayable} exclude
  1601. * @return {model:zrender/Element}
  1602. * @method
  1603. */
  1604. findHover: function(x, y, exclude) {
  1605. var list = this.storage.getDisplayList();
  1606. var out = {x: x, y: y};
  1607. for (var i = list.length - 1; i >= 0 ; i--) {
  1608. var hoverCheckResult;
  1609. if (list[i] !== exclude
  1610. // getDisplayList may include ignored item in VML mode
  1611. && !list[i].ignore
  1612. && (hoverCheckResult = isHover(list[i], x, y))
  1613. ) {
  1614. !out.topTarget && (out.topTarget = list[i]);
  1615. if (hoverCheckResult !== SILENT) {
  1616. out.target = list[i];
  1617. break;
  1618. }
  1619. }
  1620. }
  1621. return out;
  1622. }
  1623. };
  1624. // Common handlers
  1625. each$1(['click', 'mousedown', 'mouseup', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  1626. Handler.prototype[name] = function (event) {
  1627. // Find hover again to avoid click event is dispatched manually. Or click is triggered without mouseover
  1628. var hovered = this.findHover(event.zrX, event.zrY);
  1629. var hoveredTarget = hovered.target;
  1630. if (name === 'mousedown') {
  1631. this._downEl = hoveredTarget;
  1632. this._downPoint = [event.zrX, event.zrY];
  1633. // In case click triggered before mouseup
  1634. this._upEl = hoveredTarget;
  1635. }
  1636. else if (name === 'mouseup') {
  1637. this._upEl = hoveredTarget;
  1638. }
  1639. else if (name === 'click') {
  1640. if (this._downEl !== this._upEl
  1641. // Original click event is triggered on the whole canvas element,
  1642. // including the case that `mousedown` - `mousemove` - `mouseup`,
  1643. // which should be filtered, otherwise it will bring trouble to
  1644. // pan and zoom.
  1645. || !this._downPoint
  1646. // Arbitrary value
  1647. || dist(this._downPoint, [event.zrX, event.zrY]) > 4
  1648. ) {
  1649. return;
  1650. }
  1651. this._downPoint = null;
  1652. }
  1653. this.dispatchToElement(hovered, name, event);
  1654. };
  1655. });
  1656. function isHover(displayable, x, y) {
  1657. if (displayable[displayable.rectHover ? 'rectContain' : 'contain'](x, y)) {
  1658. var el = displayable;
  1659. var isSilent;
  1660. while (el) {
  1661. // If clipped by ancestor.
  1662. // FIXME: If clipPath has neither stroke nor fill,
  1663. // el.clipPath.contain(x, y) will always return false.
  1664. if (el.clipPath && !el.clipPath.contain(x, y)) {
  1665. return false;
  1666. }
  1667. if (el.silent) {
  1668. isSilent = true;
  1669. }
  1670. el = el.parent;
  1671. }
  1672. return isSilent ? SILENT : true;
  1673. }
  1674. return false;
  1675. }
  1676. mixin(Handler, Eventful);
  1677. mixin(Handler, Draggable);
  1678. /**
  1679. * 3x2矩阵操作类
  1680. * @exports zrender/tool/matrix
  1681. */
  1682. var ArrayCtor$1 = typeof Float32Array === 'undefined'
  1683. ? Array
  1684. : Float32Array;
  1685. /**
  1686. * Create a identity matrix.
  1687. * @return {Float32Array|Array.<number>}
  1688. */
  1689. function create$1() {
  1690. var out = new ArrayCtor$1(6);
  1691. identity(out);
  1692. return out;
  1693. }
  1694. /**
  1695. * 设置矩阵为单位矩阵
  1696. * @param {Float32Array|Array.<number>} out
  1697. */
  1698. function identity(out) {
  1699. out[0] = 1;
  1700. out[1] = 0;
  1701. out[2] = 0;
  1702. out[3] = 1;
  1703. out[4] = 0;
  1704. out[5] = 0;
  1705. return out;
  1706. }
  1707. /**
  1708. * 复制矩阵
  1709. * @param {Float32Array|Array.<number>} out
  1710. * @param {Float32Array|Array.<number>} m
  1711. */
  1712. function copy$1(out, m) {
  1713. out[0] = m[0];
  1714. out[1] = m[1];
  1715. out[2] = m[2];
  1716. out[3] = m[3];
  1717. out[4] = m[4];
  1718. out[5] = m[5];
  1719. return out;
  1720. }
  1721. /**
  1722. * 矩阵相乘
  1723. * @param {Float32Array|Array.<number>} out
  1724. * @param {Float32Array|Array.<number>} m1
  1725. * @param {Float32Array|Array.<number>} m2
  1726. */
  1727. function mul$1(out, m1, m2) {
  1728. // Consider matrix.mul(m, m2, m);
  1729. // where out is the same as m2.
  1730. // So use temp variable to escape error.
  1731. var out0 = m1[0] * m2[0] + m1[2] * m2[1];
  1732. var out1 = m1[1] * m2[0] + m1[3] * m2[1];
  1733. var out2 = m1[0] * m2[2] + m1[2] * m2[3];
  1734. var out3 = m1[1] * m2[2] + m1[3] * m2[3];
  1735. var out4 = m1[0] * m2[4] + m1[2] * m2[5] + m1[4];
  1736. var out5 = m1[1] * m2[4] + m1[3] * m2[5] + m1[5];
  1737. out[0] = out0;
  1738. out[1] = out1;
  1739. out[2] = out2;
  1740. out[3] = out3;
  1741. out[4] = out4;
  1742. out[5] = out5;
  1743. return out;
  1744. }
  1745. /**
  1746. * 平移变换
  1747. * @param {Float32Array|Array.<number>} out
  1748. * @param {Float32Array|Array.<number>} a
  1749. * @param {Float32Array|Array.<number>} v
  1750. */
  1751. function translate(out, a, v) {
  1752. out[0] = a[0];
  1753. out[1] = a[1];
  1754. out[2] = a[2];
  1755. out[3] = a[3];
  1756. out[4] = a[4] + v[0];
  1757. out[5] = a[5] + v[1];
  1758. return out;
  1759. }
  1760. /**
  1761. * 旋转变换
  1762. * @param {Float32Array|Array.<number>} out
  1763. * @param {Float32Array|Array.<number>} a
  1764. * @param {number} rad
  1765. */
  1766. function rotate(out, a, rad) {
  1767. var aa = a[0];
  1768. var ac = a[2];
  1769. var atx = a[4];
  1770. var ab = a[1];
  1771. var ad = a[3];
  1772. var aty = a[5];
  1773. var st = Math.sin(rad);
  1774. var ct = Math.cos(rad);
  1775. out[0] = aa * ct + ab * st;
  1776. out[1] = -aa * st + ab * ct;
  1777. out[2] = ac * ct + ad * st;
  1778. out[3] = -ac * st + ct * ad;
  1779. out[4] = ct * atx + st * aty;
  1780. out[5] = ct * aty - st * atx;
  1781. return out;
  1782. }
  1783. /**
  1784. * 缩放变换
  1785. * @param {Float32Array|Array.<number>} out
  1786. * @param {Float32Array|Array.<number>} a
  1787. * @param {Float32Array|Array.<number>} v
  1788. */
  1789. function scale$1(out, a, v) {
  1790. var vx = v[0];
  1791. var vy = v[1];
  1792. out[0] = a[0] * vx;
  1793. out[1] = a[1] * vy;
  1794. out[2] = a[2] * vx;
  1795. out[3] = a[3] * vy;
  1796. out[4] = a[4] * vx;
  1797. out[5] = a[5] * vy;
  1798. return out;
  1799. }
  1800. /**
  1801. * 求逆矩阵
  1802. * @param {Float32Array|Array.<number>} out
  1803. * @param {Float32Array|Array.<number>} a
  1804. */
  1805. function invert(out, a) {
  1806. var aa = a[0];
  1807. var ac = a[2];
  1808. var atx = a[4];
  1809. var ab = a[1];
  1810. var ad = a[3];
  1811. var aty = a[5];
  1812. var det = aa * ad - ab * ac;
  1813. if (!det) {
  1814. return null;
  1815. }
  1816. det = 1.0 / det;
  1817. out[0] = ad * det;
  1818. out[1] = -ab * det;
  1819. out[2] = -ac * det;
  1820. out[3] = aa * det;
  1821. out[4] = (ac * aty - ad * atx) * det;
  1822. out[5] = (ab * atx - aa * aty) * det;
  1823. return out;
  1824. }
  1825. /**
  1826. * Clone a new matrix.
  1827. * @param {Float32Array|Array.<number>} a
  1828. */
  1829. function clone$2(a) {
  1830. var b = create$1();
  1831. copy$1(b, a);
  1832. return b;
  1833. }
  1834. var matrix = (Object.freeze || Object)({
  1835. create: create$1,
  1836. identity: identity,
  1837. copy: copy$1,
  1838. mul: mul$1,
  1839. translate: translate,
  1840. rotate: rotate,
  1841. scale: scale$1,
  1842. invert: invert,
  1843. clone: clone$2
  1844. });
  1845. /**
  1846. * 提供变换扩展
  1847. * @module zrender/mixin/Transformable
  1848. * @author pissang (https://www.github.com/pissang)
  1849. */
  1850. var mIdentity = identity;
  1851. var EPSILON = 5e-5;
  1852. function isNotAroundZero(val) {
  1853. return val > EPSILON || val < -EPSILON;
  1854. }
  1855. /**
  1856. * @alias module:zrender/mixin/Transformable
  1857. * @constructor
  1858. */
  1859. var Transformable = function (opts) {
  1860. opts = opts || {};
  1861. // If there are no given position, rotation, scale
  1862. if (!opts.position) {
  1863. /**
  1864. * 平移
  1865. * @type {Array.<number>}
  1866. * @default [0, 0]
  1867. */
  1868. this.position = [0, 0];
  1869. }
  1870. if (opts.rotation == null) {
  1871. /**
  1872. * 旋转
  1873. * @type {Array.<number>}
  1874. * @default 0
  1875. */
  1876. this.rotation = 0;
  1877. }
  1878. if (!opts.scale) {
  1879. /**
  1880. * 缩放
  1881. * @type {Array.<number>}
  1882. * @default [1, 1]
  1883. */
  1884. this.scale = [1, 1];
  1885. }
  1886. /**
  1887. * 旋转和缩放的原点
  1888. * @type {Array.<number>}
  1889. * @default null
  1890. */
  1891. this.origin = this.origin || null;
  1892. };
  1893. var transformableProto = Transformable.prototype;
  1894. transformableProto.transform = null;
  1895. /**
  1896. * 判断是否需要有坐标变换
  1897. * 如果有坐标变换, 则从position, rotation, scale以及父节点的transform计算出自身的transform矩阵
  1898. */
  1899. transformableProto.needLocalTransform = function () {
  1900. return isNotAroundZero(this.rotation)
  1901. || isNotAroundZero(this.position[0])
  1902. || isNotAroundZero(this.position[1])
  1903. || isNotAroundZero(this.scale[0] - 1)
  1904. || isNotAroundZero(this.scale[1] - 1);
  1905. };
  1906. transformableProto.updateTransform = function () {
  1907. var parent = this.parent;
  1908. var parentHasTransform = parent && parent.transform;
  1909. var needLocalTransform = this.needLocalTransform();
  1910. var m = this.transform;
  1911. if (!(needLocalTransform || parentHasTransform)) {
  1912. m && mIdentity(m);
  1913. return;
  1914. }
  1915. m = m || create$1();
  1916. if (needLocalTransform) {
  1917. this.getLocalTransform(m);
  1918. }
  1919. else {
  1920. mIdentity(m);
  1921. }
  1922. // 应用父节点变换
  1923. if (parentHasTransform) {
  1924. if (needLocalTransform) {
  1925. mul$1(m, parent.transform, m);
  1926. }
  1927. else {
  1928. copy$1(m, parent.transform);
  1929. }
  1930. }
  1931. // 保存这个变换矩阵
  1932. this.transform = m;
  1933. this.invTransform = this.invTransform || create$1();
  1934. invert(this.invTransform, m);
  1935. };
  1936. transformableProto.getLocalTransform = function (m) {
  1937. return Transformable.getLocalTransform(this, m);
  1938. };
  1939. /**
  1940. * 将自己的transform应用到context上
  1941. * @param {CanvasRenderingContext2D} ctx
  1942. */
  1943. transformableProto.setTransform = function (ctx) {
  1944. var m = this.transform;
  1945. var dpr = ctx.dpr || 1;
  1946. if (m) {
  1947. ctx.setTransform(dpr * m[0], dpr * m[1], dpr * m[2], dpr * m[3], dpr * m[4], dpr * m[5]);
  1948. }
  1949. else {
  1950. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  1951. }
  1952. };
  1953. transformableProto.restoreTransform = function (ctx) {
  1954. var dpr = ctx.dpr || 1;
  1955. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  1956. };
  1957. var tmpTransform = [];
  1958. /**
  1959. * 分解`transform`矩阵到`position`, `rotation`, `scale`
  1960. */
  1961. transformableProto.decomposeTransform = function () {
  1962. if (!this.transform) {
  1963. return;
  1964. }
  1965. var parent = this.parent;
  1966. var m = this.transform;
  1967. if (parent && parent.transform) {
  1968. // Get local transform and decompose them to position, scale, rotation
  1969. mul$1(tmpTransform, parent.invTransform, m);
  1970. m = tmpTransform;
  1971. }
  1972. var sx = m[0] * m[0] + m[1] * m[1];
  1973. var sy = m[2] * m[2] + m[3] * m[3];
  1974. var position = this.position;
  1975. var scale$$1 = this.scale;
  1976. if (isNotAroundZero(sx - 1)) {
  1977. sx = Math.sqrt(sx);
  1978. }
  1979. if (isNotAroundZero(sy - 1)) {
  1980. sy = Math.sqrt(sy);
  1981. }
  1982. if (m[0] < 0) {
  1983. sx = -sx;
  1984. }
  1985. if (m[3] < 0) {
  1986. sy = -sy;
  1987. }
  1988. position[0] = m[4];
  1989. position[1] = m[5];
  1990. scale$$1[0] = sx;
  1991. scale$$1[1] = sy;
  1992. this.rotation = Math.atan2(-m[1] / sy, m[0] / sx);
  1993. };
  1994. /**
  1995. * Get global scale
  1996. * @return {Array.<number>}
  1997. */
  1998. transformableProto.getGlobalScale = function () {
  1999. var m = this.transform;
  2000. if (!m) {
  2001. return [1, 1];
  2002. }
  2003. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1]);
  2004. var sy = Math.sqrt(m[2] * m[2] + m[3] * m[3]);
  2005. if (m[0] < 0) {
  2006. sx = -sx;
  2007. }
  2008. if (m[3] < 0) {
  2009. sy = -sy;
  2010. }
  2011. return [sx, sy];
  2012. };
  2013. /**
  2014. * 变换坐标位置到 shape 的局部坐标空间
  2015. * @method
  2016. * @param {number} x
  2017. * @param {number} y
  2018. * @return {Array.<number>}
  2019. */
  2020. transformableProto.transformCoordToLocal = function (x, y) {
  2021. var v2 = [x, y];
  2022. var invTransform = this.invTransform;
  2023. if (invTransform) {
  2024. applyTransform(v2, v2, invTransform);
  2025. }
  2026. return v2;
  2027. };
  2028. /**
  2029. * 变换局部坐标位置到全局坐标空间
  2030. * @method
  2031. * @param {number} x
  2032. * @param {number} y
  2033. * @return {Array.<number>}
  2034. */
  2035. transformableProto.transformCoordToGlobal = function (x, y) {
  2036. var v2 = [x, y];
  2037. var transform = this.transform;
  2038. if (transform) {
  2039. applyTransform(v2, v2, transform);
  2040. }
  2041. return v2;
  2042. };
  2043. /**
  2044. * @static
  2045. * @param {Object} target
  2046. * @param {Array.<number>} target.origin
  2047. * @param {number} target.rotation
  2048. * @param {Array.<number>} target.position
  2049. * @param {Array.<number>} [m]
  2050. */
  2051. Transformable.getLocalTransform = function (target, m) {
  2052. m = m || [];
  2053. mIdentity(m);
  2054. var origin = target.origin;
  2055. var scale$$1 = target.scale || [1, 1];
  2056. var rotation = target.rotation || 0;
  2057. var position = target.position || [0, 0];
  2058. if (origin) {
  2059. // Translate to origin
  2060. m[4] -= origin[0];
  2061. m[5] -= origin[1];
  2062. }
  2063. scale$1(m, m, scale$$1);
  2064. if (rotation) {
  2065. rotate(m, m, rotation);
  2066. }
  2067. if (origin) {
  2068. // Translate back from origin
  2069. m[4] += origin[0];
  2070. m[5] += origin[1];
  2071. }
  2072. m[4] += position[0];
  2073. m[5] += position[1];
  2074. return m;
  2075. };
  2076. /**
  2077. * 缓动代码来自 https://github.com/sole/tween.js/blob/master/src/Tween.js
  2078. * @see http://sole.github.io/tween.js/examples/03_graphs.html
  2079. * @exports zrender/animation/easing
  2080. */
  2081. var easing = {
  2082. /**
  2083. * @param {number} k
  2084. * @return {number}
  2085. */
  2086. linear: function (k) {
  2087. return k;
  2088. },
  2089. /**
  2090. * @param {number} k
  2091. * @return {number}
  2092. */
  2093. quadraticIn: function (k) {
  2094. return k * k;
  2095. },
  2096. /**
  2097. * @param {number} k
  2098. * @return {number}
  2099. */
  2100. quadraticOut: function (k) {
  2101. return k * (2 - k);
  2102. },
  2103. /**
  2104. * @param {number} k
  2105. * @return {number}
  2106. */
  2107. quadraticInOut: function (k) {
  2108. if ((k *= 2) < 1) {
  2109. return 0.5 * k * k;
  2110. }
  2111. return -0.5 * (--k * (k - 2) - 1);
  2112. },
  2113. // 三次方的缓动(t^3)
  2114. /**
  2115. * @param {number} k
  2116. * @return {number}
  2117. */
  2118. cubicIn: function (k) {
  2119. return k * k * k;
  2120. },
  2121. /**
  2122. * @param {number} k
  2123. * @return {number}
  2124. */
  2125. cubicOut: function (k) {
  2126. return --k * k * k + 1;
  2127. },
  2128. /**
  2129. * @param {number} k
  2130. * @return {number}
  2131. */
  2132. cubicInOut: function (k) {
  2133. if ((k *= 2) < 1) {
  2134. return 0.5 * k * k * k;
  2135. }
  2136. return 0.5 * ((k -= 2) * k * k + 2);
  2137. },
  2138. // 四次方的缓动(t^4)
  2139. /**
  2140. * @param {number} k
  2141. * @return {number}
  2142. */
  2143. quarticIn: function (k) {
  2144. return k * k * k * k;
  2145. },
  2146. /**
  2147. * @param {number} k
  2148. * @return {number}
  2149. */
  2150. quarticOut: function (k) {
  2151. return 1 - (--k * k * k * k);
  2152. },
  2153. /**
  2154. * @param {number} k
  2155. * @return {number}
  2156. */
  2157. quarticInOut: function (k) {
  2158. if ((k *= 2) < 1) {
  2159. return 0.5 * k * k * k * k;
  2160. }
  2161. return -0.5 * ((k -= 2) * k * k * k - 2);
  2162. },
  2163. // 五次方的缓动(t^5)
  2164. /**
  2165. * @param {number} k
  2166. * @return {number}
  2167. */
  2168. quinticIn: function (k) {
  2169. return k * k * k * k * k;
  2170. },
  2171. /**
  2172. * @param {number} k
  2173. * @return {number}
  2174. */
  2175. quinticOut: function (k) {
  2176. return --k * k * k * k * k + 1;
  2177. },
  2178. /**
  2179. * @param {number} k
  2180. * @return {number}
  2181. */
  2182. quinticInOut: function (k) {
  2183. if ((k *= 2) < 1) {
  2184. return 0.5 * k * k * k * k * k;
  2185. }
  2186. return 0.5 * ((k -= 2) * k * k * k * k + 2);
  2187. },
  2188. // 正弦曲线的缓动(sin(t))
  2189. /**
  2190. * @param {number} k
  2191. * @return {number}
  2192. */
  2193. sinusoidalIn: function (k) {
  2194. return 1 - Math.cos(k * Math.PI / 2);
  2195. },
  2196. /**
  2197. * @param {number} k
  2198. * @return {number}
  2199. */
  2200. sinusoidalOut: function (k) {
  2201. return Math.sin(k * Math.PI / 2);
  2202. },
  2203. /**
  2204. * @param {number} k
  2205. * @return {number}
  2206. */
  2207. sinusoidalInOut: function (k) {
  2208. return 0.5 * (1 - Math.cos(Math.PI * k));
  2209. },
  2210. // 指数曲线的缓动(2^t)
  2211. /**
  2212. * @param {number} k
  2213. * @return {number}
  2214. */
  2215. exponentialIn: function (k) {
  2216. return k === 0 ? 0 : Math.pow(1024, k - 1);
  2217. },
  2218. /**
  2219. * @param {number} k
  2220. * @return {number}
  2221. */
  2222. exponentialOut: function (k) {
  2223. return k === 1 ? 1 : 1 - Math.pow(2, -10 * k);
  2224. },
  2225. /**
  2226. * @param {number} k
  2227. * @return {number}
  2228. */
  2229. exponentialInOut: function (k) {
  2230. if (k === 0) {
  2231. return 0;
  2232. }
  2233. if (k === 1) {
  2234. return 1;
  2235. }
  2236. if ((k *= 2) < 1) {
  2237. return 0.5 * Math.pow(1024, k - 1);
  2238. }
  2239. return 0.5 * (-Math.pow(2, -10 * (k - 1)) + 2);
  2240. },
  2241. // 圆形曲线的缓动(sqrt(1-t^2))
  2242. /**
  2243. * @param {number} k
  2244. * @return {number}
  2245. */
  2246. circularIn: function (k) {
  2247. return 1 - Math.sqrt(1 - k * k);
  2248. },
  2249. /**
  2250. * @param {number} k
  2251. * @return {number}
  2252. */
  2253. circularOut: function (k) {
  2254. return Math.sqrt(1 - (--k * k));
  2255. },
  2256. /**
  2257. * @param {number} k
  2258. * @return {number}
  2259. */
  2260. circularInOut: function (k) {
  2261. if ((k *= 2) < 1) {
  2262. return -0.5 * (Math.sqrt(1 - k * k) - 1);
  2263. }
  2264. return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1);
  2265. },
  2266. // 创建类似于弹簧在停止前来回振荡的动画
  2267. /**
  2268. * @param {number} k
  2269. * @return {number}
  2270. */
  2271. elasticIn: function (k) {
  2272. var s;
  2273. var a = 0.1;
  2274. var p = 0.4;
  2275. if (k === 0) {
  2276. return 0;
  2277. }
  2278. if (k === 1) {
  2279. return 1;
  2280. }
  2281. if (!a || a < 1) {
  2282. a = 1; s = p / 4;
  2283. }
  2284. else {
  2285. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2286. }
  2287. return -(a * Math.pow(2, 10 * (k -= 1)) *
  2288. Math.sin((k - s) * (2 * Math.PI) / p));
  2289. },
  2290. /**
  2291. * @param {number} k
  2292. * @return {number}
  2293. */
  2294. elasticOut: function (k) {
  2295. var s;
  2296. var a = 0.1;
  2297. var p = 0.4;
  2298. if (k === 0) {
  2299. return 0;
  2300. }
  2301. if (k === 1) {
  2302. return 1;
  2303. }
  2304. if (!a || a < 1) {
  2305. a = 1; s = p / 4;
  2306. }
  2307. else {
  2308. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2309. }
  2310. return (a * Math.pow(2, -10 * k) *
  2311. Math.sin((k - s) * (2 * Math.PI) / p) + 1);
  2312. },
  2313. /**
  2314. * @param {number} k
  2315. * @return {number}
  2316. */
  2317. elasticInOut: function (k) {
  2318. var s;
  2319. var a = 0.1;
  2320. var p = 0.4;
  2321. if (k === 0) {
  2322. return 0;
  2323. }
  2324. if (k === 1) {
  2325. return 1;
  2326. }
  2327. if (!a || a < 1) {
  2328. a = 1; s = p / 4;
  2329. }
  2330. else {
  2331. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2332. }
  2333. if ((k *= 2) < 1) {
  2334. return -0.5 * (a * Math.pow(2, 10 * (k -= 1))
  2335. * Math.sin((k - s) * (2 * Math.PI) / p));
  2336. }
  2337. return a * Math.pow(2, -10 * (k -= 1))
  2338. * Math.sin((k - s) * (2 * Math.PI) / p) * 0.5 + 1;
  2339. },
  2340. // 在某一动画开始沿指示的路径进行动画处理前稍稍收回该动画的移动
  2341. /**
  2342. * @param {number} k
  2343. * @return {number}
  2344. */
  2345. backIn: function (k) {
  2346. var s = 1.70158;
  2347. return k * k * ((s + 1) * k - s);
  2348. },
  2349. /**
  2350. * @param {number} k
  2351. * @return {number}
  2352. */
  2353. backOut: function (k) {
  2354. var s = 1.70158;
  2355. return --k * k * ((s + 1) * k + s) + 1;
  2356. },
  2357. /**
  2358. * @param {number} k
  2359. * @return {number}
  2360. */
  2361. backInOut: function (k) {
  2362. var s = 1.70158 * 1.525;
  2363. if ((k *= 2) < 1) {
  2364. return 0.5 * (k * k * ((s + 1) * k - s));
  2365. }
  2366. return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2);
  2367. },
  2368. // 创建弹跳效果
  2369. /**
  2370. * @param {number} k
  2371. * @return {number}
  2372. */
  2373. bounceIn: function (k) {
  2374. return 1 - easing.bounceOut(1 - k);
  2375. },
  2376. /**
  2377. * @param {number} k
  2378. * @return {number}
  2379. */
  2380. bounceOut: function (k) {
  2381. if (k < (1 / 2.75)) {
  2382. return 7.5625 * k * k;
  2383. }
  2384. else if (k < (2 / 2.75)) {
  2385. return 7.5625 * (k -= (1.5 / 2.75)) * k + 0.75;
  2386. }
  2387. else if (k < (2.5 / 2.75)) {
  2388. return 7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375;
  2389. }
  2390. else {
  2391. return 7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375;
  2392. }
  2393. },
  2394. /**
  2395. * @param {number} k
  2396. * @return {number}
  2397. */
  2398. bounceInOut: function (k) {
  2399. if (k < 0.5) {
  2400. return easing.bounceIn(k * 2) * 0.5;
  2401. }
  2402. return easing.bounceOut(k * 2 - 1) * 0.5 + 0.5;
  2403. }
  2404. };
  2405. /**
  2406. * 动画主控制器
  2407. * @config target 动画对象,可以是数组,如果是数组的话会批量分发onframe等事件
  2408. * @config life(1000) 动画时长
  2409. * @config delay(0) 动画延迟时间
  2410. * @config loop(true)
  2411. * @config gap(0) 循环的间隔时间
  2412. * @config onframe
  2413. * @config easing(optional)
  2414. * @config ondestroy(optional)
  2415. * @config onrestart(optional)
  2416. *
  2417. * TODO pause
  2418. */
  2419. function Clip(options) {
  2420. this._target = options.target;
  2421. // 生命周期
  2422. this._life = options.life || 1000;
  2423. // 延时
  2424. this._delay = options.delay || 0;
  2425. // 开始时间
  2426. // this._startTime = new Date().getTime() + this._delay;// 单位毫秒
  2427. this._initialized = false;
  2428. // 是否循环
  2429. this.loop = options.loop == null ? false : options.loop;
  2430. this.gap = options.gap || 0;
  2431. this.easing = options.easing || 'Linear';
  2432. this.onframe = options.onframe;
  2433. this.ondestroy = options.ondestroy;
  2434. this.onrestart = options.onrestart;
  2435. this._pausedTime = 0;
  2436. this._paused = false;
  2437. }
  2438. Clip.prototype = {
  2439. constructor: Clip,
  2440. step: function (globalTime, deltaTime) {
  2441. // Set startTime on first step, or _startTime may has milleseconds different between clips
  2442. // PENDING
  2443. if (!this._initialized) {
  2444. this._startTime = globalTime + this._delay;
  2445. this._initialized = true;
  2446. }
  2447. if (this._paused) {
  2448. this._pausedTime += deltaTime;
  2449. return;
  2450. }
  2451. var percent = (globalTime - this._startTime - this._pausedTime) / this._life;
  2452. // 还没开始
  2453. if (percent < 0) {
  2454. return;
  2455. }
  2456. percent = Math.min(percent, 1);
  2457. var easing$$1 = this.easing;
  2458. var easingFunc = typeof easing$$1 == 'string' ? easing[easing$$1] : easing$$1;
  2459. var schedule = typeof easingFunc === 'function'
  2460. ? easingFunc(percent)
  2461. : percent;
  2462. this.fire('frame', schedule);
  2463. // 结束
  2464. if (percent == 1) {
  2465. if (this.loop) {
  2466. this.restart (globalTime);
  2467. // 重新开始周期
  2468. // 抛出而不是直接调用事件直到 stage.update 后再统一调用这些事件
  2469. return 'restart';
  2470. }
  2471. // 动画完成将这个控制器标识为待删除
  2472. // 在Animation.update中进行批量删除
  2473. this._needsRemove = true;
  2474. return 'destroy';
  2475. }
  2476. return null;
  2477. },
  2478. restart: function (globalTime) {
  2479. var remainder = (globalTime - this._startTime - this._pausedTime) % this._life;
  2480. this._startTime = globalTime - remainder + this.gap;
  2481. this._pausedTime = 0;
  2482. this._needsRemove = false;
  2483. },
  2484. fire: function (eventType, arg) {
  2485. eventType = 'on' + eventType;
  2486. if (this[eventType]) {
  2487. this[eventType](this._target, arg);
  2488. }
  2489. },
  2490. pause: function () {
  2491. this._paused = true;
  2492. },
  2493. resume: function () {
  2494. this._paused = false;
  2495. }
  2496. };
  2497. // Simple LRU cache use doubly linked list
  2498. // @module zrender/core/LRU
  2499. /**
  2500. * Simple double linked list. Compared with array, it has O(1) remove operation.
  2501. * @constructor
  2502. */
  2503. var LinkedList = function () {
  2504. /**
  2505. * @type {module:zrender/core/LRU~Entry}
  2506. */
  2507. this.head = null;
  2508. /**
  2509. * @type {module:zrender/core/LRU~Entry}
  2510. */
  2511. this.tail = null;
  2512. this._len = 0;
  2513. };
  2514. var linkedListProto = LinkedList.prototype;
  2515. /**
  2516. * Insert a new value at the tail
  2517. * @param {} val
  2518. * @return {module:zrender/core/LRU~Entry}
  2519. */
  2520. linkedListProto.insert = function (val) {
  2521. var entry = new Entry(val);
  2522. this.insertEntry(entry);
  2523. return entry;
  2524. };
  2525. /**
  2526. * Insert an entry at the tail
  2527. * @param {module:zrender/core/LRU~Entry} entry
  2528. */
  2529. linkedListProto.insertEntry = function (entry) {
  2530. if (!this.head) {
  2531. this.head = this.tail = entry;
  2532. }
  2533. else {
  2534. this.tail.next = entry;
  2535. entry.prev = this.tail;
  2536. entry.next = null;
  2537. this.tail = entry;
  2538. }
  2539. this._len++;
  2540. };
  2541. /**
  2542. * Remove entry.
  2543. * @param {module:zrender/core/LRU~Entry} entry
  2544. */
  2545. linkedListProto.remove = function (entry) {
  2546. var prev = entry.prev;
  2547. var next = entry.next;
  2548. if (prev) {
  2549. prev.next = next;
  2550. }
  2551. else {
  2552. // Is head
  2553. this.head = next;
  2554. }
  2555. if (next) {
  2556. next.prev = prev;
  2557. }
  2558. else {
  2559. // Is tail
  2560. this.tail = prev;
  2561. }
  2562. entry.next = entry.prev = null;
  2563. this._len--;
  2564. };
  2565. /**
  2566. * @return {number}
  2567. */
  2568. linkedListProto.len = function () {
  2569. return this._len;
  2570. };
  2571. /**
  2572. * Clear list
  2573. */
  2574. linkedListProto.clear = function () {
  2575. this.head = this.tail = null;
  2576. this._len = 0;
  2577. };
  2578. /**
  2579. * @constructor
  2580. * @param {} val
  2581. */
  2582. var Entry = function (val) {
  2583. /**
  2584. * @type {}
  2585. */
  2586. this.value = val;
  2587. /**
  2588. * @type {module:zrender/core/LRU~Entry}
  2589. */
  2590. this.next;
  2591. /**
  2592. * @type {module:zrender/core/LRU~Entry}
  2593. */
  2594. this.prev;
  2595. };
  2596. /**
  2597. * LRU Cache
  2598. * @constructor
  2599. * @alias module:zrender/core/LRU
  2600. */
  2601. var LRU = function (maxSize) {
  2602. this._list = new LinkedList();
  2603. this._map = {};
  2604. this._maxSize = maxSize || 10;
  2605. this._lastRemovedEntry = null;
  2606. };
  2607. var LRUProto = LRU.prototype;
  2608. /**
  2609. * @param {string} key
  2610. * @param {} value
  2611. * @return {} Removed value
  2612. */
  2613. LRUProto.put = function (key, value) {
  2614. var list = this._list;
  2615. var map = this._map;
  2616. var removed = null;
  2617. if (map[key] == null) {
  2618. var len = list.len();
  2619. // Reuse last removed entry
  2620. var entry = this._lastRemovedEntry;
  2621. if (len >= this._maxSize && len > 0) {
  2622. // Remove the least recently used
  2623. var leastUsedEntry = list.head;
  2624. list.remove(leastUsedEntry);
  2625. delete map[leastUsedEntry.key];
  2626. removed = leastUsedEntry.value;
  2627. this._lastRemovedEntry = leastUsedEntry;
  2628. }
  2629. if (entry) {
  2630. entry.value = value;
  2631. }
  2632. else {
  2633. entry = new Entry(value);
  2634. }
  2635. entry.key = key;
  2636. list.insertEntry(entry);
  2637. map[key] = entry;
  2638. }
  2639. return removed;
  2640. };
  2641. /**
  2642. * @param {string} key
  2643. * @return {}
  2644. */
  2645. LRUProto.get = function (key) {
  2646. var entry = this._map[key];
  2647. var list = this._list;
  2648. if (entry != null) {
  2649. // Put the latest used entry in the tail
  2650. if (entry !== list.tail) {
  2651. list.remove(entry);
  2652. list.insertEntry(entry);
  2653. }
  2654. return entry.value;
  2655. }
  2656. };
  2657. /**
  2658. * Clear the cache
  2659. */
  2660. LRUProto.clear = function () {
  2661. this._list.clear();
  2662. this._map = {};
  2663. };
  2664. var kCSSColorTable = {
  2665. 'transparent': [0,0,0,0], 'aliceblue': [240,248,255,1],
  2666. 'antiquewhite': [250,235,215,1], 'aqua': [0,255,255,1],
  2667. 'aquamarine': [127,255,212,1], 'azure': [240,255,255,1],
  2668. 'beige': [245,245,220,1], 'bisque': [255,228,196,1],
  2669. 'black': [0,0,0,1], 'blanchedalmond': [255,235,205,1],
  2670. 'blue': [0,0,255,1], 'blueviolet': [138,43,226,1],
  2671. 'brown': [165,42,42,1], 'burlywood': [222,184,135,1],
  2672. 'cadetblue': [95,158,160,1], 'chartreuse': [127,255,0,1],
  2673. 'chocolate': [210,105,30,1], 'coral': [255,127,80,1],
  2674. 'cornflowerblue': [100,149,237,1], 'cornsilk': [255,248,220,1],
  2675. 'crimson': [220,20,60,1], 'cyan': [0,255,255,1],
  2676. 'darkblue': [0,0,139,1], 'darkcyan': [0,139,139,1],
  2677. 'darkgoldenrod': [184,134,11,1], 'darkgray': [169,169,169,1],
  2678. 'darkgreen': [0,100,0,1], 'darkgrey': [169,169,169,1],
  2679. 'darkkhaki': [189,183,107,1], 'darkmagenta': [139,0,139,1],
  2680. 'darkolivegreen': [85,107,47,1], 'darkorange': [255,140,0,1],
  2681. 'darkorchid': [153,50,204,1], 'darkred': [139,0,0,1],
  2682. 'darksalmon': [233,150,122,1], 'darkseagreen': [143,188,143,1],
  2683. 'darkslateblue': [72,61,139,1], 'darkslategray': [47,79,79,1],
  2684. 'darkslategrey': [47,79,79,1], 'darkturquoise': [0,206,209,1],
  2685. 'darkviolet': [148,0,211,1], 'deeppink': [255,20,147,1],
  2686. 'deepskyblue': [0,191,255,1], 'dimgray': [105,105,105,1],
  2687. 'dimgrey': [105,105,105,1], 'dodgerblue': [30,144,255,1],
  2688. 'firebrick': [178,34,34,1], 'floralwhite': [255,250,240,1],
  2689. 'forestgreen': [34,139,34,1], 'fuchsia': [255,0,255,1],
  2690. 'gainsboro': [220,220,220,1], 'ghostwhite': [248,248,255,1],
  2691. 'gold': [255,215,0,1], 'goldenrod': [218,165,32,1],
  2692. 'gray': [128,128,128,1], 'green': [0,128,0,1],
  2693. 'greenyellow': [173,255,47,1], 'grey': [128,128,128,1],
  2694. 'honeydew': [240,255,240,1], 'hotpink': [255,105,180,1],
  2695. 'indianred': [205,92,92,1], 'indigo': [75,0,130,1],
  2696. 'ivory': [255,255,240,1], 'khaki': [240,230,140,1],
  2697. 'lavender': [230,230,250,1], 'lavenderblush': [255,240,245,1],
  2698. 'lawngreen': [124,252,0,1], 'lemonchiffon': [255,250,205,1],
  2699. 'lightblue': [173,216,230,1], 'lightcoral': [240,128,128,1],
  2700. 'lightcyan': [224,255,255,1], 'lightgoldenrodyellow': [250,250,210,1],
  2701. 'lightgray': [211,211,211,1], 'lightgreen': [144,238,144,1],
  2702. 'lightgrey': [211,211,211,1], 'lightpink': [255,182,193,1],
  2703. 'lightsalmon': [255,160,122,1], 'lightseagreen': [32,178,170,1],
  2704. 'lightskyblue': [135,206,250,1], 'lightslategray': [119,136,153,1],
  2705. 'lightslategrey': [119,136,153,1], 'lightsteelblue': [176,196,222,1],
  2706. 'lightyellow': [255,255,224,1], 'lime': [0,255,0,1],
  2707. 'limegreen': [50,205,50,1], 'linen': [250,240,230,1],
  2708. 'magenta': [255,0,255,1], 'maroon': [128,0,0,1],
  2709. 'mediumaquamarine': [102,205,170,1], 'mediumblue': [0,0,205,1],
  2710. 'mediumorchid': [186,85,211,1], 'mediumpurple': [147,112,219,1],
  2711. 'mediumseagreen': [60,179,113,1], 'mediumslateblue': [123,104,238,1],
  2712. 'mediumspringgreen': [0,250,154,1], 'mediumturquoise': [72,209,204,1],
  2713. 'mediumvioletred': [199,21,133,1], 'midnightblue': [25,25,112,1],
  2714. 'mintcream': [245,255,250,1], 'mistyrose': [255,228,225,1],
  2715. 'moccasin': [255,228,181,1], 'navajowhite': [255,222,173,1],
  2716. 'navy': [0,0,128,1], 'oldlace': [253,245,230,1],
  2717. 'olive': [128,128,0,1], 'olivedrab': [107,142,35,1],
  2718. 'orange': [255,165,0,1], 'orangered': [255,69,0,1],
  2719. 'orchid': [218,112,214,1], 'palegoldenrod': [238,232,170,1],
  2720. 'palegreen': [152,251,152,1], 'paleturquoise': [175,238,238,1],
  2721. 'palevioletred': [219,112,147,1], 'papayawhip': [255,239,213,1],
  2722. 'peachpuff': [255,218,185,1], 'peru': [205,133,63,1],
  2723. 'pink': [255,192,203,1], 'plum': [221,160,221,1],
  2724. 'powderblue': [176,224,230,1], 'purple': [128,0,128,1],
  2725. 'red': [255,0,0,1], 'rosybrown': [188,143,143,1],
  2726. 'royalblue': [65,105,225,1], 'saddlebrown': [139,69,19,1],
  2727. 'salmon': [250,128,114,1], 'sandybrown': [244,164,96,1],
  2728. 'seagreen': [46,139,87,1], 'seashell': [255,245,238,1],
  2729. 'sienna': [160,82,45,1], 'silver': [192,192,192,1],
  2730. 'skyblue': [135,206,235,1], 'slateblue': [106,90,205,1],
  2731. 'slategray': [112,128,144,1], 'slategrey': [112,128,144,1],
  2732. 'snow': [255,250,250,1], 'springgreen': [0,255,127,1],
  2733. 'steelblue': [70,130,180,1], 'tan': [210,180,140,1],
  2734. 'teal': [0,128,128,1], 'thistle': [216,191,216,1],
  2735. 'tomato': [255,99,71,1], 'turquoise': [64,224,208,1],
  2736. 'violet': [238,130,238,1], 'wheat': [245,222,179,1],
  2737. 'white': [255,255,255,1], 'whitesmoke': [245,245,245,1],
  2738. 'yellow': [255,255,0,1], 'yellowgreen': [154,205,50,1]
  2739. };
  2740. function clampCssByte(i) { // Clamp to integer 0 .. 255.
  2741. i = Math.round(i); // Seems to be what Chrome does (vs truncation).
  2742. return i < 0 ? 0 : i > 255 ? 255 : i;
  2743. }
  2744. function clampCssAngle(i) { // Clamp to integer 0 .. 360.
  2745. i = Math.round(i); // Seems to be what Chrome does (vs truncation).
  2746. return i < 0 ? 0 : i > 360 ? 360 : i;
  2747. }
  2748. function clampCssFloat(f) { // Clamp to float 0.0 .. 1.0.
  2749. return f < 0 ? 0 : f > 1 ? 1 : f;
  2750. }
  2751. function parseCssInt(str) { // int or percentage.
  2752. if (str.length && str.charAt(str.length - 1) === '%') {
  2753. return clampCssByte(parseFloat(str) / 100 * 255);
  2754. }
  2755. return clampCssByte(parseInt(str, 10));
  2756. }
  2757. function parseCssFloat(str) { // float or percentage.
  2758. if (str.length && str.charAt(str.length - 1) === '%') {
  2759. return clampCssFloat(parseFloat(str) / 100);
  2760. }
  2761. return clampCssFloat(parseFloat(str));
  2762. }
  2763. function cssHueToRgb(m1, m2, h) {
  2764. if (h < 0) {
  2765. h += 1;
  2766. }
  2767. else if (h > 1) {
  2768. h -= 1;
  2769. }
  2770. if (h * 6 < 1) {
  2771. return m1 + (m2 - m1) * h * 6;
  2772. }
  2773. if (h * 2 < 1) {
  2774. return m2;
  2775. }
  2776. if (h * 3 < 2) {
  2777. return m1 + (m2 - m1) * (2/3 - h) * 6;
  2778. }
  2779. return m1;
  2780. }
  2781. function lerpNumber(a, b, p) {
  2782. return a + (b - a) * p;
  2783. }
  2784. function setRgba(out, r, g, b, a) {
  2785. out[0] = r; out[1] = g; out[2] = b; out[3] = a;
  2786. return out;
  2787. }
  2788. function copyRgba(out, a) {
  2789. out[0] = a[0]; out[1] = a[1]; out[2] = a[2]; out[3] = a[3];
  2790. return out;
  2791. }
  2792. var colorCache = new LRU(20);
  2793. var lastRemovedArr = null;
  2794. function putToCache(colorStr, rgbaArr) {
  2795. // Reuse removed array
  2796. if (lastRemovedArr) {
  2797. copyRgba(lastRemovedArr, rgbaArr);
  2798. }
  2799. lastRemovedArr = colorCache.put(colorStr, lastRemovedArr || (rgbaArr.slice()));
  2800. }
  2801. /**
  2802. * @param {string} colorStr
  2803. * @param {Array.<number>} out
  2804. * @return {Array.<number>}
  2805. * @memberOf module:zrender/util/color
  2806. */
  2807. function parse(colorStr, rgbaArr) {
  2808. if (!colorStr) {
  2809. return;
  2810. }
  2811. rgbaArr = rgbaArr || [];
  2812. var cached = colorCache.get(colorStr);
  2813. if (cached) {
  2814. return copyRgba(rgbaArr, cached);
  2815. }
  2816. // colorStr may be not string
  2817. colorStr = colorStr + '';
  2818. // Remove all whitespace, not compliant, but should just be more accepting.
  2819. var str = colorStr.replace(/ /g, '').toLowerCase();
  2820. // Color keywords (and transparent) lookup.
  2821. if (str in kCSSColorTable) {
  2822. copyRgba(rgbaArr, kCSSColorTable[str]);
  2823. putToCache(colorStr, rgbaArr);
  2824. return rgbaArr;
  2825. }
  2826. // #abc and #abc123 syntax.
  2827. if (str.charAt(0) === '#') {
  2828. if (str.length === 4) {
  2829. var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
  2830. if (!(iv >= 0 && iv <= 0xfff)) {
  2831. setRgba(rgbaArr, 0, 0, 0, 1);
  2832. return; // Covers NaN.
  2833. }
  2834. setRgba(rgbaArr,
  2835. ((iv & 0xf00) >> 4) | ((iv & 0xf00) >> 8),
  2836. (iv & 0xf0) | ((iv & 0xf0) >> 4),
  2837. (iv & 0xf) | ((iv & 0xf) << 4),
  2838. 1
  2839. );
  2840. putToCache(colorStr, rgbaArr);
  2841. return rgbaArr;
  2842. }
  2843. else if (str.length === 7) {
  2844. var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
  2845. if (!(iv >= 0 && iv <= 0xffffff)) {
  2846. setRgba(rgbaArr, 0, 0, 0, 1);
  2847. return; // Covers NaN.
  2848. }
  2849. setRgba(rgbaArr,
  2850. (iv & 0xff0000) >> 16,
  2851. (iv & 0xff00) >> 8,
  2852. iv & 0xff,
  2853. 1
  2854. );
  2855. putToCache(colorStr, rgbaArr);
  2856. return rgbaArr;
  2857. }
  2858. return;
  2859. }
  2860. var op = str.indexOf('('), ep = str.indexOf(')');
  2861. if (op !== -1 && ep + 1 === str.length) {
  2862. var fname = str.substr(0, op);
  2863. var params = str.substr(op + 1, ep - (op + 1)).split(',');
  2864. var alpha = 1; // To allow case fallthrough.
  2865. switch (fname) {
  2866. case 'rgba':
  2867. if (params.length !== 4) {
  2868. setRgba(rgbaArr, 0, 0, 0, 1);
  2869. return;
  2870. }
  2871. alpha = parseCssFloat(params.pop()); // jshint ignore:line
  2872. // Fall through.
  2873. case 'rgb':
  2874. if (params.length !== 3) {
  2875. setRgba(rgbaArr, 0, 0, 0, 1);
  2876. return;
  2877. }
  2878. setRgba(rgbaArr,
  2879. parseCssInt(params[0]),
  2880. parseCssInt(params[1]),
  2881. parseCssInt(params[2]),
  2882. alpha
  2883. );
  2884. putToCache(colorStr, rgbaArr);
  2885. return rgbaArr;
  2886. case 'hsla':
  2887. if (params.length !== 4) {
  2888. setRgba(rgbaArr, 0, 0, 0, 1);
  2889. return;
  2890. }
  2891. params[3] = parseCssFloat(params[3]);
  2892. hsla2rgba(params, rgbaArr);
  2893. putToCache(colorStr, rgbaArr);
  2894. return rgbaArr;
  2895. case 'hsl':
  2896. if (params.length !== 3) {
  2897. setRgba(rgbaArr, 0, 0, 0, 1);
  2898. return;
  2899. }
  2900. hsla2rgba(params, rgbaArr);
  2901. putToCache(colorStr, rgbaArr);
  2902. return rgbaArr;
  2903. default:
  2904. return;
  2905. }
  2906. }
  2907. setRgba(rgbaArr, 0, 0, 0, 1);
  2908. return;
  2909. }
  2910. /**
  2911. * @param {Array.<number>} hsla
  2912. * @param {Array.<number>} rgba
  2913. * @return {Array.<number>} rgba
  2914. */
  2915. function hsla2rgba(hsla, rgba) {
  2916. var h = (((parseFloat(hsla[0]) % 360) + 360) % 360) / 360; // 0 .. 1
  2917. // NOTE(deanm): According to the CSS spec s/l should only be
  2918. // percentages, but we don't bother and let float or percentage.
  2919. var s = parseCssFloat(hsla[1]);
  2920. var l = parseCssFloat(hsla[2]);
  2921. var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
  2922. var m1 = l * 2 - m2;
  2923. rgba = rgba || [];
  2924. setRgba(rgba,
  2925. clampCssByte(cssHueToRgb(m1, m2, h + 1 / 3) * 255),
  2926. clampCssByte(cssHueToRgb(m1, m2, h) * 255),
  2927. clampCssByte(cssHueToRgb(m1, m2, h - 1 / 3) * 255),
  2928. 1
  2929. );
  2930. if (hsla.length === 4) {
  2931. rgba[3] = hsla[3];
  2932. }
  2933. return rgba;
  2934. }
  2935. /**
  2936. * @param {Array.<number>} rgba
  2937. * @return {Array.<number>} hsla
  2938. */
  2939. function rgba2hsla(rgba) {
  2940. if (!rgba) {
  2941. return;
  2942. }
  2943. // RGB from 0 to 255
  2944. var R = rgba[0] / 255;
  2945. var G = rgba[1] / 255;
  2946. var B = rgba[2] / 255;
  2947. var vMin = Math.min(R, G, B); // Min. value of RGB
  2948. var vMax = Math.max(R, G, B); // Max. value of RGB
  2949. var delta = vMax - vMin; // Delta RGB value
  2950. var L = (vMax + vMin) / 2;
  2951. var H;
  2952. var S;
  2953. // HSL results from 0 to 1
  2954. if (delta === 0) {
  2955. H = 0;
  2956. S = 0;
  2957. }
  2958. else {
  2959. if (L < 0.5) {
  2960. S = delta / (vMax + vMin);
  2961. }
  2962. else {
  2963. S = delta / (2 - vMax - vMin);
  2964. }
  2965. var deltaR = (((vMax - R) / 6) + (delta / 2)) / delta;
  2966. var deltaG = (((vMax - G) / 6) + (delta / 2)) / delta;
  2967. var deltaB = (((vMax - B) / 6) + (delta / 2)) / delta;
  2968. if (R === vMax) {
  2969. H = deltaB - deltaG;
  2970. }
  2971. else if (G === vMax) {
  2972. H = (1 / 3) + deltaR - deltaB;
  2973. }
  2974. else if (B === vMax) {
  2975. H = (2 / 3) + deltaG - deltaR;
  2976. }
  2977. if (H < 0) {
  2978. H += 1;
  2979. }
  2980. if (H > 1) {
  2981. H -= 1;
  2982. }
  2983. }
  2984. var hsla = [H * 360, S, L];
  2985. if (rgba[3] != null) {
  2986. hsla.push(rgba[3]);
  2987. }
  2988. return hsla;
  2989. }
  2990. /**
  2991. * @param {string} color
  2992. * @param {number} level
  2993. * @return {string}
  2994. * @memberOf module:zrender/util/color
  2995. */
  2996. function lift(color, level) {
  2997. var colorArr = parse(color);
  2998. if (colorArr) {
  2999. for (var i = 0; i < 3; i++) {
  3000. if (level < 0) {
  3001. colorArr[i] = colorArr[i] * (1 - level) | 0;
  3002. }
  3003. else {
  3004. colorArr[i] = ((255 - colorArr[i]) * level + colorArr[i]) | 0;
  3005. }
  3006. if (colorArr[i] > 255) {
  3007. colorArr[i] = 255;
  3008. }
  3009. else if (color[i] < 0) {
  3010. colorArr[i] = 0;
  3011. }
  3012. }
  3013. return stringify(colorArr, colorArr.length === 4 ? 'rgba' : 'rgb');
  3014. }
  3015. }
  3016. /**
  3017. * @param {string} color
  3018. * @return {string}
  3019. * @memberOf module:zrender/util/color
  3020. */
  3021. function toHex(color) {
  3022. var colorArr = parse(color);
  3023. if (colorArr) {
  3024. return ((1 << 24) + (colorArr[0] << 16) + (colorArr[1] << 8) + (+colorArr[2])).toString(16).slice(1);
  3025. }
  3026. }
  3027. /**
  3028. * Map value to color. Faster than lerp methods because color is represented by rgba array.
  3029. * @param {number} normalizedValue A float between 0 and 1.
  3030. * @param {Array.<Array.<number>>} colors List of rgba color array
  3031. * @param {Array.<number>} [out] Mapped gba color array
  3032. * @return {Array.<number>} will be null/undefined if input illegal.
  3033. */
  3034. function fastLerp(normalizedValue, colors, out) {
  3035. if (!(colors && colors.length)
  3036. || !(normalizedValue >= 0 && normalizedValue <= 1)
  3037. ) {
  3038. return;
  3039. }
  3040. out = out || [];
  3041. var value = normalizedValue * (colors.length - 1);
  3042. var leftIndex = Math.floor(value);
  3043. var rightIndex = Math.ceil(value);
  3044. var leftColor = colors[leftIndex];
  3045. var rightColor = colors[rightIndex];
  3046. var dv = value - leftIndex;
  3047. out[0] = clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv));
  3048. out[1] = clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv));
  3049. out[2] = clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv));
  3050. out[3] = clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv));
  3051. return out;
  3052. }
  3053. /**
  3054. * @deprecated
  3055. */
  3056. var fastMapToColor = fastLerp;
  3057. /**
  3058. * @param {number} normalizedValue A float between 0 and 1.
  3059. * @param {Array.<string>} colors Color list.
  3060. * @param {boolean=} fullOutput Default false.
  3061. * @return {(string|Object)} Result color. If fullOutput,
  3062. * return {color: ..., leftIndex: ..., rightIndex: ..., value: ...},
  3063. * @memberOf module:zrender/util/color
  3064. */
  3065. function lerp$1(normalizedValue, colors, fullOutput) {
  3066. if (!(colors && colors.length)
  3067. || !(normalizedValue >= 0 && normalizedValue <= 1)
  3068. ) {
  3069. return;
  3070. }
  3071. var value = normalizedValue * (colors.length - 1);
  3072. var leftIndex = Math.floor(value);
  3073. var rightIndex = Math.ceil(value);
  3074. var leftColor = parse(colors[leftIndex]);
  3075. var rightColor = parse(colors[rightIndex]);
  3076. var dv = value - leftIndex;
  3077. var color = stringify(
  3078. [
  3079. clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv)),
  3080. clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv)),
  3081. clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv)),
  3082. clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv))
  3083. ],
  3084. 'rgba'
  3085. );
  3086. return fullOutput
  3087. ? {
  3088. color: color,
  3089. leftIndex: leftIndex,
  3090. rightIndex: rightIndex,
  3091. value: value
  3092. }
  3093. : color;
  3094. }
  3095. /**
  3096. * @deprecated
  3097. */
  3098. var mapToColor = lerp$1;
  3099. /**
  3100. * @param {string} color
  3101. * @param {number=} h 0 ~ 360, ignore when null.
  3102. * @param {number=} s 0 ~ 1, ignore when null.
  3103. * @param {number=} l 0 ~ 1, ignore when null.
  3104. * @return {string} Color string in rgba format.
  3105. * @memberOf module:zrender/util/color
  3106. */
  3107. function modifyHSL(color, h, s, l) {
  3108. color = parse(color);
  3109. if (color) {
  3110. color = rgba2hsla(color);
  3111. h != null && (color[0] = clampCssAngle(h));
  3112. s != null && (color[1] = parseCssFloat(s));
  3113. l != null && (color[2] = parseCssFloat(l));
  3114. return stringify(hsla2rgba(color), 'rgba');
  3115. }
  3116. }
  3117. /**
  3118. * @param {string} color
  3119. * @param {number=} alpha 0 ~ 1
  3120. * @return {string} Color string in rgba format.
  3121. * @memberOf module:zrender/util/color
  3122. */
  3123. function modifyAlpha(color, alpha) {
  3124. color = parse(color);
  3125. if (color && alpha != null) {
  3126. color[3] = clampCssFloat(alpha);
  3127. return stringify(color, 'rgba');
  3128. }
  3129. }
  3130. /**
  3131. * @param {Array.<number>} arrColor like [12,33,44,0.4]
  3132. * @param {string} type 'rgba', 'hsva', ...
  3133. * @return {string} Result color. (If input illegal, return undefined).
  3134. */
  3135. function stringify(arrColor, type) {
  3136. if (!arrColor || !arrColor.length) {
  3137. return;
  3138. }
  3139. var colorStr = arrColor[0] + ',' + arrColor[1] + ',' + arrColor[2];
  3140. if (type === 'rgba' || type === 'hsva' || type === 'hsla') {
  3141. colorStr += ',' + arrColor[3];
  3142. }
  3143. return type + '(' + colorStr + ')';
  3144. }
  3145. var color = (Object.freeze || Object)({
  3146. parse: parse,
  3147. lift: lift,
  3148. toHex: toHex,
  3149. fastLerp: fastLerp,
  3150. fastMapToColor: fastMapToColor,
  3151. lerp: lerp$1,
  3152. mapToColor: mapToColor,
  3153. modifyHSL: modifyHSL,
  3154. modifyAlpha: modifyAlpha,
  3155. stringify: stringify
  3156. });
  3157. /**
  3158. * @module echarts/animation/Animator
  3159. */
  3160. var arraySlice = Array.prototype.slice;
  3161. function defaultGetter(target, key) {
  3162. return target[key];
  3163. }
  3164. function defaultSetter(target, key, value) {
  3165. target[key] = value;
  3166. }
  3167. /**
  3168. * @param {number} p0
  3169. * @param {number} p1
  3170. * @param {number} percent
  3171. * @return {number}
  3172. */
  3173. function interpolateNumber(p0, p1, percent) {
  3174. return (p1 - p0) * percent + p0;
  3175. }
  3176. /**
  3177. * @param {string} p0
  3178. * @param {string} p1
  3179. * @param {number} percent
  3180. * @return {string}
  3181. */
  3182. function interpolateString(p0, p1, percent) {
  3183. return percent > 0.5 ? p1 : p0;
  3184. }
  3185. /**
  3186. * @param {Array} p0
  3187. * @param {Array} p1
  3188. * @param {number} percent
  3189. * @param {Array} out
  3190. * @param {number} arrDim
  3191. */
  3192. function interpolateArray(p0, p1, percent, out, arrDim) {
  3193. var len = p0.length;
  3194. if (arrDim == 1) {
  3195. for (var i = 0; i < len; i++) {
  3196. out[i] = interpolateNumber(p0[i], p1[i], percent);
  3197. }
  3198. }
  3199. else {
  3200. var len2 = len && p0[0].length;
  3201. for (var i = 0; i < len; i++) {
  3202. for (var j = 0; j < len2; j++) {
  3203. out[i][j] = interpolateNumber(
  3204. p0[i][j], p1[i][j], percent
  3205. );
  3206. }
  3207. }
  3208. }
  3209. }
  3210. // arr0 is source array, arr1 is target array.
  3211. // Do some preprocess to avoid error happened when interpolating from arr0 to arr1
  3212. function fillArr(arr0, arr1, arrDim) {
  3213. var arr0Len = arr0.length;
  3214. var arr1Len = arr1.length;
  3215. if (arr0Len !== arr1Len) {
  3216. // FIXME Not work for TypedArray
  3217. var isPreviousLarger = arr0Len > arr1Len;
  3218. if (isPreviousLarger) {
  3219. // Cut the previous
  3220. arr0.length = arr1Len;
  3221. }
  3222. else {
  3223. // Fill the previous
  3224. for (var i = arr0Len; i < arr1Len; i++) {
  3225. arr0.push(
  3226. arrDim === 1 ? arr1[i] : arraySlice.call(arr1[i])
  3227. );
  3228. }
  3229. }
  3230. }
  3231. // Handling NaN value
  3232. var len2 = arr0[0] && arr0[0].length;
  3233. for (var i = 0; i < arr0.length; i++) {
  3234. if (arrDim === 1) {
  3235. if (isNaN(arr0[i])) {
  3236. arr0[i] = arr1[i];
  3237. }
  3238. }
  3239. else {
  3240. for (var j = 0; j < len2; j++) {
  3241. if (isNaN(arr0[i][j])) {
  3242. arr0[i][j] = arr1[i][j];
  3243. }
  3244. }
  3245. }
  3246. }
  3247. }
  3248. /**
  3249. * @param {Array} arr0
  3250. * @param {Array} arr1
  3251. * @param {number} arrDim
  3252. * @return {boolean}
  3253. */
  3254. function isArraySame(arr0, arr1, arrDim) {
  3255. if (arr0 === arr1) {
  3256. return true;
  3257. }
  3258. var len = arr0.length;
  3259. if (len !== arr1.length) {
  3260. return false;
  3261. }
  3262. if (arrDim === 1) {
  3263. for (var i = 0; i < len; i++) {
  3264. if (arr0[i] !== arr1[i]) {
  3265. return false;
  3266. }
  3267. }
  3268. }
  3269. else {
  3270. var len2 = arr0[0].length;
  3271. for (var i = 0; i < len; i++) {
  3272. for (var j = 0; j < len2; j++) {
  3273. if (arr0[i][j] !== arr1[i][j]) {
  3274. return false;
  3275. }
  3276. }
  3277. }
  3278. }
  3279. return true;
  3280. }
  3281. /**
  3282. * Catmull Rom interpolate array
  3283. * @param {Array} p0
  3284. * @param {Array} p1
  3285. * @param {Array} p2
  3286. * @param {Array} p3
  3287. * @param {number} t
  3288. * @param {number} t2
  3289. * @param {number} t3
  3290. * @param {Array} out
  3291. * @param {number} arrDim
  3292. */
  3293. function catmullRomInterpolateArray(
  3294. p0, p1, p2, p3, t, t2, t3, out, arrDim
  3295. ) {
  3296. var len = p0.length;
  3297. if (arrDim == 1) {
  3298. for (var i = 0; i < len; i++) {
  3299. out[i] = catmullRomInterpolate(
  3300. p0[i], p1[i], p2[i], p3[i], t, t2, t3
  3301. );
  3302. }
  3303. }
  3304. else {
  3305. var len2 = p0[0].length;
  3306. for (var i = 0; i < len; i++) {
  3307. for (var j = 0; j < len2; j++) {
  3308. out[i][j] = catmullRomInterpolate(
  3309. p0[i][j], p1[i][j], p2[i][j], p3[i][j],
  3310. t, t2, t3
  3311. );
  3312. }
  3313. }
  3314. }
  3315. }
  3316. /**
  3317. * Catmull Rom interpolate number
  3318. * @param {number} p0
  3319. * @param {number} p1
  3320. * @param {number} p2
  3321. * @param {number} p3
  3322. * @param {number} t
  3323. * @param {number} t2
  3324. * @param {number} t3
  3325. * @return {number}
  3326. */
  3327. function catmullRomInterpolate(p0, p1, p2, p3, t, t2, t3) {
  3328. var v0 = (p2 - p0) * 0.5;
  3329. var v1 = (p3 - p1) * 0.5;
  3330. return (2 * (p1 - p2) + v0 + v1) * t3
  3331. + (-3 * (p1 - p2) - 2 * v0 - v1) * t2
  3332. + v0 * t + p1;
  3333. }
  3334. function cloneValue(value) {
  3335. if (isArrayLike(value)) {
  3336. var len = value.length;
  3337. if (isArrayLike(value[0])) {
  3338. var ret = [];
  3339. for (var i = 0; i < len; i++) {
  3340. ret.push(arraySlice.call(value[i]));
  3341. }
  3342. return ret;
  3343. }
  3344. return arraySlice.call(value);
  3345. }
  3346. return value;
  3347. }
  3348. function rgba2String(rgba) {
  3349. rgba[0] = Math.floor(rgba[0]);
  3350. rgba[1] = Math.floor(rgba[1]);
  3351. rgba[2] = Math.floor(rgba[2]);
  3352. return 'rgba(' + rgba.join(',') + ')';
  3353. }
  3354. function getArrayDim(keyframes) {
  3355. var lastValue = keyframes[keyframes.length - 1].value;
  3356. return isArrayLike(lastValue && lastValue[0]) ? 2 : 1;
  3357. }
  3358. function createTrackClip(animator, easing, oneTrackDone, keyframes, propName, forceAnimate) {
  3359. var getter = animator._getter;
  3360. var setter = animator._setter;
  3361. var useSpline = easing === 'spline';
  3362. var trackLen = keyframes.length;
  3363. if (!trackLen) {
  3364. return;
  3365. }
  3366. // Guess data type
  3367. var firstVal = keyframes[0].value;
  3368. var isValueArray = isArrayLike(firstVal);
  3369. var isValueColor = false;
  3370. var isValueString = false;
  3371. // For vertices morphing
  3372. var arrDim = isValueArray ? getArrayDim(keyframes) : 0;
  3373. var trackMaxTime;
  3374. // Sort keyframe as ascending
  3375. keyframes.sort(function(a, b) {
  3376. return a.time - b.time;
  3377. });
  3378. trackMaxTime = keyframes[trackLen - 1].time;
  3379. // Percents of each keyframe
  3380. var kfPercents = [];
  3381. // Value of each keyframe
  3382. var kfValues = [];
  3383. var prevValue = keyframes[0].value;
  3384. var isAllValueEqual = true;
  3385. for (var i = 0; i < trackLen; i++) {
  3386. kfPercents.push(keyframes[i].time / trackMaxTime);
  3387. // Assume value is a color when it is a string
  3388. var value = keyframes[i].value;
  3389. // Check if value is equal, deep check if value is array
  3390. if (!((isValueArray && isArraySame(value, prevValue, arrDim))
  3391. || (!isValueArray && value === prevValue))) {
  3392. isAllValueEqual = false;
  3393. }
  3394. prevValue = value;
  3395. // Try converting a string to a color array
  3396. if (typeof value == 'string') {
  3397. var colorArray = parse(value);
  3398. if (colorArray) {
  3399. value = colorArray;
  3400. isValueColor = true;
  3401. }
  3402. else {
  3403. isValueString = true;
  3404. }
  3405. }
  3406. kfValues.push(value);
  3407. }
  3408. if (!forceAnimate && isAllValueEqual) {
  3409. return;
  3410. }
  3411. var lastValue = kfValues[trackLen - 1];
  3412. // Polyfill array and NaN value
  3413. for (var i = 0; i < trackLen - 1; i++) {
  3414. if (isValueArray) {
  3415. fillArr(kfValues[i], lastValue, arrDim);
  3416. }
  3417. else {
  3418. if (isNaN(kfValues[i]) && !isNaN(lastValue) && !isValueString && !isValueColor) {
  3419. kfValues[i] = lastValue;
  3420. }
  3421. }
  3422. }
  3423. isValueArray && fillArr(getter(animator._target, propName), lastValue, arrDim);
  3424. // Cache the key of last frame to speed up when
  3425. // animation playback is sequency
  3426. var lastFrame = 0;
  3427. var lastFramePercent = 0;
  3428. var start;
  3429. var w;
  3430. var p0;
  3431. var p1;
  3432. var p2;
  3433. var p3;
  3434. if (isValueColor) {
  3435. var rgba = [0, 0, 0, 0];
  3436. }
  3437. var onframe = function (target, percent) {
  3438. // Find the range keyframes
  3439. // kf1-----kf2---------current--------kf3
  3440. // find kf2 and kf3 and do interpolation
  3441. var frame;
  3442. // In the easing function like elasticOut, percent may less than 0
  3443. if (percent < 0) {
  3444. frame = 0;
  3445. }
  3446. else if (percent < lastFramePercent) {
  3447. // Start from next key
  3448. // PENDING start from lastFrame ?
  3449. start = Math.min(lastFrame + 1, trackLen - 1);
  3450. for (frame = start; frame >= 0; frame--) {
  3451. if (kfPercents[frame] <= percent) {
  3452. break;
  3453. }
  3454. }
  3455. // PENDING really need to do this ?
  3456. frame = Math.min(frame, trackLen - 2);
  3457. }
  3458. else {
  3459. for (frame = lastFrame; frame < trackLen; frame++) {
  3460. if (kfPercents[frame] > percent) {
  3461. break;
  3462. }
  3463. }
  3464. frame = Math.min(frame - 1, trackLen - 2);
  3465. }
  3466. lastFrame = frame;
  3467. lastFramePercent = percent;
  3468. var range = (kfPercents[frame + 1] - kfPercents[frame]);
  3469. if (range === 0) {
  3470. return;
  3471. }
  3472. else {
  3473. w = (percent - kfPercents[frame]) / range;
  3474. }
  3475. if (useSpline) {
  3476. p1 = kfValues[frame];
  3477. p0 = kfValues[frame === 0 ? frame : frame - 1];
  3478. p2 = kfValues[frame > trackLen - 2 ? trackLen - 1 : frame + 1];
  3479. p3 = kfValues[frame > trackLen - 3 ? trackLen - 1 : frame + 2];
  3480. if (isValueArray) {
  3481. catmullRomInterpolateArray(
  3482. p0, p1, p2, p3, w, w * w, w * w * w,
  3483. getter(target, propName),
  3484. arrDim
  3485. );
  3486. }
  3487. else {
  3488. var value;
  3489. if (isValueColor) {
  3490. value = catmullRomInterpolateArray(
  3491. p0, p1, p2, p3, w, w * w, w * w * w,
  3492. rgba, 1
  3493. );
  3494. value = rgba2String(rgba);
  3495. }
  3496. else if (isValueString) {
  3497. // String is step(0.5)
  3498. return interpolateString(p1, p2, w);
  3499. }
  3500. else {
  3501. value = catmullRomInterpolate(
  3502. p0, p1, p2, p3, w, w * w, w * w * w
  3503. );
  3504. }
  3505. setter(
  3506. target,
  3507. propName,
  3508. value
  3509. );
  3510. }
  3511. }
  3512. else {
  3513. if (isValueArray) {
  3514. interpolateArray(
  3515. kfValues[frame], kfValues[frame + 1], w,
  3516. getter(target, propName),
  3517. arrDim
  3518. );
  3519. }
  3520. else {
  3521. var value;
  3522. if (isValueColor) {
  3523. interpolateArray(
  3524. kfValues[frame], kfValues[frame + 1], w,
  3525. rgba, 1
  3526. );
  3527. value = rgba2String(rgba);
  3528. }
  3529. else if (isValueString) {
  3530. // String is step(0.5)
  3531. return interpolateString(kfValues[frame], kfValues[frame + 1], w);
  3532. }
  3533. else {
  3534. value = interpolateNumber(kfValues[frame], kfValues[frame + 1], w);
  3535. }
  3536. setter(
  3537. target,
  3538. propName,
  3539. value
  3540. );
  3541. }
  3542. }
  3543. };
  3544. var clip = new Clip({
  3545. target: animator._target,
  3546. life: trackMaxTime,
  3547. loop: animator._loop,
  3548. delay: animator._delay,
  3549. onframe: onframe,
  3550. ondestroy: oneTrackDone
  3551. });
  3552. if (easing && easing !== 'spline') {
  3553. clip.easing = easing;
  3554. }
  3555. return clip;
  3556. }
  3557. /**
  3558. * @alias module:zrender/animation/Animator
  3559. * @constructor
  3560. * @param {Object} target
  3561. * @param {boolean} loop
  3562. * @param {Function} getter
  3563. * @param {Function} setter
  3564. */
  3565. var Animator = function(target, loop, getter, setter) {
  3566. this._tracks = {};
  3567. this._target = target;
  3568. this._loop = loop || false;
  3569. this._getter = getter || defaultGetter;
  3570. this._setter = setter || defaultSetter;
  3571. this._clipCount = 0;
  3572. this._delay = 0;
  3573. this._doneList = [];
  3574. this._onframeList = [];
  3575. this._clipList = [];
  3576. };
  3577. Animator.prototype = {
  3578. /**
  3579. * 设置动画关键帧
  3580. * @param {number} time 关键帧时间,单位是ms
  3581. * @param {Object} props 关键帧的属性值,key-value表示
  3582. * @return {module:zrender/animation/Animator}
  3583. */
  3584. when: function(time /* ms */, props) {
  3585. var tracks = this._tracks;
  3586. for (var propName in props) {
  3587. if (!props.hasOwnProperty(propName)) {
  3588. continue;
  3589. }
  3590. if (!tracks[propName]) {
  3591. tracks[propName] = [];
  3592. // Invalid value
  3593. var value = this._getter(this._target, propName);
  3594. if (value == null) {
  3595. // zrLog('Invalid property ' + propName);
  3596. continue;
  3597. }
  3598. // If time is 0
  3599. // Then props is given initialize value
  3600. // Else
  3601. // Initialize value from current prop value
  3602. if (time !== 0) {
  3603. tracks[propName].push({
  3604. time: 0,
  3605. value: cloneValue(value)
  3606. });
  3607. }
  3608. }
  3609. tracks[propName].push({
  3610. time: time,
  3611. value: props[propName]
  3612. });
  3613. }
  3614. return this;
  3615. },
  3616. /**
  3617. * 添加动画每一帧的回调函数
  3618. * @param {Function} callback
  3619. * @return {module:zrender/animation/Animator}
  3620. */
  3621. during: function (callback) {
  3622. this._onframeList.push(callback);
  3623. return this;
  3624. },
  3625. pause: function () {
  3626. for (var i = 0; i < this._clipList.length; i++) {
  3627. this._clipList[i].pause();
  3628. }
  3629. this._paused = true;
  3630. },
  3631. resume: function () {
  3632. for (var i = 0; i < this._clipList.length; i++) {
  3633. this._clipList[i].resume();
  3634. }
  3635. this._paused = false;
  3636. },
  3637. isPaused: function () {
  3638. return !!this._paused;
  3639. },
  3640. _doneCallback: function () {
  3641. // Clear all tracks
  3642. this._tracks = {};
  3643. // Clear all clips
  3644. this._clipList.length = 0;
  3645. var doneList = this._doneList;
  3646. var len = doneList.length;
  3647. for (var i = 0; i < len; i++) {
  3648. doneList[i].call(this);
  3649. }
  3650. },
  3651. /**
  3652. * 开始执行动画
  3653. * @param {string|Function} [easing]
  3654. * 动画缓动函数,详见{@link module:zrender/animation/easing}
  3655. * @param {boolean} forceAnimate
  3656. * @return {module:zrender/animation/Animator}
  3657. */
  3658. start: function (easing, forceAnimate) {
  3659. var self = this;
  3660. var clipCount = 0;
  3661. var oneTrackDone = function() {
  3662. clipCount--;
  3663. if (!clipCount) {
  3664. self._doneCallback();
  3665. }
  3666. };
  3667. var lastClip;
  3668. for (var propName in this._tracks) {
  3669. if (!this._tracks.hasOwnProperty(propName)) {
  3670. continue;
  3671. }
  3672. var clip = createTrackClip(
  3673. this, easing, oneTrackDone,
  3674. this._tracks[propName], propName, forceAnimate
  3675. );
  3676. if (clip) {
  3677. this._clipList.push(clip);
  3678. clipCount++;
  3679. // If start after added to animation
  3680. if (this.animation) {
  3681. this.animation.addClip(clip);
  3682. }
  3683. lastClip = clip;
  3684. }
  3685. }
  3686. // Add during callback on the last clip
  3687. if (lastClip) {
  3688. var oldOnFrame = lastClip.onframe;
  3689. lastClip.onframe = function (target, percent) {
  3690. oldOnFrame(target, percent);
  3691. for (var i = 0; i < self._onframeList.length; i++) {
  3692. self._onframeList[i](target, percent);
  3693. }
  3694. };
  3695. }
  3696. // This optimization will help the case that in the upper application
  3697. // the view may be refreshed frequently, where animation will be
  3698. // called repeatly but nothing changed.
  3699. if (!clipCount) {
  3700. this._doneCallback();
  3701. }
  3702. return this;
  3703. },
  3704. /**
  3705. * 停止动画
  3706. * @param {boolean} forwardToLast If move to last frame before stop
  3707. */
  3708. stop: function (forwardToLast) {
  3709. var clipList = this._clipList;
  3710. var animation = this.animation;
  3711. for (var i = 0; i < clipList.length; i++) {
  3712. var clip = clipList[i];
  3713. if (forwardToLast) {
  3714. // Move to last frame before stop
  3715. clip.onframe(this._target, 1);
  3716. }
  3717. animation && animation.removeClip(clip);
  3718. }
  3719. clipList.length = 0;
  3720. },
  3721. /**
  3722. * 设置动画延迟开始的时间
  3723. * @param {number} time 单位ms
  3724. * @return {module:zrender/animation/Animator}
  3725. */
  3726. delay: function (time) {
  3727. this._delay = time;
  3728. return this;
  3729. },
  3730. /**
  3731. * 添加动画结束的回调
  3732. * @param {Function} cb
  3733. * @return {module:zrender/animation/Animator}
  3734. */
  3735. done: function(cb) {
  3736. if (cb) {
  3737. this._doneList.push(cb);
  3738. }
  3739. return this;
  3740. },
  3741. /**
  3742. * @return {Array.<module:zrender/animation/Clip>}
  3743. */
  3744. getClips: function () {
  3745. return this._clipList;
  3746. }
  3747. };
  3748. var dpr = 1;
  3749. // If in browser environment
  3750. if (typeof window !== 'undefined') {
  3751. dpr = Math.max(window.devicePixelRatio || 1, 1);
  3752. }
  3753. /**
  3754. * config默认配置项
  3755. * @exports zrender/config
  3756. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  3757. */
  3758. /**
  3759. * debug日志选项:catchBrushException为true下有效
  3760. * 0 : 不生成debug数据,发布用
  3761. * 1 : 异常抛出,调试用
  3762. * 2 : 控制台输出,调试用
  3763. */
  3764. var debugMode = 0;
  3765. // retina 屏幕优化
  3766. var devicePixelRatio = dpr;
  3767. var log = function () {
  3768. };
  3769. if (debugMode === 1) {
  3770. log = function () {
  3771. for (var k in arguments) {
  3772. throw new Error(arguments[k]);
  3773. }
  3774. };
  3775. }
  3776. else if (debugMode > 1) {
  3777. log = function () {
  3778. for (var k in arguments) {
  3779. console.log(arguments[k]);
  3780. }
  3781. };
  3782. }
  3783. var zrLog = log;
  3784. /**
  3785. * @alias modue:zrender/mixin/Animatable
  3786. * @constructor
  3787. */
  3788. var Animatable = function () {
  3789. /**
  3790. * @type {Array.<module:zrender/animation/Animator>}
  3791. * @readOnly
  3792. */
  3793. this.animators = [];
  3794. };
  3795. Animatable.prototype = {
  3796. constructor: Animatable,
  3797. /**
  3798. * 动画
  3799. *
  3800. * @param {string} path The path to fetch value from object, like 'a.b.c'.
  3801. * @param {boolean} [loop] Whether to loop animation.
  3802. * @return {module:zrender/animation/Animator}
  3803. * @example:
  3804. * el.animate('style', false)
  3805. * .when(1000, {x: 10} )
  3806. * .done(function(){ // Animation done })
  3807. * .start()
  3808. */
  3809. animate: function (path, loop) {
  3810. var target;
  3811. var animatingShape = false;
  3812. var el = this;
  3813. var zr = this.__zr;
  3814. if (path) {
  3815. var pathSplitted = path.split('.');
  3816. var prop = el;
  3817. // If animating shape
  3818. animatingShape = pathSplitted[0] === 'shape';
  3819. for (var i = 0, l = pathSplitted.length; i < l; i++) {
  3820. if (!prop) {
  3821. continue;
  3822. }
  3823. prop = prop[pathSplitted[i]];
  3824. }
  3825. if (prop) {
  3826. target = prop;
  3827. }
  3828. }
  3829. else {
  3830. target = el;
  3831. }
  3832. if (!target) {
  3833. zrLog(
  3834. 'Property "'
  3835. + path
  3836. + '" is not existed in element '
  3837. + el.id
  3838. );
  3839. return;
  3840. }
  3841. var animators = el.animators;
  3842. var animator = new Animator(target, loop);
  3843. animator.during(function (target) {
  3844. el.dirty(animatingShape);
  3845. })
  3846. .done(function () {
  3847. // FIXME Animator will not be removed if use `Animator#stop` to stop animation
  3848. animators.splice(indexOf(animators, animator), 1);
  3849. });
  3850. animators.push(animator);
  3851. // If animate after added to the zrender
  3852. if (zr) {
  3853. zr.animation.addAnimator(animator);
  3854. }
  3855. return animator;
  3856. },
  3857. /**
  3858. * 停止动画
  3859. * @param {boolean} forwardToLast If move to last frame before stop
  3860. */
  3861. stopAnimation: function (forwardToLast) {
  3862. var animators = this.animators;
  3863. var len = animators.length;
  3864. for (var i = 0; i < len; i++) {
  3865. animators[i].stop(forwardToLast);
  3866. }
  3867. animators.length = 0;
  3868. return this;
  3869. },
  3870. /**
  3871. * Caution: this method will stop previous animation.
  3872. * So do not use this method to one element twice before
  3873. * animation starts, unless you know what you are doing.
  3874. * @param {Object} target
  3875. * @param {number} [time=500] Time in ms
  3876. * @param {string} [easing='linear']
  3877. * @param {number} [delay=0]
  3878. * @param {Function} [callback]
  3879. * @param {Function} [forceAnimate] Prevent stop animation and callback
  3880. * immediently when target values are the same as current values.
  3881. *
  3882. * @example
  3883. * // Animate position
  3884. * el.animateTo({
  3885. * position: [10, 10]
  3886. * }, function () { // done })
  3887. *
  3888. * // Animate shape, style and position in 100ms, delayed 100ms, with cubicOut easing
  3889. * el.animateTo({
  3890. * shape: {
  3891. * width: 500
  3892. * },
  3893. * style: {
  3894. * fill: 'red'
  3895. * }
  3896. * position: [10, 10]
  3897. * }, 100, 100, 'cubicOut', function () { // done })
  3898. */
  3899. // TODO Return animation key
  3900. animateTo: function (target, time, delay, easing, callback, forceAnimate) {
  3901. // animateTo(target, time, easing, callback);
  3902. if (isString(delay)) {
  3903. callback = easing;
  3904. easing = delay;
  3905. delay = 0;
  3906. }
  3907. // animateTo(target, time, delay, callback);
  3908. else if (isFunction$1(easing)) {
  3909. callback = easing;
  3910. easing = 'linear';
  3911. delay = 0;
  3912. }
  3913. // animateTo(target, time, callback);
  3914. else if (isFunction$1(delay)) {
  3915. callback = delay;
  3916. delay = 0;
  3917. }
  3918. // animateTo(target, callback)
  3919. else if (isFunction$1(time)) {
  3920. callback = time;
  3921. time = 500;
  3922. }
  3923. // animateTo(target)
  3924. else if (!time) {
  3925. time = 500;
  3926. }
  3927. // Stop all previous animations
  3928. this.stopAnimation();
  3929. this._animateToShallow('', this, target, time, delay);
  3930. // Animators may be removed immediately after start
  3931. // if there is nothing to animate
  3932. var animators = this.animators.slice();
  3933. var count = animators.length;
  3934. function done() {
  3935. count--;
  3936. if (!count) {
  3937. callback && callback();
  3938. }
  3939. }
  3940. // No animators. This should be checked before animators[i].start(),
  3941. // because 'done' may be executed immediately if no need to animate.
  3942. if (!count) {
  3943. callback && callback();
  3944. }
  3945. // Start after all animators created
  3946. // Incase any animator is done immediately when all animation properties are not changed
  3947. for (var i = 0; i < animators.length; i++) {
  3948. animators[i]
  3949. .done(done)
  3950. .start(easing, forceAnimate);
  3951. }
  3952. },
  3953. /**
  3954. * @private
  3955. * @param {string} path=''
  3956. * @param {Object} source=this
  3957. * @param {Object} target
  3958. * @param {number} [time=500]
  3959. * @param {number} [delay=0]
  3960. *
  3961. * @example
  3962. * // Animate position
  3963. * el._animateToShallow({
  3964. * position: [10, 10]
  3965. * })
  3966. *
  3967. * // Animate shape, style and position in 100ms, delayed 100ms
  3968. * el._animateToShallow({
  3969. * shape: {
  3970. * width: 500
  3971. * },
  3972. * style: {
  3973. * fill: 'red'
  3974. * }
  3975. * position: [10, 10]
  3976. * }, 100, 100)
  3977. */
  3978. _animateToShallow: function (path, source, target, time, delay) {
  3979. var objShallow = {};
  3980. var propertyCount = 0;
  3981. for (var name in target) {
  3982. if (!target.hasOwnProperty(name)) {
  3983. continue;
  3984. }
  3985. if (source[name] != null) {
  3986. if (isObject$1(target[name]) && !isArrayLike(target[name])) {
  3987. this._animateToShallow(
  3988. path ? path + '.' + name : name,
  3989. source[name],
  3990. target[name],
  3991. time,
  3992. delay
  3993. );
  3994. }
  3995. else {
  3996. objShallow[name] = target[name];
  3997. propertyCount++;
  3998. }
  3999. }
  4000. else if (target[name] != null) {
  4001. // Attr directly if not has property
  4002. // FIXME, if some property not needed for element ?
  4003. if (!path) {
  4004. this.attr(name, target[name]);
  4005. }
  4006. else { // Shape or style
  4007. var props = {};
  4008. props[path] = {};
  4009. props[path][name] = target[name];
  4010. this.attr(props);
  4011. }
  4012. }
  4013. }
  4014. if (propertyCount > 0) {
  4015. this.animate(path, false)
  4016. .when(time == null ? 500 : time, objShallow)
  4017. .delay(delay || 0);
  4018. }
  4019. return this;
  4020. }
  4021. };
  4022. /**
  4023. * @alias module:zrender/Element
  4024. * @constructor
  4025. * @extends {module:zrender/mixin/Animatable}
  4026. * @extends {module:zrender/mixin/Transformable}
  4027. * @extends {module:zrender/mixin/Eventful}
  4028. */
  4029. var Element = function (opts) { // jshint ignore:line
  4030. Transformable.call(this, opts);
  4031. Eventful.call(this, opts);
  4032. Animatable.call(this, opts);
  4033. /**
  4034. * 画布元素ID
  4035. * @type {string}
  4036. */
  4037. this.id = opts.id || guid();
  4038. };
  4039. Element.prototype = {
  4040. /**
  4041. * 元素类型
  4042. * Element type
  4043. * @type {string}
  4044. */
  4045. type: 'element',
  4046. /**
  4047. * 元素名字
  4048. * Element name
  4049. * @type {string}
  4050. */
  4051. name: '',
  4052. /**
  4053. * ZRender 实例对象,会在 element 添加到 zrender 实例中后自动赋值
  4054. * ZRender instance will be assigned when element is associated with zrender
  4055. * @name module:/zrender/Element#__zr
  4056. * @type {module:zrender/ZRender}
  4057. */
  4058. __zr: null,
  4059. /**
  4060. * 图形是否忽略,为true时忽略图形的绘制以及事件触发
  4061. * If ignore drawing and events of the element object
  4062. * @name module:/zrender/Element#ignore
  4063. * @type {boolean}
  4064. * @default false
  4065. */
  4066. ignore: false,
  4067. /**
  4068. * 用于裁剪的路径(shape),所有 Group 内的路径在绘制时都会被这个路径裁剪
  4069. * 该路径会继承被裁减对象的变换
  4070. * @type {module:zrender/graphic/Path}
  4071. * @see http://www.w3.org/TR/2dcontext/#clipping-region
  4072. * @readOnly
  4073. */
  4074. clipPath: null,
  4075. /**
  4076. * 是否是 Group
  4077. * @type {boolean}
  4078. */
  4079. isGroup: false,
  4080. /**
  4081. * Drift element
  4082. * @param {number} dx dx on the global space
  4083. * @param {number} dy dy on the global space
  4084. */
  4085. drift: function (dx, dy) {
  4086. switch (this.draggable) {
  4087. case 'horizontal':
  4088. dy = 0;
  4089. break;
  4090. case 'vertical':
  4091. dx = 0;
  4092. break;
  4093. }
  4094. var m = this.transform;
  4095. if (!m) {
  4096. m = this.transform = [1, 0, 0, 1, 0, 0];
  4097. }
  4098. m[4] += dx;
  4099. m[5] += dy;
  4100. this.decomposeTransform();
  4101. this.dirty(false);
  4102. },
  4103. /**
  4104. * Hook before update
  4105. */
  4106. beforeUpdate: function () {},
  4107. /**
  4108. * Hook after update
  4109. */
  4110. afterUpdate: function () {},
  4111. /**
  4112. * Update each frame
  4113. */
  4114. update: function () {
  4115. this.updateTransform();
  4116. },
  4117. /**
  4118. * @param {Function} cb
  4119. * @param {} context
  4120. */
  4121. traverse: function (cb, context) {},
  4122. /**
  4123. * @protected
  4124. */
  4125. attrKV: function (key, value) {
  4126. if (key === 'position' || key === 'scale' || key === 'origin') {
  4127. // Copy the array
  4128. if (value) {
  4129. var target = this[key];
  4130. if (!target) {
  4131. target = this[key] = [];
  4132. }
  4133. target[0] = value[0];
  4134. target[1] = value[1];
  4135. }
  4136. }
  4137. else {
  4138. this[key] = value;
  4139. }
  4140. },
  4141. /**
  4142. * Hide the element
  4143. */
  4144. hide: function () {
  4145. this.ignore = true;
  4146. this.__zr && this.__zr.refresh();
  4147. },
  4148. /**
  4149. * Show the element
  4150. */
  4151. show: function () {
  4152. this.ignore = false;
  4153. this.__zr && this.__zr.refresh();
  4154. },
  4155. /**
  4156. * @param {string|Object} key
  4157. * @param {*} value
  4158. */
  4159. attr: function (key, value) {
  4160. if (typeof key === 'string') {
  4161. this.attrKV(key, value);
  4162. }
  4163. else if (isObject$1(key)) {
  4164. for (var name in key) {
  4165. if (key.hasOwnProperty(name)) {
  4166. this.attrKV(name, key[name]);
  4167. }
  4168. }
  4169. }
  4170. this.dirty(false);
  4171. return this;
  4172. },
  4173. /**
  4174. * @param {module:zrender/graphic/Path} clipPath
  4175. */
  4176. setClipPath: function (clipPath) {
  4177. var zr = this.__zr;
  4178. if (zr) {
  4179. clipPath.addSelfToZr(zr);
  4180. }
  4181. // Remove previous clip path
  4182. if (this.clipPath && this.clipPath !== clipPath) {
  4183. this.removeClipPath();
  4184. }
  4185. this.clipPath = clipPath;
  4186. clipPath.__zr = zr;
  4187. clipPath.__clipTarget = this;
  4188. this.dirty(false);
  4189. },
  4190. /**
  4191. */
  4192. removeClipPath: function () {
  4193. var clipPath = this.clipPath;
  4194. if (clipPath) {
  4195. if (clipPath.__zr) {
  4196. clipPath.removeSelfFromZr(clipPath.__zr);
  4197. }
  4198. clipPath.__zr = null;
  4199. clipPath.__clipTarget = null;
  4200. this.clipPath = null;
  4201. this.dirty(false);
  4202. }
  4203. },
  4204. /**
  4205. * Add self from zrender instance.
  4206. * Not recursively because it will be invoked when element added to storage.
  4207. * @param {module:zrender/ZRender} zr
  4208. */
  4209. addSelfToZr: function (zr) {
  4210. this.__zr = zr;
  4211. // 添加动画
  4212. var animators = this.animators;
  4213. if (animators) {
  4214. for (var i = 0; i < animators.length; i++) {
  4215. zr.animation.addAnimator(animators[i]);
  4216. }
  4217. }
  4218. if (this.clipPath) {
  4219. this.clipPath.addSelfToZr(zr);
  4220. }
  4221. },
  4222. /**
  4223. * Remove self from zrender instance.
  4224. * Not recursively because it will be invoked when element added to storage.
  4225. * @param {module:zrender/ZRender} zr
  4226. */
  4227. removeSelfFromZr: function (zr) {
  4228. this.__zr = null;
  4229. // 移除动画
  4230. var animators = this.animators;
  4231. if (animators) {
  4232. for (var i = 0; i < animators.length; i++) {
  4233. zr.animation.removeAnimator(animators[i]);
  4234. }
  4235. }
  4236. if (this.clipPath) {
  4237. this.clipPath.removeSelfFromZr(zr);
  4238. }
  4239. }
  4240. };
  4241. mixin(Element, Animatable);
  4242. mixin(Element, Transformable);
  4243. mixin(Element, Eventful);
  4244. /**
  4245. * @module echarts/core/BoundingRect
  4246. */
  4247. var v2ApplyTransform = applyTransform;
  4248. var mathMin = Math.min;
  4249. var mathMax = Math.max;
  4250. /**
  4251. * @alias module:echarts/core/BoundingRect
  4252. */
  4253. function BoundingRect(x, y, width, height) {
  4254. if (width < 0) {
  4255. x = x + width;
  4256. width = -width;
  4257. }
  4258. if (height < 0) {
  4259. y = y + height;
  4260. height = -height;
  4261. }
  4262. /**
  4263. * @type {number}
  4264. */
  4265. this.x = x;
  4266. /**
  4267. * @type {number}
  4268. */
  4269. this.y = y;
  4270. /**
  4271. * @type {number}
  4272. */
  4273. this.width = width;
  4274. /**
  4275. * @type {number}
  4276. */
  4277. this.height = height;
  4278. }
  4279. BoundingRect.prototype = {
  4280. constructor: BoundingRect,
  4281. /**
  4282. * @param {module:echarts/core/BoundingRect} other
  4283. */
  4284. union: function (other) {
  4285. var x = mathMin(other.x, this.x);
  4286. var y = mathMin(other.y, this.y);
  4287. this.width = mathMax(
  4288. other.x + other.width,
  4289. this.x + this.width
  4290. ) - x;
  4291. this.height = mathMax(
  4292. other.y + other.height,
  4293. this.y + this.height
  4294. ) - y;
  4295. this.x = x;
  4296. this.y = y;
  4297. },
  4298. /**
  4299. * @param {Array.<number>} m
  4300. * @methods
  4301. */
  4302. applyTransform: (function () {
  4303. var lt = [];
  4304. var rb = [];
  4305. var lb = [];
  4306. var rt = [];
  4307. return function (m) {
  4308. // In case usage like this
  4309. // el.getBoundingRect().applyTransform(el.transform)
  4310. // And element has no transform
  4311. if (!m) {
  4312. return;
  4313. }
  4314. lt[0] = lb[0] = this.x;
  4315. lt[1] = rt[1] = this.y;
  4316. rb[0] = rt[0] = this.x + this.width;
  4317. rb[1] = lb[1] = this.y + this.height;
  4318. v2ApplyTransform(lt, lt, m);
  4319. v2ApplyTransform(rb, rb, m);
  4320. v2ApplyTransform(lb, lb, m);
  4321. v2ApplyTransform(rt, rt, m);
  4322. this.x = mathMin(lt[0], rb[0], lb[0], rt[0]);
  4323. this.y = mathMin(lt[1], rb[1], lb[1], rt[1]);
  4324. var maxX = mathMax(lt[0], rb[0], lb[0], rt[0]);
  4325. var maxY = mathMax(lt[1], rb[1], lb[1], rt[1]);
  4326. this.width = maxX - this.x;
  4327. this.height = maxY - this.y;
  4328. };
  4329. })(),
  4330. /**
  4331. * Calculate matrix of transforming from self to target rect
  4332. * @param {module:zrender/core/BoundingRect} b
  4333. * @return {Array.<number>}
  4334. */
  4335. calculateTransform: function (b) {
  4336. var a = this;
  4337. var sx = b.width / a.width;
  4338. var sy = b.height / a.height;
  4339. var m = create$1();
  4340. // 矩阵右乘
  4341. translate(m, m, [-a.x, -a.y]);
  4342. scale$1(m, m, [sx, sy]);
  4343. translate(m, m, [b.x, b.y]);
  4344. return m;
  4345. },
  4346. /**
  4347. * @param {(module:echarts/core/BoundingRect|Object)} b
  4348. * @return {boolean}
  4349. */
  4350. intersect: function (b) {
  4351. if (!b) {
  4352. return false;
  4353. }
  4354. if (!(b instanceof BoundingRect)) {
  4355. // Normalize negative width/height.
  4356. b = BoundingRect.create(b);
  4357. }
  4358. var a = this;
  4359. var ax0 = a.x;
  4360. var ax1 = a.x + a.width;
  4361. var ay0 = a.y;
  4362. var ay1 = a.y + a.height;
  4363. var bx0 = b.x;
  4364. var bx1 = b.x + b.width;
  4365. var by0 = b.y;
  4366. var by1 = b.y + b.height;
  4367. return ! (ax1 < bx0 || bx1 < ax0 || ay1 < by0 || by1 < ay0);
  4368. },
  4369. contain: function (x, y) {
  4370. var rect = this;
  4371. return x >= rect.x
  4372. && x <= (rect.x + rect.width)
  4373. && y >= rect.y
  4374. && y <= (rect.y + rect.height);
  4375. },
  4376. /**
  4377. * @return {module:echarts/core/BoundingRect}
  4378. */
  4379. clone: function () {
  4380. return new BoundingRect(this.x, this.y, this.width, this.height);
  4381. },
  4382. /**
  4383. * Copy from another rect
  4384. */
  4385. copy: function (other) {
  4386. this.x = other.x;
  4387. this.y = other.y;
  4388. this.width = other.width;
  4389. this.height = other.height;
  4390. },
  4391. plain: function () {
  4392. return {
  4393. x: this.x,
  4394. y: this.y,
  4395. width: this.width,
  4396. height: this.height
  4397. };
  4398. }
  4399. };
  4400. /**
  4401. * @param {Object|module:zrender/core/BoundingRect} rect
  4402. * @param {number} rect.x
  4403. * @param {number} rect.y
  4404. * @param {number} rect.width
  4405. * @param {number} rect.height
  4406. * @return {module:zrender/core/BoundingRect}
  4407. */
  4408. BoundingRect.create = function (rect) {
  4409. return new BoundingRect(rect.x, rect.y, rect.width, rect.height);
  4410. };
  4411. /**
  4412. * Group是一个容器,可以插入子节点,Group的变换也会被应用到子节点上
  4413. * @module zrender/graphic/Group
  4414. * @example
  4415. * var Group = require('zrender/container/Group');
  4416. * var Circle = require('zrender/graphic/shape/Circle');
  4417. * var g = new Group();
  4418. * g.position[0] = 100;
  4419. * g.position[1] = 100;
  4420. * g.add(new Circle({
  4421. * style: {
  4422. * x: 100,
  4423. * y: 100,
  4424. * r: 20,
  4425. * }
  4426. * }));
  4427. * zr.add(g);
  4428. */
  4429. /**
  4430. * @alias module:zrender/graphic/Group
  4431. * @constructor
  4432. * @extends module:zrender/mixin/Transformable
  4433. * @extends module:zrender/mixin/Eventful
  4434. */
  4435. var Group = function (opts) {
  4436. opts = opts || {};
  4437. Element.call(this, opts);
  4438. for (var key in opts) {
  4439. if (opts.hasOwnProperty(key)) {
  4440. this[key] = opts[key];
  4441. }
  4442. }
  4443. this._children = [];
  4444. this.__storage = null;
  4445. this.__dirty = true;
  4446. };
  4447. Group.prototype = {
  4448. constructor: Group,
  4449. isGroup: true,
  4450. /**
  4451. * @type {string}
  4452. */
  4453. type: 'group',
  4454. /**
  4455. * 所有子孙元素是否响应鼠标事件
  4456. * @name module:/zrender/container/Group#silent
  4457. * @type {boolean}
  4458. * @default false
  4459. */
  4460. silent: false,
  4461. /**
  4462. * @return {Array.<module:zrender/Element>}
  4463. */
  4464. children: function () {
  4465. return this._children.slice();
  4466. },
  4467. /**
  4468. * 获取指定 index 的儿子节点
  4469. * @param {number} idx
  4470. * @return {module:zrender/Element}
  4471. */
  4472. childAt: function (idx) {
  4473. return this._children[idx];
  4474. },
  4475. /**
  4476. * 获取指定名字的儿子节点
  4477. * @param {string} name
  4478. * @return {module:zrender/Element}
  4479. */
  4480. childOfName: function (name) {
  4481. var children = this._children;
  4482. for (var i = 0; i < children.length; i++) {
  4483. if (children[i].name === name) {
  4484. return children[i];
  4485. }
  4486. }
  4487. },
  4488. /**
  4489. * @return {number}
  4490. */
  4491. childCount: function () {
  4492. return this._children.length;
  4493. },
  4494. /**
  4495. * 添加子节点到最后
  4496. * @param {module:zrender/Element} child
  4497. */
  4498. add: function (child) {
  4499. if (child && child !== this && child.parent !== this) {
  4500. this._children.push(child);
  4501. this._doAdd(child);
  4502. }
  4503. return this;
  4504. },
  4505. /**
  4506. * 添加子节点在 nextSibling 之前
  4507. * @param {module:zrender/Element} child
  4508. * @param {module:zrender/Element} nextSibling
  4509. */
  4510. addBefore: function (child, nextSibling) {
  4511. if (child && child !== this && child.parent !== this
  4512. && nextSibling && nextSibling.parent === this) {
  4513. var children = this._children;
  4514. var idx = children.indexOf(nextSibling);
  4515. if (idx >= 0) {
  4516. children.splice(idx, 0, child);
  4517. this._doAdd(child);
  4518. }
  4519. }
  4520. return this;
  4521. },
  4522. _doAdd: function (child) {
  4523. if (child.parent) {
  4524. child.parent.remove(child);
  4525. }
  4526. child.parent = this;
  4527. var storage = this.__storage;
  4528. var zr = this.__zr;
  4529. if (storage && storage !== child.__storage) {
  4530. storage.addToStorage(child);
  4531. if (child instanceof Group) {
  4532. child.addChildrenToStorage(storage);
  4533. }
  4534. }
  4535. zr && zr.refresh();
  4536. },
  4537. /**
  4538. * 移除子节点
  4539. * @param {module:zrender/Element} child
  4540. */
  4541. remove: function (child) {
  4542. var zr = this.__zr;
  4543. var storage = this.__storage;
  4544. var children = this._children;
  4545. var idx = indexOf(children, child);
  4546. if (idx < 0) {
  4547. return this;
  4548. }
  4549. children.splice(idx, 1);
  4550. child.parent = null;
  4551. if (storage) {
  4552. storage.delFromStorage(child);
  4553. if (child instanceof Group) {
  4554. child.delChildrenFromStorage(storage);
  4555. }
  4556. }
  4557. zr && zr.refresh();
  4558. return this;
  4559. },
  4560. /**
  4561. * 移除所有子节点
  4562. */
  4563. removeAll: function () {
  4564. var children = this._children;
  4565. var storage = this.__storage;
  4566. var child;
  4567. var i;
  4568. for (i = 0; i < children.length; i++) {
  4569. child = children[i];
  4570. if (storage) {
  4571. storage.delFromStorage(child);
  4572. if (child instanceof Group) {
  4573. child.delChildrenFromStorage(storage);
  4574. }
  4575. }
  4576. child.parent = null;
  4577. }
  4578. children.length = 0;
  4579. return this;
  4580. },
  4581. /**
  4582. * 遍历所有子节点
  4583. * @param {Function} cb
  4584. * @param {} context
  4585. */
  4586. eachChild: function (cb, context) {
  4587. var children = this._children;
  4588. for (var i = 0; i < children.length; i++) {
  4589. var child = children[i];
  4590. cb.call(context, child, i);
  4591. }
  4592. return this;
  4593. },
  4594. /**
  4595. * 深度优先遍历所有子孙节点
  4596. * @param {Function} cb
  4597. * @param {} context
  4598. */
  4599. traverse: function (cb, context) {
  4600. for (var i = 0; i < this._children.length; i++) {
  4601. var child = this._children[i];
  4602. cb.call(context, child);
  4603. if (child.type === 'group') {
  4604. child.traverse(cb, context);
  4605. }
  4606. }
  4607. return this;
  4608. },
  4609. addChildrenToStorage: function (storage) {
  4610. for (var i = 0; i < this._children.length; i++) {
  4611. var child = this._children[i];
  4612. storage.addToStorage(child);
  4613. if (child instanceof Group) {
  4614. child.addChildrenToStorage(storage);
  4615. }
  4616. }
  4617. },
  4618. delChildrenFromStorage: function (storage) {
  4619. for (var i = 0; i < this._children.length; i++) {
  4620. var child = this._children[i];
  4621. storage.delFromStorage(child);
  4622. if (child instanceof Group) {
  4623. child.delChildrenFromStorage(storage);
  4624. }
  4625. }
  4626. },
  4627. dirty: function () {
  4628. this.__dirty = true;
  4629. this.__zr && this.__zr.refresh();
  4630. return this;
  4631. },
  4632. /**
  4633. * @return {module:zrender/core/BoundingRect}
  4634. */
  4635. getBoundingRect: function (includeChildren) {
  4636. // TODO Caching
  4637. var rect = null;
  4638. var tmpRect = new BoundingRect(0, 0, 0, 0);
  4639. var children = includeChildren || this._children;
  4640. var tmpMat = [];
  4641. for (var i = 0; i < children.length; i++) {
  4642. var child = children[i];
  4643. if (child.ignore || child.invisible) {
  4644. continue;
  4645. }
  4646. var childRect = child.getBoundingRect();
  4647. var transform = child.getLocalTransform(tmpMat);
  4648. // TODO
  4649. // The boundingRect cacluated by transforming original
  4650. // rect may be bigger than the actual bundingRect when rotation
  4651. // is used. (Consider a circle rotated aginst its center, where
  4652. // the actual boundingRect should be the same as that not be
  4653. // rotated.) But we can not find better approach to calculate
  4654. // actual boundingRect yet, considering performance.
  4655. if (transform) {
  4656. tmpRect.copy(childRect);
  4657. tmpRect.applyTransform(transform);
  4658. rect = rect || tmpRect.clone();
  4659. rect.union(tmpRect);
  4660. }
  4661. else {
  4662. rect = rect || childRect.clone();
  4663. rect.union(childRect);
  4664. }
  4665. }
  4666. return rect || tmpRect;
  4667. }
  4668. };
  4669. inherits(Group, Element);
  4670. // https://github.com/mziccard/node-timsort
  4671. var DEFAULT_MIN_MERGE = 32;
  4672. var DEFAULT_MIN_GALLOPING = 7;
  4673. function minRunLength(n) {
  4674. var r = 0;
  4675. while (n >= DEFAULT_MIN_MERGE) {
  4676. r |= n & 1;
  4677. n >>= 1;
  4678. }
  4679. return n + r;
  4680. }
  4681. function makeAscendingRun(array, lo, hi, compare) {
  4682. var runHi = lo + 1;
  4683. if (runHi === hi) {
  4684. return 1;
  4685. }
  4686. if (compare(array[runHi++], array[lo]) < 0) {
  4687. while (runHi < hi && compare(array[runHi], array[runHi - 1]) < 0) {
  4688. runHi++;
  4689. }
  4690. reverseRun(array, lo, runHi);
  4691. }
  4692. else {
  4693. while (runHi < hi && compare(array[runHi], array[runHi - 1]) >= 0) {
  4694. runHi++;
  4695. }
  4696. }
  4697. return runHi - lo;
  4698. }
  4699. function reverseRun(array, lo, hi) {
  4700. hi--;
  4701. while (lo < hi) {
  4702. var t = array[lo];
  4703. array[lo++] = array[hi];
  4704. array[hi--] = t;
  4705. }
  4706. }
  4707. function binaryInsertionSort(array, lo, hi, start, compare) {
  4708. if (start === lo) {
  4709. start++;
  4710. }
  4711. for (; start < hi; start++) {
  4712. var pivot = array[start];
  4713. var left = lo;
  4714. var right = start;
  4715. var mid;
  4716. while (left < right) {
  4717. mid = left + right >>> 1;
  4718. if (compare(pivot, array[mid]) < 0) {
  4719. right = mid;
  4720. }
  4721. else {
  4722. left = mid + 1;
  4723. }
  4724. }
  4725. var n = start - left;
  4726. switch (n) {
  4727. case 3:
  4728. array[left + 3] = array[left + 2];
  4729. case 2:
  4730. array[left + 2] = array[left + 1];
  4731. case 1:
  4732. array[left + 1] = array[left];
  4733. break;
  4734. default:
  4735. while (n > 0) {
  4736. array[left + n] = array[left + n - 1];
  4737. n--;
  4738. }
  4739. }
  4740. array[left] = pivot;
  4741. }
  4742. }
  4743. function gallopLeft(value, array, start, length, hint, compare) {
  4744. var lastOffset = 0;
  4745. var maxOffset = 0;
  4746. var offset = 1;
  4747. if (compare(value, array[start + hint]) > 0) {
  4748. maxOffset = length - hint;
  4749. while (offset < maxOffset && compare(value, array[start + hint + offset]) > 0) {
  4750. lastOffset = offset;
  4751. offset = (offset << 1) + 1;
  4752. if (offset <= 0) {
  4753. offset = maxOffset;
  4754. }
  4755. }
  4756. if (offset > maxOffset) {
  4757. offset = maxOffset;
  4758. }
  4759. lastOffset += hint;
  4760. offset += hint;
  4761. }
  4762. else {
  4763. maxOffset = hint + 1;
  4764. while (offset < maxOffset && compare(value, array[start + hint - offset]) <= 0) {
  4765. lastOffset = offset;
  4766. offset = (offset << 1) + 1;
  4767. if (offset <= 0) {
  4768. offset = maxOffset;
  4769. }
  4770. }
  4771. if (offset > maxOffset) {
  4772. offset = maxOffset;
  4773. }
  4774. var tmp = lastOffset;
  4775. lastOffset = hint - offset;
  4776. offset = hint - tmp;
  4777. }
  4778. lastOffset++;
  4779. while (lastOffset < offset) {
  4780. var m = lastOffset + (offset - lastOffset >>> 1);
  4781. if (compare(value, array[start + m]) > 0) {
  4782. lastOffset = m + 1;
  4783. }
  4784. else {
  4785. offset = m;
  4786. }
  4787. }
  4788. return offset;
  4789. }
  4790. function gallopRight(value, array, start, length, hint, compare) {
  4791. var lastOffset = 0;
  4792. var maxOffset = 0;
  4793. var offset = 1;
  4794. if (compare(value, array[start + hint]) < 0) {
  4795. maxOffset = hint + 1;
  4796. while (offset < maxOffset && compare(value, array[start + hint - offset]) < 0) {
  4797. lastOffset = offset;
  4798. offset = (offset << 1) + 1;
  4799. if (offset <= 0) {
  4800. offset = maxOffset;
  4801. }
  4802. }
  4803. if (offset > maxOffset) {
  4804. offset = maxOffset;
  4805. }
  4806. var tmp = lastOffset;
  4807. lastOffset = hint - offset;
  4808. offset = hint - tmp;
  4809. }
  4810. else {
  4811. maxOffset = length - hint;
  4812. while (offset < maxOffset && compare(value, array[start + hint + offset]) >= 0) {
  4813. lastOffset = offset;
  4814. offset = (offset << 1) + 1;
  4815. if (offset <= 0) {
  4816. offset = maxOffset;
  4817. }
  4818. }
  4819. if (offset > maxOffset) {
  4820. offset = maxOffset;
  4821. }
  4822. lastOffset += hint;
  4823. offset += hint;
  4824. }
  4825. lastOffset++;
  4826. while (lastOffset < offset) {
  4827. var m = lastOffset + (offset - lastOffset >>> 1);
  4828. if (compare(value, array[start + m]) < 0) {
  4829. offset = m;
  4830. }
  4831. else {
  4832. lastOffset = m + 1;
  4833. }
  4834. }
  4835. return offset;
  4836. }
  4837. function TimSort(array, compare) {
  4838. var minGallop = DEFAULT_MIN_GALLOPING;
  4839. var runStart;
  4840. var runLength;
  4841. var stackSize = 0;
  4842. var tmp = [];
  4843. runStart = [];
  4844. runLength = [];
  4845. function pushRun(_runStart, _runLength) {
  4846. runStart[stackSize] = _runStart;
  4847. runLength[stackSize] = _runLength;
  4848. stackSize += 1;
  4849. }
  4850. function mergeRuns() {
  4851. while (stackSize > 1) {
  4852. var n = stackSize - 2;
  4853. if (n >= 1 && runLength[n - 1] <= runLength[n] + runLength[n + 1] || n >= 2 && runLength[n - 2] <= runLength[n] + runLength[n - 1]) {
  4854. if (runLength[n - 1] < runLength[n + 1]) {
  4855. n--;
  4856. }
  4857. }
  4858. else if (runLength[n] > runLength[n + 1]) {
  4859. break;
  4860. }
  4861. mergeAt(n);
  4862. }
  4863. }
  4864. function forceMergeRuns() {
  4865. while (stackSize > 1) {
  4866. var n = stackSize - 2;
  4867. if (n > 0 && runLength[n - 1] < runLength[n + 1]) {
  4868. n--;
  4869. }
  4870. mergeAt(n);
  4871. }
  4872. }
  4873. function mergeAt(i) {
  4874. var start1 = runStart[i];
  4875. var length1 = runLength[i];
  4876. var start2 = runStart[i + 1];
  4877. var length2 = runLength[i + 1];
  4878. runLength[i] = length1 + length2;
  4879. if (i === stackSize - 3) {
  4880. runStart[i + 1] = runStart[i + 2];
  4881. runLength[i + 1] = runLength[i + 2];
  4882. }
  4883. stackSize--;
  4884. var k = gallopRight(array[start2], array, start1, length1, 0, compare);
  4885. start1 += k;
  4886. length1 -= k;
  4887. if (length1 === 0) {
  4888. return;
  4889. }
  4890. length2 = gallopLeft(array[start1 + length1 - 1], array, start2, length2, length2 - 1, compare);
  4891. if (length2 === 0) {
  4892. return;
  4893. }
  4894. if (length1 <= length2) {
  4895. mergeLow(start1, length1, start2, length2);
  4896. }
  4897. else {
  4898. mergeHigh(start1, length1, start2, length2);
  4899. }
  4900. }
  4901. function mergeLow(start1, length1, start2, length2) {
  4902. var i = 0;
  4903. for (i = 0; i < length1; i++) {
  4904. tmp[i] = array[start1 + i];
  4905. }
  4906. var cursor1 = 0;
  4907. var cursor2 = start2;
  4908. var dest = start1;
  4909. array[dest++] = array[cursor2++];
  4910. if (--length2 === 0) {
  4911. for (i = 0; i < length1; i++) {
  4912. array[dest + i] = tmp[cursor1 + i];
  4913. }
  4914. return;
  4915. }
  4916. if (length1 === 1) {
  4917. for (i = 0; i < length2; i++) {
  4918. array[dest + i] = array[cursor2 + i];
  4919. }
  4920. array[dest + length2] = tmp[cursor1];
  4921. return;
  4922. }
  4923. var _minGallop = minGallop;
  4924. var count1, count2, exit;
  4925. while (1) {
  4926. count1 = 0;
  4927. count2 = 0;
  4928. exit = false;
  4929. do {
  4930. if (compare(array[cursor2], tmp[cursor1]) < 0) {
  4931. array[dest++] = array[cursor2++];
  4932. count2++;
  4933. count1 = 0;
  4934. if (--length2 === 0) {
  4935. exit = true;
  4936. break;
  4937. }
  4938. }
  4939. else {
  4940. array[dest++] = tmp[cursor1++];
  4941. count1++;
  4942. count2 = 0;
  4943. if (--length1 === 1) {
  4944. exit = true;
  4945. break;
  4946. }
  4947. }
  4948. } while ((count1 | count2) < _minGallop);
  4949. if (exit) {
  4950. break;
  4951. }
  4952. do {
  4953. count1 = gallopRight(array[cursor2], tmp, cursor1, length1, 0, compare);
  4954. if (count1 !== 0) {
  4955. for (i = 0; i < count1; i++) {
  4956. array[dest + i] = tmp[cursor1 + i];
  4957. }
  4958. dest += count1;
  4959. cursor1 += count1;
  4960. length1 -= count1;
  4961. if (length1 <= 1) {
  4962. exit = true;
  4963. break;
  4964. }
  4965. }
  4966. array[dest++] = array[cursor2++];
  4967. if (--length2 === 0) {
  4968. exit = true;
  4969. break;
  4970. }
  4971. count2 = gallopLeft(tmp[cursor1], array, cursor2, length2, 0, compare);
  4972. if (count2 !== 0) {
  4973. for (i = 0; i < count2; i++) {
  4974. array[dest + i] = array[cursor2 + i];
  4975. }
  4976. dest += count2;
  4977. cursor2 += count2;
  4978. length2 -= count2;
  4979. if (length2 === 0) {
  4980. exit = true;
  4981. break;
  4982. }
  4983. }
  4984. array[dest++] = tmp[cursor1++];
  4985. if (--length1 === 1) {
  4986. exit = true;
  4987. break;
  4988. }
  4989. _minGallop--;
  4990. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  4991. if (exit) {
  4992. break;
  4993. }
  4994. if (_minGallop < 0) {
  4995. _minGallop = 0;
  4996. }
  4997. _minGallop += 2;
  4998. }
  4999. minGallop = _minGallop;
  5000. minGallop < 1 && (minGallop = 1);
  5001. if (length1 === 1) {
  5002. for (i = 0; i < length2; i++) {
  5003. array[dest + i] = array[cursor2 + i];
  5004. }
  5005. array[dest + length2] = tmp[cursor1];
  5006. }
  5007. else if (length1 === 0) {
  5008. throw new Error();
  5009. // throw new Error('mergeLow preconditions were not respected');
  5010. }
  5011. else {
  5012. for (i = 0; i < length1; i++) {
  5013. array[dest + i] = tmp[cursor1 + i];
  5014. }
  5015. }
  5016. }
  5017. function mergeHigh (start1, length1, start2, length2) {
  5018. var i = 0;
  5019. for (i = 0; i < length2; i++) {
  5020. tmp[i] = array[start2 + i];
  5021. }
  5022. var cursor1 = start1 + length1 - 1;
  5023. var cursor2 = length2 - 1;
  5024. var dest = start2 + length2 - 1;
  5025. var customCursor = 0;
  5026. var customDest = 0;
  5027. array[dest--] = array[cursor1--];
  5028. if (--length1 === 0) {
  5029. customCursor = dest - (length2 - 1);
  5030. for (i = 0; i < length2; i++) {
  5031. array[customCursor + i] = tmp[i];
  5032. }
  5033. return;
  5034. }
  5035. if (length2 === 1) {
  5036. dest -= length1;
  5037. cursor1 -= length1;
  5038. customDest = dest + 1;
  5039. customCursor = cursor1 + 1;
  5040. for (i = length1 - 1; i >= 0; i--) {
  5041. array[customDest + i] = array[customCursor + i];
  5042. }
  5043. array[dest] = tmp[cursor2];
  5044. return;
  5045. }
  5046. var _minGallop = minGallop;
  5047. while (true) {
  5048. var count1 = 0;
  5049. var count2 = 0;
  5050. var exit = false;
  5051. do {
  5052. if (compare(tmp[cursor2], array[cursor1]) < 0) {
  5053. array[dest--] = array[cursor1--];
  5054. count1++;
  5055. count2 = 0;
  5056. if (--length1 === 0) {
  5057. exit = true;
  5058. break;
  5059. }
  5060. }
  5061. else {
  5062. array[dest--] = tmp[cursor2--];
  5063. count2++;
  5064. count1 = 0;
  5065. if (--length2 === 1) {
  5066. exit = true;
  5067. break;
  5068. }
  5069. }
  5070. } while ((count1 | count2) < _minGallop);
  5071. if (exit) {
  5072. break;
  5073. }
  5074. do {
  5075. count1 = length1 - gallopRight(tmp[cursor2], array, start1, length1, length1 - 1, compare);
  5076. if (count1 !== 0) {
  5077. dest -= count1;
  5078. cursor1 -= count1;
  5079. length1 -= count1;
  5080. customDest = dest + 1;
  5081. customCursor = cursor1 + 1;
  5082. for (i = count1 - 1; i >= 0; i--) {
  5083. array[customDest + i] = array[customCursor + i];
  5084. }
  5085. if (length1 === 0) {
  5086. exit = true;
  5087. break;
  5088. }
  5089. }
  5090. array[dest--] = tmp[cursor2--];
  5091. if (--length2 === 1) {
  5092. exit = true;
  5093. break;
  5094. }
  5095. count2 = length2 - gallopLeft(array[cursor1], tmp, 0, length2, length2 - 1, compare);
  5096. if (count2 !== 0) {
  5097. dest -= count2;
  5098. cursor2 -= count2;
  5099. length2 -= count2;
  5100. customDest = dest + 1;
  5101. customCursor = cursor2 + 1;
  5102. for (i = 0; i < count2; i++) {
  5103. array[customDest + i] = tmp[customCursor + i];
  5104. }
  5105. if (length2 <= 1) {
  5106. exit = true;
  5107. break;
  5108. }
  5109. }
  5110. array[dest--] = array[cursor1--];
  5111. if (--length1 === 0) {
  5112. exit = true;
  5113. break;
  5114. }
  5115. _minGallop--;
  5116. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  5117. if (exit) {
  5118. break;
  5119. }
  5120. if (_minGallop < 0) {
  5121. _minGallop = 0;
  5122. }
  5123. _minGallop += 2;
  5124. }
  5125. minGallop = _minGallop;
  5126. if (minGallop < 1) {
  5127. minGallop = 1;
  5128. }
  5129. if (length2 === 1) {
  5130. dest -= length1;
  5131. cursor1 -= length1;
  5132. customDest = dest + 1;
  5133. customCursor = cursor1 + 1;
  5134. for (i = length1 - 1; i >= 0; i--) {
  5135. array[customDest + i] = array[customCursor + i];
  5136. }
  5137. array[dest] = tmp[cursor2];
  5138. }
  5139. else if (length2 === 0) {
  5140. throw new Error();
  5141. // throw new Error('mergeHigh preconditions were not respected');
  5142. }
  5143. else {
  5144. customCursor = dest - (length2 - 1);
  5145. for (i = 0; i < length2; i++) {
  5146. array[customCursor + i] = tmp[i];
  5147. }
  5148. }
  5149. }
  5150. this.mergeRuns = mergeRuns;
  5151. this.forceMergeRuns = forceMergeRuns;
  5152. this.pushRun = pushRun;
  5153. }
  5154. function sort(array, compare, lo, hi) {
  5155. if (!lo) {
  5156. lo = 0;
  5157. }
  5158. if (!hi) {
  5159. hi = array.length;
  5160. }
  5161. var remaining = hi - lo;
  5162. if (remaining < 2) {
  5163. return;
  5164. }
  5165. var runLength = 0;
  5166. if (remaining < DEFAULT_MIN_MERGE) {
  5167. runLength = makeAscendingRun(array, lo, hi, compare);
  5168. binaryInsertionSort(array, lo, hi, lo + runLength, compare);
  5169. return;
  5170. }
  5171. var ts = new TimSort(array, compare);
  5172. var minRun = minRunLength(remaining);
  5173. do {
  5174. runLength = makeAscendingRun(array, lo, hi, compare);
  5175. if (runLength < minRun) {
  5176. var force = remaining;
  5177. if (force > minRun) {
  5178. force = minRun;
  5179. }
  5180. binaryInsertionSort(array, lo, lo + force, lo + runLength, compare);
  5181. runLength = force;
  5182. }
  5183. ts.pushRun(lo, runLength);
  5184. ts.mergeRuns();
  5185. remaining -= runLength;
  5186. lo += runLength;
  5187. } while (remaining !== 0);
  5188. ts.forceMergeRuns();
  5189. }
  5190. // Use timsort because in most case elements are partially sorted
  5191. // https://jsfiddle.net/pissang/jr4x7mdm/8/
  5192. function shapeCompareFunc(a, b) {
  5193. if (a.zlevel === b.zlevel) {
  5194. if (a.z === b.z) {
  5195. // if (a.z2 === b.z2) {
  5196. // // FIXME Slow has renderidx compare
  5197. // // http://stackoverflow.com/questions/20883421/sorting-in-javascript-should-every-compare-function-have-a-return-0-statement
  5198. // // https://github.com/v8/v8/blob/47cce544a31ed5577ffe2963f67acb4144ee0232/src/js/array.js#L1012
  5199. // return a.__renderidx - b.__renderidx;
  5200. // }
  5201. return a.z2 - b.z2;
  5202. }
  5203. return a.z - b.z;
  5204. }
  5205. return a.zlevel - b.zlevel;
  5206. }
  5207. /**
  5208. * 内容仓库 (M)
  5209. * @alias module:zrender/Storage
  5210. * @constructor
  5211. */
  5212. var Storage = function () { // jshint ignore:line
  5213. this._roots = [];
  5214. this._displayList = [];
  5215. this._displayListLen = 0;
  5216. };
  5217. Storage.prototype = {
  5218. constructor: Storage,
  5219. /**
  5220. * @param {Function} cb
  5221. *
  5222. */
  5223. traverse: function (cb, context) {
  5224. for (var i = 0; i < this._roots.length; i++) {
  5225. this._roots[i].traverse(cb, context);
  5226. }
  5227. },
  5228. /**
  5229. * 返回所有图形的绘制队列
  5230. * @param {boolean} [update=false] 是否在返回前更新该数组
  5231. * @param {boolean} [includeIgnore=false] 是否包含 ignore 的数组, 在 update 为 true 的时候有效
  5232. *
  5233. * 详见{@link module:zrender/graphic/Displayable.prototype.updateDisplayList}
  5234. * @return {Array.<module:zrender/graphic/Displayable>}
  5235. */
  5236. getDisplayList: function (update, includeIgnore) {
  5237. includeIgnore = includeIgnore || false;
  5238. if (update) {
  5239. this.updateDisplayList(includeIgnore);
  5240. }
  5241. return this._displayList;
  5242. },
  5243. /**
  5244. * 更新图形的绘制队列。
  5245. * 每次绘制前都会调用,该方法会先深度优先遍历整个树,更新所有Group和Shape的变换并且把所有可见的Shape保存到数组中,
  5246. * 最后根据绘制的优先级(zlevel > z > 插入顺序)排序得到绘制队列
  5247. * @param {boolean} [includeIgnore=false] 是否包含 ignore 的数组
  5248. */
  5249. updateDisplayList: function (includeIgnore) {
  5250. this._displayListLen = 0;
  5251. var roots = this._roots;
  5252. var displayList = this._displayList;
  5253. for (var i = 0, len = roots.length; i < len; i++) {
  5254. this._updateAndAddDisplayable(roots[i], null, includeIgnore);
  5255. }
  5256. displayList.length = this._displayListLen;
  5257. env$1.canvasSupported && sort(displayList, shapeCompareFunc);
  5258. },
  5259. _updateAndAddDisplayable: function (el, clipPaths, includeIgnore) {
  5260. if (el.ignore && !includeIgnore) {
  5261. return;
  5262. }
  5263. el.beforeUpdate();
  5264. if (el.__dirty) {
  5265. el.update();
  5266. }
  5267. el.afterUpdate();
  5268. var userSetClipPath = el.clipPath;
  5269. if (userSetClipPath) {
  5270. // FIXME 效率影响
  5271. if (clipPaths) {
  5272. clipPaths = clipPaths.slice();
  5273. }
  5274. else {
  5275. clipPaths = [];
  5276. }
  5277. var currentClipPath = userSetClipPath;
  5278. var parentClipPath = el;
  5279. // Recursively add clip path
  5280. while (currentClipPath) {
  5281. // clipPath 的变换是基于使用这个 clipPath 的元素
  5282. currentClipPath.parent = parentClipPath;
  5283. currentClipPath.updateTransform();
  5284. clipPaths.push(currentClipPath);
  5285. parentClipPath = currentClipPath;
  5286. currentClipPath = currentClipPath.clipPath;
  5287. }
  5288. }
  5289. if (el.isGroup) {
  5290. var children = el._children;
  5291. for (var i = 0; i < children.length; i++) {
  5292. var child = children[i];
  5293. // Force to mark as dirty if group is dirty
  5294. // FIXME __dirtyPath ?
  5295. if (el.__dirty) {
  5296. child.__dirty = true;
  5297. }
  5298. this._updateAndAddDisplayable(child, clipPaths, includeIgnore);
  5299. }
  5300. // Mark group clean here
  5301. el.__dirty = false;
  5302. }
  5303. else {
  5304. el.__clipPaths = clipPaths;
  5305. this._displayList[this._displayListLen++] = el;
  5306. }
  5307. },
  5308. /**
  5309. * 添加图形(Shape)或者组(Group)到根节点
  5310. * @param {module:zrender/Element} el
  5311. */
  5312. addRoot: function (el) {
  5313. if (el.__storage === this) {
  5314. return;
  5315. }
  5316. if (el instanceof Group) {
  5317. el.addChildrenToStorage(this);
  5318. }
  5319. this.addToStorage(el);
  5320. this._roots.push(el);
  5321. },
  5322. /**
  5323. * 删除指定的图形(Shape)或者组(Group)
  5324. * @param {string|Array.<string>} [el] 如果为空清空整个Storage
  5325. */
  5326. delRoot: function (el) {
  5327. if (el == null) {
  5328. // 不指定el清空
  5329. for (var i = 0; i < this._roots.length; i++) {
  5330. var root = this._roots[i];
  5331. if (root instanceof Group) {
  5332. root.delChildrenFromStorage(this);
  5333. }
  5334. }
  5335. this._roots = [];
  5336. this._displayList = [];
  5337. this._displayListLen = 0;
  5338. return;
  5339. }
  5340. if (el instanceof Array) {
  5341. for (var i = 0, l = el.length; i < l; i++) {
  5342. this.delRoot(el[i]);
  5343. }
  5344. return;
  5345. }
  5346. var idx = indexOf(this._roots, el);
  5347. if (idx >= 0) {
  5348. this.delFromStorage(el);
  5349. this._roots.splice(idx, 1);
  5350. if (el instanceof Group) {
  5351. el.delChildrenFromStorage(this);
  5352. }
  5353. }
  5354. },
  5355. addToStorage: function (el) {
  5356. if (el) {
  5357. el.__storage = this;
  5358. el.dirty(false);
  5359. }
  5360. return this;
  5361. },
  5362. delFromStorage: function (el) {
  5363. if (el) {
  5364. el.__storage = null;
  5365. }
  5366. return this;
  5367. },
  5368. /**
  5369. * 清空并且释放Storage
  5370. */
  5371. dispose: function () {
  5372. this._renderList =
  5373. this._roots = null;
  5374. },
  5375. displayableSortFunc: shapeCompareFunc
  5376. };
  5377. var SHADOW_PROPS = {
  5378. 'shadowBlur': 1,
  5379. 'shadowOffsetX': 1,
  5380. 'shadowOffsetY': 1,
  5381. 'textShadowBlur': 1,
  5382. 'textShadowOffsetX': 1,
  5383. 'textShadowOffsetY': 1,
  5384. 'textBoxShadowBlur': 1,
  5385. 'textBoxShadowOffsetX': 1,
  5386. 'textBoxShadowOffsetY': 1
  5387. };
  5388. var fixShadow = function (ctx, propName, value) {
  5389. if (SHADOW_PROPS.hasOwnProperty(propName)) {
  5390. return value *= ctx.dpr;
  5391. }
  5392. return value;
  5393. };
  5394. var STYLE_COMMON_PROPS = [
  5395. ['shadowBlur', 0], ['shadowOffsetX', 0], ['shadowOffsetY', 0], ['shadowColor', '#000'],
  5396. ['lineCap', 'butt'], ['lineJoin', 'miter'], ['miterLimit', 10]
  5397. ];
  5398. // var SHADOW_PROPS = STYLE_COMMON_PROPS.slice(0, 4);
  5399. // var LINE_PROPS = STYLE_COMMON_PROPS.slice(4);
  5400. var Style = function (opts, host) {
  5401. this.extendFrom(opts, false);
  5402. this.host = host;
  5403. };
  5404. function createLinearGradient(ctx, obj, rect) {
  5405. var x = obj.x == null ? 0 : obj.x;
  5406. var x2 = obj.x2 == null ? 1 : obj.x2;
  5407. var y = obj.y == null ? 0 : obj.y;
  5408. var y2 = obj.y2 == null ? 0 : obj.y2;
  5409. if (!obj.global) {
  5410. x = x * rect.width + rect.x;
  5411. x2 = x2 * rect.width + rect.x;
  5412. y = y * rect.height + rect.y;
  5413. y2 = y2 * rect.height + rect.y;
  5414. }
  5415. // Fix NaN when rect is Infinity
  5416. x = isNaN(x) ? 0 : x;
  5417. x2 = isNaN(x2) ? 1 : x2;
  5418. y = isNaN(y) ? 0 : y;
  5419. y2 = isNaN(y2) ? 0 : y2;
  5420. var canvasGradient = ctx.createLinearGradient(x, y, x2, y2);
  5421. return canvasGradient;
  5422. }
  5423. function createRadialGradient(ctx, obj, rect) {
  5424. var width = rect.width;
  5425. var height = rect.height;
  5426. var min = Math.min(width, height);
  5427. var x = obj.x == null ? 0.5 : obj.x;
  5428. var y = obj.y == null ? 0.5 : obj.y;
  5429. var r = obj.r == null ? 0.5 : obj.r;
  5430. if (!obj.global) {
  5431. x = x * width + rect.x;
  5432. y = y * height + rect.y;
  5433. r = r * min;
  5434. }
  5435. var canvasGradient = ctx.createRadialGradient(x, y, 0, x, y, r);
  5436. return canvasGradient;
  5437. }
  5438. Style.prototype = {
  5439. constructor: Style,
  5440. /**
  5441. * @type {module:zrender/graphic/Displayable}
  5442. */
  5443. host: null,
  5444. /**
  5445. * @type {string}
  5446. */
  5447. fill: '#000',
  5448. /**
  5449. * @type {string}
  5450. */
  5451. stroke: null,
  5452. /**
  5453. * @type {number}
  5454. */
  5455. opacity: 1,
  5456. /**
  5457. * @type {Array.<number>}
  5458. */
  5459. lineDash: null,
  5460. /**
  5461. * @type {number}
  5462. */
  5463. lineDashOffset: 0,
  5464. /**
  5465. * @type {number}
  5466. */
  5467. shadowBlur: 0,
  5468. /**
  5469. * @type {number}
  5470. */
  5471. shadowOffsetX: 0,
  5472. /**
  5473. * @type {number}
  5474. */
  5475. shadowOffsetY: 0,
  5476. /**
  5477. * @type {number}
  5478. */
  5479. lineWidth: 1,
  5480. /**
  5481. * If stroke ignore scale
  5482. * @type {Boolean}
  5483. */
  5484. strokeNoScale: false,
  5485. // Bounding rect text configuration
  5486. // Not affected by element transform
  5487. /**
  5488. * @type {string}
  5489. */
  5490. text: null,
  5491. /**
  5492. * If `fontSize` or `fontFamily` exists, `font` will be reset by
  5493. * `fontSize`, `fontStyle`, `fontWeight`, `fontFamily`.
  5494. * So do not visit it directly in upper application (like echarts),
  5495. * but use `contain/text#makeFont` instead.
  5496. * @type {string}
  5497. */
  5498. font: null,
  5499. /**
  5500. * The same as font. Use font please.
  5501. * @deprecated
  5502. * @type {string}
  5503. */
  5504. textFont: null,
  5505. /**
  5506. * It helps merging respectively, rather than parsing an entire font string.
  5507. * @type {string}
  5508. */
  5509. fontStyle: null,
  5510. /**
  5511. * It helps merging respectively, rather than parsing an entire font string.
  5512. * @type {string}
  5513. */
  5514. fontWeight: null,
  5515. /**
  5516. * It helps merging respectively, rather than parsing an entire font string.
  5517. * Should be 12 but not '12px'.
  5518. * @type {number}
  5519. */
  5520. fontSize: null,
  5521. /**
  5522. * It helps merging respectively, rather than parsing an entire font string.
  5523. * @type {string}
  5524. */
  5525. fontFamily: null,
  5526. /**
  5527. * Reserved for special functinality, like 'hr'.
  5528. * @type {string}
  5529. */
  5530. textTag: null,
  5531. /**
  5532. * @type {string}
  5533. */
  5534. textFill: '#000',
  5535. /**
  5536. * @type {string}
  5537. */
  5538. textStroke: null,
  5539. /**
  5540. * @type {number}
  5541. */
  5542. textWidth: null,
  5543. /**
  5544. * Only for textBackground.
  5545. * @type {number}
  5546. */
  5547. textHeight: null,
  5548. /**
  5549. * textStroke may be set as some color as a default
  5550. * value in upper applicaion, where the default value
  5551. * of textStrokeWidth should be 0 to make sure that
  5552. * user can choose to do not use text stroke.
  5553. * @type {number}
  5554. */
  5555. textStrokeWidth: 0,
  5556. /**
  5557. * @type {number}
  5558. */
  5559. textLineHeight: null,
  5560. /**
  5561. * 'inside', 'left', 'right', 'top', 'bottom'
  5562. * [x, y]
  5563. * Based on x, y of rect.
  5564. * @type {string|Array.<number>}
  5565. * @default 'inside'
  5566. */
  5567. textPosition: 'inside',
  5568. /**
  5569. * If not specified, use the boundingRect of a `displayable`.
  5570. * @type {Object}
  5571. */
  5572. textRect: null,
  5573. /**
  5574. * [x, y]
  5575. * @type {Array.<number>}
  5576. */
  5577. textOffset: null,
  5578. /**
  5579. * @type {string}
  5580. */
  5581. textAlign: null,
  5582. /**
  5583. * @type {string}
  5584. */
  5585. textVerticalAlign: null,
  5586. /**
  5587. * @type {number}
  5588. */
  5589. textDistance: 5,
  5590. /**
  5591. * @type {string}
  5592. */
  5593. textShadowColor: 'transparent',
  5594. /**
  5595. * @type {number}
  5596. */
  5597. textShadowBlur: 0,
  5598. /**
  5599. * @type {number}
  5600. */
  5601. textShadowOffsetX: 0,
  5602. /**
  5603. * @type {number}
  5604. */
  5605. textShadowOffsetY: 0,
  5606. /**
  5607. * @type {string}
  5608. */
  5609. textBoxShadowColor: 'transparent',
  5610. /**
  5611. * @type {number}
  5612. */
  5613. textBoxShadowBlur: 0,
  5614. /**
  5615. * @type {number}
  5616. */
  5617. textBoxShadowOffsetX: 0,
  5618. /**
  5619. * @type {number}
  5620. */
  5621. textBoxShadowOffsetY: 0,
  5622. /**
  5623. * Whether transform text.
  5624. * Only useful in Path and Image element
  5625. * @type {boolean}
  5626. */
  5627. transformText: false,
  5628. /**
  5629. * Text rotate around position of Path or Image
  5630. * Only useful in Path and Image element and transformText is false.
  5631. */
  5632. textRotation: 0,
  5633. /**
  5634. * Text origin of text rotation, like [10, 40].
  5635. * Based on x, y of rect.
  5636. * Useful in label rotation of circular symbol.
  5637. * By default, this origin is textPosition.
  5638. * Can be 'center'.
  5639. * @type {string|Array.<number>}
  5640. */
  5641. textOrigin: null,
  5642. /**
  5643. * @type {string}
  5644. */
  5645. textBackgroundColor: null,
  5646. /**
  5647. * @type {string}
  5648. */
  5649. textBorderColor: null,
  5650. /**
  5651. * @type {number}
  5652. */
  5653. textBorderWidth: 0,
  5654. /**
  5655. * @type {number}
  5656. */
  5657. textBorderRadius: 0,
  5658. /**
  5659. * Can be `2` or `[2, 4]` or `[2, 3, 4, 5]`
  5660. * @type {number|Array.<number>}
  5661. */
  5662. textPadding: null,
  5663. /**
  5664. * Text styles for rich text.
  5665. * @type {Object}
  5666. */
  5667. rich: null,
  5668. /**
  5669. * {outerWidth, outerHeight, ellipsis, placeholder}
  5670. * @type {Object}
  5671. */
  5672. truncate: null,
  5673. /**
  5674. * https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  5675. * @type {string}
  5676. */
  5677. blend: null,
  5678. /**
  5679. * @param {CanvasRenderingContext2D} ctx
  5680. */
  5681. bind: function (ctx, el, prevEl) {
  5682. var style = this;
  5683. var prevStyle = prevEl && prevEl.style;
  5684. var firstDraw = !prevStyle;
  5685. for (var i = 0; i < STYLE_COMMON_PROPS.length; i++) {
  5686. var prop = STYLE_COMMON_PROPS[i];
  5687. var styleName = prop[0];
  5688. if (firstDraw || style[styleName] !== prevStyle[styleName]) {
  5689. // FIXME Invalid property value will cause style leak from previous element.
  5690. ctx[styleName] =
  5691. fixShadow(ctx, styleName, style[styleName] || prop[1]);
  5692. }
  5693. }
  5694. if ((firstDraw || style.fill !== prevStyle.fill)) {
  5695. ctx.fillStyle = style.fill;
  5696. }
  5697. if ((firstDraw || style.stroke !== prevStyle.stroke)) {
  5698. ctx.strokeStyle = style.stroke;
  5699. }
  5700. if ((firstDraw || style.opacity !== prevStyle.opacity)) {
  5701. ctx.globalAlpha = style.opacity == null ? 1 : style.opacity;
  5702. }
  5703. if ((firstDraw || style.blend !== prevStyle.blend)) {
  5704. ctx.globalCompositeOperation = style.blend || 'source-over';
  5705. }
  5706. if (this.hasStroke()) {
  5707. var lineWidth = style.lineWidth;
  5708. ctx.lineWidth = lineWidth / (
  5709. (this.strokeNoScale && el && el.getLineScale) ? el.getLineScale() : 1
  5710. );
  5711. }
  5712. },
  5713. hasFill: function () {
  5714. var fill = this.fill;
  5715. return fill != null && fill !== 'none';
  5716. },
  5717. hasStroke: function () {
  5718. var stroke = this.stroke;
  5719. return stroke != null && stroke !== 'none' && this.lineWidth > 0;
  5720. },
  5721. /**
  5722. * Extend from other style
  5723. * @param {zrender/graphic/Style} otherStyle
  5724. * @param {boolean} overwrite true: overwrirte any way.
  5725. * false: overwrite only when !target.hasOwnProperty
  5726. * others: overwrite when property is not null/undefined.
  5727. */
  5728. extendFrom: function (otherStyle, overwrite) {
  5729. if (otherStyle) {
  5730. for (var name in otherStyle) {
  5731. if (otherStyle.hasOwnProperty(name)
  5732. && (overwrite === true
  5733. || (
  5734. overwrite === false
  5735. ? !this.hasOwnProperty(name)
  5736. : otherStyle[name] != null
  5737. )
  5738. )
  5739. ) {
  5740. this[name] = otherStyle[name];
  5741. }
  5742. }
  5743. }
  5744. },
  5745. /**
  5746. * Batch setting style with a given object
  5747. * @param {Object|string} obj
  5748. * @param {*} [obj]
  5749. */
  5750. set: function (obj, value) {
  5751. if (typeof obj === 'string') {
  5752. this[obj] = value;
  5753. }
  5754. else {
  5755. this.extendFrom(obj, true);
  5756. }
  5757. },
  5758. /**
  5759. * Clone
  5760. * @return {zrender/graphic/Style} [description]
  5761. */
  5762. clone: function () {
  5763. var newStyle = new this.constructor();
  5764. newStyle.extendFrom(this, true);
  5765. return newStyle;
  5766. },
  5767. getGradient: function (ctx, obj, rect) {
  5768. var method = obj.type === 'radial' ? createRadialGradient : createLinearGradient;
  5769. var canvasGradient = method(ctx, obj, rect);
  5770. var colorStops = obj.colorStops;
  5771. for (var i = 0; i < colorStops.length; i++) {
  5772. canvasGradient.addColorStop(
  5773. colorStops[i].offset, colorStops[i].color
  5774. );
  5775. }
  5776. return canvasGradient;
  5777. }
  5778. };
  5779. var styleProto = Style.prototype;
  5780. for (var i = 0; i < STYLE_COMMON_PROPS.length; i++) {
  5781. var prop = STYLE_COMMON_PROPS[i];
  5782. if (!(prop[0] in styleProto)) {
  5783. styleProto[prop[0]] = prop[1];
  5784. }
  5785. }
  5786. // Provide for others
  5787. Style.getGradient = styleProto.getGradient;
  5788. var Pattern = function (image, repeat) {
  5789. // Should do nothing more in this constructor. Because gradient can be
  5790. // declard by `color: {image: ...}`, where this constructor will not be called.
  5791. this.image = image;
  5792. this.repeat = repeat;
  5793. // Can be cloned
  5794. this.type = 'pattern';
  5795. };
  5796. Pattern.prototype.getCanvasPattern = function (ctx) {
  5797. return ctx.createPattern(this.image, this.repeat || 'repeat');
  5798. };
  5799. /**
  5800. * @module zrender/Layer
  5801. * @author pissang(https://www.github.com/pissang)
  5802. */
  5803. function returnFalse() {
  5804. return false;
  5805. }
  5806. /**
  5807. * 创建dom
  5808. *
  5809. * @inner
  5810. * @param {string} id dom id 待用
  5811. * @param {Painter} painter painter instance
  5812. * @param {number} number
  5813. */
  5814. function createDom(id, painter, dpr) {
  5815. var newDom = createCanvas();
  5816. var width = painter.getWidth();
  5817. var height = painter.getHeight();
  5818. var newDomStyle = newDom.style;
  5819. if (newDomStyle) { // In node or some other non-browser environment
  5820. newDomStyle.position = 'absolute';
  5821. newDomStyle.left = 0;
  5822. newDomStyle.top = 0;
  5823. newDomStyle.width = width + 'px';
  5824. newDomStyle.height = height + 'px';
  5825. newDom.setAttribute('data-zr-dom-id', id);
  5826. }
  5827. newDom.width = width * dpr;
  5828. newDom.height = height * dpr;
  5829. return newDom;
  5830. }
  5831. /**
  5832. * @alias module:zrender/Layer
  5833. * @constructor
  5834. * @extends module:zrender/mixin/Transformable
  5835. * @param {string} id
  5836. * @param {module:zrender/Painter} painter
  5837. * @param {number} [dpr]
  5838. */
  5839. var Layer = function(id, painter, dpr) {
  5840. var dom;
  5841. dpr = dpr || devicePixelRatio;
  5842. if (typeof id === 'string') {
  5843. dom = createDom(id, painter, dpr);
  5844. }
  5845. // Not using isDom because in node it will return false
  5846. else if (isObject$1(id)) {
  5847. dom = id;
  5848. id = dom.id;
  5849. }
  5850. this.id = id;
  5851. this.dom = dom;
  5852. var domStyle = dom.style;
  5853. if (domStyle) { // Not in node
  5854. dom.onselectstart = returnFalse; // 避免页面选中的尴尬
  5855. domStyle['-webkit-user-select'] = 'none';
  5856. domStyle['user-select'] = 'none';
  5857. domStyle['-webkit-touch-callout'] = 'none';
  5858. domStyle['-webkit-tap-highlight-color'] = 'rgba(0,0,0,0)';
  5859. domStyle['padding'] = 0;
  5860. domStyle['margin'] = 0;
  5861. domStyle['border-width'] = 0;
  5862. }
  5863. this.domBack = null;
  5864. this.ctxBack = null;
  5865. this.painter = painter;
  5866. this.config = null;
  5867. // Configs
  5868. /**
  5869. * 每次清空画布的颜色
  5870. * @type {string}
  5871. * @default 0
  5872. */
  5873. this.clearColor = 0;
  5874. /**
  5875. * 是否开启动态模糊
  5876. * @type {boolean}
  5877. * @default false
  5878. */
  5879. this.motionBlur = false;
  5880. /**
  5881. * 在开启动态模糊的时候使用,与上一帧混合的alpha值,值越大尾迹越明显
  5882. * @type {number}
  5883. * @default 0.7
  5884. */
  5885. this.lastFrameAlpha = 0.7;
  5886. /**
  5887. * Layer dpr
  5888. * @type {number}
  5889. */
  5890. this.dpr = dpr;
  5891. };
  5892. Layer.prototype = {
  5893. constructor: Layer,
  5894. __dirty: true,
  5895. __used: false,
  5896. __drawIndex: 0,
  5897. __startIndex: 0,
  5898. __endIndex: 0,
  5899. incremental: false,
  5900. getElementCount: function () {
  5901. return this.__endIndex - this.__startIndex;
  5902. },
  5903. initContext: function () {
  5904. this.ctx = this.dom.getContext('2d');
  5905. this.ctx.dpr = this.dpr;
  5906. },
  5907. createBackBuffer: function () {
  5908. var dpr = this.dpr;
  5909. this.domBack = createDom('back-' + this.id, this.painter, dpr);
  5910. this.ctxBack = this.domBack.getContext('2d');
  5911. if (dpr != 1) {
  5912. this.ctxBack.scale(dpr, dpr);
  5913. }
  5914. },
  5915. /**
  5916. * @param {number} width
  5917. * @param {number} height
  5918. */
  5919. resize: function (width, height) {
  5920. var dpr = this.dpr;
  5921. var dom = this.dom;
  5922. var domStyle = dom.style;
  5923. var domBack = this.domBack;
  5924. if (domStyle) {
  5925. domStyle.width = width + 'px';
  5926. domStyle.height = height + 'px';
  5927. }
  5928. dom.width = width * dpr;
  5929. dom.height = height * dpr;
  5930. if (domBack) {
  5931. domBack.width = width * dpr;
  5932. domBack.height = height * dpr;
  5933. if (dpr != 1) {
  5934. this.ctxBack.scale(dpr, dpr);
  5935. }
  5936. }
  5937. },
  5938. /**
  5939. * 清空该层画布
  5940. * @param {boolean} [clearAll]=false Clear all with out motion blur
  5941. * @param {Color} [clearColor]
  5942. */
  5943. clear: function (clearAll, clearColor) {
  5944. var dom = this.dom;
  5945. var ctx = this.ctx;
  5946. var width = dom.width;
  5947. var height = dom.height;
  5948. var clearColor = clearColor || this.clearColor;
  5949. var haveMotionBLur = this.motionBlur && !clearAll;
  5950. var lastFrameAlpha = this.lastFrameAlpha;
  5951. var dpr = this.dpr;
  5952. if (haveMotionBLur) {
  5953. if (!this.domBack) {
  5954. this.createBackBuffer();
  5955. }
  5956. this.ctxBack.globalCompositeOperation = 'copy';
  5957. this.ctxBack.drawImage(
  5958. dom, 0, 0,
  5959. width / dpr,
  5960. height / dpr
  5961. );
  5962. }
  5963. ctx.clearRect(0, 0, width, height);
  5964. if (clearColor && clearColor !== 'transparent') {
  5965. var clearColorGradientOrPattern;
  5966. // Gradient
  5967. if (clearColor.colorStops) {
  5968. // Cache canvas gradient
  5969. clearColorGradientOrPattern = clearColor.__canvasGradient || Style.getGradient(ctx, clearColor, {
  5970. x: 0,
  5971. y: 0,
  5972. width: width,
  5973. height: height
  5974. });
  5975. clearColor.__canvasGradient = clearColorGradientOrPattern;
  5976. }
  5977. // Pattern
  5978. else if (clearColor.image) {
  5979. clearColorGradientOrPattern = Pattern.prototype.getCanvasPattern.call(clearColor, ctx);
  5980. }
  5981. ctx.save();
  5982. ctx.fillStyle = clearColorGradientOrPattern || clearColor;
  5983. ctx.fillRect(0, 0, width, height);
  5984. ctx.restore();
  5985. }
  5986. if (haveMotionBLur) {
  5987. var domBack = this.domBack;
  5988. ctx.save();
  5989. ctx.globalAlpha = lastFrameAlpha;
  5990. ctx.drawImage(domBack, 0, 0, width, height);
  5991. ctx.restore();
  5992. }
  5993. }
  5994. };
  5995. var requestAnimationFrame = (
  5996. typeof window !== 'undefined'
  5997. && (
  5998. (window.requestAnimationFrame && window.requestAnimationFrame.bind(window))
  5999. // https://github.com/ecomfe/zrender/issues/189#issuecomment-224919809
  6000. || (window.msRequestAnimationFrame && window.msRequestAnimationFrame.bind(window))
  6001. || window.mozRequestAnimationFrame
  6002. || window.webkitRequestAnimationFrame
  6003. )
  6004. ) || function (func) {
  6005. setTimeout(func, 16);
  6006. };
  6007. var globalImageCache = new LRU(50);
  6008. /**
  6009. * @param {string|HTMLImageElement|HTMLCanvasElement|Canvas} newImageOrSrc
  6010. * @return {HTMLImageElement|HTMLCanvasElement|Canvas} image
  6011. */
  6012. function findExistImage(newImageOrSrc) {
  6013. if (typeof newImageOrSrc === 'string') {
  6014. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  6015. return cachedImgObj && cachedImgObj.image;
  6016. }
  6017. else {
  6018. return newImageOrSrc;
  6019. }
  6020. }
  6021. /**
  6022. * Caution: User should cache loaded images, but not just count on LRU.
  6023. * Consider if required images more than LRU size, will dead loop occur?
  6024. *
  6025. * @param {string|HTMLImageElement|HTMLCanvasElement|Canvas} newImageOrSrc
  6026. * @param {HTMLImageElement|HTMLCanvasElement|Canvas} image Existent image.
  6027. * @param {module:zrender/Element} [hostEl] For calling `dirty`.
  6028. * @param {Function} [cb] params: (image, cbPayload)
  6029. * @param {Object} [cbPayload] Payload on cb calling.
  6030. * @return {HTMLImageElement|HTMLCanvasElement|Canvas} image
  6031. */
  6032. function createOrUpdateImage(newImageOrSrc, image, hostEl, cb, cbPayload) {
  6033. if (!newImageOrSrc) {
  6034. return image;
  6035. }
  6036. else if (typeof newImageOrSrc === 'string') {
  6037. // Image should not be loaded repeatly.
  6038. if ((image && image.__zrImageSrc === newImageOrSrc) || !hostEl) {
  6039. return image;
  6040. }
  6041. // Only when there is no existent image or existent image src
  6042. // is different, this method is responsible for load.
  6043. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  6044. var pendingWrap = {hostEl: hostEl, cb: cb, cbPayload: cbPayload};
  6045. if (cachedImgObj) {
  6046. image = cachedImgObj.image;
  6047. !isImageReady(image) && cachedImgObj.pending.push(pendingWrap);
  6048. }
  6049. else {
  6050. !image && (image = new Image());
  6051. image.onload = imageOnLoad;
  6052. globalImageCache.put(
  6053. newImageOrSrc,
  6054. image.__cachedImgObj = {
  6055. image: image,
  6056. pending: [pendingWrap]
  6057. }
  6058. );
  6059. image.src = image.__zrImageSrc = newImageOrSrc;
  6060. }
  6061. return image;
  6062. }
  6063. // newImageOrSrc is an HTMLImageElement or HTMLCanvasElement or Canvas
  6064. else {
  6065. return newImageOrSrc;
  6066. }
  6067. }
  6068. function imageOnLoad() {
  6069. var cachedImgObj = this.__cachedImgObj;
  6070. this.onload = this.__cachedImgObj = null;
  6071. for (var i = 0; i < cachedImgObj.pending.length; i++) {
  6072. var pendingWrap = cachedImgObj.pending[i];
  6073. var cb = pendingWrap.cb;
  6074. cb && cb(this, pendingWrap.cbPayload);
  6075. pendingWrap.hostEl.dirty();
  6076. }
  6077. cachedImgObj.pending.length = 0;
  6078. }
  6079. function isImageReady(image) {
  6080. return image && image.width && image.height;
  6081. }
  6082. var textWidthCache = {};
  6083. var textWidthCacheCounter = 0;
  6084. var TEXT_CACHE_MAX = 5000;
  6085. var STYLE_REG = /\{([a-zA-Z0-9_]+)\|([^}]*)\}/g;
  6086. var DEFAULT_FONT = '12px sans-serif';
  6087. // Avoid assign to an exported variable, for transforming to cjs.
  6088. var methods$1 = {};
  6089. function $override$1(name, fn) {
  6090. methods$1[name] = fn;
  6091. }
  6092. /**
  6093. * @public
  6094. * @param {string} text
  6095. * @param {string} font
  6096. * @return {number} width
  6097. */
  6098. function getWidth(text, font) {
  6099. font = font || DEFAULT_FONT;
  6100. var key = text + ':' + font;
  6101. if (textWidthCache[key]) {
  6102. return textWidthCache[key];
  6103. }
  6104. var textLines = (text + '').split('\n');
  6105. var width = 0;
  6106. for (var i = 0, l = textLines.length; i < l; i++) {
  6107. // textContain.measureText may be overrided in SVG or VML
  6108. width = Math.max(measureText(textLines[i], font).width, width);
  6109. }
  6110. if (textWidthCacheCounter > TEXT_CACHE_MAX) {
  6111. textWidthCacheCounter = 0;
  6112. textWidthCache = {};
  6113. }
  6114. textWidthCacheCounter++;
  6115. textWidthCache[key] = width;
  6116. return width;
  6117. }
  6118. /**
  6119. * @public
  6120. * @param {string} text
  6121. * @param {string} font
  6122. * @param {string} [textAlign='left']
  6123. * @param {string} [textVerticalAlign='top']
  6124. * @param {Array.<number>} [textPadding]
  6125. * @param {Object} [rich]
  6126. * @param {Object} [truncate]
  6127. * @return {Object} {x, y, width, height, lineHeight}
  6128. */
  6129. function getBoundingRect(text, font, textAlign, textVerticalAlign, textPadding, rich, truncate) {
  6130. return rich
  6131. ? getRichTextRect(text, font, textAlign, textVerticalAlign, textPadding, rich, truncate)
  6132. : getPlainTextRect(text, font, textAlign, textVerticalAlign, textPadding, truncate);
  6133. }
  6134. function getPlainTextRect(text, font, textAlign, textVerticalAlign, textPadding, truncate) {
  6135. var contentBlock = parsePlainText(text, font, textPadding, truncate);
  6136. var outerWidth = getWidth(text, font);
  6137. if (textPadding) {
  6138. outerWidth += textPadding[1] + textPadding[3];
  6139. }
  6140. var outerHeight = contentBlock.outerHeight;
  6141. var x = adjustTextX(0, outerWidth, textAlign);
  6142. var y = adjustTextY(0, outerHeight, textVerticalAlign);
  6143. var rect = new BoundingRect(x, y, outerWidth, outerHeight);
  6144. rect.lineHeight = contentBlock.lineHeight;
  6145. return rect;
  6146. }
  6147. function getRichTextRect(text, font, textAlign, textVerticalAlign, textPadding, rich, truncate) {
  6148. var contentBlock = parseRichText(text, {
  6149. rich: rich,
  6150. truncate: truncate,
  6151. font: font,
  6152. textAlign: textAlign,
  6153. textPadding: textPadding
  6154. });
  6155. var outerWidth = contentBlock.outerWidth;
  6156. var outerHeight = contentBlock.outerHeight;
  6157. var x = adjustTextX(0, outerWidth, textAlign);
  6158. var y = adjustTextY(0, outerHeight, textVerticalAlign);
  6159. return new BoundingRect(x, y, outerWidth, outerHeight);
  6160. }
  6161. /**
  6162. * @public
  6163. * @param {number} x
  6164. * @param {number} width
  6165. * @param {string} [textAlign='left']
  6166. * @return {number} Adjusted x.
  6167. */
  6168. function adjustTextX(x, width, textAlign) {
  6169. // FIXME Right to left language
  6170. if (textAlign === 'right') {
  6171. x -= width;
  6172. }
  6173. else if (textAlign === 'center') {
  6174. x -= width / 2;
  6175. }
  6176. return x;
  6177. }
  6178. /**
  6179. * @public
  6180. * @param {number} y
  6181. * @param {number} height
  6182. * @param {string} [textVerticalAlign='top']
  6183. * @return {number} Adjusted y.
  6184. */
  6185. function adjustTextY(y, height, textVerticalAlign) {
  6186. if (textVerticalAlign === 'middle') {
  6187. y -= height / 2;
  6188. }
  6189. else if (textVerticalAlign === 'bottom') {
  6190. y -= height;
  6191. }
  6192. return y;
  6193. }
  6194. /**
  6195. * @public
  6196. * @param {stirng} textPosition
  6197. * @param {Object} rect {x, y, width, height}
  6198. * @param {number} distance
  6199. * @return {Object} {x, y, textAlign, textVerticalAlign}
  6200. */
  6201. function adjustTextPositionOnRect(textPosition, rect, distance) {
  6202. var x = rect.x;
  6203. var y = rect.y;
  6204. var height = rect.height;
  6205. var width = rect.width;
  6206. var halfHeight = height / 2;
  6207. var textAlign = 'left';
  6208. var textVerticalAlign = 'top';
  6209. switch (textPosition) {
  6210. case 'left':
  6211. x -= distance;
  6212. y += halfHeight;
  6213. textAlign = 'right';
  6214. textVerticalAlign = 'middle';
  6215. break;
  6216. case 'right':
  6217. x += distance + width;
  6218. y += halfHeight;
  6219. textVerticalAlign = 'middle';
  6220. break;
  6221. case 'top':
  6222. x += width / 2;
  6223. y -= distance;
  6224. textAlign = 'center';
  6225. textVerticalAlign = 'bottom';
  6226. break;
  6227. case 'bottom':
  6228. x += width / 2;
  6229. y += height + distance;
  6230. textAlign = 'center';
  6231. break;
  6232. case 'inside':
  6233. x += width / 2;
  6234. y += halfHeight;
  6235. textAlign = 'center';
  6236. textVerticalAlign = 'middle';
  6237. break;
  6238. case 'insideLeft':
  6239. x += distance;
  6240. y += halfHeight;
  6241. textVerticalAlign = 'middle';
  6242. break;
  6243. case 'insideRight':
  6244. x += width - distance;
  6245. y += halfHeight;
  6246. textAlign = 'right';
  6247. textVerticalAlign = 'middle';
  6248. break;
  6249. case 'insideTop':
  6250. x += width / 2;
  6251. y += distance;
  6252. textAlign = 'center';
  6253. break;
  6254. case 'insideBottom':
  6255. x += width / 2;
  6256. y += height - distance;
  6257. textAlign = 'center';
  6258. textVerticalAlign = 'bottom';
  6259. break;
  6260. case 'insideTopLeft':
  6261. x += distance;
  6262. y += distance;
  6263. break;
  6264. case 'insideTopRight':
  6265. x += width - distance;
  6266. y += distance;
  6267. textAlign = 'right';
  6268. break;
  6269. case 'insideBottomLeft':
  6270. x += distance;
  6271. y += height - distance;
  6272. textVerticalAlign = 'bottom';
  6273. break;
  6274. case 'insideBottomRight':
  6275. x += width - distance;
  6276. y += height - distance;
  6277. textAlign = 'right';
  6278. textVerticalAlign = 'bottom';
  6279. break;
  6280. }
  6281. return {
  6282. x: x,
  6283. y: y,
  6284. textAlign: textAlign,
  6285. textVerticalAlign: textVerticalAlign
  6286. };
  6287. }
  6288. /**
  6289. * Show ellipsis if overflow.
  6290. *
  6291. * @public
  6292. * @param {string} text
  6293. * @param {string} containerWidth
  6294. * @param {string} font
  6295. * @param {number} [ellipsis='...']
  6296. * @param {Object} [options]
  6297. * @param {number} [options.maxIterations=3]
  6298. * @param {number} [options.minChar=0] If truncate result are less
  6299. * then minChar, ellipsis will not show, which is
  6300. * better for user hint in some cases.
  6301. * @param {number} [options.placeholder=''] When all truncated, use the placeholder.
  6302. * @return {string}
  6303. */
  6304. function truncateText(text, containerWidth, font, ellipsis, options) {
  6305. if (!containerWidth) {
  6306. return '';
  6307. }
  6308. var textLines = (text + '').split('\n');
  6309. options = prepareTruncateOptions(containerWidth, font, ellipsis, options);
  6310. // FIXME
  6311. // It is not appropriate that every line has '...' when truncate multiple lines.
  6312. for (var i = 0, len = textLines.length; i < len; i++) {
  6313. textLines[i] = truncateSingleLine(textLines[i], options);
  6314. }
  6315. return textLines.join('\n');
  6316. }
  6317. function prepareTruncateOptions(containerWidth, font, ellipsis, options) {
  6318. options = extend({}, options);
  6319. options.font = font;
  6320. var ellipsis = retrieve2(ellipsis, '...');
  6321. options.maxIterations = retrieve2(options.maxIterations, 2);
  6322. var minChar = options.minChar = retrieve2(options.minChar, 0);
  6323. // FIXME
  6324. // Other languages?
  6325. options.cnCharWidth = getWidth('国', font);
  6326. // FIXME
  6327. // Consider proportional font?
  6328. var ascCharWidth = options.ascCharWidth = getWidth('a', font);
  6329. options.placeholder = retrieve2(options.placeholder, '');
  6330. // Example 1: minChar: 3, text: 'asdfzxcv', truncate result: 'asdf', but not: 'a...'.
  6331. // Example 2: minChar: 3, text: '维度', truncate result: '维', but not: '...'.
  6332. var contentWidth = containerWidth = Math.max(0, containerWidth - 1); // Reserve some gap.
  6333. for (var i = 0; i < minChar && contentWidth >= ascCharWidth; i++) {
  6334. contentWidth -= ascCharWidth;
  6335. }
  6336. var ellipsisWidth = getWidth(ellipsis);
  6337. if (ellipsisWidth > contentWidth) {
  6338. ellipsis = '';
  6339. ellipsisWidth = 0;
  6340. }
  6341. contentWidth = containerWidth - ellipsisWidth;
  6342. options.ellipsis = ellipsis;
  6343. options.ellipsisWidth = ellipsisWidth;
  6344. options.contentWidth = contentWidth;
  6345. options.containerWidth = containerWidth;
  6346. return options;
  6347. }
  6348. function truncateSingleLine(textLine, options) {
  6349. var containerWidth = options.containerWidth;
  6350. var font = options.font;
  6351. var contentWidth = options.contentWidth;
  6352. if (!containerWidth) {
  6353. return '';
  6354. }
  6355. var lineWidth = getWidth(textLine, font);
  6356. if (lineWidth <= containerWidth) {
  6357. return textLine;
  6358. }
  6359. for (var j = 0;; j++) {
  6360. if (lineWidth <= contentWidth || j >= options.maxIterations) {
  6361. textLine += options.ellipsis;
  6362. break;
  6363. }
  6364. var subLength = j === 0
  6365. ? estimateLength(textLine, contentWidth, options.ascCharWidth, options.cnCharWidth)
  6366. : lineWidth > 0
  6367. ? Math.floor(textLine.length * contentWidth / lineWidth)
  6368. : 0;
  6369. textLine = textLine.substr(0, subLength);
  6370. lineWidth = getWidth(textLine, font);
  6371. }
  6372. if (textLine === '') {
  6373. textLine = options.placeholder;
  6374. }
  6375. return textLine;
  6376. }
  6377. function estimateLength(text, contentWidth, ascCharWidth, cnCharWidth) {
  6378. var width = 0;
  6379. var i = 0;
  6380. for (var len = text.length; i < len && width < contentWidth; i++) {
  6381. var charCode = text.charCodeAt(i);
  6382. width += (0 <= charCode && charCode <= 127) ? ascCharWidth : cnCharWidth;
  6383. }
  6384. return i;
  6385. }
  6386. /**
  6387. * @public
  6388. * @param {string} font
  6389. * @return {number} line height
  6390. */
  6391. function getLineHeight(font) {
  6392. // FIXME A rough approach.
  6393. return getWidth('国', font);
  6394. }
  6395. /**
  6396. * @public
  6397. * @param {string} text
  6398. * @param {string} font
  6399. * @return {Object} width
  6400. */
  6401. function measureText(text, font) {
  6402. return methods$1.measureText(text, font);
  6403. }
  6404. // Avoid assign to an exported variable, for transforming to cjs.
  6405. methods$1.measureText = function (text, font) {
  6406. var ctx = getContext();
  6407. ctx.font = font || DEFAULT_FONT;
  6408. return ctx.measureText(text);
  6409. };
  6410. /**
  6411. * @public
  6412. * @param {string} text
  6413. * @param {string} font
  6414. * @param {Object} [truncate]
  6415. * @return {Object} block: {lineHeight, lines, height, outerHeight}
  6416. * Notice: for performance, do not calculate outerWidth util needed.
  6417. */
  6418. function parsePlainText(text, font, padding, truncate) {
  6419. text != null && (text += '');
  6420. var lineHeight = getLineHeight(font);
  6421. var lines = text ? text.split('\n') : [];
  6422. var height = lines.length * lineHeight;
  6423. var outerHeight = height;
  6424. if (padding) {
  6425. outerHeight += padding[0] + padding[2];
  6426. }
  6427. if (text && truncate) {
  6428. var truncOuterHeight = truncate.outerHeight;
  6429. var truncOuterWidth = truncate.outerWidth;
  6430. if (truncOuterHeight != null && outerHeight > truncOuterHeight) {
  6431. text = '';
  6432. lines = [];
  6433. }
  6434. else if (truncOuterWidth != null) {
  6435. var options = prepareTruncateOptions(
  6436. truncOuterWidth - (padding ? padding[1] + padding[3] : 0),
  6437. font,
  6438. truncate.ellipsis,
  6439. {minChar: truncate.minChar, placeholder: truncate.placeholder}
  6440. );
  6441. // FIXME
  6442. // It is not appropriate that every line has '...' when truncate multiple lines.
  6443. for (var i = 0, len = lines.length; i < len; i++) {
  6444. lines[i] = truncateSingleLine(lines[i], options);
  6445. }
  6446. }
  6447. }
  6448. return {
  6449. lines: lines,
  6450. height: height,
  6451. outerHeight: outerHeight,
  6452. lineHeight: lineHeight
  6453. };
  6454. }
  6455. /**
  6456. * For example: 'some text {a|some text}other text{b|some text}xxx{c|}xxx'
  6457. * Also consider 'bbbb{a|xxx\nzzz}xxxx\naaaa'.
  6458. *
  6459. * @public
  6460. * @param {string} text
  6461. * @param {Object} style
  6462. * @return {Object} block
  6463. * {
  6464. * width,
  6465. * height,
  6466. * lines: [{
  6467. * lineHeight,
  6468. * width,
  6469. * tokens: [[{
  6470. * styleName,
  6471. * text,
  6472. * width, // include textPadding
  6473. * height, // include textPadding
  6474. * textWidth, // pure text width
  6475. * textHeight, // pure text height
  6476. * lineHeihgt,
  6477. * font,
  6478. * textAlign,
  6479. * textVerticalAlign
  6480. * }], [...], ...]
  6481. * }, ...]
  6482. * }
  6483. * If styleName is undefined, it is plain text.
  6484. */
  6485. function parseRichText(text, style) {
  6486. var contentBlock = {lines: [], width: 0, height: 0};
  6487. text != null && (text += '');
  6488. if (!text) {
  6489. return contentBlock;
  6490. }
  6491. var lastIndex = STYLE_REG.lastIndex = 0;
  6492. var result;
  6493. while ((result = STYLE_REG.exec(text)) != null) {
  6494. var matchedIndex = result.index;
  6495. if (matchedIndex > lastIndex) {
  6496. pushTokens(contentBlock, text.substring(lastIndex, matchedIndex));
  6497. }
  6498. pushTokens(contentBlock, result[2], result[1]);
  6499. lastIndex = STYLE_REG.lastIndex;
  6500. }
  6501. if (lastIndex < text.length) {
  6502. pushTokens(contentBlock, text.substring(lastIndex, text.length));
  6503. }
  6504. var lines = contentBlock.lines;
  6505. var contentHeight = 0;
  6506. var contentWidth = 0;
  6507. // For `textWidth: 100%`
  6508. var pendingList = [];
  6509. var stlPadding = style.textPadding;
  6510. var truncate = style.truncate;
  6511. var truncateWidth = truncate && truncate.outerWidth;
  6512. var truncateHeight = truncate && truncate.outerHeight;
  6513. if (stlPadding) {
  6514. truncateWidth != null && (truncateWidth -= stlPadding[1] + stlPadding[3]);
  6515. truncateHeight != null && (truncateHeight -= stlPadding[0] + stlPadding[2]);
  6516. }
  6517. // Calculate layout info of tokens.
  6518. for (var i = 0; i < lines.length; i++) {
  6519. var line = lines[i];
  6520. var lineHeight = 0;
  6521. var lineWidth = 0;
  6522. for (var j = 0; j < line.tokens.length; j++) {
  6523. var token = line.tokens[j];
  6524. var tokenStyle = token.styleName && style.rich[token.styleName] || {};
  6525. // textPadding should not inherit from style.
  6526. var textPadding = token.textPadding = tokenStyle.textPadding;
  6527. // textFont has been asigned to font by `normalizeStyle`.
  6528. var font = token.font = tokenStyle.font || style.font;
  6529. // textHeight can be used when textVerticalAlign is specified in token.
  6530. var tokenHeight = token.textHeight = retrieve2(
  6531. // textHeight should not be inherited, consider it can be specified
  6532. // as box height of the block.
  6533. tokenStyle.textHeight, getLineHeight(font)
  6534. );
  6535. textPadding && (tokenHeight += textPadding[0] + textPadding[2]);
  6536. token.height = tokenHeight;
  6537. token.lineHeight = retrieve3(
  6538. tokenStyle.textLineHeight, style.textLineHeight, tokenHeight
  6539. );
  6540. token.textAlign = tokenStyle && tokenStyle.textAlign || style.textAlign;
  6541. token.textVerticalAlign = tokenStyle && tokenStyle.textVerticalAlign || 'middle';
  6542. if (truncateHeight != null && contentHeight + token.lineHeight > truncateHeight) {
  6543. return {lines: [], width: 0, height: 0};
  6544. }
  6545. token.textWidth = getWidth(token.text, font);
  6546. var tokenWidth = tokenStyle.textWidth;
  6547. var tokenWidthNotSpecified = tokenWidth == null || tokenWidth === 'auto';
  6548. // Percent width, can be `100%`, can be used in drawing separate
  6549. // line when box width is needed to be auto.
  6550. if (typeof tokenWidth === 'string' && tokenWidth.charAt(tokenWidth.length - 1) === '%') {
  6551. token.percentWidth = tokenWidth;
  6552. pendingList.push(token);
  6553. tokenWidth = 0;
  6554. // Do not truncate in this case, because there is no user case
  6555. // and it is too complicated.
  6556. }
  6557. else {
  6558. if (tokenWidthNotSpecified) {
  6559. tokenWidth = token.textWidth;
  6560. // FIXME: If image is not loaded and textWidth is not specified, calling
  6561. // `getBoundingRect()` will not get correct result.
  6562. var textBackgroundColor = tokenStyle.textBackgroundColor;
  6563. var bgImg = textBackgroundColor && textBackgroundColor.image;
  6564. // Use cases:
  6565. // (1) If image is not loaded, it will be loaded at render phase and call
  6566. // `dirty()` and `textBackgroundColor.image` will be replaced with the loaded
  6567. // image, and then the right size will be calculated here at the next tick.
  6568. // See `graphic/helper/text.js`.
  6569. // (2) If image loaded, and `textBackgroundColor.image` is image src string,
  6570. // use `imageHelper.findExistImage` to find cached image.
  6571. // `imageHelper.findExistImage` will always be called here before
  6572. // `imageHelper.createOrUpdateImage` in `graphic/helper/text.js#renderRichText`
  6573. // which ensures that image will not be rendered before correct size calcualted.
  6574. if (bgImg) {
  6575. bgImg = findExistImage(bgImg);
  6576. if (isImageReady(bgImg)) {
  6577. tokenWidth = Math.max(tokenWidth, bgImg.width * tokenHeight / bgImg.height);
  6578. }
  6579. }
  6580. }
  6581. var paddingW = textPadding ? textPadding[1] + textPadding[3] : 0;
  6582. tokenWidth += paddingW;
  6583. var remianTruncWidth = truncateWidth != null ? truncateWidth - lineWidth : null;
  6584. if (remianTruncWidth != null && remianTruncWidth < tokenWidth) {
  6585. if (!tokenWidthNotSpecified || remianTruncWidth < paddingW) {
  6586. token.text = '';
  6587. token.textWidth = tokenWidth = 0;
  6588. }
  6589. else {
  6590. token.text = truncateText(
  6591. token.text, remianTruncWidth - paddingW, font, truncate.ellipsis,
  6592. {minChar: truncate.minChar}
  6593. );
  6594. token.textWidth = getWidth(token.text, font);
  6595. tokenWidth = token.textWidth + paddingW;
  6596. }
  6597. }
  6598. }
  6599. lineWidth += (token.width = tokenWidth);
  6600. tokenStyle && (lineHeight = Math.max(lineHeight, token.lineHeight));
  6601. }
  6602. line.width = lineWidth;
  6603. line.lineHeight = lineHeight;
  6604. contentHeight += lineHeight;
  6605. contentWidth = Math.max(contentWidth, lineWidth);
  6606. }
  6607. contentBlock.outerWidth = contentBlock.width = retrieve2(style.textWidth, contentWidth);
  6608. contentBlock.outerHeight = contentBlock.height = retrieve2(style.textHeight, contentHeight);
  6609. if (stlPadding) {
  6610. contentBlock.outerWidth += stlPadding[1] + stlPadding[3];
  6611. contentBlock.outerHeight += stlPadding[0] + stlPadding[2];
  6612. }
  6613. for (var i = 0; i < pendingList.length; i++) {
  6614. var token = pendingList[i];
  6615. var percentWidth = token.percentWidth;
  6616. // Should not base on outerWidth, because token can not be placed out of padding.
  6617. token.width = parseInt(percentWidth, 10) / 100 * contentWidth;
  6618. }
  6619. return contentBlock;
  6620. }
  6621. function pushTokens(block, str, styleName) {
  6622. var isEmptyStr = str === '';
  6623. var strs = str.split('\n');
  6624. var lines = block.lines;
  6625. for (var i = 0; i < strs.length; i++) {
  6626. var text = strs[i];
  6627. var token = {
  6628. styleName: styleName,
  6629. text: text,
  6630. isLineHolder: !text && !isEmptyStr
  6631. };
  6632. // The first token should be appended to the last line.
  6633. if (!i) {
  6634. var tokens = (lines[lines.length - 1] || (lines[0] = {tokens: []})).tokens;
  6635. // Consider cases:
  6636. // (1) ''.split('\n') => ['', '\n', ''], the '' at the first item
  6637. // (which is a placeholder) should be replaced by new token.
  6638. // (2) A image backage, where token likes {a|}.
  6639. // (3) A redundant '' will affect textAlign in line.
  6640. // (4) tokens with the same tplName should not be merged, because
  6641. // they should be displayed in different box (with border and padding).
  6642. var tokensLen = tokens.length;
  6643. (tokensLen === 1 && tokens[0].isLineHolder)
  6644. ? (tokens[0] = token)
  6645. // Consider text is '', only insert when it is the "lineHolder" or
  6646. // "emptyStr". Otherwise a redundant '' will affect textAlign in line.
  6647. : ((text || !tokensLen || isEmptyStr) && tokens.push(token));
  6648. }
  6649. // Other tokens always start a new line.
  6650. else {
  6651. // If there is '', insert it as a placeholder.
  6652. lines.push({tokens: [token]});
  6653. }
  6654. }
  6655. }
  6656. function makeFont(style) {
  6657. // FIXME in node-canvas fontWeight is before fontStyle
  6658. // Use `fontSize` `fontFamily` to check whether font properties are defined.
  6659. var font = (style.fontSize || style.fontFamily) && [
  6660. style.fontStyle,
  6661. style.fontWeight,
  6662. (style.fontSize || 12) + 'px',
  6663. // If font properties are defined, `fontFamily` should not be ignored.
  6664. style.fontFamily || 'sans-serif'
  6665. ].join(' ');
  6666. return font && trim(font) || style.textFont || style.font;
  6667. }
  6668. function buildPath(ctx, shape) {
  6669. var x = shape.x;
  6670. var y = shape.y;
  6671. var width = shape.width;
  6672. var height = shape.height;
  6673. var r = shape.r;
  6674. var r1;
  6675. var r2;
  6676. var r3;
  6677. var r4;
  6678. // Convert width and height to positive for better borderRadius
  6679. if (width < 0) {
  6680. x = x + width;
  6681. width = -width;
  6682. }
  6683. if (height < 0) {
  6684. y = y + height;
  6685. height = -height;
  6686. }
  6687. if (typeof r === 'number') {
  6688. r1 = r2 = r3 = r4 = r;
  6689. }
  6690. else if (r instanceof Array) {
  6691. if (r.length === 1) {
  6692. r1 = r2 = r3 = r4 = r[0];
  6693. }
  6694. else if (r.length === 2) {
  6695. r1 = r3 = r[0];
  6696. r2 = r4 = r[1];
  6697. }
  6698. else if (r.length === 3) {
  6699. r1 = r[0];
  6700. r2 = r4 = r[1];
  6701. r3 = r[2];
  6702. }
  6703. else {
  6704. r1 = r[0];
  6705. r2 = r[1];
  6706. r3 = r[2];
  6707. r4 = r[3];
  6708. }
  6709. }
  6710. else {
  6711. r1 = r2 = r3 = r4 = 0;
  6712. }
  6713. var total;
  6714. if (r1 + r2 > width) {
  6715. total = r1 + r2;
  6716. r1 *= width / total;
  6717. r2 *= width / total;
  6718. }
  6719. if (r3 + r4 > width) {
  6720. total = r3 + r4;
  6721. r3 *= width / total;
  6722. r4 *= width / total;
  6723. }
  6724. if (r2 + r3 > height) {
  6725. total = r2 + r3;
  6726. r2 *= height / total;
  6727. r3 *= height / total;
  6728. }
  6729. if (r1 + r4 > height) {
  6730. total = r1 + r4;
  6731. r1 *= height / total;
  6732. r4 *= height / total;
  6733. }
  6734. ctx.moveTo(x + r1, y);
  6735. ctx.lineTo(x + width - r2, y);
  6736. r2 !== 0 && ctx.arc(x + width - r2, y + r2, r2, -Math.PI / 2, 0);
  6737. ctx.lineTo(x + width, y + height - r3);
  6738. r3 !== 0 && ctx.arc(x + width - r3, y + height - r3, r3, 0, Math.PI / 2);
  6739. ctx.lineTo(x + r4, y + height);
  6740. r4 !== 0 && ctx.arc(x + r4, y + height - r4, r4, Math.PI / 2, Math.PI);
  6741. ctx.lineTo(x, y + r1);
  6742. r1 !== 0 && ctx.arc(x + r1, y + r1, r1, Math.PI, Math.PI * 1.5);
  6743. }
  6744. // TODO: Have not support 'start', 'end' yet.
  6745. var VALID_TEXT_ALIGN = {left: 1, right: 1, center: 1};
  6746. var VALID_TEXT_VERTICAL_ALIGN = {top: 1, bottom: 1, middle: 1};
  6747. /**
  6748. * @param {module:zrender/graphic/Style} style
  6749. * @return {module:zrender/graphic/Style} The input style.
  6750. */
  6751. function normalizeTextStyle(style) {
  6752. normalizeStyle(style);
  6753. each$1(style.rich, normalizeStyle);
  6754. return style;
  6755. }
  6756. function normalizeStyle(style) {
  6757. if (style) {
  6758. style.font = makeFont(style);
  6759. var textAlign = style.textAlign;
  6760. textAlign === 'middle' && (textAlign = 'center');
  6761. style.textAlign = (
  6762. textAlign == null || VALID_TEXT_ALIGN[textAlign]
  6763. ) ? textAlign : 'left';
  6764. // Compatible with textBaseline.
  6765. var textVerticalAlign = style.textVerticalAlign || style.textBaseline;
  6766. textVerticalAlign === 'center' && (textVerticalAlign = 'middle');
  6767. style.textVerticalAlign = (
  6768. textVerticalAlign == null || VALID_TEXT_VERTICAL_ALIGN[textVerticalAlign]
  6769. ) ? textVerticalAlign : 'top';
  6770. var textPadding = style.textPadding;
  6771. if (textPadding) {
  6772. style.textPadding = normalizeCssArray(style.textPadding);
  6773. }
  6774. }
  6775. }
  6776. /**
  6777. * @param {CanvasRenderingContext2D} ctx
  6778. * @param {string} text
  6779. * @param {module:zrender/graphic/Style} style
  6780. * @param {Object|boolean} [rect] {x, y, width, height}
  6781. * If set false, rect text is not used.
  6782. */
  6783. function renderText(hostEl, ctx, text, style, rect) {
  6784. style.rich
  6785. ? renderRichText(hostEl, ctx, text, style, rect)
  6786. : renderPlainText(hostEl, ctx, text, style, rect);
  6787. }
  6788. function renderPlainText(hostEl, ctx, text, style, rect) {
  6789. var font = setCtx(ctx, 'font', style.font || DEFAULT_FONT);
  6790. var textPadding = style.textPadding;
  6791. var contentBlock = hostEl.__textCotentBlock;
  6792. if (!contentBlock || hostEl.__dirty) {
  6793. contentBlock = hostEl.__textCotentBlock = parsePlainText(
  6794. text, font, textPadding, style.truncate
  6795. );
  6796. }
  6797. var outerHeight = contentBlock.outerHeight;
  6798. var textLines = contentBlock.lines;
  6799. var lineHeight = contentBlock.lineHeight;
  6800. var boxPos = getBoxPosition(outerHeight, style, rect);
  6801. var baseX = boxPos.baseX;
  6802. var baseY = boxPos.baseY;
  6803. var textAlign = boxPos.textAlign;
  6804. var textVerticalAlign = boxPos.textVerticalAlign;
  6805. // Origin of textRotation should be the base point of text drawing.
  6806. applyTextRotation(ctx, style, rect, baseX, baseY);
  6807. var boxY = adjustTextY(baseY, outerHeight, textVerticalAlign);
  6808. var textX = baseX;
  6809. var textY = boxY;
  6810. var needDrawBg = needDrawBackground(style);
  6811. if (needDrawBg || textPadding) {
  6812. // Consider performance, do not call getTextWidth util necessary.
  6813. var textWidth = getWidth(text, font);
  6814. var outerWidth = textWidth;
  6815. textPadding && (outerWidth += textPadding[1] + textPadding[3]);
  6816. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  6817. needDrawBg && drawBackground(hostEl, ctx, style, boxX, boxY, outerWidth, outerHeight);
  6818. if (textPadding) {
  6819. textX = getTextXForPadding(baseX, textAlign, textPadding);
  6820. textY += textPadding[0];
  6821. }
  6822. }
  6823. setCtx(ctx, 'textAlign', textAlign || 'left');
  6824. // Force baseline to be "middle". Otherwise, if using "top", the
  6825. // text will offset downward a little bit in font "Microsoft YaHei".
  6826. setCtx(ctx, 'textBaseline', 'middle');
  6827. // Always set shadowBlur and shadowOffset to avoid leak from displayable.
  6828. setCtx(ctx, 'shadowBlur', style.textShadowBlur || 0);
  6829. setCtx(ctx, 'shadowColor', style.textShadowColor || 'transparent');
  6830. setCtx(ctx, 'shadowOffsetX', style.textShadowOffsetX || 0);
  6831. setCtx(ctx, 'shadowOffsetY', style.textShadowOffsetY || 0);
  6832. // `textBaseline` is set as 'middle'.
  6833. textY += lineHeight / 2;
  6834. var textStrokeWidth = style.textStrokeWidth;
  6835. var textStroke = getStroke(style.textStroke, textStrokeWidth);
  6836. var textFill = getFill(style.textFill);
  6837. if (textStroke) {
  6838. setCtx(ctx, 'lineWidth', textStrokeWidth);
  6839. setCtx(ctx, 'strokeStyle', textStroke);
  6840. }
  6841. if (textFill) {
  6842. setCtx(ctx, 'fillStyle', textFill);
  6843. }
  6844. for (var i = 0; i < textLines.length; i++) {
  6845. // Fill after stroke so the outline will not cover the main part.
  6846. textStroke && ctx.strokeText(textLines[i], textX, textY);
  6847. textFill && ctx.fillText(textLines[i], textX, textY);
  6848. textY += lineHeight;
  6849. }
  6850. }
  6851. function renderRichText(hostEl, ctx, text, style, rect) {
  6852. var contentBlock = hostEl.__textCotentBlock;
  6853. if (!contentBlock || hostEl.__dirty) {
  6854. contentBlock = hostEl.__textCotentBlock = parseRichText(text, style);
  6855. }
  6856. drawRichText(hostEl, ctx, contentBlock, style, rect);
  6857. }
  6858. function drawRichText(hostEl, ctx, contentBlock, style, rect) {
  6859. var contentWidth = contentBlock.width;
  6860. var outerWidth = contentBlock.outerWidth;
  6861. var outerHeight = contentBlock.outerHeight;
  6862. var textPadding = style.textPadding;
  6863. var boxPos = getBoxPosition(outerHeight, style, rect);
  6864. var baseX = boxPos.baseX;
  6865. var baseY = boxPos.baseY;
  6866. var textAlign = boxPos.textAlign;
  6867. var textVerticalAlign = boxPos.textVerticalAlign;
  6868. // Origin of textRotation should be the base point of text drawing.
  6869. applyTextRotation(ctx, style, rect, baseX, baseY);
  6870. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  6871. var boxY = adjustTextY(baseY, outerHeight, textVerticalAlign);
  6872. var xLeft = boxX;
  6873. var lineTop = boxY;
  6874. if (textPadding) {
  6875. xLeft += textPadding[3];
  6876. lineTop += textPadding[0];
  6877. }
  6878. var xRight = xLeft + contentWidth;
  6879. needDrawBackground(style) && drawBackground(
  6880. hostEl, ctx, style, boxX, boxY, outerWidth, outerHeight
  6881. );
  6882. for (var i = 0; i < contentBlock.lines.length; i++) {
  6883. var line = contentBlock.lines[i];
  6884. var tokens = line.tokens;
  6885. var tokenCount = tokens.length;
  6886. var lineHeight = line.lineHeight;
  6887. var usedWidth = line.width;
  6888. var leftIndex = 0;
  6889. var lineXLeft = xLeft;
  6890. var lineXRight = xRight;
  6891. var rightIndex = tokenCount - 1;
  6892. var token;
  6893. while (
  6894. leftIndex < tokenCount
  6895. && (token = tokens[leftIndex], !token.textAlign || token.textAlign === 'left')
  6896. ) {
  6897. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXLeft, 'left');
  6898. usedWidth -= token.width;
  6899. lineXLeft += token.width;
  6900. leftIndex++;
  6901. }
  6902. while (
  6903. rightIndex >= 0
  6904. && (token = tokens[rightIndex], token.textAlign === 'right')
  6905. ) {
  6906. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXRight, 'right');
  6907. usedWidth -= token.width;
  6908. lineXRight -= token.width;
  6909. rightIndex--;
  6910. }
  6911. // The other tokens are placed as textAlign 'center' if there is enough space.
  6912. lineXLeft += (contentWidth - (lineXLeft - xLeft) - (xRight - lineXRight) - usedWidth) / 2;
  6913. while (leftIndex <= rightIndex) {
  6914. token = tokens[leftIndex];
  6915. // Consider width specified by user, use 'center' rather than 'left'.
  6916. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXLeft + token.width / 2, 'center');
  6917. lineXLeft += token.width;
  6918. leftIndex++;
  6919. }
  6920. lineTop += lineHeight;
  6921. }
  6922. }
  6923. function applyTextRotation(ctx, style, rect, x, y) {
  6924. // textRotation only apply in RectText.
  6925. if (rect && style.textRotation) {
  6926. var origin = style.textOrigin;
  6927. if (origin === 'center') {
  6928. x = rect.width / 2 + rect.x;
  6929. y = rect.height / 2 + rect.y;
  6930. }
  6931. else if (origin) {
  6932. x = origin[0] + rect.x;
  6933. y = origin[1] + rect.y;
  6934. }
  6935. ctx.translate(x, y);
  6936. // Positive: anticlockwise
  6937. ctx.rotate(-style.textRotation);
  6938. ctx.translate(-x, -y);
  6939. }
  6940. }
  6941. function placeToken(hostEl, ctx, token, style, lineHeight, lineTop, x, textAlign) {
  6942. var tokenStyle = style.rich[token.styleName] || {};
  6943. // 'ctx.textBaseline' is always set as 'middle', for sake of
  6944. // the bias of "Microsoft YaHei".
  6945. var textVerticalAlign = token.textVerticalAlign;
  6946. var y = lineTop + lineHeight / 2;
  6947. if (textVerticalAlign === 'top') {
  6948. y = lineTop + token.height / 2;
  6949. }
  6950. else if (textVerticalAlign === 'bottom') {
  6951. y = lineTop + lineHeight - token.height / 2;
  6952. }
  6953. !token.isLineHolder && needDrawBackground(tokenStyle) && drawBackground(
  6954. hostEl,
  6955. ctx,
  6956. tokenStyle,
  6957. textAlign === 'right'
  6958. ? x - token.width
  6959. : textAlign === 'center'
  6960. ? x - token.width / 2
  6961. : x,
  6962. y - token.height / 2,
  6963. token.width,
  6964. token.height
  6965. );
  6966. var textPadding = token.textPadding;
  6967. if (textPadding) {
  6968. x = getTextXForPadding(x, textAlign, textPadding);
  6969. y -= token.height / 2 - textPadding[2] - token.textHeight / 2;
  6970. }
  6971. setCtx(ctx, 'shadowBlur', retrieve3(tokenStyle.textShadowBlur, style.textShadowBlur, 0));
  6972. setCtx(ctx, 'shadowColor', tokenStyle.textShadowColor || style.textShadowColor || 'transparent');
  6973. setCtx(ctx, 'shadowOffsetX', retrieve3(tokenStyle.textShadowOffsetX, style.textShadowOffsetX, 0));
  6974. setCtx(ctx, 'shadowOffsetY', retrieve3(tokenStyle.textShadowOffsetY, style.textShadowOffsetY, 0));
  6975. setCtx(ctx, 'textAlign', textAlign);
  6976. // Force baseline to be "middle". Otherwise, if using "top", the
  6977. // text will offset downward a little bit in font "Microsoft YaHei".
  6978. setCtx(ctx, 'textBaseline', 'middle');
  6979. setCtx(ctx, 'font', token.font || DEFAULT_FONT);
  6980. var textStroke = getStroke(tokenStyle.textStroke || style.textStroke, textStrokeWidth);
  6981. var textFill = getFill(tokenStyle.textFill || style.textFill);
  6982. var textStrokeWidth = retrieve2(tokenStyle.textStrokeWidth, style.textStrokeWidth);
  6983. // Fill after stroke so the outline will not cover the main part.
  6984. if (textStroke) {
  6985. setCtx(ctx, 'lineWidth', textStrokeWidth);
  6986. setCtx(ctx, 'strokeStyle', textStroke);
  6987. ctx.strokeText(token.text, x, y);
  6988. }
  6989. if (textFill) {
  6990. setCtx(ctx, 'fillStyle', textFill);
  6991. ctx.fillText(token.text, x, y);
  6992. }
  6993. }
  6994. function needDrawBackground(style) {
  6995. return style.textBackgroundColor
  6996. || (style.textBorderWidth && style.textBorderColor);
  6997. }
  6998. // style: {textBackgroundColor, textBorderWidth, textBorderColor, textBorderRadius}
  6999. // shape: {x, y, width, height}
  7000. function drawBackground(hostEl, ctx, style, x, y, width, height) {
  7001. var textBackgroundColor = style.textBackgroundColor;
  7002. var textBorderWidth = style.textBorderWidth;
  7003. var textBorderColor = style.textBorderColor;
  7004. var isPlainBg = isString(textBackgroundColor);
  7005. setCtx(ctx, 'shadowBlur', style.textBoxShadowBlur || 0);
  7006. setCtx(ctx, 'shadowColor', style.textBoxShadowColor || 'transparent');
  7007. setCtx(ctx, 'shadowOffsetX', style.textBoxShadowOffsetX || 0);
  7008. setCtx(ctx, 'shadowOffsetY', style.textBoxShadowOffsetY || 0);
  7009. if (isPlainBg || (textBorderWidth && textBorderColor)) {
  7010. ctx.beginPath();
  7011. var textBorderRadius = style.textBorderRadius;
  7012. if (!textBorderRadius) {
  7013. ctx.rect(x, y, width, height);
  7014. }
  7015. else {
  7016. buildPath(ctx, {
  7017. x: x, y: y, width: width, height: height, r: textBorderRadius
  7018. });
  7019. }
  7020. ctx.closePath();
  7021. }
  7022. if (isPlainBg) {
  7023. setCtx(ctx, 'fillStyle', textBackgroundColor);
  7024. ctx.fill();
  7025. }
  7026. else if (isObject$1(textBackgroundColor)) {
  7027. var image = textBackgroundColor.image;
  7028. image = createOrUpdateImage(
  7029. image, null, hostEl, onBgImageLoaded, textBackgroundColor
  7030. );
  7031. if (image && isImageReady(image)) {
  7032. ctx.drawImage(image, x, y, width, height);
  7033. }
  7034. }
  7035. if (textBorderWidth && textBorderColor) {
  7036. setCtx(ctx, 'lineWidth', textBorderWidth);
  7037. setCtx(ctx, 'strokeStyle', textBorderColor);
  7038. ctx.stroke();
  7039. }
  7040. }
  7041. function onBgImageLoaded(image, textBackgroundColor) {
  7042. // Replace image, so that `contain/text.js#parseRichText`
  7043. // will get correct result in next tick.
  7044. textBackgroundColor.image = image;
  7045. }
  7046. function getBoxPosition(blockHeiht, style, rect) {
  7047. var baseX = style.x || 0;
  7048. var baseY = style.y || 0;
  7049. var textAlign = style.textAlign;
  7050. var textVerticalAlign = style.textVerticalAlign;
  7051. // Text position represented by coord
  7052. if (rect) {
  7053. var textPosition = style.textPosition;
  7054. if (textPosition instanceof Array) {
  7055. // Percent
  7056. baseX = rect.x + parsePercent(textPosition[0], rect.width);
  7057. baseY = rect.y + parsePercent(textPosition[1], rect.height);
  7058. }
  7059. else {
  7060. var res = adjustTextPositionOnRect(
  7061. textPosition, rect, style.textDistance
  7062. );
  7063. baseX = res.x;
  7064. baseY = res.y;
  7065. // Default align and baseline when has textPosition
  7066. textAlign = textAlign || res.textAlign;
  7067. textVerticalAlign = textVerticalAlign || res.textVerticalAlign;
  7068. }
  7069. // textOffset is only support in RectText, otherwise
  7070. // we have to adjust boundingRect for textOffset.
  7071. var textOffset = style.textOffset;
  7072. if (textOffset) {
  7073. baseX += textOffset[0];
  7074. baseY += textOffset[1];
  7075. }
  7076. }
  7077. return {
  7078. baseX: baseX,
  7079. baseY: baseY,
  7080. textAlign: textAlign,
  7081. textVerticalAlign: textVerticalAlign
  7082. };
  7083. }
  7084. function setCtx(ctx, prop, value) {
  7085. ctx[prop] = fixShadow(ctx, prop, value);
  7086. return ctx[prop];
  7087. }
  7088. /**
  7089. * @param {string} [stroke] If specified, do not check style.textStroke.
  7090. * @param {string} [lineWidth] If specified, do not check style.textStroke.
  7091. * @param {number} style
  7092. */
  7093. function getStroke(stroke, lineWidth) {
  7094. return (stroke == null || lineWidth <= 0 || stroke === 'transparent' || stroke === 'none')
  7095. ? null
  7096. // TODO pattern and gradient?
  7097. : (stroke.image || stroke.colorStops)
  7098. ? '#000'
  7099. : stroke;
  7100. }
  7101. function getFill(fill) {
  7102. return (fill == null || fill === 'none')
  7103. ? null
  7104. // TODO pattern and gradient?
  7105. : (fill.image || fill.colorStops)
  7106. ? '#000'
  7107. : fill;
  7108. }
  7109. function parsePercent(value, maxValue) {
  7110. if (typeof value === 'string') {
  7111. if (value.lastIndexOf('%') >= 0) {
  7112. return parseFloat(value) / 100 * maxValue;
  7113. }
  7114. return parseFloat(value);
  7115. }
  7116. return value;
  7117. }
  7118. function getTextXForPadding(x, textAlign, textPadding) {
  7119. return textAlign === 'right'
  7120. ? (x - textPadding[1])
  7121. : textAlign === 'center'
  7122. ? (x + textPadding[3] / 2 - textPadding[1] / 2)
  7123. : (x + textPadding[3]);
  7124. }
  7125. /**
  7126. * @param {string} text
  7127. * @param {module:zrender/Style} style
  7128. * @return {boolean}
  7129. */
  7130. function needDrawText(text, style) {
  7131. return text != null
  7132. && (text
  7133. || style.textBackgroundColor
  7134. || (style.textBorderWidth && style.textBorderColor)
  7135. || style.textPadding
  7136. );
  7137. }
  7138. /**
  7139. * Mixin for drawing text in a element bounding rect
  7140. * @module zrender/mixin/RectText
  7141. */
  7142. var tmpRect$1 = new BoundingRect();
  7143. var RectText = function () {};
  7144. RectText.prototype = {
  7145. constructor: RectText,
  7146. /**
  7147. * Draw text in a rect with specified position.
  7148. * @param {CanvasRenderingContext2D} ctx
  7149. * @param {Object} rect Displayable rect
  7150. */
  7151. drawRectText: function (ctx, rect) {
  7152. var style = this.style;
  7153. rect = style.textRect || rect;
  7154. // Optimize, avoid normalize every time.
  7155. this.__dirty && normalizeTextStyle(style, true);
  7156. var text = style.text;
  7157. // Convert to string
  7158. text != null && (text += '');
  7159. if (!needDrawText(text, style)) {
  7160. return;
  7161. }
  7162. // FIXME
  7163. ctx.save();
  7164. // Transform rect to view space
  7165. var transform = this.transform;
  7166. if (!style.transformText) {
  7167. if (transform) {
  7168. tmpRect$1.copy(rect);
  7169. tmpRect$1.applyTransform(transform);
  7170. rect = tmpRect$1;
  7171. }
  7172. }
  7173. else {
  7174. this.setTransform(ctx);
  7175. }
  7176. // transformText and textRotation can not be used at the same time.
  7177. renderText(this, ctx, text, style, rect);
  7178. ctx.restore();
  7179. }
  7180. };
  7181. /**
  7182. * 可绘制的图形基类
  7183. * Base class of all displayable graphic objects
  7184. * @module zrender/graphic/Displayable
  7185. */
  7186. /**
  7187. * @alias module:zrender/graphic/Displayable
  7188. * @extends module:zrender/Element
  7189. * @extends module:zrender/graphic/mixin/RectText
  7190. */
  7191. function Displayable(opts) {
  7192. opts = opts || {};
  7193. Element.call(this, opts);
  7194. // Extend properties
  7195. for (var name in opts) {
  7196. if (
  7197. opts.hasOwnProperty(name) &&
  7198. name !== 'style'
  7199. ) {
  7200. this[name] = opts[name];
  7201. }
  7202. }
  7203. /**
  7204. * @type {module:zrender/graphic/Style}
  7205. */
  7206. this.style = new Style(opts.style, this);
  7207. this._rect = null;
  7208. // Shapes for cascade clipping.
  7209. this.__clipPaths = [];
  7210. // FIXME Stateful must be mixined after style is setted
  7211. // Stateful.call(this, opts);
  7212. }
  7213. Displayable.prototype = {
  7214. constructor: Displayable,
  7215. type: 'displayable',
  7216. /**
  7217. * Displayable 是否为脏,Painter 中会根据该标记判断是否需要是否需要重新绘制
  7218. * Dirty flag. From which painter will determine if this displayable object needs brush
  7219. * @name module:zrender/graphic/Displayable#__dirty
  7220. * @type {boolean}
  7221. */
  7222. __dirty: true,
  7223. /**
  7224. * 图形是否可见,为true时不绘制图形,但是仍能触发鼠标事件
  7225. * If ignore drawing of the displayable object. Mouse event will still be triggered
  7226. * @name module:/zrender/graphic/Displayable#invisible
  7227. * @type {boolean}
  7228. * @default false
  7229. */
  7230. invisible: false,
  7231. /**
  7232. * @name module:/zrender/graphic/Displayable#z
  7233. * @type {number}
  7234. * @default 0
  7235. */
  7236. z: 0,
  7237. /**
  7238. * @name module:/zrender/graphic/Displayable#z
  7239. * @type {number}
  7240. * @default 0
  7241. */
  7242. z2: 0,
  7243. /**
  7244. * z层level,决定绘画在哪层canvas中
  7245. * @name module:/zrender/graphic/Displayable#zlevel
  7246. * @type {number}
  7247. * @default 0
  7248. */
  7249. zlevel: 0,
  7250. /**
  7251. * 是否可拖拽
  7252. * @name module:/zrender/graphic/Displayable#draggable
  7253. * @type {boolean}
  7254. * @default false
  7255. */
  7256. draggable: false,
  7257. /**
  7258. * 是否正在拖拽
  7259. * @name module:/zrender/graphic/Displayable#draggable
  7260. * @type {boolean}
  7261. * @default false
  7262. */
  7263. dragging: false,
  7264. /**
  7265. * 是否相应鼠标事件
  7266. * @name module:/zrender/graphic/Displayable#silent
  7267. * @type {boolean}
  7268. * @default false
  7269. */
  7270. silent: false,
  7271. /**
  7272. * If enable culling
  7273. * @type {boolean}
  7274. * @default false
  7275. */
  7276. culling: false,
  7277. /**
  7278. * Mouse cursor when hovered
  7279. * @name module:/zrender/graphic/Displayable#cursor
  7280. * @type {string}
  7281. */
  7282. cursor: 'pointer',
  7283. /**
  7284. * If hover area is bounding rect
  7285. * @name module:/zrender/graphic/Displayable#rectHover
  7286. * @type {string}
  7287. */
  7288. rectHover: false,
  7289. /**
  7290. * Render the element progressively when the value >= 0,
  7291. * usefull for large data.
  7292. * @type {boolean}
  7293. */
  7294. progressive: false,
  7295. /**
  7296. * @type {boolean}
  7297. */
  7298. incremental: false,
  7299. // inplace is used with incremental
  7300. inplace: false,
  7301. beforeBrush: function (ctx) {},
  7302. afterBrush: function (ctx) {},
  7303. /**
  7304. * 图形绘制方法
  7305. * @param {CanvasRenderingContext2D} ctx
  7306. */
  7307. // Interface
  7308. brush: function (ctx, prevEl) {},
  7309. /**
  7310. * 获取最小包围盒
  7311. * @return {module:zrender/core/BoundingRect}
  7312. */
  7313. // Interface
  7314. getBoundingRect: function () {},
  7315. /**
  7316. * 判断坐标 x, y 是否在图形上
  7317. * If displayable element contain coord x, y
  7318. * @param {number} x
  7319. * @param {number} y
  7320. * @return {boolean}
  7321. */
  7322. contain: function (x, y) {
  7323. return this.rectContain(x, y);
  7324. },
  7325. /**
  7326. * @param {Function} cb
  7327. * @param {} context
  7328. */
  7329. traverse: function (cb, context) {
  7330. cb.call(context, this);
  7331. },
  7332. /**
  7333. * 判断坐标 x, y 是否在图形的包围盒上
  7334. * If bounding rect of element contain coord x, y
  7335. * @param {number} x
  7336. * @param {number} y
  7337. * @return {boolean}
  7338. */
  7339. rectContain: function (x, y) {
  7340. var coord = this.transformCoordToLocal(x, y);
  7341. var rect = this.getBoundingRect();
  7342. return rect.contain(coord[0], coord[1]);
  7343. },
  7344. /**
  7345. * 标记图形元素为脏,并且在下一帧重绘
  7346. * Mark displayable element dirty and refresh next frame
  7347. */
  7348. dirty: function () {
  7349. this.__dirty = true;
  7350. this._rect = null;
  7351. this.__zr && this.__zr.refresh();
  7352. },
  7353. /**
  7354. * 图形是否会触发事件
  7355. * If displayable object binded any event
  7356. * @return {boolean}
  7357. */
  7358. // TODO, 通过 bind 绑定的事件
  7359. // isSilent: function () {
  7360. // return !(
  7361. // this.hoverable || this.draggable
  7362. // || this.onmousemove || this.onmouseover || this.onmouseout
  7363. // || this.onmousedown || this.onmouseup || this.onclick
  7364. // || this.ondragenter || this.ondragover || this.ondragleave
  7365. // || this.ondrop
  7366. // );
  7367. // },
  7368. /**
  7369. * Alias for animate('style')
  7370. * @param {boolean} loop
  7371. */
  7372. animateStyle: function (loop) {
  7373. return this.animate('style', loop);
  7374. },
  7375. attrKV: function (key, value) {
  7376. if (key !== 'style') {
  7377. Element.prototype.attrKV.call(this, key, value);
  7378. }
  7379. else {
  7380. this.style.set(value);
  7381. }
  7382. },
  7383. /**
  7384. * @param {Object|string} key
  7385. * @param {*} value
  7386. */
  7387. setStyle: function (key, value) {
  7388. this.style.set(key, value);
  7389. this.dirty(false);
  7390. return this;
  7391. },
  7392. /**
  7393. * Use given style object
  7394. * @param {Object} obj
  7395. */
  7396. useStyle: function (obj) {
  7397. this.style = new Style(obj, this);
  7398. this.dirty(false);
  7399. return this;
  7400. }
  7401. };
  7402. inherits(Displayable, Element);
  7403. mixin(Displayable, RectText);
  7404. /**
  7405. * @alias zrender/graphic/Image
  7406. * @extends module:zrender/graphic/Displayable
  7407. * @constructor
  7408. * @param {Object} opts
  7409. */
  7410. function ZImage(opts) {
  7411. Displayable.call(this, opts);
  7412. }
  7413. ZImage.prototype = {
  7414. constructor: ZImage,
  7415. type: 'image',
  7416. brush: function (ctx, prevEl) {
  7417. var style = this.style;
  7418. var src = style.image;
  7419. // Must bind each time
  7420. style.bind(ctx, this, prevEl);
  7421. var image = this._image = createOrUpdateImage(
  7422. src,
  7423. this._image,
  7424. this,
  7425. this.onload
  7426. );
  7427. if (!image || !isImageReady(image)) {
  7428. return;
  7429. }
  7430. // 图片已经加载完成
  7431. // if (image.nodeName.toUpperCase() == 'IMG') {
  7432. // if (!image.complete) {
  7433. // return;
  7434. // }
  7435. // }
  7436. // Else is canvas
  7437. var x = style.x || 0;
  7438. var y = style.y || 0;
  7439. var width = style.width;
  7440. var height = style.height;
  7441. var aspect = image.width / image.height;
  7442. if (width == null && height != null) {
  7443. // Keep image/height ratio
  7444. width = height * aspect;
  7445. }
  7446. else if (height == null && width != null) {
  7447. height = width / aspect;
  7448. }
  7449. else if (width == null && height == null) {
  7450. width = image.width;
  7451. height = image.height;
  7452. }
  7453. // 设置transform
  7454. this.setTransform(ctx);
  7455. if (style.sWidth && style.sHeight) {
  7456. var sx = style.sx || 0;
  7457. var sy = style.sy || 0;
  7458. ctx.drawImage(
  7459. image,
  7460. sx, sy, style.sWidth, style.sHeight,
  7461. x, y, width, height
  7462. );
  7463. }
  7464. else if (style.sx && style.sy) {
  7465. var sx = style.sx;
  7466. var sy = style.sy;
  7467. var sWidth = width - sx;
  7468. var sHeight = height - sy;
  7469. ctx.drawImage(
  7470. image,
  7471. sx, sy, sWidth, sHeight,
  7472. x, y, width, height
  7473. );
  7474. }
  7475. else {
  7476. ctx.drawImage(image, x, y, width, height);
  7477. }
  7478. // Draw rect text
  7479. if (style.text != null) {
  7480. // Only restore transform when needs draw text.
  7481. this.restoreTransform(ctx);
  7482. this.drawRectText(ctx, this.getBoundingRect());
  7483. }
  7484. },
  7485. getBoundingRect: function () {
  7486. var style = this.style;
  7487. if (! this._rect) {
  7488. this._rect = new BoundingRect(
  7489. style.x || 0, style.y || 0, style.width || 0, style.height || 0
  7490. );
  7491. }
  7492. return this._rect;
  7493. }
  7494. };
  7495. inherits(ZImage, Displayable);
  7496. var HOVER_LAYER_ZLEVEL = 1e5;
  7497. var CANVAS_ZLEVEL = 314159;
  7498. var EL_AFTER_INCREMENTAL_INC = 0.01;
  7499. var INCREMENTAL_INC = 0.001;
  7500. function parseInt10(val) {
  7501. return parseInt(val, 10);
  7502. }
  7503. function isLayerValid(layer) {
  7504. if (!layer) {
  7505. return false;
  7506. }
  7507. if (layer.__builtin__) {
  7508. return true;
  7509. }
  7510. if (typeof(layer.resize) !== 'function'
  7511. || typeof(layer.refresh) !== 'function'
  7512. ) {
  7513. return false;
  7514. }
  7515. return true;
  7516. }
  7517. var tmpRect = new BoundingRect(0, 0, 0, 0);
  7518. var viewRect = new BoundingRect(0, 0, 0, 0);
  7519. function isDisplayableCulled(el, width, height) {
  7520. tmpRect.copy(el.getBoundingRect());
  7521. if (el.transform) {
  7522. tmpRect.applyTransform(el.transform);
  7523. }
  7524. viewRect.width = width;
  7525. viewRect.height = height;
  7526. return !tmpRect.intersect(viewRect);
  7527. }
  7528. function isClipPathChanged(clipPaths, prevClipPaths) {
  7529. if (clipPaths == prevClipPaths) { // Can both be null or undefined
  7530. return false;
  7531. }
  7532. if (!clipPaths || !prevClipPaths || (clipPaths.length !== prevClipPaths.length)) {
  7533. return true;
  7534. }
  7535. for (var i = 0; i < clipPaths.length; i++) {
  7536. if (clipPaths[i] !== prevClipPaths[i]) {
  7537. return true;
  7538. }
  7539. }
  7540. }
  7541. function doClip(clipPaths, ctx) {
  7542. for (var i = 0; i < clipPaths.length; i++) {
  7543. var clipPath = clipPaths[i];
  7544. clipPath.setTransform(ctx);
  7545. ctx.beginPath();
  7546. clipPath.buildPath(ctx, clipPath.shape);
  7547. ctx.clip();
  7548. // Transform back
  7549. clipPath.restoreTransform(ctx);
  7550. }
  7551. }
  7552. function createRoot(width, height) {
  7553. var domRoot = document.createElement('div');
  7554. // domRoot.onselectstart = returnFalse; // 避免页面选中的尴尬
  7555. domRoot.style.cssText = [
  7556. 'position:relative',
  7557. 'overflow:hidden',
  7558. 'width:' + width + 'px',
  7559. 'height:' + height + 'px',
  7560. 'padding:0',
  7561. 'margin:0',
  7562. 'border-width:0'
  7563. ].join(';') + ';';
  7564. return domRoot;
  7565. }
  7566. /**
  7567. * @alias module:zrender/Painter
  7568. * @constructor
  7569. * @param {HTMLElement} root 绘图容器
  7570. * @param {module:zrender/Storage} storage
  7571. * @param {Object} opts
  7572. */
  7573. var Painter = function (root, storage, opts) {
  7574. this.type = 'canvas';
  7575. // In node environment using node-canvas
  7576. var singleCanvas = !root.nodeName // In node ?
  7577. || root.nodeName.toUpperCase() === 'CANVAS';
  7578. this._opts = opts = extend({}, opts || {});
  7579. /**
  7580. * @type {number}
  7581. */
  7582. this.dpr = opts.devicePixelRatio || devicePixelRatio;
  7583. /**
  7584. * @type {boolean}
  7585. * @private
  7586. */
  7587. this._singleCanvas = singleCanvas;
  7588. /**
  7589. * 绘图容器
  7590. * @type {HTMLElement}
  7591. */
  7592. this.root = root;
  7593. var rootStyle = root.style;
  7594. if (rootStyle) {
  7595. rootStyle['-webkit-tap-highlight-color'] = 'transparent';
  7596. rootStyle['-webkit-user-select'] =
  7597. rootStyle['user-select'] =
  7598. rootStyle['-webkit-touch-callout'] = 'none';
  7599. root.innerHTML = '';
  7600. }
  7601. /**
  7602. * @type {module:zrender/Storage}
  7603. */
  7604. this.storage = storage;
  7605. /**
  7606. * @type {Array.<number>}
  7607. * @private
  7608. */
  7609. var zlevelList = this._zlevelList = [];
  7610. /**
  7611. * @type {Object.<string, module:zrender/Layer>}
  7612. * @private
  7613. */
  7614. var layers = this._layers = {};
  7615. /**
  7616. * @type {Object.<string, Object>}
  7617. * @private
  7618. */
  7619. this._layerConfig = {};
  7620. /**
  7621. * zrender will do compositing when root is a canvas and have multiple zlevels.
  7622. */
  7623. this._needsManuallyCompositing = false;
  7624. if (!singleCanvas) {
  7625. this._width = this._getSize(0);
  7626. this._height = this._getSize(1);
  7627. var domRoot = this._domRoot = createRoot(
  7628. this._width, this._height
  7629. );
  7630. root.appendChild(domRoot);
  7631. }
  7632. else {
  7633. var width = root.width;
  7634. var height = root.height;
  7635. if (opts.width != null) {
  7636. width = opts.width;
  7637. }
  7638. if (opts.height != null) {
  7639. height = opts.height;
  7640. }
  7641. this.dpr = opts.devicePixelRatio || 1;
  7642. // Use canvas width and height directly
  7643. root.width = width * this.dpr;
  7644. root.height = height * this.dpr;
  7645. this._width = width;
  7646. this._height = height;
  7647. // Create layer if only one given canvas
  7648. // Device can be specified to create a high dpi image.
  7649. var mainLayer = new Layer(root, this, this.dpr);
  7650. mainLayer.__builtin__ = true;
  7651. mainLayer.initContext();
  7652. // FIXME Use canvas width and height
  7653. // mainLayer.resize(width, height);
  7654. layers[CANVAS_ZLEVEL] = mainLayer;
  7655. mainLayer.zlevel = CANVAS_ZLEVEL;
  7656. // Not use common zlevel.
  7657. zlevelList.push(CANVAS_ZLEVEL);
  7658. this._domRoot = root;
  7659. }
  7660. /**
  7661. * @type {module:zrender/Layer}
  7662. * @private
  7663. */
  7664. this._hoverlayer = null;
  7665. this._hoverElements = [];
  7666. };
  7667. Painter.prototype = {
  7668. constructor: Painter,
  7669. getType: function () {
  7670. return 'canvas';
  7671. },
  7672. /**
  7673. * If painter use a single canvas
  7674. * @return {boolean}
  7675. */
  7676. isSingleCanvas: function () {
  7677. return this._singleCanvas;
  7678. },
  7679. /**
  7680. * @return {HTMLDivElement}
  7681. */
  7682. getViewportRoot: function () {
  7683. return this._domRoot;
  7684. },
  7685. getViewportRootOffset: function () {
  7686. var viewportRoot = this.getViewportRoot();
  7687. if (viewportRoot) {
  7688. return {
  7689. offsetLeft: viewportRoot.offsetLeft || 0,
  7690. offsetTop: viewportRoot.offsetTop || 0
  7691. };
  7692. }
  7693. },
  7694. /**
  7695. * 刷新
  7696. * @param {boolean} [paintAll=false] 强制绘制所有displayable
  7697. */
  7698. refresh: function (paintAll) {
  7699. var list = this.storage.getDisplayList(true);
  7700. var zlevelList = this._zlevelList;
  7701. this._redrawId = Math.random();
  7702. this._paintList(list, paintAll, this._redrawId);
  7703. // Paint custum layers
  7704. for (var i = 0; i < zlevelList.length; i++) {
  7705. var z = zlevelList[i];
  7706. var layer = this._layers[z];
  7707. if (!layer.__builtin__ && layer.refresh) {
  7708. var clearColor = i === 0 ? this._backgroundColor : null;
  7709. layer.refresh(clearColor);
  7710. }
  7711. }
  7712. this.refreshHover();
  7713. return this;
  7714. },
  7715. addHover: function (el, hoverStyle) {
  7716. if (el.__hoverMir) {
  7717. return;
  7718. }
  7719. var elMirror = new el.constructor({
  7720. style: el.style,
  7721. shape: el.shape
  7722. });
  7723. elMirror.__from = el;
  7724. el.__hoverMir = elMirror;
  7725. elMirror.setStyle(hoverStyle);
  7726. this._hoverElements.push(elMirror);
  7727. },
  7728. removeHover: function (el) {
  7729. var elMirror = el.__hoverMir;
  7730. var hoverElements = this._hoverElements;
  7731. var idx = indexOf(hoverElements, elMirror);
  7732. if (idx >= 0) {
  7733. hoverElements.splice(idx, 1);
  7734. }
  7735. el.__hoverMir = null;
  7736. },
  7737. clearHover: function (el) {
  7738. var hoverElements = this._hoverElements;
  7739. for (var i = 0; i < hoverElements.length; i++) {
  7740. var from = hoverElements[i].__from;
  7741. if (from) {
  7742. from.__hoverMir = null;
  7743. }
  7744. }
  7745. hoverElements.length = 0;
  7746. },
  7747. refreshHover: function () {
  7748. var hoverElements = this._hoverElements;
  7749. var len = hoverElements.length;
  7750. var hoverLayer = this._hoverlayer;
  7751. hoverLayer && hoverLayer.clear();
  7752. if (!len) {
  7753. return;
  7754. }
  7755. sort(hoverElements, this.storage.displayableSortFunc);
  7756. // Use a extream large zlevel
  7757. // FIXME?
  7758. if (!hoverLayer) {
  7759. hoverLayer = this._hoverlayer = this.getLayer(HOVER_LAYER_ZLEVEL);
  7760. }
  7761. var scope = {};
  7762. hoverLayer.ctx.save();
  7763. for (var i = 0; i < len;) {
  7764. var el = hoverElements[i];
  7765. var originalEl = el.__from;
  7766. // Original el is removed
  7767. // PENDING
  7768. if (!(originalEl && originalEl.__zr)) {
  7769. hoverElements.splice(i, 1);
  7770. originalEl.__hoverMir = null;
  7771. len--;
  7772. continue;
  7773. }
  7774. i++;
  7775. // Use transform
  7776. // FIXME style and shape ?
  7777. if (!originalEl.invisible) {
  7778. el.transform = originalEl.transform;
  7779. el.invTransform = originalEl.invTransform;
  7780. el.__clipPaths = originalEl.__clipPaths;
  7781. // el.
  7782. this._doPaintEl(el, hoverLayer, true, scope);
  7783. }
  7784. }
  7785. hoverLayer.ctx.restore();
  7786. },
  7787. getHoverLayer: function () {
  7788. return this.getLayer(HOVER_LAYER_ZLEVEL);
  7789. },
  7790. _paintList: function (list, paintAll, redrawId) {
  7791. if (this._redrawId !== redrawId) {
  7792. return;
  7793. }
  7794. paintAll = paintAll || false;
  7795. this._updateLayerStatus(list);
  7796. var finished = this._doPaintList(list, paintAll);
  7797. if (this._needsManuallyCompositing) {
  7798. this._compositeManually();
  7799. }
  7800. if (!finished) {
  7801. var self = this;
  7802. requestAnimationFrame(function () {
  7803. self._paintList(list, paintAll, redrawId);
  7804. });
  7805. }
  7806. },
  7807. _compositeManually: function () {
  7808. var ctx = this.getLayer(CANVAS_ZLEVEL).ctx;
  7809. var width = this._domRoot.width;
  7810. var height = this._domRoot.height;
  7811. ctx.clearRect(0, 0, width, height);
  7812. // PENDING, If only builtin layer?
  7813. this.eachBuiltinLayer(function (layer) {
  7814. if (layer.virtual) {
  7815. ctx.drawImage(layer.dom, 0, 0, width, height);
  7816. }
  7817. });
  7818. },
  7819. _doPaintList: function (list, paintAll) {
  7820. var layerList = [];
  7821. for (var zi = 0; zi < this._zlevelList.length; zi++) {
  7822. var zlevel = this._zlevelList[zi];
  7823. var layer = this._layers[zlevel];
  7824. if (layer.__builtin__
  7825. && layer !== this._hoverlayer
  7826. && (layer.__dirty || paintAll)
  7827. ) {
  7828. layerList.push(layer);
  7829. }
  7830. }
  7831. var finished = true;
  7832. for (var k = 0; k < layerList.length; k++) {
  7833. var layer = layerList[k];
  7834. var ctx = layer.ctx;
  7835. var scope = {};
  7836. ctx.save();
  7837. var start = paintAll ? layer.__startIndex : layer.__drawIndex;
  7838. var useTimer = !paintAll && layer.incremental && Date.now;
  7839. var startTime = useTimer && Date.now();
  7840. var clearColor = layer.zlevel === this._zlevelList[0]
  7841. ? this._backgroundColor : null;
  7842. // All elements in this layer are cleared.
  7843. if (layer.__startIndex === layer.__endIndex) {
  7844. layer.clear(false, clearColor);
  7845. }
  7846. else if (start === layer.__startIndex) {
  7847. var firstEl = list[start];
  7848. if (!firstEl.incremental || !firstEl.notClear || paintAll) {
  7849. layer.clear(false, clearColor);
  7850. }
  7851. }
  7852. if (start === -1) {
  7853. console.error('For some unknown reason. drawIndex is -1');
  7854. start = layer.__startIndex;
  7855. }
  7856. for (var i = start; i < layer.__endIndex; i++) {
  7857. var el = list[i];
  7858. this._doPaintEl(el, layer, paintAll, scope);
  7859. el.__dirty = false;
  7860. if (useTimer) {
  7861. // Date.now can be executed in 13,025,305 ops/second.
  7862. var dTime = Date.now() - startTime;
  7863. // Give 15 millisecond to draw.
  7864. // The rest elements will be drawn in the next frame.
  7865. if (dTime > 15) {
  7866. break;
  7867. }
  7868. }
  7869. }
  7870. layer.__drawIndex = i;
  7871. if (layer.__drawIndex < layer.__endIndex) {
  7872. finished = false;
  7873. }
  7874. if (scope.prevElClipPaths) {
  7875. // Needs restore the state. If last drawn element is in the clipping area.
  7876. ctx.restore();
  7877. }
  7878. ctx.restore();
  7879. }
  7880. if (env$1.wxa) {
  7881. // Flush for weixin application
  7882. each$1(this._layers, function (layer) {
  7883. if (layer && layer.ctx && layer.ctx.draw) {
  7884. layer.ctx.draw();
  7885. }
  7886. });
  7887. }
  7888. return finished;
  7889. },
  7890. _doPaintEl: function (el, currentLayer, forcePaint, scope) {
  7891. var ctx = currentLayer.ctx;
  7892. var m = el.transform;
  7893. if (
  7894. (currentLayer.__dirty || forcePaint)
  7895. // Ignore invisible element
  7896. && !el.invisible
  7897. // Ignore transparent element
  7898. && el.style.opacity !== 0
  7899. // Ignore scale 0 element, in some environment like node-canvas
  7900. // Draw a scale 0 element can cause all following draw wrong
  7901. // And setTransform with scale 0 will cause set back transform failed.
  7902. && !(m && !m[0] && !m[3])
  7903. // Ignore culled element
  7904. && !(el.culling && isDisplayableCulled(el, this._width, this._height))
  7905. ) {
  7906. var clipPaths = el.__clipPaths;
  7907. // Optimize when clipping on group with several elements
  7908. if (!scope.prevElClipPaths
  7909. || isClipPathChanged(clipPaths, scope.prevElClipPaths)
  7910. ) {
  7911. // If has previous clipping state, restore from it
  7912. if (scope.prevElClipPaths) {
  7913. currentLayer.ctx.restore();
  7914. scope.prevElClipPaths = null;
  7915. // Reset prevEl since context has been restored
  7916. scope.prevEl = null;
  7917. }
  7918. // New clipping state
  7919. if (clipPaths) {
  7920. ctx.save();
  7921. doClip(clipPaths, ctx);
  7922. scope.prevElClipPaths = clipPaths;
  7923. }
  7924. }
  7925. el.beforeBrush && el.beforeBrush(ctx);
  7926. el.brush(ctx, scope.prevEl || null);
  7927. scope.prevEl = el;
  7928. el.afterBrush && el.afterBrush(ctx);
  7929. }
  7930. },
  7931. /**
  7932. * 获取 zlevel 所在层,如果不存在则会创建一个新的层
  7933. * @param {number} zlevel
  7934. * @param {boolean} virtual Virtual layer will not be inserted into dom.
  7935. * @return {module:zrender/Layer}
  7936. */
  7937. getLayer: function (zlevel, virtual) {
  7938. if (this._singleCanvas && !this._needsManuallyCompositing) {
  7939. zlevel = CANVAS_ZLEVEL;
  7940. }
  7941. var layer = this._layers[zlevel];
  7942. if (!layer) {
  7943. // Create a new layer
  7944. layer = new Layer('zr_' + zlevel, this, this.dpr);
  7945. layer.zlevel = zlevel;
  7946. layer.__builtin__ = true;
  7947. if (this._layerConfig[zlevel]) {
  7948. merge(layer, this._layerConfig[zlevel], true);
  7949. }
  7950. if (virtual) {
  7951. layer.virtual = virtual;
  7952. }
  7953. this.insertLayer(zlevel, layer);
  7954. // Context is created after dom inserted to document
  7955. // Or excanvas will get 0px clientWidth and clientHeight
  7956. layer.initContext();
  7957. }
  7958. return layer;
  7959. },
  7960. insertLayer: function (zlevel, layer) {
  7961. var layersMap = this._layers;
  7962. var zlevelList = this._zlevelList;
  7963. var len = zlevelList.length;
  7964. var prevLayer = null;
  7965. var i = -1;
  7966. var domRoot = this._domRoot;
  7967. if (layersMap[zlevel]) {
  7968. zrLog('ZLevel ' + zlevel + ' has been used already');
  7969. return;
  7970. }
  7971. // Check if is a valid layer
  7972. if (!isLayerValid(layer)) {
  7973. zrLog('Layer of zlevel ' + zlevel + ' is not valid');
  7974. return;
  7975. }
  7976. if (len > 0 && zlevel > zlevelList[0]) {
  7977. for (i = 0; i < len - 1; i++) {
  7978. if (
  7979. zlevelList[i] < zlevel
  7980. && zlevelList[i + 1] > zlevel
  7981. ) {
  7982. break;
  7983. }
  7984. }
  7985. prevLayer = layersMap[zlevelList[i]];
  7986. }
  7987. zlevelList.splice(i + 1, 0, zlevel);
  7988. layersMap[zlevel] = layer;
  7989. // Vitual layer will not directly show on the screen.
  7990. // (It can be a WebGL layer and assigned to a ZImage element)
  7991. // But it still under management of zrender.
  7992. if (!layer.virtual) {
  7993. if (prevLayer) {
  7994. var prevDom = prevLayer.dom;
  7995. if (prevDom.nextSibling) {
  7996. domRoot.insertBefore(
  7997. layer.dom,
  7998. prevDom.nextSibling
  7999. );
  8000. }
  8001. else {
  8002. domRoot.appendChild(layer.dom);
  8003. }
  8004. }
  8005. else {
  8006. if (domRoot.firstChild) {
  8007. domRoot.insertBefore(layer.dom, domRoot.firstChild);
  8008. }
  8009. else {
  8010. domRoot.appendChild(layer.dom);
  8011. }
  8012. }
  8013. }
  8014. },
  8015. // Iterate each layer
  8016. eachLayer: function (cb, context) {
  8017. var zlevelList = this._zlevelList;
  8018. var z;
  8019. var i;
  8020. for (i = 0; i < zlevelList.length; i++) {
  8021. z = zlevelList[i];
  8022. cb.call(context, this._layers[z], z);
  8023. }
  8024. },
  8025. // Iterate each buildin layer
  8026. eachBuiltinLayer: function (cb, context) {
  8027. var zlevelList = this._zlevelList;
  8028. var layer;
  8029. var z;
  8030. var i;
  8031. for (i = 0; i < zlevelList.length; i++) {
  8032. z = zlevelList[i];
  8033. layer = this._layers[z];
  8034. if (layer.__builtin__) {
  8035. cb.call(context, layer, z);
  8036. }
  8037. }
  8038. },
  8039. // Iterate each other layer except buildin layer
  8040. eachOtherLayer: function (cb, context) {
  8041. var zlevelList = this._zlevelList;
  8042. var layer;
  8043. var z;
  8044. var i;
  8045. for (i = 0; i < zlevelList.length; i++) {
  8046. z = zlevelList[i];
  8047. layer = this._layers[z];
  8048. if (!layer.__builtin__) {
  8049. cb.call(context, layer, z);
  8050. }
  8051. }
  8052. },
  8053. /**
  8054. * 获取所有已创建的层
  8055. * @param {Array.<module:zrender/Layer>} [prevLayer]
  8056. */
  8057. getLayers: function () {
  8058. return this._layers;
  8059. },
  8060. _updateLayerStatus: function (list) {
  8061. this.eachBuiltinLayer(function (layer, z) {
  8062. layer.__dirty = layer.__used = false;
  8063. });
  8064. function updatePrevLayer(idx) {
  8065. if (prevLayer) {
  8066. if (prevLayer.__endIndex !== idx) {
  8067. prevLayer.__dirty = true;
  8068. }
  8069. prevLayer.__endIndex = idx;
  8070. }
  8071. }
  8072. if (this._singleCanvas) {
  8073. for (var i = 1; i < list.length; i++) {
  8074. var el = list[i];
  8075. if (el.zlevel !== list[i - 1].zlevel || el.incremental) {
  8076. this._needsManuallyCompositing = true;
  8077. break;
  8078. }
  8079. }
  8080. }
  8081. var prevLayer = null;
  8082. var incrementalLayerCount = 0;
  8083. for (var i = 0; i < list.length; i++) {
  8084. var el = list[i];
  8085. var zlevel = el.zlevel;
  8086. var layer;
  8087. // PENDING If change one incremental element style ?
  8088. // TODO Where there are non-incremental elements between incremental elements.
  8089. if (el.incremental) {
  8090. layer = this.getLayer(zlevel + INCREMENTAL_INC, this._needsManuallyCompositing);
  8091. layer.incremental = true;
  8092. incrementalLayerCount = 1;
  8093. }
  8094. else {
  8095. layer = this.getLayer(zlevel + (incrementalLayerCount > 0 ? EL_AFTER_INCREMENTAL_INC : 0), this._needsManuallyCompositing);
  8096. }
  8097. if (!layer.__builtin__) {
  8098. zrLog('ZLevel ' + zlevel + ' has been used by unkown layer ' + layer.id);
  8099. }
  8100. if (layer !== prevLayer) {
  8101. layer.__used = true;
  8102. if (layer.__startIndex !== i) {
  8103. layer.__dirty = true;
  8104. }
  8105. layer.__startIndex = i;
  8106. if (!layer.incremental) {
  8107. layer.__drawIndex = i;
  8108. }
  8109. else {
  8110. // Mark layer draw index needs to update.
  8111. layer.__drawIndex = -1;
  8112. }
  8113. updatePrevLayer(i);
  8114. prevLayer = layer;
  8115. }
  8116. if (el.__dirty) {
  8117. layer.__dirty = true;
  8118. if (layer.incremental && layer.__drawIndex < 0) {
  8119. // Start draw from the first dirty element.
  8120. layer.__drawIndex = i;
  8121. }
  8122. }
  8123. }
  8124. updatePrevLayer(i);
  8125. this.eachBuiltinLayer(function (layer, z) {
  8126. // Used in last frame but not in this frame. Needs clear
  8127. if (!layer.__used && layer.getElementCount() > 0) {
  8128. layer.__dirty = true;
  8129. layer.__startIndex = layer.__endIndex = layer.__drawIndex = 0;
  8130. }
  8131. // For incremental layer. In case start index changed and no elements are dirty.
  8132. if (layer.__dirty && layer.__drawIndex < 0) {
  8133. layer.__drawIndex = layer.__startIndex;
  8134. }
  8135. });
  8136. },
  8137. /**
  8138. * 清除hover层外所有内容
  8139. */
  8140. clear: function () {
  8141. this.eachBuiltinLayer(this._clearLayer);
  8142. return this;
  8143. },
  8144. _clearLayer: function (layer) {
  8145. layer.clear();
  8146. },
  8147. setBackgroundColor: function (backgroundColor) {
  8148. this._backgroundColor = backgroundColor;
  8149. },
  8150. /**
  8151. * 修改指定zlevel的绘制参数
  8152. *
  8153. * @param {string} zlevel
  8154. * @param {Object} config 配置对象
  8155. * @param {string} [config.clearColor=0] 每次清空画布的颜色
  8156. * @param {string} [config.motionBlur=false] 是否开启动态模糊
  8157. * @param {number} [config.lastFrameAlpha=0.7]
  8158. * 在开启动态模糊的时候使用,与上一帧混合的alpha值,值越大尾迹越明显
  8159. */
  8160. configLayer: function (zlevel, config) {
  8161. if (config) {
  8162. var layerConfig = this._layerConfig;
  8163. if (!layerConfig[zlevel]) {
  8164. layerConfig[zlevel] = config;
  8165. }
  8166. else {
  8167. merge(layerConfig[zlevel], config, true);
  8168. }
  8169. for (var i = 0; i < this._zlevelList.length; i++) {
  8170. var _zlevel = this._zlevelList[i];
  8171. if (_zlevel === zlevel || _zlevel === zlevel + EL_AFTER_INCREMENTAL_INC) {
  8172. var layer = this._layers[_zlevel];
  8173. merge(layer, layerConfig[zlevel], true);
  8174. }
  8175. }
  8176. }
  8177. },
  8178. /**
  8179. * 删除指定层
  8180. * @param {number} zlevel 层所在的zlevel
  8181. */
  8182. delLayer: function (zlevel) {
  8183. var layers = this._layers;
  8184. var zlevelList = this._zlevelList;
  8185. var layer = layers[zlevel];
  8186. if (!layer) {
  8187. return;
  8188. }
  8189. layer.dom.parentNode.removeChild(layer.dom);
  8190. delete layers[zlevel];
  8191. zlevelList.splice(indexOf(zlevelList, zlevel), 1);
  8192. },
  8193. /**
  8194. * 区域大小变化后重绘
  8195. */
  8196. resize: function (width, height) {
  8197. if (!this._domRoot.style) { // Maybe in node or worker
  8198. if (width == null || height == null) {
  8199. return;
  8200. }
  8201. this._width = width;
  8202. this._height = height;
  8203. this.getLayer(CANVAS_ZLEVEL).resize(width, height);
  8204. }
  8205. else {
  8206. var domRoot = this._domRoot;
  8207. // FIXME Why ?
  8208. domRoot.style.display = 'none';
  8209. // Save input w/h
  8210. var opts = this._opts;
  8211. width != null && (opts.width = width);
  8212. height != null && (opts.height = height);
  8213. width = this._getSize(0);
  8214. height = this._getSize(1);
  8215. domRoot.style.display = '';
  8216. // 优化没有实际改变的resize
  8217. if (this._width != width || height != this._height) {
  8218. domRoot.style.width = width + 'px';
  8219. domRoot.style.height = height + 'px';
  8220. for (var id in this._layers) {
  8221. if (this._layers.hasOwnProperty(id)) {
  8222. this._layers[id].resize(width, height);
  8223. }
  8224. }
  8225. each$1(this._progressiveLayers, function (layer) {
  8226. layer.resize(width, height);
  8227. });
  8228. this.refresh(true);
  8229. }
  8230. this._width = width;
  8231. this._height = height;
  8232. }
  8233. return this;
  8234. },
  8235. /**
  8236. * 清除单独的一个层
  8237. * @param {number} zlevel
  8238. */
  8239. clearLayer: function (zlevel) {
  8240. var layer = this._layers[zlevel];
  8241. if (layer) {
  8242. layer.clear();
  8243. }
  8244. },
  8245. /**
  8246. * 释放
  8247. */
  8248. dispose: function () {
  8249. this.root.innerHTML = '';
  8250. this.root =
  8251. this.storage =
  8252. this._domRoot =
  8253. this._layers = null;
  8254. },
  8255. /**
  8256. * Get canvas which has all thing rendered
  8257. * @param {Object} opts
  8258. * @param {string} [opts.backgroundColor]
  8259. * @param {number} [opts.pixelRatio]
  8260. */
  8261. getRenderedCanvas: function (opts) {
  8262. opts = opts || {};
  8263. if (this._singleCanvas && !this._compositeManually) {
  8264. return this._layers[CANVAS_ZLEVEL].dom;
  8265. }
  8266. var imageLayer = new Layer('image', this, opts.pixelRatio || this.dpr);
  8267. imageLayer.initContext();
  8268. imageLayer.clear(false, opts.backgroundColor || this._backgroundColor);
  8269. if (opts.pixelRatio <= this.dpr) {
  8270. this.refresh();
  8271. var width = imageLayer.dom.width;
  8272. var height = imageLayer.dom.height;
  8273. var ctx = imageLayer.ctx;
  8274. this.eachLayer(function (layer) {
  8275. if (layer.__builtin__) {
  8276. ctx.drawImage(layer.dom, 0, 0, width, height);
  8277. }
  8278. else if (layer.renderToCanvas) {
  8279. imageLayer.ctx.save();
  8280. layer.renderToCanvas(imageLayer.ctx);
  8281. imageLayer.ctx.restore();
  8282. }
  8283. });
  8284. }
  8285. else {
  8286. // PENDING, echarts-gl and incremental rendering.
  8287. var scope = {};
  8288. var displayList = this.storage.getDisplayList(true);
  8289. for (var i = 0; i < displayList.length; i++) {
  8290. var el = displayList[i];
  8291. this._doPaintEl(el, imageLayer, true, scope);
  8292. }
  8293. }
  8294. return imageLayer.dom;
  8295. },
  8296. /**
  8297. * 获取绘图区域宽度
  8298. */
  8299. getWidth: function () {
  8300. return this._width;
  8301. },
  8302. /**
  8303. * 获取绘图区域高度
  8304. */
  8305. getHeight: function () {
  8306. return this._height;
  8307. },
  8308. _getSize: function (whIdx) {
  8309. var opts = this._opts;
  8310. var wh = ['width', 'height'][whIdx];
  8311. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  8312. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  8313. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  8314. if (opts[wh] != null && opts[wh] !== 'auto') {
  8315. return parseFloat(opts[wh]);
  8316. }
  8317. var root = this.root;
  8318. // IE8 does not support getComputedStyle, but it use VML.
  8319. var stl = document.defaultView.getComputedStyle(root);
  8320. return (
  8321. (root[cwh] || parseInt10(stl[wh]) || parseInt10(root.style[wh]))
  8322. - (parseInt10(stl[plt]) || 0)
  8323. - (parseInt10(stl[prb]) || 0)
  8324. ) | 0;
  8325. },
  8326. pathToImage: function (path, dpr) {
  8327. dpr = dpr || this.dpr;
  8328. var canvas = document.createElement('canvas');
  8329. var ctx = canvas.getContext('2d');
  8330. var rect = path.getBoundingRect();
  8331. var style = path.style;
  8332. var shadowBlurSize = style.shadowBlur * dpr;
  8333. var shadowOffsetX = style.shadowOffsetX * dpr;
  8334. var shadowOffsetY = style.shadowOffsetY * dpr;
  8335. var lineWidth = style.hasStroke() ? style.lineWidth : 0;
  8336. var leftMargin = Math.max(lineWidth / 2, -shadowOffsetX + shadowBlurSize);
  8337. var rightMargin = Math.max(lineWidth / 2, shadowOffsetX + shadowBlurSize);
  8338. var topMargin = Math.max(lineWidth / 2, -shadowOffsetY + shadowBlurSize);
  8339. var bottomMargin = Math.max(lineWidth / 2, shadowOffsetY + shadowBlurSize);
  8340. var width = rect.width + leftMargin + rightMargin;
  8341. var height = rect.height + topMargin + bottomMargin;
  8342. canvas.width = width * dpr;
  8343. canvas.height = height * dpr;
  8344. ctx.scale(dpr, dpr);
  8345. ctx.clearRect(0, 0, width, height);
  8346. ctx.dpr = dpr;
  8347. var pathTransform = {
  8348. position: path.position,
  8349. rotation: path.rotation,
  8350. scale: path.scale
  8351. };
  8352. path.position = [leftMargin - rect.x, topMargin - rect.y];
  8353. path.rotation = 0;
  8354. path.scale = [1, 1];
  8355. path.updateTransform();
  8356. if (path) {
  8357. path.brush(ctx);
  8358. }
  8359. var ImageShape = ZImage;
  8360. var imgShape = new ImageShape({
  8361. style: {
  8362. x: 0,
  8363. y: 0,
  8364. image: canvas
  8365. }
  8366. });
  8367. if (pathTransform.position != null) {
  8368. imgShape.position = path.position = pathTransform.position;
  8369. }
  8370. if (pathTransform.rotation != null) {
  8371. imgShape.rotation = path.rotation = pathTransform.rotation;
  8372. }
  8373. if (pathTransform.scale != null) {
  8374. imgShape.scale = path.scale = pathTransform.scale;
  8375. }
  8376. return imgShape;
  8377. }
  8378. };
  8379. /**
  8380. * 事件辅助类
  8381. * @module zrender/core/event
  8382. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  8383. */
  8384. var isDomLevel2 = (typeof window !== 'undefined') && !!window.addEventListener;
  8385. var MOUSE_EVENT_REG = /^(?:mouse|pointer|contextmenu|drag|drop)|click/;
  8386. function getBoundingClientRect(el) {
  8387. // BlackBerry 5, iOS 3 (original iPhone) don't have getBoundingRect
  8388. return el.getBoundingClientRect ? el.getBoundingClientRect() : {left: 0, top: 0};
  8389. }
  8390. // `calculate` is optional, default false
  8391. function clientToLocal(el, e, out, calculate) {
  8392. out = out || {};
  8393. // According to the W3C Working Draft, offsetX and offsetY should be relative
  8394. // to the padding edge of the target element. The only browser using this convention
  8395. // is IE. Webkit uses the border edge, Opera uses the content edge, and FireFox does
  8396. // not support the properties.
  8397. // (see http://www.jacklmoore.com/notes/mouse-position/)
  8398. // In zr painter.dom, padding edge equals to border edge.
  8399. // FIXME
  8400. // When mousemove event triggered on ec tooltip, target is not zr painter.dom, and
  8401. // offsetX/Y is relative to e.target, where the calculation of zrX/Y via offsetX/Y
  8402. // is too complex. So css-transfrom dont support in this case temporarily.
  8403. if (calculate || !env$1.canvasSupported) {
  8404. defaultGetZrXY(el, e, out);
  8405. }
  8406. // Caution: In FireFox, layerX/layerY Mouse position relative to the closest positioned
  8407. // ancestor element, so we should make sure el is positioned (e.g., not position:static).
  8408. // BTW1, Webkit don't return the same results as FF in non-simple cases (like add
  8409. // zoom-factor, overflow / opacity layers, transforms ...)
  8410. // BTW2, (ev.offsetY || ev.pageY - $(ev.target).offset().top) is not correct in preserve-3d.
  8411. // <https://bugs.jquery.com/ticket/8523#comment:14>
  8412. // BTW3, In ff, offsetX/offsetY is always 0.
  8413. else if (env$1.browser.firefox && e.layerX != null && e.layerX !== e.offsetX) {
  8414. out.zrX = e.layerX;
  8415. out.zrY = e.layerY;
  8416. }
  8417. // For IE6+, chrome, safari, opera. (When will ff support offsetX?)
  8418. else if (e.offsetX != null) {
  8419. out.zrX = e.offsetX;
  8420. out.zrY = e.offsetY;
  8421. }
  8422. // For some other device, e.g., IOS safari.
  8423. else {
  8424. defaultGetZrXY(el, e, out);
  8425. }
  8426. return out;
  8427. }
  8428. function defaultGetZrXY(el, e, out) {
  8429. // This well-known method below does not support css transform.
  8430. var box = getBoundingClientRect(el);
  8431. out.zrX = e.clientX - box.left;
  8432. out.zrY = e.clientY - box.top;
  8433. }
  8434. /**
  8435. * 如果存在第三方嵌入的一些dom触发的事件,或touch事件,需要转换一下事件坐标.
  8436. * `calculate` is optional, default false.
  8437. */
  8438. function normalizeEvent(el, e, calculate) {
  8439. e = e || window.event;
  8440. if (e.zrX != null) {
  8441. return e;
  8442. }
  8443. var eventType = e.type;
  8444. var isTouch = eventType && eventType.indexOf('touch') >= 0;
  8445. if (!isTouch) {
  8446. clientToLocal(el, e, e, calculate);
  8447. e.zrDelta = (e.wheelDelta) ? e.wheelDelta / 120 : -(e.detail || 0) / 3;
  8448. }
  8449. else {
  8450. var touch = eventType != 'touchend'
  8451. ? e.targetTouches[0]
  8452. : e.changedTouches[0];
  8453. touch && clientToLocal(el, touch, e, calculate);
  8454. }
  8455. // Add which for click: 1 === left; 2 === middle; 3 === right; otherwise: 0;
  8456. // See jQuery: https://github.com/jquery/jquery/blob/master/src/event.js
  8457. // If e.which has been defined, if may be readonly,
  8458. // see: https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/which
  8459. var button = e.button;
  8460. if (e.which == null && button !== undefined && MOUSE_EVENT_REG.test(e.type)) {
  8461. e.which = (button & 1 ? 1 : (button & 2 ? 3 : (button & 4 ? 2 : 0)));
  8462. }
  8463. return e;
  8464. }
  8465. /**
  8466. * @param {HTMLElement} el
  8467. * @param {string} name
  8468. * @param {Function} handler
  8469. */
  8470. function addEventListener(el, name, handler) {
  8471. if (isDomLevel2) {
  8472. // Reproduct the console warning:
  8473. // [Violation] Added non-passive event listener to a scroll-blocking <some> event.
  8474. // Consider marking event handler as 'passive' to make the page more responsive.
  8475. // Just set console log level: verbose in chrome dev tool.
  8476. // then the warning log will be printed when addEventListener called.
  8477. // See https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md
  8478. // We have not yet found a neat way to using passive. Because in zrender the dom event
  8479. // listener delegate all of the upper events of element. Some of those events need
  8480. // to prevent default. For example, the feature `preventDefaultMouseMove` of echarts.
  8481. // Before passive can be adopted, these issues should be considered:
  8482. // (1) Whether and how a zrender user specifies an event listener passive. And by default,
  8483. // passive or not.
  8484. // (2) How to tread that some zrender event listener is passive, and some is not. If
  8485. // we use other way but not preventDefault of mousewheel and touchmove, browser
  8486. // compatibility should be handled.
  8487. // var opts = (env.passiveSupported && name === 'mousewheel')
  8488. // ? {passive: true}
  8489. // // By default, the third param of el.addEventListener is `capture: false`.
  8490. // : void 0;
  8491. // el.addEventListener(name, handler /* , opts */);
  8492. el.addEventListener(name, handler);
  8493. }
  8494. else {
  8495. el.attachEvent('on' + name, handler);
  8496. }
  8497. }
  8498. function removeEventListener(el, name, handler) {
  8499. if (isDomLevel2) {
  8500. el.removeEventListener(name, handler);
  8501. }
  8502. else {
  8503. el.detachEvent('on' + name, handler);
  8504. }
  8505. }
  8506. /**
  8507. * preventDefault and stopPropagation.
  8508. * Notice: do not do that in zrender. Upper application
  8509. * do that if necessary.
  8510. *
  8511. * @memberOf module:zrender/core/event
  8512. * @method
  8513. * @param {Event} e : event对象
  8514. */
  8515. var stop = isDomLevel2
  8516. ? function (e) {
  8517. e.preventDefault();
  8518. e.stopPropagation();
  8519. e.cancelBubble = true;
  8520. }
  8521. : function (e) {
  8522. e.returnValue = false;
  8523. e.cancelBubble = true;
  8524. };
  8525. function notLeftMouse(e) {
  8526. // If e.which is undefined, considered as left mouse event.
  8527. return e.which > 1;
  8528. }
  8529. /**
  8530. * 动画主类, 调度和管理所有动画控制器
  8531. *
  8532. * @module zrender/animation/Animation
  8533. * @author pissang(https://github.com/pissang)
  8534. */
  8535. // TODO Additive animation
  8536. // http://iosoteric.com/additive-animations-animatewithduration-in-ios-8/
  8537. // https://developer.apple.com/videos/wwdc2014/#236
  8538. /**
  8539. * @typedef {Object} IZRenderStage
  8540. * @property {Function} update
  8541. */
  8542. /**
  8543. * @alias module:zrender/animation/Animation
  8544. * @constructor
  8545. * @param {Object} [options]
  8546. * @param {Function} [options.onframe]
  8547. * @param {IZRenderStage} [options.stage]
  8548. * @example
  8549. * var animation = new Animation();
  8550. * var obj = {
  8551. * x: 100,
  8552. * y: 100
  8553. * };
  8554. * animation.animate(node.position)
  8555. * .when(1000, {
  8556. * x: 500,
  8557. * y: 500
  8558. * })
  8559. * .when(2000, {
  8560. * x: 100,
  8561. * y: 100
  8562. * })
  8563. * .start('spline');
  8564. */
  8565. var Animation = function (options) {
  8566. options = options || {};
  8567. this.stage = options.stage || {};
  8568. this.onframe = options.onframe || function() {};
  8569. // private properties
  8570. this._clips = [];
  8571. this._running = false;
  8572. this._time;
  8573. this._pausedTime;
  8574. this._pauseStart;
  8575. this._paused = false;
  8576. Eventful.call(this);
  8577. };
  8578. Animation.prototype = {
  8579. constructor: Animation,
  8580. /**
  8581. * 添加 clip
  8582. * @param {module:zrender/animation/Clip} clip
  8583. */
  8584. addClip: function (clip) {
  8585. this._clips.push(clip);
  8586. },
  8587. /**
  8588. * 添加 animator
  8589. * @param {module:zrender/animation/Animator} animator
  8590. */
  8591. addAnimator: function (animator) {
  8592. animator.animation = this;
  8593. var clips = animator.getClips();
  8594. for (var i = 0; i < clips.length; i++) {
  8595. this.addClip(clips[i]);
  8596. }
  8597. },
  8598. /**
  8599. * 删除动画片段
  8600. * @param {module:zrender/animation/Clip} clip
  8601. */
  8602. removeClip: function(clip) {
  8603. var idx = indexOf(this._clips, clip);
  8604. if (idx >= 0) {
  8605. this._clips.splice(idx, 1);
  8606. }
  8607. },
  8608. /**
  8609. * 删除动画片段
  8610. * @param {module:zrender/animation/Animator} animator
  8611. */
  8612. removeAnimator: function (animator) {
  8613. var clips = animator.getClips();
  8614. for (var i = 0; i < clips.length; i++) {
  8615. this.removeClip(clips[i]);
  8616. }
  8617. animator.animation = null;
  8618. },
  8619. _update: function() {
  8620. var time = new Date().getTime() - this._pausedTime;
  8621. var delta = time - this._time;
  8622. var clips = this._clips;
  8623. var len = clips.length;
  8624. var deferredEvents = [];
  8625. var deferredClips = [];
  8626. for (var i = 0; i < len; i++) {
  8627. var clip = clips[i];
  8628. var e = clip.step(time, delta);
  8629. // Throw out the events need to be called after
  8630. // stage.update, like destroy
  8631. if (e) {
  8632. deferredEvents.push(e);
  8633. deferredClips.push(clip);
  8634. }
  8635. }
  8636. // Remove the finished clip
  8637. for (var i = 0; i < len;) {
  8638. if (clips[i]._needsRemove) {
  8639. clips[i] = clips[len - 1];
  8640. clips.pop();
  8641. len--;
  8642. }
  8643. else {
  8644. i++;
  8645. }
  8646. }
  8647. len = deferredEvents.length;
  8648. for (var i = 0; i < len; i++) {
  8649. deferredClips[i].fire(deferredEvents[i]);
  8650. }
  8651. this._time = time;
  8652. this.onframe(delta);
  8653. // 'frame' should be triggered before stage, because upper application
  8654. // depends on the sequence (e.g., echarts-stream and finish
  8655. // event judge)
  8656. this.trigger('frame', delta);
  8657. if (this.stage.update) {
  8658. this.stage.update();
  8659. }
  8660. },
  8661. _startLoop: function () {
  8662. var self = this;
  8663. this._running = true;
  8664. function step() {
  8665. if (self._running) {
  8666. requestAnimationFrame(step);
  8667. !self._paused && self._update();
  8668. }
  8669. }
  8670. requestAnimationFrame(step);
  8671. },
  8672. /**
  8673. * Start animation.
  8674. */
  8675. start: function () {
  8676. this._time = new Date().getTime();
  8677. this._pausedTime = 0;
  8678. this._startLoop();
  8679. },
  8680. /**
  8681. * Stop animation.
  8682. */
  8683. stop: function () {
  8684. this._running = false;
  8685. },
  8686. /**
  8687. * Pause animation.
  8688. */
  8689. pause: function () {
  8690. if (!this._paused) {
  8691. this._pauseStart = new Date().getTime();
  8692. this._paused = true;
  8693. }
  8694. },
  8695. /**
  8696. * Resume animation.
  8697. */
  8698. resume: function () {
  8699. if (this._paused) {
  8700. this._pausedTime += (new Date().getTime()) - this._pauseStart;
  8701. this._paused = false;
  8702. }
  8703. },
  8704. /**
  8705. * Clear animation.
  8706. */
  8707. clear: function () {
  8708. this._clips = [];
  8709. },
  8710. /**
  8711. * Whether animation finished.
  8712. */
  8713. isFinished: function () {
  8714. return !this._clips.length;
  8715. },
  8716. /**
  8717. * Creat animator for a target, whose props can be animated.
  8718. *
  8719. * @param {Object} target
  8720. * @param {Object} options
  8721. * @param {boolean} [options.loop=false] Whether loop animation.
  8722. * @param {Function} [options.getter=null] Get value from target.
  8723. * @param {Function} [options.setter=null] Set value to target.
  8724. * @return {module:zrender/animation/Animation~Animator}
  8725. */
  8726. // TODO Gap
  8727. animate: function (target, options) {
  8728. options = options || {};
  8729. var animator = new Animator(
  8730. target,
  8731. options.loop,
  8732. options.getter,
  8733. options.setter
  8734. );
  8735. this.addAnimator(animator);
  8736. return animator;
  8737. }
  8738. };
  8739. mixin(Animation, Eventful);
  8740. /**
  8741. * Only implements needed gestures for mobile.
  8742. */
  8743. var GestureMgr = function () {
  8744. /**
  8745. * @private
  8746. * @type {Array.<Object>}
  8747. */
  8748. this._track = [];
  8749. };
  8750. GestureMgr.prototype = {
  8751. constructor: GestureMgr,
  8752. recognize: function (event, target, root) {
  8753. this._doTrack(event, target, root);
  8754. return this._recognize(event);
  8755. },
  8756. clear: function () {
  8757. this._track.length = 0;
  8758. return this;
  8759. },
  8760. _doTrack: function (event, target, root) {
  8761. var touches = event.touches;
  8762. if (!touches) {
  8763. return;
  8764. }
  8765. var trackItem = {
  8766. points: [],
  8767. touches: [],
  8768. target: target,
  8769. event: event
  8770. };
  8771. for (var i = 0, len = touches.length; i < len; i++) {
  8772. var touch = touches[i];
  8773. var pos = clientToLocal(root, touch, {});
  8774. trackItem.points.push([pos.zrX, pos.zrY]);
  8775. trackItem.touches.push(touch);
  8776. }
  8777. this._track.push(trackItem);
  8778. },
  8779. _recognize: function (event) {
  8780. for (var eventName in recognizers) {
  8781. if (recognizers.hasOwnProperty(eventName)) {
  8782. var gestureInfo = recognizers[eventName](this._track, event);
  8783. if (gestureInfo) {
  8784. return gestureInfo;
  8785. }
  8786. }
  8787. }
  8788. }
  8789. };
  8790. function dist$1(pointPair) {
  8791. var dx = pointPair[1][0] - pointPair[0][0];
  8792. var dy = pointPair[1][1] - pointPair[0][1];
  8793. return Math.sqrt(dx * dx + dy * dy);
  8794. }
  8795. function center(pointPair) {
  8796. return [
  8797. (pointPair[0][0] + pointPair[1][0]) / 2,
  8798. (pointPair[0][1] + pointPair[1][1]) / 2
  8799. ];
  8800. }
  8801. var recognizers = {
  8802. pinch: function (track, event) {
  8803. var trackLen = track.length;
  8804. if (!trackLen) {
  8805. return;
  8806. }
  8807. var pinchEnd = (track[trackLen - 1] || {}).points;
  8808. var pinchPre = (track[trackLen - 2] || {}).points || pinchEnd;
  8809. if (pinchPre
  8810. && pinchPre.length > 1
  8811. && pinchEnd
  8812. && pinchEnd.length > 1
  8813. ) {
  8814. var pinchScale = dist$1(pinchEnd) / dist$1(pinchPre);
  8815. !isFinite(pinchScale) && (pinchScale = 1);
  8816. event.pinchScale = pinchScale;
  8817. var pinchCenter = center(pinchEnd);
  8818. event.pinchX = pinchCenter[0];
  8819. event.pinchY = pinchCenter[1];
  8820. return {
  8821. type: 'pinch',
  8822. target: track[0].target,
  8823. event: event
  8824. };
  8825. }
  8826. }
  8827. // Only pinch currently.
  8828. };
  8829. var TOUCH_CLICK_DELAY = 300;
  8830. var mouseHandlerNames = [
  8831. 'click', 'dblclick', 'mousewheel', 'mouseout',
  8832. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  8833. ];
  8834. var touchHandlerNames = [
  8835. 'touchstart', 'touchend', 'touchmove'
  8836. ];
  8837. var pointerEventNames = {
  8838. pointerdown: 1, pointerup: 1, pointermove: 1, pointerout: 1
  8839. };
  8840. var pointerHandlerNames = map(mouseHandlerNames, function (name) {
  8841. var nm = name.replace('mouse', 'pointer');
  8842. return pointerEventNames[nm] ? nm : name;
  8843. });
  8844. function eventNameFix(name) {
  8845. return (name === 'mousewheel' && env$1.browser.firefox) ? 'DOMMouseScroll' : name;
  8846. }
  8847. function processGesture(proxy, event, stage) {
  8848. var gestureMgr = proxy._gestureMgr;
  8849. stage === 'start' && gestureMgr.clear();
  8850. var gestureInfo = gestureMgr.recognize(
  8851. event,
  8852. proxy.handler.findHover(event.zrX, event.zrY, null).target,
  8853. proxy.dom
  8854. );
  8855. stage === 'end' && gestureMgr.clear();
  8856. // Do not do any preventDefault here. Upper application do that if necessary.
  8857. if (gestureInfo) {
  8858. var type = gestureInfo.type;
  8859. event.gestureEvent = type;
  8860. proxy.handler.dispatchToElement({target: gestureInfo.target}, type, gestureInfo.event);
  8861. }
  8862. }
  8863. // function onMSGestureChange(proxy, event) {
  8864. // if (event.translationX || event.translationY) {
  8865. // // mousemove is carried by MSGesture to reduce the sensitivity.
  8866. // proxy.handler.dispatchToElement(event.target, 'mousemove', event);
  8867. // }
  8868. // if (event.scale !== 1) {
  8869. // event.pinchX = event.offsetX;
  8870. // event.pinchY = event.offsetY;
  8871. // event.pinchScale = event.scale;
  8872. // proxy.handler.dispatchToElement(event.target, 'pinch', event);
  8873. // }
  8874. // }
  8875. /**
  8876. * Prevent mouse event from being dispatched after Touch Events action
  8877. * @see <https://github.com/deltakosh/handjs/blob/master/src/hand.base.js>
  8878. * 1. Mobile browsers dispatch mouse events 300ms after touchend.
  8879. * 2. Chrome for Android dispatch mousedown for long-touch about 650ms
  8880. * Result: Blocking Mouse Events for 700ms.
  8881. */
  8882. function setTouchTimer(instance) {
  8883. instance._touching = true;
  8884. clearTimeout(instance._touchTimer);
  8885. instance._touchTimer = setTimeout(function () {
  8886. instance._touching = false;
  8887. }, 700);
  8888. }
  8889. var domHandlers = {
  8890. /**
  8891. * Mouse move handler
  8892. * @inner
  8893. * @param {Event} event
  8894. */
  8895. mousemove: function (event) {
  8896. event = normalizeEvent(this.dom, event);
  8897. this.trigger('mousemove', event);
  8898. },
  8899. /**
  8900. * Mouse out handler
  8901. * @inner
  8902. * @param {Event} event
  8903. */
  8904. mouseout: function (event) {
  8905. event = normalizeEvent(this.dom, event);
  8906. var element = event.toElement || event.relatedTarget;
  8907. if (element != this.dom) {
  8908. while (element && element.nodeType != 9) {
  8909. // 忽略包含在root中的dom引起的mouseOut
  8910. if (element === this.dom) {
  8911. return;
  8912. }
  8913. element = element.parentNode;
  8914. }
  8915. }
  8916. this.trigger('mouseout', event);
  8917. },
  8918. /**
  8919. * Touch开始响应函数
  8920. * @inner
  8921. * @param {Event} event
  8922. */
  8923. touchstart: function (event) {
  8924. // Default mouse behaviour should not be disabled here.
  8925. // For example, page may needs to be slided.
  8926. event = normalizeEvent(this.dom, event);
  8927. // Mark touch, which is useful in distinguish touch and
  8928. // mouse event in upper applicatoin.
  8929. event.zrByTouch = true;
  8930. this._lastTouchMoment = new Date();
  8931. processGesture(this, event, 'start');
  8932. // In touch device, trigger `mousemove`(`mouseover`) should
  8933. // be triggered, and must before `mousedown` triggered.
  8934. domHandlers.mousemove.call(this, event);
  8935. domHandlers.mousedown.call(this, event);
  8936. setTouchTimer(this);
  8937. },
  8938. /**
  8939. * Touch移动响应函数
  8940. * @inner
  8941. * @param {Event} event
  8942. */
  8943. touchmove: function (event) {
  8944. event = normalizeEvent(this.dom, event);
  8945. // Mark touch, which is useful in distinguish touch and
  8946. // mouse event in upper applicatoin.
  8947. event.zrByTouch = true;
  8948. processGesture(this, event, 'change');
  8949. // Mouse move should always be triggered no matter whether
  8950. // there is gestrue event, because mouse move and pinch may
  8951. // be used at the same time.
  8952. domHandlers.mousemove.call(this, event);
  8953. setTouchTimer(this);
  8954. },
  8955. /**
  8956. * Touch结束响应函数
  8957. * @inner
  8958. * @param {Event} event
  8959. */
  8960. touchend: function (event) {
  8961. event = normalizeEvent(this.dom, event);
  8962. // Mark touch, which is useful in distinguish touch and
  8963. // mouse event in upper applicatoin.
  8964. event.zrByTouch = true;
  8965. processGesture(this, event, 'end');
  8966. domHandlers.mouseup.call(this, event);
  8967. // Do not trigger `mouseout` here, in spite of `mousemove`(`mouseover`) is
  8968. // triggered in `touchstart`. This seems to be illogical, but by this mechanism,
  8969. // we can conveniently implement "hover style" in both PC and touch device just
  8970. // by listening to `mouseover` to add "hover style" and listening to `mouseout`
  8971. // to remove "hover style" on an element, without any additional code for
  8972. // compatibility. (`mouseout` will not be triggered in `touchend`, so "hover
  8973. // style" will remain for user view)
  8974. // click event should always be triggered no matter whether
  8975. // there is gestrue event. System click can not be prevented.
  8976. if (+new Date() - this._lastTouchMoment < TOUCH_CLICK_DELAY) {
  8977. domHandlers.click.call(this, event);
  8978. }
  8979. setTouchTimer(this);
  8980. },
  8981. pointerdown: function (event) {
  8982. domHandlers.mousedown.call(this, event);
  8983. // if (useMSGuesture(this, event)) {
  8984. // this._msGesture.addPointer(event.pointerId);
  8985. // }
  8986. },
  8987. pointermove: function (event) {
  8988. // FIXME
  8989. // pointermove is so sensitive that it always triggered when
  8990. // tap(click) on touch screen, which affect some judgement in
  8991. // upper application. So, we dont support mousemove on MS touch
  8992. // device yet.
  8993. if (!isPointerFromTouch(event)) {
  8994. domHandlers.mousemove.call(this, event);
  8995. }
  8996. },
  8997. pointerup: function (event) {
  8998. domHandlers.mouseup.call(this, event);
  8999. },
  9000. pointerout: function (event) {
  9001. // pointerout will be triggered when tap on touch screen
  9002. // (IE11+/Edge on MS Surface) after click event triggered,
  9003. // which is inconsistent with the mousout behavior we defined
  9004. // in touchend. So we unify them.
  9005. // (check domHandlers.touchend for detailed explanation)
  9006. if (!isPointerFromTouch(event)) {
  9007. domHandlers.mouseout.call(this, event);
  9008. }
  9009. }
  9010. };
  9011. function isPointerFromTouch(event) {
  9012. var pointerType = event.pointerType;
  9013. return pointerType === 'pen' || pointerType === 'touch';
  9014. }
  9015. // function useMSGuesture(handlerProxy, event) {
  9016. // return isPointerFromTouch(event) && !!handlerProxy._msGesture;
  9017. // }
  9018. // Common handlers
  9019. each$1(['click', 'mousedown', 'mouseup', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  9020. domHandlers[name] = function (event) {
  9021. event = normalizeEvent(this.dom, event);
  9022. this.trigger(name, event);
  9023. };
  9024. });
  9025. /**
  9026. * 为控制类实例初始化dom 事件处理函数
  9027. *
  9028. * @inner
  9029. * @param {module:zrender/Handler} instance 控制类实例
  9030. */
  9031. function initDomHandler(instance) {
  9032. each$1(touchHandlerNames, function (name) {
  9033. instance._handlers[name] = bind(domHandlers[name], instance);
  9034. });
  9035. each$1(pointerHandlerNames, function (name) {
  9036. instance._handlers[name] = bind(domHandlers[name], instance);
  9037. });
  9038. each$1(mouseHandlerNames, function (name) {
  9039. instance._handlers[name] = makeMouseHandler(domHandlers[name], instance);
  9040. });
  9041. function makeMouseHandler(fn, instance) {
  9042. return function () {
  9043. if (instance._touching) {
  9044. return;
  9045. }
  9046. return fn.apply(instance, arguments);
  9047. };
  9048. }
  9049. }
  9050. function HandlerDomProxy(dom) {
  9051. Eventful.call(this);
  9052. this.dom = dom;
  9053. /**
  9054. * @private
  9055. * @type {boolean}
  9056. */
  9057. this._touching = false;
  9058. /**
  9059. * @private
  9060. * @type {number}
  9061. */
  9062. this._touchTimer;
  9063. /**
  9064. * @private
  9065. * @type {module:zrender/core/GestureMgr}
  9066. */
  9067. this._gestureMgr = new GestureMgr();
  9068. this._handlers = {};
  9069. initDomHandler(this);
  9070. if (env$1.pointerEventsSupported) { // Only IE11+/Edge
  9071. // 1. On devices that both enable touch and mouse (e.g., MS Surface and lenovo X240),
  9072. // IE11+/Edge do not trigger touch event, but trigger pointer event and mouse event
  9073. // at the same time.
  9074. // 2. On MS Surface, it probablely only trigger mousedown but no mouseup when tap on
  9075. // screen, which do not occurs in pointer event.
  9076. // So we use pointer event to both detect touch gesture and mouse behavior.
  9077. mountHandlers(pointerHandlerNames, this);
  9078. // FIXME
  9079. // Note: MS Gesture require CSS touch-action set. But touch-action is not reliable,
  9080. // which does not prevent defuault behavior occasionally (which may cause view port
  9081. // zoomed in but use can not zoom it back). And event.preventDefault() does not work.
  9082. // So we have to not to use MSGesture and not to support touchmove and pinch on MS
  9083. // touch screen. And we only support click behavior on MS touch screen now.
  9084. // MS Gesture Event is only supported on IE11+/Edge and on Windows 8+.
  9085. // We dont support touch on IE on win7.
  9086. // See <https://msdn.microsoft.com/en-us/library/dn433243(v=vs.85).aspx>
  9087. // if (typeof MSGesture === 'function') {
  9088. // (this._msGesture = new MSGesture()).target = dom; // jshint ignore:line
  9089. // dom.addEventListener('MSGestureChange', onMSGestureChange);
  9090. // }
  9091. }
  9092. else {
  9093. if (env$1.touchEventsSupported) {
  9094. mountHandlers(touchHandlerNames, this);
  9095. // Handler of 'mouseout' event is needed in touch mode, which will be mounted below.
  9096. // addEventListener(root, 'mouseout', this._mouseoutHandler);
  9097. }
  9098. // 1. Considering some devices that both enable touch and mouse event (like on MS Surface
  9099. // and lenovo X240, @see #2350), we make mouse event be always listened, otherwise
  9100. // mouse event can not be handle in those devices.
  9101. // 2. On MS Surface, Chrome will trigger both touch event and mouse event. How to prevent
  9102. // mouseevent after touch event triggered, see `setTouchTimer`.
  9103. mountHandlers(mouseHandlerNames, this);
  9104. }
  9105. function mountHandlers(handlerNames, instance) {
  9106. each$1(handlerNames, function (name) {
  9107. addEventListener(dom, eventNameFix(name), instance._handlers[name]);
  9108. }, instance);
  9109. }
  9110. }
  9111. var handlerDomProxyProto = HandlerDomProxy.prototype;
  9112. handlerDomProxyProto.dispose = function () {
  9113. var handlerNames = mouseHandlerNames.concat(touchHandlerNames);
  9114. for (var i = 0; i < handlerNames.length; i++) {
  9115. var name = handlerNames[i];
  9116. removeEventListener(this.dom, eventNameFix(name), this._handlers[name]);
  9117. }
  9118. };
  9119. handlerDomProxyProto.setCursor = function (cursorStyle) {
  9120. this.dom.style && (this.dom.style.cursor = cursorStyle || 'default');
  9121. };
  9122. mixin(HandlerDomProxy, Eventful);
  9123. /*!
  9124. * ZRender, a high performance 2d drawing library.
  9125. *
  9126. * Copyright (c) 2013, Baidu Inc.
  9127. * All rights reserved.
  9128. *
  9129. * LICENSE
  9130. * https://github.com/ecomfe/zrender/blob/master/LICENSE.txt
  9131. */
  9132. var useVML = !env$1.canvasSupported;
  9133. var painterCtors = {
  9134. canvas: Painter
  9135. };
  9136. var instances$1 = {}; // ZRender实例map索引
  9137. /**
  9138. * @type {string}
  9139. */
  9140. var version$1 = '4.0.4';
  9141. /**
  9142. * Initializing a zrender instance
  9143. * @param {HTMLElement} dom
  9144. * @param {Object} opts
  9145. * @param {string} [opts.renderer='canvas'] 'canvas' or 'svg'
  9146. * @param {number} [opts.devicePixelRatio]
  9147. * @param {number|string} [opts.width] Can be 'auto' (the same as null/undefined)
  9148. * @param {number|string} [opts.height] Can be 'auto' (the same as null/undefined)
  9149. * @return {module:zrender/ZRender}
  9150. */
  9151. function init$1(dom, opts) {
  9152. var zr = new ZRender(guid(), dom, opts);
  9153. instances$1[zr.id] = zr;
  9154. return zr;
  9155. }
  9156. /**
  9157. * Dispose zrender instance
  9158. * @param {module:zrender/ZRender} zr
  9159. */
  9160. function dispose$1(zr) {
  9161. if (zr) {
  9162. zr.dispose();
  9163. }
  9164. else {
  9165. for (var key in instances$1) {
  9166. if (instances$1.hasOwnProperty(key)) {
  9167. instances$1[key].dispose();
  9168. }
  9169. }
  9170. instances$1 = {};
  9171. }
  9172. return this;
  9173. }
  9174. /**
  9175. * Get zrender instance by id
  9176. * @param {string} id zrender instance id
  9177. * @return {module:zrender/ZRender}
  9178. */
  9179. function getInstance(id) {
  9180. return instances$1[id];
  9181. }
  9182. function registerPainter(name, Ctor) {
  9183. painterCtors[name] = Ctor;
  9184. }
  9185. function delInstance(id) {
  9186. delete instances$1[id];
  9187. }
  9188. /**
  9189. * @module zrender/ZRender
  9190. */
  9191. /**
  9192. * @constructor
  9193. * @alias module:zrender/ZRender
  9194. * @param {string} id
  9195. * @param {HTMLElement} dom
  9196. * @param {Object} opts
  9197. * @param {string} [opts.renderer='canvas'] 'canvas' or 'svg'
  9198. * @param {number} [opts.devicePixelRatio]
  9199. * @param {number} [opts.width] Can be 'auto' (the same as null/undefined)
  9200. * @param {number} [opts.height] Can be 'auto' (the same as null/undefined)
  9201. */
  9202. var ZRender = function (id, dom, opts) {
  9203. opts = opts || {};
  9204. /**
  9205. * @type {HTMLDomElement}
  9206. */
  9207. this.dom = dom;
  9208. /**
  9209. * @type {string}
  9210. */
  9211. this.id = id;
  9212. var self = this;
  9213. var storage = new Storage();
  9214. var rendererType = opts.renderer;
  9215. // TODO WebGL
  9216. if (useVML) {
  9217. if (!painterCtors.vml) {
  9218. throw new Error('You need to require \'zrender/vml/vml\' to support IE8');
  9219. }
  9220. rendererType = 'vml';
  9221. }
  9222. else if (!rendererType || !painterCtors[rendererType]) {
  9223. rendererType = 'canvas';
  9224. }
  9225. var painter = new painterCtors[rendererType](dom, storage, opts, id);
  9226. this.storage = storage;
  9227. this.painter = painter;
  9228. var handerProxy = (!env$1.node && !env$1.worker) ? new HandlerDomProxy(painter.getViewportRoot()) : null;
  9229. this.handler = new Handler(storage, painter, handerProxy, painter.root);
  9230. /**
  9231. * @type {module:zrender/animation/Animation}
  9232. */
  9233. this.animation = new Animation({
  9234. stage: {
  9235. update: bind(this.flush, this)
  9236. }
  9237. });
  9238. this.animation.start();
  9239. /**
  9240. * @type {boolean}
  9241. * @private
  9242. */
  9243. this._needsRefresh;
  9244. // 修改 storage.delFromStorage, 每次删除元素之前删除动画
  9245. // FIXME 有点ugly
  9246. var oldDelFromStorage = storage.delFromStorage;
  9247. var oldAddToStorage = storage.addToStorage;
  9248. storage.delFromStorage = function (el) {
  9249. oldDelFromStorage.call(storage, el);
  9250. el && el.removeSelfFromZr(self);
  9251. };
  9252. storage.addToStorage = function (el) {
  9253. oldAddToStorage.call(storage, el);
  9254. el.addSelfToZr(self);
  9255. };
  9256. };
  9257. ZRender.prototype = {
  9258. constructor: ZRender,
  9259. /**
  9260. * 获取实例唯一标识
  9261. * @return {string}
  9262. */
  9263. getId: function () {
  9264. return this.id;
  9265. },
  9266. /**
  9267. * 添加元素
  9268. * @param {module:zrender/Element} el
  9269. */
  9270. add: function (el) {
  9271. this.storage.addRoot(el);
  9272. this._needsRefresh = true;
  9273. },
  9274. /**
  9275. * 删除元素
  9276. * @param {module:zrender/Element} el
  9277. */
  9278. remove: function (el) {
  9279. this.storage.delRoot(el);
  9280. this._needsRefresh = true;
  9281. },
  9282. /**
  9283. * Change configuration of layer
  9284. * @param {string} zLevel
  9285. * @param {Object} config
  9286. * @param {string} [config.clearColor=0] Clear color
  9287. * @param {string} [config.motionBlur=false] If enable motion blur
  9288. * @param {number} [config.lastFrameAlpha=0.7] Motion blur factor. Larger value cause longer trailer
  9289. */
  9290. configLayer: function (zLevel, config) {
  9291. if (this.painter.configLayer) {
  9292. this.painter.configLayer(zLevel, config);
  9293. }
  9294. this._needsRefresh = true;
  9295. },
  9296. /**
  9297. * Set background color
  9298. * @param {string} backgroundColor
  9299. */
  9300. setBackgroundColor: function (backgroundColor) {
  9301. if (this.painter.setBackgroundColor) {
  9302. this.painter.setBackgroundColor(backgroundColor);
  9303. }
  9304. this._needsRefresh = true;
  9305. },
  9306. /**
  9307. * Repaint the canvas immediately
  9308. */
  9309. refreshImmediately: function () {
  9310. // var start = new Date();
  9311. // Clear needsRefresh ahead to avoid something wrong happens in refresh
  9312. // Or it will cause zrender refreshes again and again.
  9313. this._needsRefresh = false;
  9314. this.painter.refresh();
  9315. /**
  9316. * Avoid trigger zr.refresh in Element#beforeUpdate hook
  9317. */
  9318. this._needsRefresh = false;
  9319. // var end = new Date();
  9320. // var log = document.getElementById('log');
  9321. // if (log) {
  9322. // log.innerHTML = log.innerHTML + '<br>' + (end - start);
  9323. // }
  9324. },
  9325. /**
  9326. * Mark and repaint the canvas in the next frame of browser
  9327. */
  9328. refresh: function() {
  9329. this._needsRefresh = true;
  9330. },
  9331. /**
  9332. * Perform all refresh
  9333. */
  9334. flush: function () {
  9335. var triggerRendered;
  9336. if (this._needsRefresh) {
  9337. triggerRendered = true;
  9338. this.refreshImmediately();
  9339. }
  9340. if (this._needsRefreshHover) {
  9341. triggerRendered = true;
  9342. this.refreshHoverImmediately();
  9343. }
  9344. triggerRendered && this.trigger('rendered');
  9345. },
  9346. /**
  9347. * Add element to hover layer
  9348. * @param {module:zrender/Element} el
  9349. * @param {Object} style
  9350. */
  9351. addHover: function (el, style) {
  9352. if (this.painter.addHover) {
  9353. this.painter.addHover(el, style);
  9354. this.refreshHover();
  9355. }
  9356. },
  9357. /**
  9358. * Add element from hover layer
  9359. * @param {module:zrender/Element} el
  9360. */
  9361. removeHover: function (el) {
  9362. if (this.painter.removeHover) {
  9363. this.painter.removeHover(el);
  9364. this.refreshHover();
  9365. }
  9366. },
  9367. /**
  9368. * Clear all hover elements in hover layer
  9369. * @param {module:zrender/Element} el
  9370. */
  9371. clearHover: function () {
  9372. if (this.painter.clearHover) {
  9373. this.painter.clearHover();
  9374. this.refreshHover();
  9375. }
  9376. },
  9377. /**
  9378. * Refresh hover in next frame
  9379. */
  9380. refreshHover: function () {
  9381. this._needsRefreshHover = true;
  9382. },
  9383. /**
  9384. * Refresh hover immediately
  9385. */
  9386. refreshHoverImmediately: function () {
  9387. this._needsRefreshHover = false;
  9388. this.painter.refreshHover && this.painter.refreshHover();
  9389. },
  9390. /**
  9391. * Resize the canvas.
  9392. * Should be invoked when container size is changed
  9393. * @param {Object} [opts]
  9394. * @param {number|string} [opts.width] Can be 'auto' (the same as null/undefined)
  9395. * @param {number|string} [opts.height] Can be 'auto' (the same as null/undefined)
  9396. */
  9397. resize: function(opts) {
  9398. opts = opts || {};
  9399. this.painter.resize(opts.width, opts.height);
  9400. this.handler.resize();
  9401. },
  9402. /**
  9403. * Stop and clear all animation immediately
  9404. */
  9405. clearAnimation: function () {
  9406. this.animation.clear();
  9407. },
  9408. /**
  9409. * Get container width
  9410. */
  9411. getWidth: function() {
  9412. return this.painter.getWidth();
  9413. },
  9414. /**
  9415. * Get container height
  9416. */
  9417. getHeight: function() {
  9418. return this.painter.getHeight();
  9419. },
  9420. /**
  9421. * Export the canvas as Base64 URL
  9422. * @param {string} type
  9423. * @param {string} [backgroundColor='#fff']
  9424. * @return {string} Base64 URL
  9425. */
  9426. // toDataURL: function(type, backgroundColor) {
  9427. // return this.painter.getRenderedCanvas({
  9428. // backgroundColor: backgroundColor
  9429. // }).toDataURL(type);
  9430. // },
  9431. /**
  9432. * Converting a path to image.
  9433. * It has much better performance of drawing image rather than drawing a vector path.
  9434. * @param {module:zrender/graphic/Path} e
  9435. * @param {number} width
  9436. * @param {number} height
  9437. */
  9438. pathToImage: function(e, dpr) {
  9439. return this.painter.pathToImage(e, dpr);
  9440. },
  9441. /**
  9442. * Set default cursor
  9443. * @param {string} [cursorStyle='default'] 例如 crosshair
  9444. */
  9445. setCursorStyle: function (cursorStyle) {
  9446. this.handler.setCursorStyle(cursorStyle);
  9447. },
  9448. /**
  9449. * Find hovered element
  9450. * @param {number} x
  9451. * @param {number} y
  9452. * @return {Object} {target, topTarget}
  9453. */
  9454. findHover: function (x, y) {
  9455. return this.handler.findHover(x, y);
  9456. },
  9457. /**
  9458. * Bind event
  9459. *
  9460. * @param {string} eventName Event name
  9461. * @param {Function} eventHandler Handler function
  9462. * @param {Object} [context] Context object
  9463. */
  9464. on: function(eventName, eventHandler, context) {
  9465. this.handler.on(eventName, eventHandler, context);
  9466. },
  9467. /**
  9468. * Unbind event
  9469. * @param {string} eventName Event name
  9470. * @param {Function} [eventHandler] Handler function
  9471. */
  9472. off: function(eventName, eventHandler) {
  9473. this.handler.off(eventName, eventHandler);
  9474. },
  9475. /**
  9476. * Trigger event manually
  9477. *
  9478. * @param {string} eventName Event name
  9479. * @param {event=} event Event object
  9480. */
  9481. trigger: function (eventName, event) {
  9482. this.handler.trigger(eventName, event);
  9483. },
  9484. /**
  9485. * Clear all objects and the canvas.
  9486. */
  9487. clear: function () {
  9488. this.storage.delRoot();
  9489. this.painter.clear();
  9490. },
  9491. /**
  9492. * Dispose self.
  9493. */
  9494. dispose: function () {
  9495. this.animation.stop();
  9496. this.clear();
  9497. this.storage.dispose();
  9498. this.painter.dispose();
  9499. this.handler.dispose();
  9500. this.animation =
  9501. this.storage =
  9502. this.painter =
  9503. this.handler = null;
  9504. delInstance(this.id);
  9505. }
  9506. };
  9507. var zrender = (Object.freeze || Object)({
  9508. version: version$1,
  9509. init: init$1,
  9510. dispose: dispose$1,
  9511. getInstance: getInstance,
  9512. registerPainter: registerPainter
  9513. });
  9514. /*
  9515. * Licensed to the Apache Software Foundation (ASF) under one
  9516. * or more contributor license agreements. See the NOTICE file
  9517. * distributed with this work for additional information
  9518. * regarding copyright ownership. The ASF licenses this file
  9519. * to you under the Apache License, Version 2.0 (the
  9520. * "License"); you may not use this file except in compliance
  9521. * with the License. You may obtain a copy of the License at
  9522. *
  9523. * http://www.apache.org/licenses/LICENSE-2.0
  9524. *
  9525. * Unless required by applicable law or agreed to in writing,
  9526. * software distributed under the License is distributed on an
  9527. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  9528. * KIND, either express or implied. See the License for the
  9529. * specific language governing permissions and limitations
  9530. * under the License.
  9531. */
  9532. var each$2 = each$1;
  9533. var isObject$2 = isObject$1;
  9534. var isArray$1 = isArray;
  9535. /**
  9536. * Make the name displayable. But we should
  9537. * make sure it is not duplicated with user
  9538. * specified name, so use '\0';
  9539. */
  9540. var DUMMY_COMPONENT_NAME_PREFIX = 'series\0';
  9541. /**
  9542. * If value is not array, then translate it to array.
  9543. * @param {*} value
  9544. * @return {Array} [value] or value
  9545. */
  9546. function normalizeToArray(value) {
  9547. return value instanceof Array
  9548. ? value
  9549. : value == null
  9550. ? []
  9551. : [value];
  9552. }
  9553. /**
  9554. * Sync default option between normal and emphasis like `position` and `show`
  9555. * In case some one will write code like
  9556. * label: {
  9557. * show: false,
  9558. * position: 'outside',
  9559. * fontSize: 18
  9560. * },
  9561. * emphasis: {
  9562. * label: { show: true }
  9563. * }
  9564. * @param {Object} opt
  9565. * @param {string} key
  9566. * @param {Array.<string>} subOpts
  9567. */
  9568. function defaultEmphasis(opt, key, subOpts) {
  9569. // Caution: performance sensitive.
  9570. if (opt) {
  9571. opt[key] = opt[key] || {};
  9572. opt.emphasis = opt.emphasis || {};
  9573. opt.emphasis[key] = opt.emphasis[key] || {};
  9574. // Default emphasis option from normal
  9575. for (var i = 0, len = subOpts.length; i < len; i++) {
  9576. var subOptName = subOpts[i];
  9577. if (!opt.emphasis[key].hasOwnProperty(subOptName)
  9578. && opt[key].hasOwnProperty(subOptName)
  9579. ) {
  9580. opt.emphasis[key][subOptName] = opt[key][subOptName];
  9581. }
  9582. }
  9583. }
  9584. }
  9585. var TEXT_STYLE_OPTIONS = [
  9586. 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  9587. 'rich', 'tag', 'color', 'textBorderColor', 'textBorderWidth',
  9588. 'width', 'height', 'lineHeight', 'align', 'verticalAlign', 'baseline',
  9589. 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY',
  9590. 'textShadowColor', 'textShadowBlur', 'textShadowOffsetX', 'textShadowOffsetY',
  9591. 'backgroundColor', 'borderColor', 'borderWidth', 'borderRadius', 'padding'
  9592. ];
  9593. // modelUtil.LABEL_OPTIONS = modelUtil.TEXT_STYLE_OPTIONS.concat([
  9594. // 'position', 'offset', 'rotate', 'origin', 'show', 'distance', 'formatter',
  9595. // 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  9596. // // FIXME: deprecated, check and remove it.
  9597. // 'textStyle'
  9598. // ]);
  9599. /**
  9600. * The method do not ensure performance.
  9601. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  9602. * This helper method retieves value from data.
  9603. * @param {string|number|Date|Array|Object} dataItem
  9604. * @return {number|string|Date|Array.<number|string|Date>}
  9605. */
  9606. function getDataItemValue(dataItem) {
  9607. return (isObject$2(dataItem) && !isArray$1(dataItem) && !(dataItem instanceof Date))
  9608. ? dataItem.value : dataItem;
  9609. }
  9610. /**
  9611. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  9612. * This helper method determine if dataItem has extra option besides value
  9613. * @param {string|number|Date|Array|Object} dataItem
  9614. */
  9615. function isDataItemOption(dataItem) {
  9616. return isObject$2(dataItem)
  9617. && !(dataItem instanceof Array);
  9618. // // markLine data can be array
  9619. // && !(dataItem[0] && isObject(dataItem[0]) && !(dataItem[0] instanceof Array));
  9620. }
  9621. /**
  9622. * Mapping to exists for merge.
  9623. *
  9624. * @public
  9625. * @param {Array.<Object>|Array.<module:echarts/model/Component>} exists
  9626. * @param {Object|Array.<Object>} newCptOptions
  9627. * @return {Array.<Object>} Result, like [{exist: ..., option: ...}, {}],
  9628. * index of which is the same as exists.
  9629. */
  9630. function mappingToExists(exists, newCptOptions) {
  9631. // Mapping by the order by original option (but not order of
  9632. // new option) in merge mode. Because we should ensure
  9633. // some specified index (like xAxisIndex) is consistent with
  9634. // original option, which is easy to understand, espatially in
  9635. // media query. And in most case, merge option is used to
  9636. // update partial option but not be expected to change order.
  9637. newCptOptions = (newCptOptions || []).slice();
  9638. var result = map(exists || [], function (obj, index) {
  9639. return {exist: obj};
  9640. });
  9641. // Mapping by id or name if specified.
  9642. each$2(newCptOptions, function (cptOption, index) {
  9643. if (!isObject$2(cptOption)) {
  9644. return;
  9645. }
  9646. // id has highest priority.
  9647. for (var i = 0; i < result.length; i++) {
  9648. if (!result[i].option // Consider name: two map to one.
  9649. && cptOption.id != null
  9650. && result[i].exist.id === cptOption.id + ''
  9651. ) {
  9652. result[i].option = cptOption;
  9653. newCptOptions[index] = null;
  9654. return;
  9655. }
  9656. }
  9657. for (var i = 0; i < result.length; i++) {
  9658. var exist = result[i].exist;
  9659. if (!result[i].option // Consider name: two map to one.
  9660. // Can not match when both ids exist but different.
  9661. && (exist.id == null || cptOption.id == null)
  9662. && cptOption.name != null
  9663. && !isIdInner(cptOption)
  9664. && !isIdInner(exist)
  9665. && exist.name === cptOption.name + ''
  9666. ) {
  9667. result[i].option = cptOption;
  9668. newCptOptions[index] = null;
  9669. return;
  9670. }
  9671. }
  9672. });
  9673. // Otherwise mapping by index.
  9674. each$2(newCptOptions, function (cptOption, index) {
  9675. if (!isObject$2(cptOption)) {
  9676. return;
  9677. }
  9678. var i = 0;
  9679. for (; i < result.length; i++) {
  9680. var exist = result[i].exist;
  9681. if (!result[i].option
  9682. // Existing model that already has id should be able to
  9683. // mapped to (because after mapping performed model may
  9684. // be assigned with a id, whish should not affect next
  9685. // mapping), except those has inner id.
  9686. && !isIdInner(exist)
  9687. // Caution:
  9688. // Do not overwrite id. But name can be overwritten,
  9689. // because axis use name as 'show label text'.
  9690. // 'exist' always has id and name and we dont
  9691. // need to check it.
  9692. && cptOption.id == null
  9693. ) {
  9694. result[i].option = cptOption;
  9695. break;
  9696. }
  9697. }
  9698. if (i >= result.length) {
  9699. result.push({option: cptOption});
  9700. }
  9701. });
  9702. return result;
  9703. }
  9704. /**
  9705. * Make id and name for mapping result (result of mappingToExists)
  9706. * into `keyInfo` field.
  9707. *
  9708. * @public
  9709. * @param {Array.<Object>} Result, like [{exist: ..., option: ...}, {}],
  9710. * which order is the same as exists.
  9711. * @return {Array.<Object>} The input.
  9712. */
  9713. function makeIdAndName(mapResult) {
  9714. // We use this id to hash component models and view instances
  9715. // in echarts. id can be specified by user, or auto generated.
  9716. // The id generation rule ensures new view instance are able
  9717. // to mapped to old instance when setOption are called in
  9718. // no-merge mode. So we generate model id by name and plus
  9719. // type in view id.
  9720. // name can be duplicated among components, which is convenient
  9721. // to specify multi components (like series) by one name.
  9722. // Ensure that each id is distinct.
  9723. var idMap = createHashMap();
  9724. each$2(mapResult, function (item, index) {
  9725. var existCpt = item.exist;
  9726. existCpt && idMap.set(existCpt.id, item);
  9727. });
  9728. each$2(mapResult, function (item, index) {
  9729. var opt = item.option;
  9730. assert$1(
  9731. !opt || opt.id == null || !idMap.get(opt.id) || idMap.get(opt.id) === item,
  9732. 'id duplicates: ' + (opt && opt.id)
  9733. );
  9734. opt && opt.id != null && idMap.set(opt.id, item);
  9735. !item.keyInfo && (item.keyInfo = {});
  9736. });
  9737. // Make name and id.
  9738. each$2(mapResult, function (item, index) {
  9739. var existCpt = item.exist;
  9740. var opt = item.option;
  9741. var keyInfo = item.keyInfo;
  9742. if (!isObject$2(opt)) {
  9743. return;
  9744. }
  9745. // name can be overwitten. Consider case: axis.name = '20km'.
  9746. // But id generated by name will not be changed, which affect
  9747. // only in that case: setOption with 'not merge mode' and view
  9748. // instance will be recreated, which can be accepted.
  9749. keyInfo.name = opt.name != null
  9750. ? opt.name + ''
  9751. : existCpt
  9752. ? existCpt.name
  9753. // Avoid diffferent series has the same name,
  9754. // because name may be used like in color pallet.
  9755. : DUMMY_COMPONENT_NAME_PREFIX + index;
  9756. if (existCpt) {
  9757. keyInfo.id = existCpt.id;
  9758. }
  9759. else if (opt.id != null) {
  9760. keyInfo.id = opt.id + '';
  9761. }
  9762. else {
  9763. // Consider this situatoin:
  9764. // optionA: [{name: 'a'}, {name: 'a'}, {..}]
  9765. // optionB [{..}, {name: 'a'}, {name: 'a'}]
  9766. // Series with the same name between optionA and optionB
  9767. // should be mapped.
  9768. var idNum = 0;
  9769. do {
  9770. keyInfo.id = '\0' + keyInfo.name + '\0' + idNum++;
  9771. }
  9772. while (idMap.get(keyInfo.id));
  9773. }
  9774. idMap.set(keyInfo.id, item);
  9775. });
  9776. }
  9777. function isNameSpecified(componentModel) {
  9778. var name = componentModel.name;
  9779. // Is specified when `indexOf` get -1 or > 0.
  9780. return !!(name && name.indexOf(DUMMY_COMPONENT_NAME_PREFIX));
  9781. }
  9782. /**
  9783. * @public
  9784. * @param {Object} cptOption
  9785. * @return {boolean}
  9786. */
  9787. function isIdInner(cptOption) {
  9788. return isObject$2(cptOption)
  9789. && cptOption.id
  9790. && (cptOption.id + '').indexOf('\0_ec_\0') === 0;
  9791. }
  9792. /**
  9793. * A helper for removing duplicate items between batchA and batchB,
  9794. * and in themselves, and categorize by series.
  9795. *
  9796. * @param {Array.<Object>} batchA Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...]
  9797. * @param {Array.<Object>} batchB Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...]
  9798. * @return {Array.<Array.<Object>, Array.<Object>>} result: [resultBatchA, resultBatchB]
  9799. */
  9800. function compressBatches(batchA, batchB) {
  9801. var mapA = {};
  9802. var mapB = {};
  9803. makeMap(batchA || [], mapA);
  9804. makeMap(batchB || [], mapB, mapA);
  9805. return [mapToArray(mapA), mapToArray(mapB)];
  9806. function makeMap(sourceBatch, map$$1, otherMap) {
  9807. for (var i = 0, len = sourceBatch.length; i < len; i++) {
  9808. var seriesId = sourceBatch[i].seriesId;
  9809. var dataIndices = normalizeToArray(sourceBatch[i].dataIndex);
  9810. var otherDataIndices = otherMap && otherMap[seriesId];
  9811. for (var j = 0, lenj = dataIndices.length; j < lenj; j++) {
  9812. var dataIndex = dataIndices[j];
  9813. if (otherDataIndices && otherDataIndices[dataIndex]) {
  9814. otherDataIndices[dataIndex] = null;
  9815. }
  9816. else {
  9817. (map$$1[seriesId] || (map$$1[seriesId] = {}))[dataIndex] = 1;
  9818. }
  9819. }
  9820. }
  9821. }
  9822. function mapToArray(map$$1, isData) {
  9823. var result = [];
  9824. for (var i in map$$1) {
  9825. if (map$$1.hasOwnProperty(i) && map$$1[i] != null) {
  9826. if (isData) {
  9827. result.push(+i);
  9828. }
  9829. else {
  9830. var dataIndices = mapToArray(map$$1[i], true);
  9831. dataIndices.length && result.push({seriesId: i, dataIndex: dataIndices});
  9832. }
  9833. }
  9834. }
  9835. return result;
  9836. }
  9837. }
  9838. /**
  9839. * @param {module:echarts/data/List} data
  9840. * @param {Object} payload Contains dataIndex (means rawIndex) / dataIndexInside / name
  9841. * each of which can be Array or primary type.
  9842. * @return {number|Array.<number>} dataIndex If not found, return undefined/null.
  9843. */
  9844. function queryDataIndex(data, payload) {
  9845. if (payload.dataIndexInside != null) {
  9846. return payload.dataIndexInside;
  9847. }
  9848. else if (payload.dataIndex != null) {
  9849. return isArray(payload.dataIndex)
  9850. ? map(payload.dataIndex, function (value) {
  9851. return data.indexOfRawIndex(value);
  9852. })
  9853. : data.indexOfRawIndex(payload.dataIndex);
  9854. }
  9855. else if (payload.name != null) {
  9856. return isArray(payload.name)
  9857. ? map(payload.name, function (value) {
  9858. return data.indexOfName(value);
  9859. })
  9860. : data.indexOfName(payload.name);
  9861. }
  9862. }
  9863. /**
  9864. * Enable property storage to any host object.
  9865. * Notice: Serialization is not supported.
  9866. *
  9867. * For example:
  9868. * var inner = zrUitl.makeInner();
  9869. *
  9870. * function some1(hostObj) {
  9871. * inner(hostObj).someProperty = 1212;
  9872. * ...
  9873. * }
  9874. * function some2() {
  9875. * var fields = inner(this);
  9876. * fields.someProperty1 = 1212;
  9877. * fields.someProperty2 = 'xx';
  9878. * ...
  9879. * }
  9880. *
  9881. * @return {Function}
  9882. */
  9883. function makeInner() {
  9884. // Consider different scope by es module import.
  9885. var key = '__\0ec_inner_' + innerUniqueIndex++ + '_' + Math.random().toFixed(5);
  9886. return function (hostObj) {
  9887. return hostObj[key] || (hostObj[key] = {});
  9888. };
  9889. }
  9890. var innerUniqueIndex = 0;
  9891. /**
  9892. * @param {module:echarts/model/Global} ecModel
  9893. * @param {string|Object} finder
  9894. * If string, e.g., 'geo', means {geoIndex: 0}.
  9895. * If Object, could contain some of these properties below:
  9896. * {
  9897. * seriesIndex, seriesId, seriesName,
  9898. * geoIndex, geoId, geoName,
  9899. * bmapIndex, bmapId, bmapName,
  9900. * xAxisIndex, xAxisId, xAxisName,
  9901. * yAxisIndex, yAxisId, yAxisName,
  9902. * gridIndex, gridId, gridName,
  9903. * ... (can be extended)
  9904. * }
  9905. * Each properties can be number|string|Array.<number>|Array.<string>
  9906. * For example, a finder could be
  9907. * {
  9908. * seriesIndex: 3,
  9909. * geoId: ['aa', 'cc'],
  9910. * gridName: ['xx', 'rr']
  9911. * }
  9912. * xxxIndex can be set as 'all' (means all xxx) or 'none' (means not specify)
  9913. * If nothing or null/undefined specified, return nothing.
  9914. * @param {Object} [opt]
  9915. * @param {string} [opt.defaultMainType]
  9916. * @param {Array.<string>} [opt.includeMainTypes]
  9917. * @return {Object} result like:
  9918. * {
  9919. * seriesModels: [seriesModel1, seriesModel2],
  9920. * seriesModel: seriesModel1, // The first model
  9921. * geoModels: [geoModel1, geoModel2],
  9922. * geoModel: geoModel1, // The first model
  9923. * ...
  9924. * }
  9925. */
  9926. function parseFinder(ecModel, finder, opt) {
  9927. if (isString(finder)) {
  9928. var obj = {};
  9929. obj[finder + 'Index'] = 0;
  9930. finder = obj;
  9931. }
  9932. var defaultMainType = opt && opt.defaultMainType;
  9933. if (defaultMainType
  9934. && !has(finder, defaultMainType + 'Index')
  9935. && !has(finder, defaultMainType + 'Id')
  9936. && !has(finder, defaultMainType + 'Name')
  9937. ) {
  9938. finder[defaultMainType + 'Index'] = 0;
  9939. }
  9940. var result = {};
  9941. each$2(finder, function (value, key) {
  9942. var value = finder[key];
  9943. // Exclude 'dataIndex' and other illgal keys.
  9944. if (key === 'dataIndex' || key === 'dataIndexInside') {
  9945. result[key] = value;
  9946. return;
  9947. }
  9948. var parsedKey = key.match(/^(\w+)(Index|Id|Name)$/) || [];
  9949. var mainType = parsedKey[1];
  9950. var queryType = (parsedKey[2] || '').toLowerCase();
  9951. if (!mainType
  9952. || !queryType
  9953. || value == null
  9954. || (queryType === 'index' && value === 'none')
  9955. || (opt && opt.includeMainTypes && indexOf(opt.includeMainTypes, mainType) < 0)
  9956. ) {
  9957. return;
  9958. }
  9959. var queryParam = {mainType: mainType};
  9960. if (queryType !== 'index' || value !== 'all') {
  9961. queryParam[queryType] = value;
  9962. }
  9963. var models = ecModel.queryComponents(queryParam);
  9964. result[mainType + 'Models'] = models;
  9965. result[mainType + 'Model'] = models[0];
  9966. });
  9967. return result;
  9968. }
  9969. function has(obj, prop) {
  9970. return obj && obj.hasOwnProperty(prop);
  9971. }
  9972. function setAttribute(dom, key, value) {
  9973. dom.setAttribute
  9974. ? dom.setAttribute(key, value)
  9975. : (dom[key] = value);
  9976. }
  9977. function getAttribute(dom, key) {
  9978. return dom.getAttribute
  9979. ? dom.getAttribute(key)
  9980. : dom[key];
  9981. }
  9982. /*
  9983. * Licensed to the Apache Software Foundation (ASF) under one
  9984. * or more contributor license agreements. See the NOTICE file
  9985. * distributed with this work for additional information
  9986. * regarding copyright ownership. The ASF licenses this file
  9987. * to you under the Apache License, Version 2.0 (the
  9988. * "License"); you may not use this file except in compliance
  9989. * with the License. You may obtain a copy of the License at
  9990. *
  9991. * http://www.apache.org/licenses/LICENSE-2.0
  9992. *
  9993. * Unless required by applicable law or agreed to in writing,
  9994. * software distributed under the License is distributed on an
  9995. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  9996. * KIND, either express or implied. See the License for the
  9997. * specific language governing permissions and limitations
  9998. * under the License.
  9999. */
  10000. var TYPE_DELIMITER = '.';
  10001. var IS_CONTAINER = '___EC__COMPONENT__CONTAINER___';
  10002. /**
  10003. * Notice, parseClassType('') should returns {main: '', sub: ''}
  10004. * @public
  10005. */
  10006. function parseClassType$1(componentType) {
  10007. var ret = {main: '', sub: ''};
  10008. if (componentType) {
  10009. componentType = componentType.split(TYPE_DELIMITER);
  10010. ret.main = componentType[0] || '';
  10011. ret.sub = componentType[1] || '';
  10012. }
  10013. return ret;
  10014. }
  10015. /**
  10016. * @public
  10017. */
  10018. function checkClassType(componentType) {
  10019. assert$1(
  10020. /^[a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)?$/.test(componentType),
  10021. 'componentType "' + componentType + '" illegal'
  10022. );
  10023. }
  10024. /**
  10025. * @public
  10026. */
  10027. function enableClassExtend(RootClass, mandatoryMethods) {
  10028. RootClass.$constructor = RootClass;
  10029. RootClass.extend = function (proto) {
  10030. if (__DEV__) {
  10031. each$1(mandatoryMethods, function (method) {
  10032. if (!proto[method]) {
  10033. console.warn(
  10034. 'Method `' + method + '` should be implemented'
  10035. + (proto.type ? ' in ' + proto.type : '') + '.'
  10036. );
  10037. }
  10038. });
  10039. }
  10040. var superClass = this;
  10041. var ExtendedClass = function () {
  10042. if (!proto.$constructor) {
  10043. superClass.apply(this, arguments);
  10044. }
  10045. else {
  10046. proto.$constructor.apply(this, arguments);
  10047. }
  10048. };
  10049. extend(ExtendedClass.prototype, proto);
  10050. ExtendedClass.extend = this.extend;
  10051. ExtendedClass.superCall = superCall;
  10052. ExtendedClass.superApply = superApply;
  10053. inherits(ExtendedClass, this);
  10054. ExtendedClass.superClass = superClass;
  10055. return ExtendedClass;
  10056. };
  10057. }
  10058. var classBase = 0;
  10059. /**
  10060. * Can not use instanceof, consider different scope by
  10061. * cross domain or es module import in ec extensions.
  10062. * Mount a method "isInstance()" to Clz.
  10063. */
  10064. function enableClassCheck(Clz) {
  10065. var classAttr = ['__\0is_clz', classBase++, Math.random().toFixed(3)].join('_');
  10066. Clz.prototype[classAttr] = true;
  10067. if (__DEV__) {
  10068. assert$1(!Clz.isInstance, 'The method "is" can not be defined.');
  10069. }
  10070. Clz.isInstance = function (obj) {
  10071. return !!(obj && obj[classAttr]);
  10072. };
  10073. }
  10074. // superCall should have class info, which can not be fetch from 'this'.
  10075. // Consider this case:
  10076. // class A has method f,
  10077. // class B inherits class A, overrides method f, f call superApply('f'),
  10078. // class C inherits class B, do not overrides method f,
  10079. // then when method of class C is called, dead loop occured.
  10080. function superCall(context, methodName) {
  10081. var args = slice(arguments, 2);
  10082. return this.superClass.prototype[methodName].apply(context, args);
  10083. }
  10084. function superApply(context, methodName, args) {
  10085. return this.superClass.prototype[methodName].apply(context, args);
  10086. }
  10087. /**
  10088. * @param {Object} entity
  10089. * @param {Object} options
  10090. * @param {boolean} [options.registerWhenExtend]
  10091. * @public
  10092. */
  10093. function enableClassManagement(entity, options) {
  10094. options = options || {};
  10095. /**
  10096. * Component model classes
  10097. * key: componentType,
  10098. * value:
  10099. * componentClass, when componentType is 'xxx'
  10100. * or Object.<subKey, componentClass>, when componentType is 'xxx.yy'
  10101. * @type {Object}
  10102. */
  10103. var storage = {};
  10104. entity.registerClass = function (Clazz, componentType) {
  10105. if (componentType) {
  10106. checkClassType(componentType);
  10107. componentType = parseClassType$1(componentType);
  10108. if (!componentType.sub) {
  10109. if (__DEV__) {
  10110. if (storage[componentType.main]) {
  10111. console.warn(componentType.main + ' exists.');
  10112. }
  10113. }
  10114. storage[componentType.main] = Clazz;
  10115. }
  10116. else if (componentType.sub !== IS_CONTAINER) {
  10117. var container = makeContainer(componentType);
  10118. container[componentType.sub] = Clazz;
  10119. }
  10120. }
  10121. return Clazz;
  10122. };
  10123. entity.getClass = function (componentMainType, subType, throwWhenNotFound) {
  10124. var Clazz = storage[componentMainType];
  10125. if (Clazz && Clazz[IS_CONTAINER]) {
  10126. Clazz = subType ? Clazz[subType] : null;
  10127. }
  10128. if (throwWhenNotFound && !Clazz) {
  10129. throw new Error(
  10130. !subType
  10131. ? componentMainType + '.' + 'type should be specified.'
  10132. : 'Component ' + componentMainType + '.' + (subType || '') + ' not exists. Load it first.'
  10133. );
  10134. }
  10135. return Clazz;
  10136. };
  10137. entity.getClassesByMainType = function (componentType) {
  10138. componentType = parseClassType$1(componentType);
  10139. var result = [];
  10140. var obj = storage[componentType.main];
  10141. if (obj && obj[IS_CONTAINER]) {
  10142. each$1(obj, function (o, type) {
  10143. type !== IS_CONTAINER && result.push(o);
  10144. });
  10145. }
  10146. else {
  10147. result.push(obj);
  10148. }
  10149. return result;
  10150. };
  10151. entity.hasClass = function (componentType) {
  10152. // Just consider componentType.main.
  10153. componentType = parseClassType$1(componentType);
  10154. return !!storage[componentType.main];
  10155. };
  10156. /**
  10157. * @return {Array.<string>} Like ['aa', 'bb'], but can not be ['aa.xx']
  10158. */
  10159. entity.getAllClassMainTypes = function () {
  10160. var types = [];
  10161. each$1(storage, function (obj, type) {
  10162. types.push(type);
  10163. });
  10164. return types;
  10165. };
  10166. /**
  10167. * If a main type is container and has sub types
  10168. * @param {string} mainType
  10169. * @return {boolean}
  10170. */
  10171. entity.hasSubTypes = function (componentType) {
  10172. componentType = parseClassType$1(componentType);
  10173. var obj = storage[componentType.main];
  10174. return obj && obj[IS_CONTAINER];
  10175. };
  10176. entity.parseClassType = parseClassType$1;
  10177. function makeContainer(componentType) {
  10178. var container = storage[componentType.main];
  10179. if (!container || !container[IS_CONTAINER]) {
  10180. container = storage[componentType.main] = {};
  10181. container[IS_CONTAINER] = true;
  10182. }
  10183. return container;
  10184. }
  10185. if (options.registerWhenExtend) {
  10186. var originalExtend = entity.extend;
  10187. if (originalExtend) {
  10188. entity.extend = function (proto) {
  10189. var ExtendedClass = originalExtend.call(this, proto);
  10190. return entity.registerClass(ExtendedClass, proto.type);
  10191. };
  10192. }
  10193. }
  10194. return entity;
  10195. }
  10196. /**
  10197. * @param {string|Array.<string>} properties
  10198. */
  10199. /*
  10200. * Licensed to the Apache Software Foundation (ASF) under one
  10201. * or more contributor license agreements. See the NOTICE file
  10202. * distributed with this work for additional information
  10203. * regarding copyright ownership. The ASF licenses this file
  10204. * to you under the Apache License, Version 2.0 (the
  10205. * "License"); you may not use this file except in compliance
  10206. * with the License. You may obtain a copy of the License at
  10207. *
  10208. * http://www.apache.org/licenses/LICENSE-2.0
  10209. *
  10210. * Unless required by applicable law or agreed to in writing,
  10211. * software distributed under the License is distributed on an
  10212. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10213. * KIND, either express or implied. See the License for the
  10214. * specific language governing permissions and limitations
  10215. * under the License.
  10216. */
  10217. // TODO Parse shadow style
  10218. // TODO Only shallow path support
  10219. var makeStyleMapper = function (properties) {
  10220. // Normalize
  10221. for (var i = 0; i < properties.length; i++) {
  10222. if (!properties[i][1]) {
  10223. properties[i][1] = properties[i][0];
  10224. }
  10225. }
  10226. return function (model, excludes, includes) {
  10227. var style = {};
  10228. for (var i = 0; i < properties.length; i++) {
  10229. var propName = properties[i][1];
  10230. if ((excludes && indexOf(excludes, propName) >= 0)
  10231. || (includes && indexOf(includes, propName) < 0)
  10232. ) {
  10233. continue;
  10234. }
  10235. var val = model.getShallow(propName);
  10236. if (val != null) {
  10237. style[properties[i][0]] = val;
  10238. }
  10239. }
  10240. return style;
  10241. };
  10242. };
  10243. /*
  10244. * Licensed to the Apache Software Foundation (ASF) under one
  10245. * or more contributor license agreements. See the NOTICE file
  10246. * distributed with this work for additional information
  10247. * regarding copyright ownership. The ASF licenses this file
  10248. * to you under the Apache License, Version 2.0 (the
  10249. * "License"); you may not use this file except in compliance
  10250. * with the License. You may obtain a copy of the License at
  10251. *
  10252. * http://www.apache.org/licenses/LICENSE-2.0
  10253. *
  10254. * Unless required by applicable law or agreed to in writing,
  10255. * software distributed under the License is distributed on an
  10256. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10257. * KIND, either express or implied. See the License for the
  10258. * specific language governing permissions and limitations
  10259. * under the License.
  10260. */
  10261. var getLineStyle = makeStyleMapper(
  10262. [
  10263. ['lineWidth', 'width'],
  10264. ['stroke', 'color'],
  10265. ['opacity'],
  10266. ['shadowBlur'],
  10267. ['shadowOffsetX'],
  10268. ['shadowOffsetY'],
  10269. ['shadowColor']
  10270. ]
  10271. );
  10272. var lineStyleMixin = {
  10273. getLineStyle: function (excludes) {
  10274. var style = getLineStyle(this, excludes);
  10275. var lineDash = this.getLineDash(style.lineWidth);
  10276. lineDash && (style.lineDash = lineDash);
  10277. return style;
  10278. },
  10279. getLineDash: function (lineWidth) {
  10280. if (lineWidth == null) {
  10281. lineWidth = 1;
  10282. }
  10283. var lineType = this.get('type');
  10284. var dotSize = Math.max(lineWidth, 2);
  10285. var dashSize = lineWidth * 4;
  10286. return (lineType === 'solid' || lineType == null) ? null
  10287. : (lineType === 'dashed' ? [dashSize, dashSize] : [dotSize, dotSize]);
  10288. }
  10289. };
  10290. /*
  10291. * Licensed to the Apache Software Foundation (ASF) under one
  10292. * or more contributor license agreements. See the NOTICE file
  10293. * distributed with this work for additional information
  10294. * regarding copyright ownership. The ASF licenses this file
  10295. * to you under the Apache License, Version 2.0 (the
  10296. * "License"); you may not use this file except in compliance
  10297. * with the License. You may obtain a copy of the License at
  10298. *
  10299. * http://www.apache.org/licenses/LICENSE-2.0
  10300. *
  10301. * Unless required by applicable law or agreed to in writing,
  10302. * software distributed under the License is distributed on an
  10303. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10304. * KIND, either express or implied. See the License for the
  10305. * specific language governing permissions and limitations
  10306. * under the License.
  10307. */
  10308. var getAreaStyle = makeStyleMapper(
  10309. [
  10310. ['fill', 'color'],
  10311. ['shadowBlur'],
  10312. ['shadowOffsetX'],
  10313. ['shadowOffsetY'],
  10314. ['opacity'],
  10315. ['shadowColor']
  10316. ]
  10317. );
  10318. var areaStyleMixin = {
  10319. getAreaStyle: function (excludes, includes) {
  10320. return getAreaStyle(this, excludes, includes);
  10321. }
  10322. };
  10323. /**
  10324. * 曲线辅助模块
  10325. * @module zrender/core/curve
  10326. * @author pissang(https://www.github.com/pissang)
  10327. */
  10328. var mathPow = Math.pow;
  10329. var mathSqrt$2 = Math.sqrt;
  10330. var EPSILON$1 = 1e-8;
  10331. var EPSILON_NUMERIC = 1e-4;
  10332. var THREE_SQRT = mathSqrt$2(3);
  10333. var ONE_THIRD = 1 / 3;
  10334. // 临时变量
  10335. var _v0 = create();
  10336. var _v1 = create();
  10337. var _v2 = create();
  10338. function isAroundZero(val) {
  10339. return val > -EPSILON$1 && val < EPSILON$1;
  10340. }
  10341. function isNotAroundZero$1(val) {
  10342. return val > EPSILON$1 || val < -EPSILON$1;
  10343. }
  10344. /**
  10345. * 计算三次贝塞尔值
  10346. * @memberOf module:zrender/core/curve
  10347. * @param {number} p0
  10348. * @param {number} p1
  10349. * @param {number} p2
  10350. * @param {number} p3
  10351. * @param {number} t
  10352. * @return {number}
  10353. */
  10354. function cubicAt(p0, p1, p2, p3, t) {
  10355. var onet = 1 - t;
  10356. return onet * onet * (onet * p0 + 3 * t * p1)
  10357. + t * t * (t * p3 + 3 * onet * p2);
  10358. }
  10359. /**
  10360. * 计算三次贝塞尔导数值
  10361. * @memberOf module:zrender/core/curve
  10362. * @param {number} p0
  10363. * @param {number} p1
  10364. * @param {number} p2
  10365. * @param {number} p3
  10366. * @param {number} t
  10367. * @return {number}
  10368. */
  10369. function cubicDerivativeAt(p0, p1, p2, p3, t) {
  10370. var onet = 1 - t;
  10371. return 3 * (
  10372. ((p1 - p0) * onet + 2 * (p2 - p1) * t) * onet
  10373. + (p3 - p2) * t * t
  10374. );
  10375. }
  10376. /**
  10377. * 计算三次贝塞尔方程根,使用盛金公式
  10378. * @memberOf module:zrender/core/curve
  10379. * @param {number} p0
  10380. * @param {number} p1
  10381. * @param {number} p2
  10382. * @param {number} p3
  10383. * @param {number} val
  10384. * @param {Array.<number>} roots
  10385. * @return {number} 有效根数目
  10386. */
  10387. function cubicRootAt(p0, p1, p2, p3, val, roots) {
  10388. // Evaluate roots of cubic functions
  10389. var a = p3 + 3 * (p1 - p2) - p0;
  10390. var b = 3 * (p2 - p1 * 2 + p0);
  10391. var c = 3 * (p1 - p0);
  10392. var d = p0 - val;
  10393. var A = b * b - 3 * a * c;
  10394. var B = b * c - 9 * a * d;
  10395. var C = c * c - 3 * b * d;
  10396. var n = 0;
  10397. if (isAroundZero(A) && isAroundZero(B)) {
  10398. if (isAroundZero(b)) {
  10399. roots[0] = 0;
  10400. }
  10401. else {
  10402. var t1 = -c / b; //t1, t2, t3, b is not zero
  10403. if (t1 >= 0 && t1 <= 1) {
  10404. roots[n++] = t1;
  10405. }
  10406. }
  10407. }
  10408. else {
  10409. var disc = B * B - 4 * A * C;
  10410. if (isAroundZero(disc)) {
  10411. var K = B / A;
  10412. var t1 = -b / a + K; // t1, a is not zero
  10413. var t2 = -K / 2; // t2, t3
  10414. if (t1 >= 0 && t1 <= 1) {
  10415. roots[n++] = t1;
  10416. }
  10417. if (t2 >= 0 && t2 <= 1) {
  10418. roots[n++] = t2;
  10419. }
  10420. }
  10421. else if (disc > 0) {
  10422. var discSqrt = mathSqrt$2(disc);
  10423. var Y1 = A * b + 1.5 * a * (-B + discSqrt);
  10424. var Y2 = A * b + 1.5 * a * (-B - discSqrt);
  10425. if (Y1 < 0) {
  10426. Y1 = -mathPow(-Y1, ONE_THIRD);
  10427. }
  10428. else {
  10429. Y1 = mathPow(Y1, ONE_THIRD);
  10430. }
  10431. if (Y2 < 0) {
  10432. Y2 = -mathPow(-Y2, ONE_THIRD);
  10433. }
  10434. else {
  10435. Y2 = mathPow(Y2, ONE_THIRD);
  10436. }
  10437. var t1 = (-b - (Y1 + Y2)) / (3 * a);
  10438. if (t1 >= 0 && t1 <= 1) {
  10439. roots[n++] = t1;
  10440. }
  10441. }
  10442. else {
  10443. var T = (2 * A * b - 3 * a * B) / (2 * mathSqrt$2(A * A * A));
  10444. var theta = Math.acos(T) / 3;
  10445. var ASqrt = mathSqrt$2(A);
  10446. var tmp = Math.cos(theta);
  10447. var t1 = (-b - 2 * ASqrt * tmp) / (3 * a);
  10448. var t2 = (-b + ASqrt * (tmp + THREE_SQRT * Math.sin(theta))) / (3 * a);
  10449. var t3 = (-b + ASqrt * (tmp - THREE_SQRT * Math.sin(theta))) / (3 * a);
  10450. if (t1 >= 0 && t1 <= 1) {
  10451. roots[n++] = t1;
  10452. }
  10453. if (t2 >= 0 && t2 <= 1) {
  10454. roots[n++] = t2;
  10455. }
  10456. if (t3 >= 0 && t3 <= 1) {
  10457. roots[n++] = t3;
  10458. }
  10459. }
  10460. }
  10461. return n;
  10462. }
  10463. /**
  10464. * 计算三次贝塞尔方程极限值的位置
  10465. * @memberOf module:zrender/core/curve
  10466. * @param {number} p0
  10467. * @param {number} p1
  10468. * @param {number} p2
  10469. * @param {number} p3
  10470. * @param {Array.<number>} extrema
  10471. * @return {number} 有效数目
  10472. */
  10473. function cubicExtrema(p0, p1, p2, p3, extrema) {
  10474. var b = 6 * p2 - 12 * p1 + 6 * p0;
  10475. var a = 9 * p1 + 3 * p3 - 3 * p0 - 9 * p2;
  10476. var c = 3 * p1 - 3 * p0;
  10477. var n = 0;
  10478. if (isAroundZero(a)) {
  10479. if (isNotAroundZero$1(b)) {
  10480. var t1 = -c / b;
  10481. if (t1 >= 0 && t1 <=1) {
  10482. extrema[n++] = t1;
  10483. }
  10484. }
  10485. }
  10486. else {
  10487. var disc = b * b - 4 * a * c;
  10488. if (isAroundZero(disc)) {
  10489. extrema[0] = -b / (2 * a);
  10490. }
  10491. else if (disc > 0) {
  10492. var discSqrt = mathSqrt$2(disc);
  10493. var t1 = (-b + discSqrt) / (2 * a);
  10494. var t2 = (-b - discSqrt) / (2 * a);
  10495. if (t1 >= 0 && t1 <= 1) {
  10496. extrema[n++] = t1;
  10497. }
  10498. if (t2 >= 0 && t2 <= 1) {
  10499. extrema[n++] = t2;
  10500. }
  10501. }
  10502. }
  10503. return n;
  10504. }
  10505. /**
  10506. * 细分三次贝塞尔曲线
  10507. * @memberOf module:zrender/core/curve
  10508. * @param {number} p0
  10509. * @param {number} p1
  10510. * @param {number} p2
  10511. * @param {number} p3
  10512. * @param {number} t
  10513. * @param {Array.<number>} out
  10514. */
  10515. function cubicSubdivide(p0, p1, p2, p3, t, out) {
  10516. var p01 = (p1 - p0) * t + p0;
  10517. var p12 = (p2 - p1) * t + p1;
  10518. var p23 = (p3 - p2) * t + p2;
  10519. var p012 = (p12 - p01) * t + p01;
  10520. var p123 = (p23 - p12) * t + p12;
  10521. var p0123 = (p123 - p012) * t + p012;
  10522. // Seg0
  10523. out[0] = p0;
  10524. out[1] = p01;
  10525. out[2] = p012;
  10526. out[3] = p0123;
  10527. // Seg1
  10528. out[4] = p0123;
  10529. out[5] = p123;
  10530. out[6] = p23;
  10531. out[7] = p3;
  10532. }
  10533. /**
  10534. * 投射点到三次贝塞尔曲线上,返回投射距离。
  10535. * 投射点有可能会有一个或者多个,这里只返回其中距离最短的一个。
  10536. * @param {number} x0
  10537. * @param {number} y0
  10538. * @param {number} x1
  10539. * @param {number} y1
  10540. * @param {number} x2
  10541. * @param {number} y2
  10542. * @param {number} x3
  10543. * @param {number} y3
  10544. * @param {number} x
  10545. * @param {number} y
  10546. * @param {Array.<number>} [out] 投射点
  10547. * @return {number}
  10548. */
  10549. function cubicProjectPoint(
  10550. x0, y0, x1, y1, x2, y2, x3, y3,
  10551. x, y, out
  10552. ) {
  10553. // http://pomax.github.io/bezierinfo/#projections
  10554. var t;
  10555. var interval = 0.005;
  10556. var d = Infinity;
  10557. var prev;
  10558. var next;
  10559. var d1;
  10560. var d2;
  10561. _v0[0] = x;
  10562. _v0[1] = y;
  10563. // 先粗略估计一下可能的最小距离的 t 值
  10564. // PENDING
  10565. for (var _t = 0; _t < 1; _t += 0.05) {
  10566. _v1[0] = cubicAt(x0, x1, x2, x3, _t);
  10567. _v1[1] = cubicAt(y0, y1, y2, y3, _t);
  10568. d1 = distSquare(_v0, _v1);
  10569. if (d1 < d) {
  10570. t = _t;
  10571. d = d1;
  10572. }
  10573. }
  10574. d = Infinity;
  10575. // At most 32 iteration
  10576. for (var i = 0; i < 32; i++) {
  10577. if (interval < EPSILON_NUMERIC) {
  10578. break;
  10579. }
  10580. prev = t - interval;
  10581. next = t + interval;
  10582. // t - interval
  10583. _v1[0] = cubicAt(x0, x1, x2, x3, prev);
  10584. _v1[1] = cubicAt(y0, y1, y2, y3, prev);
  10585. d1 = distSquare(_v1, _v0);
  10586. if (prev >= 0 && d1 < d) {
  10587. t = prev;
  10588. d = d1;
  10589. }
  10590. else {
  10591. // t + interval
  10592. _v2[0] = cubicAt(x0, x1, x2, x3, next);
  10593. _v2[1] = cubicAt(y0, y1, y2, y3, next);
  10594. d2 = distSquare(_v2, _v0);
  10595. if (next <= 1 && d2 < d) {
  10596. t = next;
  10597. d = d2;
  10598. }
  10599. else {
  10600. interval *= 0.5;
  10601. }
  10602. }
  10603. }
  10604. // t
  10605. if (out) {
  10606. out[0] = cubicAt(x0, x1, x2, x3, t);
  10607. out[1] = cubicAt(y0, y1, y2, y3, t);
  10608. }
  10609. // console.log(interval, i);
  10610. return mathSqrt$2(d);
  10611. }
  10612. /**
  10613. * 计算二次方贝塞尔值
  10614. * @param {number} p0
  10615. * @param {number} p1
  10616. * @param {number} p2
  10617. * @param {number} t
  10618. * @return {number}
  10619. */
  10620. function quadraticAt(p0, p1, p2, t) {
  10621. var onet = 1 - t;
  10622. return onet * (onet * p0 + 2 * t * p1) + t * t * p2;
  10623. }
  10624. /**
  10625. * 计算二次方贝塞尔导数值
  10626. * @param {number} p0
  10627. * @param {number} p1
  10628. * @param {number} p2
  10629. * @param {number} t
  10630. * @return {number}
  10631. */
  10632. function quadraticDerivativeAt(p0, p1, p2, t) {
  10633. return 2 * ((1 - t) * (p1 - p0) + t * (p2 - p1));
  10634. }
  10635. /**
  10636. * 计算二次方贝塞尔方程根
  10637. * @param {number} p0
  10638. * @param {number} p1
  10639. * @param {number} p2
  10640. * @param {number} t
  10641. * @param {Array.<number>} roots
  10642. * @return {number} 有效根数目
  10643. */
  10644. function quadraticRootAt(p0, p1, p2, val, roots) {
  10645. var a = p0 - 2 * p1 + p2;
  10646. var b = 2 * (p1 - p0);
  10647. var c = p0 - val;
  10648. var n = 0;
  10649. if (isAroundZero(a)) {
  10650. if (isNotAroundZero$1(b)) {
  10651. var t1 = -c / b;
  10652. if (t1 >= 0 && t1 <= 1) {
  10653. roots[n++] = t1;
  10654. }
  10655. }
  10656. }
  10657. else {
  10658. var disc = b * b - 4 * a * c;
  10659. if (isAroundZero(disc)) {
  10660. var t1 = -b / (2 * a);
  10661. if (t1 >= 0 && t1 <= 1) {
  10662. roots[n++] = t1;
  10663. }
  10664. }
  10665. else if (disc > 0) {
  10666. var discSqrt = mathSqrt$2(disc);
  10667. var t1 = (-b + discSqrt) / (2 * a);
  10668. var t2 = (-b - discSqrt) / (2 * a);
  10669. if (t1 >= 0 && t1 <= 1) {
  10670. roots[n++] = t1;
  10671. }
  10672. if (t2 >= 0 && t2 <= 1) {
  10673. roots[n++] = t2;
  10674. }
  10675. }
  10676. }
  10677. return n;
  10678. }
  10679. /**
  10680. * 计算二次贝塞尔方程极限值
  10681. * @memberOf module:zrender/core/curve
  10682. * @param {number} p0
  10683. * @param {number} p1
  10684. * @param {number} p2
  10685. * @return {number}
  10686. */
  10687. function quadraticExtremum(p0, p1, p2) {
  10688. var divider = p0 + p2 - 2 * p1;
  10689. if (divider === 0) {
  10690. // p1 is center of p0 and p2
  10691. return 0.5;
  10692. }
  10693. else {
  10694. return (p0 - p1) / divider;
  10695. }
  10696. }
  10697. /**
  10698. * 细分二次贝塞尔曲线
  10699. * @memberOf module:zrender/core/curve
  10700. * @param {number} p0
  10701. * @param {number} p1
  10702. * @param {number} p2
  10703. * @param {number} t
  10704. * @param {Array.<number>} out
  10705. */
  10706. function quadraticSubdivide(p0, p1, p2, t, out) {
  10707. var p01 = (p1 - p0) * t + p0;
  10708. var p12 = (p2 - p1) * t + p1;
  10709. var p012 = (p12 - p01) * t + p01;
  10710. // Seg0
  10711. out[0] = p0;
  10712. out[1] = p01;
  10713. out[2] = p012;
  10714. // Seg1
  10715. out[3] = p012;
  10716. out[4] = p12;
  10717. out[5] = p2;
  10718. }
  10719. /**
  10720. * 投射点到二次贝塞尔曲线上,返回投射距离。
  10721. * 投射点有可能会有一个或者多个,这里只返回其中距离最短的一个。
  10722. * @param {number} x0
  10723. * @param {number} y0
  10724. * @param {number} x1
  10725. * @param {number} y1
  10726. * @param {number} x2
  10727. * @param {number} y2
  10728. * @param {number} x
  10729. * @param {number} y
  10730. * @param {Array.<number>} out 投射点
  10731. * @return {number}
  10732. */
  10733. function quadraticProjectPoint(
  10734. x0, y0, x1, y1, x2, y2,
  10735. x, y, out
  10736. ) {
  10737. // http://pomax.github.io/bezierinfo/#projections
  10738. var t;
  10739. var interval = 0.005;
  10740. var d = Infinity;
  10741. _v0[0] = x;
  10742. _v0[1] = y;
  10743. // 先粗略估计一下可能的最小距离的 t 值
  10744. // PENDING
  10745. for (var _t = 0; _t < 1; _t += 0.05) {
  10746. _v1[0] = quadraticAt(x0, x1, x2, _t);
  10747. _v1[1] = quadraticAt(y0, y1, y2, _t);
  10748. var d1 = distSquare(_v0, _v1);
  10749. if (d1 < d) {
  10750. t = _t;
  10751. d = d1;
  10752. }
  10753. }
  10754. d = Infinity;
  10755. // At most 32 iteration
  10756. for (var i = 0; i < 32; i++) {
  10757. if (interval < EPSILON_NUMERIC) {
  10758. break;
  10759. }
  10760. var prev = t - interval;
  10761. var next = t + interval;
  10762. // t - interval
  10763. _v1[0] = quadraticAt(x0, x1, x2, prev);
  10764. _v1[1] = quadraticAt(y0, y1, y2, prev);
  10765. var d1 = distSquare(_v1, _v0);
  10766. if (prev >= 0 && d1 < d) {
  10767. t = prev;
  10768. d = d1;
  10769. }
  10770. else {
  10771. // t + interval
  10772. _v2[0] = quadraticAt(x0, x1, x2, next);
  10773. _v2[1] = quadraticAt(y0, y1, y2, next);
  10774. var d2 = distSquare(_v2, _v0);
  10775. if (next <= 1 && d2 < d) {
  10776. t = next;
  10777. d = d2;
  10778. }
  10779. else {
  10780. interval *= 0.5;
  10781. }
  10782. }
  10783. }
  10784. // t
  10785. if (out) {
  10786. out[0] = quadraticAt(x0, x1, x2, t);
  10787. out[1] = quadraticAt(y0, y1, y2, t);
  10788. }
  10789. // console.log(interval, i);
  10790. return mathSqrt$2(d);
  10791. }
  10792. /**
  10793. * @author Yi Shen(https://github.com/pissang)
  10794. */
  10795. var mathMin$3 = Math.min;
  10796. var mathMax$3 = Math.max;
  10797. var mathSin$2 = Math.sin;
  10798. var mathCos$2 = Math.cos;
  10799. var PI2 = Math.PI * 2;
  10800. var start = create();
  10801. var end = create();
  10802. var extremity = create();
  10803. /**
  10804. * 从顶点数组中计算出最小包围盒,写入`min`和`max`中
  10805. * @module zrender/core/bbox
  10806. * @param {Array<Object>} points 顶点数组
  10807. * @param {number} min
  10808. * @param {number} max
  10809. */
  10810. function fromPoints(points, min$$1, max$$1) {
  10811. if (points.length === 0) {
  10812. return;
  10813. }
  10814. var p = points[0];
  10815. var left = p[0];
  10816. var right = p[0];
  10817. var top = p[1];
  10818. var bottom = p[1];
  10819. var i;
  10820. for (i = 1; i < points.length; i++) {
  10821. p = points[i];
  10822. left = mathMin$3(left, p[0]);
  10823. right = mathMax$3(right, p[0]);
  10824. top = mathMin$3(top, p[1]);
  10825. bottom = mathMax$3(bottom, p[1]);
  10826. }
  10827. min$$1[0] = left;
  10828. min$$1[1] = top;
  10829. max$$1[0] = right;
  10830. max$$1[1] = bottom;
  10831. }
  10832. /**
  10833. * @memberOf module:zrender/core/bbox
  10834. * @param {number} x0
  10835. * @param {number} y0
  10836. * @param {number} x1
  10837. * @param {number} y1
  10838. * @param {Array.<number>} min
  10839. * @param {Array.<number>} max
  10840. */
  10841. function fromLine(x0, y0, x1, y1, min$$1, max$$1) {
  10842. min$$1[0] = mathMin$3(x0, x1);
  10843. min$$1[1] = mathMin$3(y0, y1);
  10844. max$$1[0] = mathMax$3(x0, x1);
  10845. max$$1[1] = mathMax$3(y0, y1);
  10846. }
  10847. var xDim = [];
  10848. var yDim = [];
  10849. /**
  10850. * 从三阶贝塞尔曲线(p0, p1, p2, p3)中计算出最小包围盒,写入`min`和`max`中
  10851. * @memberOf module:zrender/core/bbox
  10852. * @param {number} x0
  10853. * @param {number} y0
  10854. * @param {number} x1
  10855. * @param {number} y1
  10856. * @param {number} x2
  10857. * @param {number} y2
  10858. * @param {number} x3
  10859. * @param {number} y3
  10860. * @param {Array.<number>} min
  10861. * @param {Array.<number>} max
  10862. */
  10863. function fromCubic(
  10864. x0, y0, x1, y1, x2, y2, x3, y3, min$$1, max$$1
  10865. ) {
  10866. var cubicExtrema$$1 = cubicExtrema;
  10867. var cubicAt$$1 = cubicAt;
  10868. var i;
  10869. var n = cubicExtrema$$1(x0, x1, x2, x3, xDim);
  10870. min$$1[0] = Infinity;
  10871. min$$1[1] = Infinity;
  10872. max$$1[0] = -Infinity;
  10873. max$$1[1] = -Infinity;
  10874. for (i = 0; i < n; i++) {
  10875. var x = cubicAt$$1(x0, x1, x2, x3, xDim[i]);
  10876. min$$1[0] = mathMin$3(x, min$$1[0]);
  10877. max$$1[0] = mathMax$3(x, max$$1[0]);
  10878. }
  10879. n = cubicExtrema$$1(y0, y1, y2, y3, yDim);
  10880. for (i = 0; i < n; i++) {
  10881. var y = cubicAt$$1(y0, y1, y2, y3, yDim[i]);
  10882. min$$1[1] = mathMin$3(y, min$$1[1]);
  10883. max$$1[1] = mathMax$3(y, max$$1[1]);
  10884. }
  10885. min$$1[0] = mathMin$3(x0, min$$1[0]);
  10886. max$$1[0] = mathMax$3(x0, max$$1[0]);
  10887. min$$1[0] = mathMin$3(x3, min$$1[0]);
  10888. max$$1[0] = mathMax$3(x3, max$$1[0]);
  10889. min$$1[1] = mathMin$3(y0, min$$1[1]);
  10890. max$$1[1] = mathMax$3(y0, max$$1[1]);
  10891. min$$1[1] = mathMin$3(y3, min$$1[1]);
  10892. max$$1[1] = mathMax$3(y3, max$$1[1]);
  10893. }
  10894. /**
  10895. * 从二阶贝塞尔曲线(p0, p1, p2)中计算出最小包围盒,写入`min`和`max`中
  10896. * @memberOf module:zrender/core/bbox
  10897. * @param {number} x0
  10898. * @param {number} y0
  10899. * @param {number} x1
  10900. * @param {number} y1
  10901. * @param {number} x2
  10902. * @param {number} y2
  10903. * @param {Array.<number>} min
  10904. * @param {Array.<number>} max
  10905. */
  10906. function fromQuadratic(x0, y0, x1, y1, x2, y2, min$$1, max$$1) {
  10907. var quadraticExtremum$$1 = quadraticExtremum;
  10908. var quadraticAt$$1 = quadraticAt;
  10909. // Find extremities, where derivative in x dim or y dim is zero
  10910. var tx =
  10911. mathMax$3(
  10912. mathMin$3(quadraticExtremum$$1(x0, x1, x2), 1), 0
  10913. );
  10914. var ty =
  10915. mathMax$3(
  10916. mathMin$3(quadraticExtremum$$1(y0, y1, y2), 1), 0
  10917. );
  10918. var x = quadraticAt$$1(x0, x1, x2, tx);
  10919. var y = quadraticAt$$1(y0, y1, y2, ty);
  10920. min$$1[0] = mathMin$3(x0, x2, x);
  10921. min$$1[1] = mathMin$3(y0, y2, y);
  10922. max$$1[0] = mathMax$3(x0, x2, x);
  10923. max$$1[1] = mathMax$3(y0, y2, y);
  10924. }
  10925. /**
  10926. * 从圆弧中计算出最小包围盒,写入`min`和`max`中
  10927. * @method
  10928. * @memberOf module:zrender/core/bbox
  10929. * @param {number} x
  10930. * @param {number} y
  10931. * @param {number} rx
  10932. * @param {number} ry
  10933. * @param {number} startAngle
  10934. * @param {number} endAngle
  10935. * @param {number} anticlockwise
  10936. * @param {Array.<number>} min
  10937. * @param {Array.<number>} max
  10938. */
  10939. function fromArc(
  10940. x, y, rx, ry, startAngle, endAngle, anticlockwise, min$$1, max$$1
  10941. ) {
  10942. var vec2Min = min;
  10943. var vec2Max = max;
  10944. var diff = Math.abs(startAngle - endAngle);
  10945. if (diff % PI2 < 1e-4 && diff > 1e-4) {
  10946. // Is a circle
  10947. min$$1[0] = x - rx;
  10948. min$$1[1] = y - ry;
  10949. max$$1[0] = x + rx;
  10950. max$$1[1] = y + ry;
  10951. return;
  10952. }
  10953. start[0] = mathCos$2(startAngle) * rx + x;
  10954. start[1] = mathSin$2(startAngle) * ry + y;
  10955. end[0] = mathCos$2(endAngle) * rx + x;
  10956. end[1] = mathSin$2(endAngle) * ry + y;
  10957. vec2Min(min$$1, start, end);
  10958. vec2Max(max$$1, start, end);
  10959. // Thresh to [0, Math.PI * 2]
  10960. startAngle = startAngle % (PI2);
  10961. if (startAngle < 0) {
  10962. startAngle = startAngle + PI2;
  10963. }
  10964. endAngle = endAngle % (PI2);
  10965. if (endAngle < 0) {
  10966. endAngle = endAngle + PI2;
  10967. }
  10968. if (startAngle > endAngle && !anticlockwise) {
  10969. endAngle += PI2;
  10970. }
  10971. else if (startAngle < endAngle && anticlockwise) {
  10972. startAngle += PI2;
  10973. }
  10974. if (anticlockwise) {
  10975. var tmp = endAngle;
  10976. endAngle = startAngle;
  10977. startAngle = tmp;
  10978. }
  10979. // var number = 0;
  10980. // var step = (anticlockwise ? -Math.PI : Math.PI) / 2;
  10981. for (var angle = 0; angle < endAngle; angle += Math.PI / 2) {
  10982. if (angle > startAngle) {
  10983. extremity[0] = mathCos$2(angle) * rx + x;
  10984. extremity[1] = mathSin$2(angle) * ry + y;
  10985. vec2Min(min$$1, extremity, min$$1);
  10986. vec2Max(max$$1, extremity, max$$1);
  10987. }
  10988. }
  10989. }
  10990. /**
  10991. * Path 代理,可以在`buildPath`中用于替代`ctx`, 会保存每个path操作的命令到pathCommands属性中
  10992. * 可以用于 isInsidePath 判断以及获取boundingRect
  10993. *
  10994. * @module zrender/core/PathProxy
  10995. * @author Yi Shen (http://www.github.com/pissang)
  10996. */
  10997. // TODO getTotalLength, getPointAtLength
  10998. var CMD = {
  10999. M: 1,
  11000. L: 2,
  11001. C: 3,
  11002. Q: 4,
  11003. A: 5,
  11004. Z: 6,
  11005. // Rect
  11006. R: 7
  11007. };
  11008. // var CMD_MEM_SIZE = {
  11009. // M: 3,
  11010. // L: 3,
  11011. // C: 7,
  11012. // Q: 5,
  11013. // A: 9,
  11014. // R: 5,
  11015. // Z: 1
  11016. // };
  11017. var min$1 = [];
  11018. var max$1 = [];
  11019. var min2 = [];
  11020. var max2 = [];
  11021. var mathMin$2 = Math.min;
  11022. var mathMax$2 = Math.max;
  11023. var mathCos$1 = Math.cos;
  11024. var mathSin$1 = Math.sin;
  11025. var mathSqrt$1 = Math.sqrt;
  11026. var mathAbs = Math.abs;
  11027. var hasTypedArray = typeof Float32Array != 'undefined';
  11028. /**
  11029. * @alias module:zrender/core/PathProxy
  11030. * @constructor
  11031. */
  11032. var PathProxy = function (notSaveData) {
  11033. this._saveData = !(notSaveData || false);
  11034. if (this._saveData) {
  11035. /**
  11036. * Path data. Stored as flat array
  11037. * @type {Array.<Object>}
  11038. */
  11039. this.data = [];
  11040. }
  11041. this._ctx = null;
  11042. };
  11043. /**
  11044. * 快速计算Path包围盒(并不是最小包围盒)
  11045. * @return {Object}
  11046. */
  11047. PathProxy.prototype = {
  11048. constructor: PathProxy,
  11049. _xi: 0,
  11050. _yi: 0,
  11051. _x0: 0,
  11052. _y0: 0,
  11053. // Unit x, Unit y. Provide for avoiding drawing that too short line segment
  11054. _ux: 0,
  11055. _uy: 0,
  11056. _len: 0,
  11057. _lineDash: null,
  11058. _dashOffset: 0,
  11059. _dashIdx: 0,
  11060. _dashSum: 0,
  11061. /**
  11062. * @readOnly
  11063. */
  11064. setScale: function (sx, sy) {
  11065. this._ux = mathAbs(1 / devicePixelRatio / sx) || 0;
  11066. this._uy = mathAbs(1 / devicePixelRatio / sy) || 0;
  11067. },
  11068. getContext: function () {
  11069. return this._ctx;
  11070. },
  11071. /**
  11072. * @param {CanvasRenderingContext2D} ctx
  11073. * @return {module:zrender/core/PathProxy}
  11074. */
  11075. beginPath: function (ctx) {
  11076. this._ctx = ctx;
  11077. ctx && ctx.beginPath();
  11078. ctx && (this.dpr = ctx.dpr);
  11079. // Reset
  11080. if (this._saveData) {
  11081. this._len = 0;
  11082. }
  11083. if (this._lineDash) {
  11084. this._lineDash = null;
  11085. this._dashOffset = 0;
  11086. }
  11087. return this;
  11088. },
  11089. /**
  11090. * @param {number} x
  11091. * @param {number} y
  11092. * @return {module:zrender/core/PathProxy}
  11093. */
  11094. moveTo: function (x, y) {
  11095. this.addData(CMD.M, x, y);
  11096. this._ctx && this._ctx.moveTo(x, y);
  11097. // x0, y0, xi, yi 是记录在 _dashedXXXXTo 方法中使用
  11098. // xi, yi 记录当前点, x0, y0 在 closePath 的时候回到起始点。
  11099. // 有可能在 beginPath 之后直接调用 lineTo,这时候 x0, y0 需要
  11100. // 在 lineTo 方法中记录,这里先不考虑这种情况,dashed line 也只在 IE10- 中不支持
  11101. this._x0 = x;
  11102. this._y0 = y;
  11103. this._xi = x;
  11104. this._yi = y;
  11105. return this;
  11106. },
  11107. /**
  11108. * @param {number} x
  11109. * @param {number} y
  11110. * @return {module:zrender/core/PathProxy}
  11111. */
  11112. lineTo: function (x, y) {
  11113. var exceedUnit = mathAbs(x - this._xi) > this._ux
  11114. || mathAbs(y - this._yi) > this._uy
  11115. // Force draw the first segment
  11116. || this._len < 5;
  11117. this.addData(CMD.L, x, y);
  11118. if (this._ctx && exceedUnit) {
  11119. this._needsDash() ? this._dashedLineTo(x, y)
  11120. : this._ctx.lineTo(x, y);
  11121. }
  11122. if (exceedUnit) {
  11123. this._xi = x;
  11124. this._yi = y;
  11125. }
  11126. return this;
  11127. },
  11128. /**
  11129. * @param {number} x1
  11130. * @param {number} y1
  11131. * @param {number} x2
  11132. * @param {number} y2
  11133. * @param {number} x3
  11134. * @param {number} y3
  11135. * @return {module:zrender/core/PathProxy}
  11136. */
  11137. bezierCurveTo: function (x1, y1, x2, y2, x3, y3) {
  11138. this.addData(CMD.C, x1, y1, x2, y2, x3, y3);
  11139. if (this._ctx) {
  11140. this._needsDash() ? this._dashedBezierTo(x1, y1, x2, y2, x3, y3)
  11141. : this._ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
  11142. }
  11143. this._xi = x3;
  11144. this._yi = y3;
  11145. return this;
  11146. },
  11147. /**
  11148. * @param {number} x1
  11149. * @param {number} y1
  11150. * @param {number} x2
  11151. * @param {number} y2
  11152. * @return {module:zrender/core/PathProxy}
  11153. */
  11154. quadraticCurveTo: function (x1, y1, x2, y2) {
  11155. this.addData(CMD.Q, x1, y1, x2, y2);
  11156. if (this._ctx) {
  11157. this._needsDash() ? this._dashedQuadraticTo(x1, y1, x2, y2)
  11158. : this._ctx.quadraticCurveTo(x1, y1, x2, y2);
  11159. }
  11160. this._xi = x2;
  11161. this._yi = y2;
  11162. return this;
  11163. },
  11164. /**
  11165. * @param {number} cx
  11166. * @param {number} cy
  11167. * @param {number} r
  11168. * @param {number} startAngle
  11169. * @param {number} endAngle
  11170. * @param {boolean} anticlockwise
  11171. * @return {module:zrender/core/PathProxy}
  11172. */
  11173. arc: function (cx, cy, r, startAngle, endAngle, anticlockwise) {
  11174. this.addData(
  11175. CMD.A, cx, cy, r, r, startAngle, endAngle - startAngle, 0, anticlockwise ? 0 : 1
  11176. );
  11177. this._ctx && this._ctx.arc(cx, cy, r, startAngle, endAngle, anticlockwise);
  11178. this._xi = mathCos$1(endAngle) * r + cx;
  11179. this._yi = mathSin$1(endAngle) * r + cx;
  11180. return this;
  11181. },
  11182. // TODO
  11183. arcTo: function (x1, y1, x2, y2, radius) {
  11184. if (this._ctx) {
  11185. this._ctx.arcTo(x1, y1, x2, y2, radius);
  11186. }
  11187. return this;
  11188. },
  11189. // TODO
  11190. rect: function (x, y, w, h) {
  11191. this._ctx && this._ctx.rect(x, y, w, h);
  11192. this.addData(CMD.R, x, y, w, h);
  11193. return this;
  11194. },
  11195. /**
  11196. * @return {module:zrender/core/PathProxy}
  11197. */
  11198. closePath: function () {
  11199. this.addData(CMD.Z);
  11200. var ctx = this._ctx;
  11201. var x0 = this._x0;
  11202. var y0 = this._y0;
  11203. if (ctx) {
  11204. this._needsDash() && this._dashedLineTo(x0, y0);
  11205. ctx.closePath();
  11206. }
  11207. this._xi = x0;
  11208. this._yi = y0;
  11209. return this;
  11210. },
  11211. /**
  11212. * Context 从外部传入,因为有可能是 rebuildPath 完之后再 fill。
  11213. * stroke 同样
  11214. * @param {CanvasRenderingContext2D} ctx
  11215. * @return {module:zrender/core/PathProxy}
  11216. */
  11217. fill: function (ctx) {
  11218. ctx && ctx.fill();
  11219. this.toStatic();
  11220. },
  11221. /**
  11222. * @param {CanvasRenderingContext2D} ctx
  11223. * @return {module:zrender/core/PathProxy}
  11224. */
  11225. stroke: function (ctx) {
  11226. ctx && ctx.stroke();
  11227. this.toStatic();
  11228. },
  11229. /**
  11230. * 必须在其它绘制命令前调用
  11231. * Must be invoked before all other path drawing methods
  11232. * @return {module:zrender/core/PathProxy}
  11233. */
  11234. setLineDash: function (lineDash) {
  11235. if (lineDash instanceof Array) {
  11236. this._lineDash = lineDash;
  11237. this._dashIdx = 0;
  11238. var lineDashSum = 0;
  11239. for (var i = 0; i < lineDash.length; i++) {
  11240. lineDashSum += lineDash[i];
  11241. }
  11242. this._dashSum = lineDashSum;
  11243. }
  11244. return this;
  11245. },
  11246. /**
  11247. * 必须在其它绘制命令前调用
  11248. * Must be invoked before all other path drawing methods
  11249. * @return {module:zrender/core/PathProxy}
  11250. */
  11251. setLineDashOffset: function (offset) {
  11252. this._dashOffset = offset;
  11253. return this;
  11254. },
  11255. /**
  11256. *
  11257. * @return {boolean}
  11258. */
  11259. len: function () {
  11260. return this._len;
  11261. },
  11262. /**
  11263. * 直接设置 Path 数据
  11264. */
  11265. setData: function (data) {
  11266. var len$$1 = data.length;
  11267. if (! (this.data && this.data.length == len$$1) && hasTypedArray) {
  11268. this.data = new Float32Array(len$$1);
  11269. }
  11270. for (var i = 0; i < len$$1; i++) {
  11271. this.data[i] = data[i];
  11272. }
  11273. this._len = len$$1;
  11274. },
  11275. /**
  11276. * 添加子路径
  11277. * @param {module:zrender/core/PathProxy|Array.<module:zrender/core/PathProxy>} path
  11278. */
  11279. appendPath: function (path) {
  11280. if (!(path instanceof Array)) {
  11281. path = [path];
  11282. }
  11283. var len$$1 = path.length;
  11284. var appendSize = 0;
  11285. var offset = this._len;
  11286. for (var i = 0; i < len$$1; i++) {
  11287. appendSize += path[i].len();
  11288. }
  11289. if (hasTypedArray && (this.data instanceof Float32Array)) {
  11290. this.data = new Float32Array(offset + appendSize);
  11291. }
  11292. for (var i = 0; i < len$$1; i++) {
  11293. var appendPathData = path[i].data;
  11294. for (var k = 0; k < appendPathData.length; k++) {
  11295. this.data[offset++] = appendPathData[k];
  11296. }
  11297. }
  11298. this._len = offset;
  11299. },
  11300. /**
  11301. * 填充 Path 数据。
  11302. * 尽量复用而不申明新的数组。大部分图形重绘的指令数据长度都是不变的。
  11303. */
  11304. addData: function (cmd) {
  11305. if (!this._saveData) {
  11306. return;
  11307. }
  11308. var data = this.data;
  11309. if (this._len + arguments.length > data.length) {
  11310. // 因为之前的数组已经转换成静态的 Float32Array
  11311. // 所以不够用时需要扩展一个新的动态数组
  11312. this._expandData();
  11313. data = this.data;
  11314. }
  11315. for (var i = 0; i < arguments.length; i++) {
  11316. data[this._len++] = arguments[i];
  11317. }
  11318. this._prevCmd = cmd;
  11319. },
  11320. _expandData: function () {
  11321. // Only if data is Float32Array
  11322. if (!(this.data instanceof Array)) {
  11323. var newData = [];
  11324. for (var i = 0; i < this._len; i++) {
  11325. newData[i] = this.data[i];
  11326. }
  11327. this.data = newData;
  11328. }
  11329. },
  11330. /**
  11331. * If needs js implemented dashed line
  11332. * @return {boolean}
  11333. * @private
  11334. */
  11335. _needsDash: function () {
  11336. return this._lineDash;
  11337. },
  11338. _dashedLineTo: function (x1, y1) {
  11339. var dashSum = this._dashSum;
  11340. var offset = this._dashOffset;
  11341. var lineDash = this._lineDash;
  11342. var ctx = this._ctx;
  11343. var x0 = this._xi;
  11344. var y0 = this._yi;
  11345. var dx = x1 - x0;
  11346. var dy = y1 - y0;
  11347. var dist$$1 = mathSqrt$1(dx * dx + dy * dy);
  11348. var x = x0;
  11349. var y = y0;
  11350. var dash;
  11351. var nDash = lineDash.length;
  11352. var idx;
  11353. dx /= dist$$1;
  11354. dy /= dist$$1;
  11355. if (offset < 0) {
  11356. // Convert to positive offset
  11357. offset = dashSum + offset;
  11358. }
  11359. offset %= dashSum;
  11360. x -= offset * dx;
  11361. y -= offset * dy;
  11362. while ((dx > 0 && x <= x1) || (dx < 0 && x >= x1)
  11363. || (dx == 0 && ((dy > 0 && y <= y1) || (dy < 0 && y >= y1)))) {
  11364. idx = this._dashIdx;
  11365. dash = lineDash[idx];
  11366. x += dx * dash;
  11367. y += dy * dash;
  11368. this._dashIdx = (idx + 1) % nDash;
  11369. // Skip positive offset
  11370. if ((dx > 0 && x < x0) || (dx < 0 && x > x0) || (dy > 0 && y < y0) || (dy < 0 && y > y0)) {
  11371. continue;
  11372. }
  11373. ctx[idx % 2 ? 'moveTo' : 'lineTo'](
  11374. dx >= 0 ? mathMin$2(x, x1) : mathMax$2(x, x1),
  11375. dy >= 0 ? mathMin$2(y, y1) : mathMax$2(y, y1)
  11376. );
  11377. }
  11378. // Offset for next lineTo
  11379. dx = x - x1;
  11380. dy = y - y1;
  11381. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  11382. },
  11383. // Not accurate dashed line to
  11384. _dashedBezierTo: function (x1, y1, x2, y2, x3, y3) {
  11385. var dashSum = this._dashSum;
  11386. var offset = this._dashOffset;
  11387. var lineDash = this._lineDash;
  11388. var ctx = this._ctx;
  11389. var x0 = this._xi;
  11390. var y0 = this._yi;
  11391. var t;
  11392. var dx;
  11393. var dy;
  11394. var cubicAt$$1 = cubicAt;
  11395. var bezierLen = 0;
  11396. var idx = this._dashIdx;
  11397. var nDash = lineDash.length;
  11398. var x;
  11399. var y;
  11400. var tmpLen = 0;
  11401. if (offset < 0) {
  11402. // Convert to positive offset
  11403. offset = dashSum + offset;
  11404. }
  11405. offset %= dashSum;
  11406. // Bezier approx length
  11407. for (t = 0; t < 1; t += 0.1) {
  11408. dx = cubicAt$$1(x0, x1, x2, x3, t + 0.1)
  11409. - cubicAt$$1(x0, x1, x2, x3, t);
  11410. dy = cubicAt$$1(y0, y1, y2, y3, t + 0.1)
  11411. - cubicAt$$1(y0, y1, y2, y3, t);
  11412. bezierLen += mathSqrt$1(dx * dx + dy * dy);
  11413. }
  11414. // Find idx after add offset
  11415. for (; idx < nDash; idx++) {
  11416. tmpLen += lineDash[idx];
  11417. if (tmpLen > offset) {
  11418. break;
  11419. }
  11420. }
  11421. t = (tmpLen - offset) / bezierLen;
  11422. while (t <= 1) {
  11423. x = cubicAt$$1(x0, x1, x2, x3, t);
  11424. y = cubicAt$$1(y0, y1, y2, y3, t);
  11425. // Use line to approximate dashed bezier
  11426. // Bad result if dash is long
  11427. idx % 2 ? ctx.moveTo(x, y)
  11428. : ctx.lineTo(x, y);
  11429. t += lineDash[idx] / bezierLen;
  11430. idx = (idx + 1) % nDash;
  11431. }
  11432. // Finish the last segment and calculate the new offset
  11433. (idx % 2 !== 0) && ctx.lineTo(x3, y3);
  11434. dx = x3 - x;
  11435. dy = y3 - y;
  11436. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  11437. },
  11438. _dashedQuadraticTo: function (x1, y1, x2, y2) {
  11439. // Convert quadratic to cubic using degree elevation
  11440. var x3 = x2;
  11441. var y3 = y2;
  11442. x2 = (x2 + 2 * x1) / 3;
  11443. y2 = (y2 + 2 * y1) / 3;
  11444. x1 = (this._xi + 2 * x1) / 3;
  11445. y1 = (this._yi + 2 * y1) / 3;
  11446. this._dashedBezierTo(x1, y1, x2, y2, x3, y3);
  11447. },
  11448. /**
  11449. * 转成静态的 Float32Array 减少堆内存占用
  11450. * Convert dynamic array to static Float32Array
  11451. */
  11452. toStatic: function () {
  11453. var data = this.data;
  11454. if (data instanceof Array) {
  11455. data.length = this._len;
  11456. if (hasTypedArray) {
  11457. this.data = new Float32Array(data);
  11458. }
  11459. }
  11460. },
  11461. /**
  11462. * @return {module:zrender/core/BoundingRect}
  11463. */
  11464. getBoundingRect: function () {
  11465. min$1[0] = min$1[1] = min2[0] = min2[1] = Number.MAX_VALUE;
  11466. max$1[0] = max$1[1] = max2[0] = max2[1] = -Number.MAX_VALUE;
  11467. var data = this.data;
  11468. var xi = 0;
  11469. var yi = 0;
  11470. var x0 = 0;
  11471. var y0 = 0;
  11472. for (var i = 0; i < data.length;) {
  11473. var cmd = data[i++];
  11474. if (i == 1) {
  11475. // 如果第一个命令是 L, C, Q
  11476. // 则 previous point 同绘制命令的第一个 point
  11477. //
  11478. // 第一个命令为 Arc 的情况下会在后面特殊处理
  11479. xi = data[i];
  11480. yi = data[i + 1];
  11481. x0 = xi;
  11482. y0 = yi;
  11483. }
  11484. switch (cmd) {
  11485. case CMD.M:
  11486. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  11487. // 在 closePath 的时候使用
  11488. x0 = data[i++];
  11489. y0 = data[i++];
  11490. xi = x0;
  11491. yi = y0;
  11492. min2[0] = x0;
  11493. min2[1] = y0;
  11494. max2[0] = x0;
  11495. max2[1] = y0;
  11496. break;
  11497. case CMD.L:
  11498. fromLine(xi, yi, data[i], data[i + 1], min2, max2);
  11499. xi = data[i++];
  11500. yi = data[i++];
  11501. break;
  11502. case CMD.C:
  11503. fromCubic(
  11504. xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  11505. min2, max2
  11506. );
  11507. xi = data[i++];
  11508. yi = data[i++];
  11509. break;
  11510. case CMD.Q:
  11511. fromQuadratic(
  11512. xi, yi, data[i++], data[i++], data[i], data[i + 1],
  11513. min2, max2
  11514. );
  11515. xi = data[i++];
  11516. yi = data[i++];
  11517. break;
  11518. case CMD.A:
  11519. // TODO Arc 判断的开销比较大
  11520. var cx = data[i++];
  11521. var cy = data[i++];
  11522. var rx = data[i++];
  11523. var ry = data[i++];
  11524. var startAngle = data[i++];
  11525. var endAngle = data[i++] + startAngle;
  11526. // TODO Arc 旋转
  11527. var psi = data[i++];
  11528. var anticlockwise = 1 - data[i++];
  11529. if (i == 1) {
  11530. // 直接使用 arc 命令
  11531. // 第一个命令起点还未定义
  11532. x0 = mathCos$1(startAngle) * rx + cx;
  11533. y0 = mathSin$1(startAngle) * ry + cy;
  11534. }
  11535. fromArc(
  11536. cx, cy, rx, ry, startAngle, endAngle,
  11537. anticlockwise, min2, max2
  11538. );
  11539. xi = mathCos$1(endAngle) * rx + cx;
  11540. yi = mathSin$1(endAngle) * ry + cy;
  11541. break;
  11542. case CMD.R:
  11543. x0 = xi = data[i++];
  11544. y0 = yi = data[i++];
  11545. var width = data[i++];
  11546. var height = data[i++];
  11547. // Use fromLine
  11548. fromLine(x0, y0, x0 + width, y0 + height, min2, max2);
  11549. break;
  11550. case CMD.Z:
  11551. xi = x0;
  11552. yi = y0;
  11553. break;
  11554. }
  11555. // Union
  11556. min(min$1, min$1, min2);
  11557. max(max$1, max$1, max2);
  11558. }
  11559. // No data
  11560. if (i === 0) {
  11561. min$1[0] = min$1[1] = max$1[0] = max$1[1] = 0;
  11562. }
  11563. return new BoundingRect(
  11564. min$1[0], min$1[1], max$1[0] - min$1[0], max$1[1] - min$1[1]
  11565. );
  11566. },
  11567. /**
  11568. * Rebuild path from current data
  11569. * Rebuild path will not consider javascript implemented line dash.
  11570. * @param {CanvasRenderingContext2D} ctx
  11571. */
  11572. rebuildPath: function (ctx) {
  11573. var d = this.data;
  11574. var x0, y0;
  11575. var xi, yi;
  11576. var x, y;
  11577. var ux = this._ux;
  11578. var uy = this._uy;
  11579. var len$$1 = this._len;
  11580. for (var i = 0; i < len$$1;) {
  11581. var cmd = d[i++];
  11582. if (i == 1) {
  11583. // 如果第一个命令是 L, C, Q
  11584. // 则 previous point 同绘制命令的第一个 point
  11585. //
  11586. // 第一个命令为 Arc 的情况下会在后面特殊处理
  11587. xi = d[i];
  11588. yi = d[i + 1];
  11589. x0 = xi;
  11590. y0 = yi;
  11591. }
  11592. switch (cmd) {
  11593. case CMD.M:
  11594. x0 = xi = d[i++];
  11595. y0 = yi = d[i++];
  11596. ctx.moveTo(xi, yi);
  11597. break;
  11598. case CMD.L:
  11599. x = d[i++];
  11600. y = d[i++];
  11601. // Not draw too small seg between
  11602. if (mathAbs(x - xi) > ux || mathAbs(y - yi) > uy || i === len$$1 - 1) {
  11603. ctx.lineTo(x, y);
  11604. xi = x;
  11605. yi = y;
  11606. }
  11607. break;
  11608. case CMD.C:
  11609. ctx.bezierCurveTo(
  11610. d[i++], d[i++], d[i++], d[i++], d[i++], d[i++]
  11611. );
  11612. xi = d[i - 2];
  11613. yi = d[i - 1];
  11614. break;
  11615. case CMD.Q:
  11616. ctx.quadraticCurveTo(d[i++], d[i++], d[i++], d[i++]);
  11617. xi = d[i - 2];
  11618. yi = d[i - 1];
  11619. break;
  11620. case CMD.A:
  11621. var cx = d[i++];
  11622. var cy = d[i++];
  11623. var rx = d[i++];
  11624. var ry = d[i++];
  11625. var theta = d[i++];
  11626. var dTheta = d[i++];
  11627. var psi = d[i++];
  11628. var fs = d[i++];
  11629. var r = (rx > ry) ? rx : ry;
  11630. var scaleX = (rx > ry) ? 1 : rx / ry;
  11631. var scaleY = (rx > ry) ? ry / rx : 1;
  11632. var isEllipse = Math.abs(rx - ry) > 1e-3;
  11633. var endAngle = theta + dTheta;
  11634. if (isEllipse) {
  11635. ctx.translate(cx, cy);
  11636. ctx.rotate(psi);
  11637. ctx.scale(scaleX, scaleY);
  11638. ctx.arc(0, 0, r, theta, endAngle, 1 - fs);
  11639. ctx.scale(1 / scaleX, 1 / scaleY);
  11640. ctx.rotate(-psi);
  11641. ctx.translate(-cx, -cy);
  11642. }
  11643. else {
  11644. ctx.arc(cx, cy, r, theta, endAngle, 1 - fs);
  11645. }
  11646. if (i == 1) {
  11647. // 直接使用 arc 命令
  11648. // 第一个命令起点还未定义
  11649. x0 = mathCos$1(theta) * rx + cx;
  11650. y0 = mathSin$1(theta) * ry + cy;
  11651. }
  11652. xi = mathCos$1(endAngle) * rx + cx;
  11653. yi = mathSin$1(endAngle) * ry + cy;
  11654. break;
  11655. case CMD.R:
  11656. x0 = xi = d[i];
  11657. y0 = yi = d[i + 1];
  11658. ctx.rect(d[i++], d[i++], d[i++], d[i++]);
  11659. break;
  11660. case CMD.Z:
  11661. ctx.closePath();
  11662. xi = x0;
  11663. yi = y0;
  11664. }
  11665. }
  11666. }
  11667. };
  11668. PathProxy.CMD = CMD;
  11669. /**
  11670. * 线段包含判断
  11671. * @param {number} x0
  11672. * @param {number} y0
  11673. * @param {number} x1
  11674. * @param {number} y1
  11675. * @param {number} lineWidth
  11676. * @param {number} x
  11677. * @param {number} y
  11678. * @return {boolean}
  11679. */
  11680. function containStroke$1(x0, y0, x1, y1, lineWidth, x, y) {
  11681. if (lineWidth === 0) {
  11682. return false;
  11683. }
  11684. var _l = lineWidth;
  11685. var _a = 0;
  11686. var _b = x0;
  11687. // Quick reject
  11688. if (
  11689. (y > y0 + _l && y > y1 + _l)
  11690. || (y < y0 - _l && y < y1 - _l)
  11691. || (x > x0 + _l && x > x1 + _l)
  11692. || (x < x0 - _l && x < x1 - _l)
  11693. ) {
  11694. return false;
  11695. }
  11696. if (x0 !== x1) {
  11697. _a = (y0 - y1) / (x0 - x1);
  11698. _b = (x0 * y1 - x1 * y0) / (x0 - x1) ;
  11699. }
  11700. else {
  11701. return Math.abs(x - x0) <= _l / 2;
  11702. }
  11703. var tmp = _a * x - y + _b;
  11704. var _s = tmp * tmp / (_a * _a + 1);
  11705. return _s <= _l / 2 * _l / 2;
  11706. }
  11707. /**
  11708. * 三次贝塞尔曲线描边包含判断
  11709. * @param {number} x0
  11710. * @param {number} y0
  11711. * @param {number} x1
  11712. * @param {number} y1
  11713. * @param {number} x2
  11714. * @param {number} y2
  11715. * @param {number} x3
  11716. * @param {number} y3
  11717. * @param {number} lineWidth
  11718. * @param {number} x
  11719. * @param {number} y
  11720. * @return {boolean}
  11721. */
  11722. function containStroke$2(x0, y0, x1, y1, x2, y2, x3, y3, lineWidth, x, y) {
  11723. if (lineWidth === 0) {
  11724. return false;
  11725. }
  11726. var _l = lineWidth;
  11727. // Quick reject
  11728. if (
  11729. (y > y0 + _l && y > y1 + _l && y > y2 + _l && y > y3 + _l)
  11730. || (y < y0 - _l && y < y1 - _l && y < y2 - _l && y < y3 - _l)
  11731. || (x > x0 + _l && x > x1 + _l && x > x2 + _l && x > x3 + _l)
  11732. || (x < x0 - _l && x < x1 - _l && x < x2 - _l && x < x3 - _l)
  11733. ) {
  11734. return false;
  11735. }
  11736. var d = cubicProjectPoint(
  11737. x0, y0, x1, y1, x2, y2, x3, y3,
  11738. x, y, null
  11739. );
  11740. return d <= _l / 2;
  11741. }
  11742. /**
  11743. * 二次贝塞尔曲线描边包含判断
  11744. * @param {number} x0
  11745. * @param {number} y0
  11746. * @param {number} x1
  11747. * @param {number} y1
  11748. * @param {number} x2
  11749. * @param {number} y2
  11750. * @param {number} lineWidth
  11751. * @param {number} x
  11752. * @param {number} y
  11753. * @return {boolean}
  11754. */
  11755. function containStroke$3(x0, y0, x1, y1, x2, y2, lineWidth, x, y) {
  11756. if (lineWidth === 0) {
  11757. return false;
  11758. }
  11759. var _l = lineWidth;
  11760. // Quick reject
  11761. if (
  11762. (y > y0 + _l && y > y1 + _l && y > y2 + _l)
  11763. || (y < y0 - _l && y < y1 - _l && y < y2 - _l)
  11764. || (x > x0 + _l && x > x1 + _l && x > x2 + _l)
  11765. || (x < x0 - _l && x < x1 - _l && x < x2 - _l)
  11766. ) {
  11767. return false;
  11768. }
  11769. var d = quadraticProjectPoint(
  11770. x0, y0, x1, y1, x2, y2,
  11771. x, y, null
  11772. );
  11773. return d <= _l / 2;
  11774. }
  11775. var PI2$3 = Math.PI * 2;
  11776. function normalizeRadian(angle) {
  11777. angle %= PI2$3;
  11778. if (angle < 0) {
  11779. angle += PI2$3;
  11780. }
  11781. return angle;
  11782. }
  11783. var PI2$2 = Math.PI * 2;
  11784. /**
  11785. * 圆弧描边包含判断
  11786. * @param {number} cx
  11787. * @param {number} cy
  11788. * @param {number} r
  11789. * @param {number} startAngle
  11790. * @param {number} endAngle
  11791. * @param {boolean} anticlockwise
  11792. * @param {number} lineWidth
  11793. * @param {number} x
  11794. * @param {number} y
  11795. * @return {Boolean}
  11796. */
  11797. function containStroke$4(
  11798. cx, cy, r, startAngle, endAngle, anticlockwise,
  11799. lineWidth, x, y
  11800. ) {
  11801. if (lineWidth === 0) {
  11802. return false;
  11803. }
  11804. var _l = lineWidth;
  11805. x -= cx;
  11806. y -= cy;
  11807. var d = Math.sqrt(x * x + y * y);
  11808. if ((d - _l > r) || (d + _l < r)) {
  11809. return false;
  11810. }
  11811. if (Math.abs(startAngle - endAngle) % PI2$2 < 1e-4) {
  11812. // Is a circle
  11813. return true;
  11814. }
  11815. if (anticlockwise) {
  11816. var tmp = startAngle;
  11817. startAngle = normalizeRadian(endAngle);
  11818. endAngle = normalizeRadian(tmp);
  11819. } else {
  11820. startAngle = normalizeRadian(startAngle);
  11821. endAngle = normalizeRadian(endAngle);
  11822. }
  11823. if (startAngle > endAngle) {
  11824. endAngle += PI2$2;
  11825. }
  11826. var angle = Math.atan2(y, x);
  11827. if (angle < 0) {
  11828. angle += PI2$2;
  11829. }
  11830. return (angle >= startAngle && angle <= endAngle)
  11831. || (angle + PI2$2 >= startAngle && angle + PI2$2 <= endAngle);
  11832. }
  11833. function windingLine(x0, y0, x1, y1, x, y) {
  11834. if ((y > y0 && y > y1) || (y < y0 && y < y1)) {
  11835. return 0;
  11836. }
  11837. // Ignore horizontal line
  11838. if (y1 === y0) {
  11839. return 0;
  11840. }
  11841. var dir = y1 < y0 ? 1 : -1;
  11842. var t = (y - y0) / (y1 - y0);
  11843. // Avoid winding error when intersection point is the connect point of two line of polygon
  11844. if (t === 1 || t === 0) {
  11845. dir = y1 < y0 ? 0.5 : -0.5;
  11846. }
  11847. var x_ = t * (x1 - x0) + x0;
  11848. // If (x, y) on the line, considered as "contain".
  11849. return x_ === x ? Infinity : x_ > x ? dir : 0;
  11850. }
  11851. var CMD$1 = PathProxy.CMD;
  11852. var PI2$1 = Math.PI * 2;
  11853. var EPSILON$2 = 1e-4;
  11854. function isAroundEqual(a, b) {
  11855. return Math.abs(a - b) < EPSILON$2;
  11856. }
  11857. // 临时数组
  11858. var roots = [-1, -1, -1];
  11859. var extrema = [-1, -1];
  11860. function swapExtrema() {
  11861. var tmp = extrema[0];
  11862. extrema[0] = extrema[1];
  11863. extrema[1] = tmp;
  11864. }
  11865. function windingCubic(x0, y0, x1, y1, x2, y2, x3, y3, x, y) {
  11866. // Quick reject
  11867. if (
  11868. (y > y0 && y > y1 && y > y2 && y > y3)
  11869. || (y < y0 && y < y1 && y < y2 && y < y3)
  11870. ) {
  11871. return 0;
  11872. }
  11873. var nRoots = cubicRootAt(y0, y1, y2, y3, y, roots);
  11874. if (nRoots === 0) {
  11875. return 0;
  11876. }
  11877. else {
  11878. var w = 0;
  11879. var nExtrema = -1;
  11880. var y0_, y1_;
  11881. for (var i = 0; i < nRoots; i++) {
  11882. var t = roots[i];
  11883. // Avoid winding error when intersection point is the connect point of two line of polygon
  11884. var unit = (t === 0 || t === 1) ? 0.5 : 1;
  11885. var x_ = cubicAt(x0, x1, x2, x3, t);
  11886. if (x_ < x) { // Quick reject
  11887. continue;
  11888. }
  11889. if (nExtrema < 0) {
  11890. nExtrema = cubicExtrema(y0, y1, y2, y3, extrema);
  11891. if (extrema[1] < extrema[0] && nExtrema > 1) {
  11892. swapExtrema();
  11893. }
  11894. y0_ = cubicAt(y0, y1, y2, y3, extrema[0]);
  11895. if (nExtrema > 1) {
  11896. y1_ = cubicAt(y0, y1, y2, y3, extrema[1]);
  11897. }
  11898. }
  11899. if (nExtrema == 2) {
  11900. // 分成三段单调函数
  11901. if (t < extrema[0]) {
  11902. w += y0_ < y0 ? unit : -unit;
  11903. }
  11904. else if (t < extrema[1]) {
  11905. w += y1_ < y0_ ? unit : -unit;
  11906. }
  11907. else {
  11908. w += y3 < y1_ ? unit : -unit;
  11909. }
  11910. }
  11911. else {
  11912. // 分成两段单调函数
  11913. if (t < extrema[0]) {
  11914. w += y0_ < y0 ? unit : -unit;
  11915. }
  11916. else {
  11917. w += y3 < y0_ ? unit : -unit;
  11918. }
  11919. }
  11920. }
  11921. return w;
  11922. }
  11923. }
  11924. function windingQuadratic(x0, y0, x1, y1, x2, y2, x, y) {
  11925. // Quick reject
  11926. if (
  11927. (y > y0 && y > y1 && y > y2)
  11928. || (y < y0 && y < y1 && y < y2)
  11929. ) {
  11930. return 0;
  11931. }
  11932. var nRoots = quadraticRootAt(y0, y1, y2, y, roots);
  11933. if (nRoots === 0) {
  11934. return 0;
  11935. }
  11936. else {
  11937. var t = quadraticExtremum(y0, y1, y2);
  11938. if (t >= 0 && t <= 1) {
  11939. var w = 0;
  11940. var y_ = quadraticAt(y0, y1, y2, t);
  11941. for (var i = 0; i < nRoots; i++) {
  11942. // Remove one endpoint.
  11943. var unit = (roots[i] === 0 || roots[i] === 1) ? 0.5 : 1;
  11944. var x_ = quadraticAt(x0, x1, x2, roots[i]);
  11945. if (x_ < x) { // Quick reject
  11946. continue;
  11947. }
  11948. if (roots[i] < t) {
  11949. w += y_ < y0 ? unit : -unit;
  11950. }
  11951. else {
  11952. w += y2 < y_ ? unit : -unit;
  11953. }
  11954. }
  11955. return w;
  11956. }
  11957. else {
  11958. // Remove one endpoint.
  11959. var unit = (roots[0] === 0 || roots[0] === 1) ? 0.5 : 1;
  11960. var x_ = quadraticAt(x0, x1, x2, roots[0]);
  11961. if (x_ < x) { // Quick reject
  11962. return 0;
  11963. }
  11964. return y2 < y0 ? unit : -unit;
  11965. }
  11966. }
  11967. }
  11968. // TODO
  11969. // Arc 旋转
  11970. function windingArc(
  11971. cx, cy, r, startAngle, endAngle, anticlockwise, x, y
  11972. ) {
  11973. y -= cy;
  11974. if (y > r || y < -r) {
  11975. return 0;
  11976. }
  11977. var tmp = Math.sqrt(r * r - y * y);
  11978. roots[0] = -tmp;
  11979. roots[1] = tmp;
  11980. var diff = Math.abs(startAngle - endAngle);
  11981. if (diff < 1e-4) {
  11982. return 0;
  11983. }
  11984. if (diff % PI2$1 < 1e-4) {
  11985. // Is a circle
  11986. startAngle = 0;
  11987. endAngle = PI2$1;
  11988. var dir = anticlockwise ? 1 : -1;
  11989. if (x >= roots[0] + cx && x <= roots[1] + cx) {
  11990. return dir;
  11991. } else {
  11992. return 0;
  11993. }
  11994. }
  11995. if (anticlockwise) {
  11996. var tmp = startAngle;
  11997. startAngle = normalizeRadian(endAngle);
  11998. endAngle = normalizeRadian(tmp);
  11999. }
  12000. else {
  12001. startAngle = normalizeRadian(startAngle);
  12002. endAngle = normalizeRadian(endAngle);
  12003. }
  12004. if (startAngle > endAngle) {
  12005. endAngle += PI2$1;
  12006. }
  12007. var w = 0;
  12008. for (var i = 0; i < 2; i++) {
  12009. var x_ = roots[i];
  12010. if (x_ + cx > x) {
  12011. var angle = Math.atan2(y, x_);
  12012. var dir = anticlockwise ? 1 : -1;
  12013. if (angle < 0) {
  12014. angle = PI2$1 + angle;
  12015. }
  12016. if (
  12017. (angle >= startAngle && angle <= endAngle)
  12018. || (angle + PI2$1 >= startAngle && angle + PI2$1 <= endAngle)
  12019. ) {
  12020. if (angle > Math.PI / 2 && angle < Math.PI * 1.5) {
  12021. dir = -dir;
  12022. }
  12023. w += dir;
  12024. }
  12025. }
  12026. }
  12027. return w;
  12028. }
  12029. function containPath(data, lineWidth, isStroke, x, y) {
  12030. var w = 0;
  12031. var xi = 0;
  12032. var yi = 0;
  12033. var x0 = 0;
  12034. var y0 = 0;
  12035. for (var i = 0; i < data.length;) {
  12036. var cmd = data[i++];
  12037. // Begin a new subpath
  12038. if (cmd === CMD$1.M && i > 1) {
  12039. // Close previous subpath
  12040. if (!isStroke) {
  12041. w += windingLine(xi, yi, x0, y0, x, y);
  12042. }
  12043. // 如果被任何一个 subpath 包含
  12044. // if (w !== 0) {
  12045. // return true;
  12046. // }
  12047. }
  12048. if (i == 1) {
  12049. // 如果第一个命令是 L, C, Q
  12050. // 则 previous point 同绘制命令的第一个 point
  12051. //
  12052. // 第一个命令为 Arc 的情况下会在后面特殊处理
  12053. xi = data[i];
  12054. yi = data[i + 1];
  12055. x0 = xi;
  12056. y0 = yi;
  12057. }
  12058. switch (cmd) {
  12059. case CMD$1.M:
  12060. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  12061. // 在 closePath 的时候使用
  12062. x0 = data[i++];
  12063. y0 = data[i++];
  12064. xi = x0;
  12065. yi = y0;
  12066. break;
  12067. case CMD$1.L:
  12068. if (isStroke) {
  12069. if (containStroke$1(xi, yi, data[i], data[i + 1], lineWidth, x, y)) {
  12070. return true;
  12071. }
  12072. }
  12073. else {
  12074. // NOTE 在第一个命令为 L, C, Q 的时候会计算出 NaN
  12075. w += windingLine(xi, yi, data[i], data[i + 1], x, y) || 0;
  12076. }
  12077. xi = data[i++];
  12078. yi = data[i++];
  12079. break;
  12080. case CMD$1.C:
  12081. if (isStroke) {
  12082. if (containStroke$2(xi, yi,
  12083. data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  12084. lineWidth, x, y
  12085. )) {
  12086. return true;
  12087. }
  12088. }
  12089. else {
  12090. w += windingCubic(
  12091. xi, yi,
  12092. data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  12093. x, y
  12094. ) || 0;
  12095. }
  12096. xi = data[i++];
  12097. yi = data[i++];
  12098. break;
  12099. case CMD$1.Q:
  12100. if (isStroke) {
  12101. if (containStroke$3(xi, yi,
  12102. data[i++], data[i++], data[i], data[i + 1],
  12103. lineWidth, x, y
  12104. )) {
  12105. return true;
  12106. }
  12107. }
  12108. else {
  12109. w += windingQuadratic(
  12110. xi, yi,
  12111. data[i++], data[i++], data[i], data[i + 1],
  12112. x, y
  12113. ) || 0;
  12114. }
  12115. xi = data[i++];
  12116. yi = data[i++];
  12117. break;
  12118. case CMD$1.A:
  12119. // TODO Arc 判断的开销比较大
  12120. var cx = data[i++];
  12121. var cy = data[i++];
  12122. var rx = data[i++];
  12123. var ry = data[i++];
  12124. var theta = data[i++];
  12125. var dTheta = data[i++];
  12126. // TODO Arc 旋转
  12127. var psi = data[i++];
  12128. var anticlockwise = 1 - data[i++];
  12129. var x1 = Math.cos(theta) * rx + cx;
  12130. var y1 = Math.sin(theta) * ry + cy;
  12131. // 不是直接使用 arc 命令
  12132. if (i > 1) {
  12133. w += windingLine(xi, yi, x1, y1, x, y);
  12134. }
  12135. else {
  12136. // 第一个命令起点还未定义
  12137. x0 = x1;
  12138. y0 = y1;
  12139. }
  12140. // zr 使用scale来模拟椭圆, 这里也对x做一定的缩放
  12141. var _x = (x - cx) * ry / rx + cx;
  12142. if (isStroke) {
  12143. if (containStroke$4(
  12144. cx, cy, ry, theta, theta + dTheta, anticlockwise,
  12145. lineWidth, _x, y
  12146. )) {
  12147. return true;
  12148. }
  12149. }
  12150. else {
  12151. w += windingArc(
  12152. cx, cy, ry, theta, theta + dTheta, anticlockwise,
  12153. _x, y
  12154. );
  12155. }
  12156. xi = Math.cos(theta + dTheta) * rx + cx;
  12157. yi = Math.sin(theta + dTheta) * ry + cy;
  12158. break;
  12159. case CMD$1.R:
  12160. x0 = xi = data[i++];
  12161. y0 = yi = data[i++];
  12162. var width = data[i++];
  12163. var height = data[i++];
  12164. var x1 = x0 + width;
  12165. var y1 = y0 + height;
  12166. if (isStroke) {
  12167. if (containStroke$1(x0, y0, x1, y0, lineWidth, x, y)
  12168. || containStroke$1(x1, y0, x1, y1, lineWidth, x, y)
  12169. || containStroke$1(x1, y1, x0, y1, lineWidth, x, y)
  12170. || containStroke$1(x0, y1, x0, y0, lineWidth, x, y)
  12171. ) {
  12172. return true;
  12173. }
  12174. }
  12175. else {
  12176. // FIXME Clockwise ?
  12177. w += windingLine(x1, y0, x1, y1, x, y);
  12178. w += windingLine(x0, y1, x0, y0, x, y);
  12179. }
  12180. break;
  12181. case CMD$1.Z:
  12182. if (isStroke) {
  12183. if (containStroke$1(
  12184. xi, yi, x0, y0, lineWidth, x, y
  12185. )) {
  12186. return true;
  12187. }
  12188. }
  12189. else {
  12190. // Close a subpath
  12191. w += windingLine(xi, yi, x0, y0, x, y);
  12192. // 如果被任何一个 subpath 包含
  12193. // FIXME subpaths may overlap
  12194. // if (w !== 0) {
  12195. // return true;
  12196. // }
  12197. }
  12198. xi = x0;
  12199. yi = y0;
  12200. break;
  12201. }
  12202. }
  12203. if (!isStroke && !isAroundEqual(yi, y0)) {
  12204. w += windingLine(xi, yi, x0, y0, x, y) || 0;
  12205. }
  12206. return w !== 0;
  12207. }
  12208. function contain(pathData, x, y) {
  12209. return containPath(pathData, 0, false, x, y);
  12210. }
  12211. function containStroke(pathData, lineWidth, x, y) {
  12212. return containPath(pathData, lineWidth, true, x, y);
  12213. }
  12214. var getCanvasPattern = Pattern.prototype.getCanvasPattern;
  12215. var abs = Math.abs;
  12216. var pathProxyForDraw = new PathProxy(true);
  12217. /**
  12218. * @alias module:zrender/graphic/Path
  12219. * @extends module:zrender/graphic/Displayable
  12220. * @constructor
  12221. * @param {Object} opts
  12222. */
  12223. function Path(opts) {
  12224. Displayable.call(this, opts);
  12225. /**
  12226. * @type {module:zrender/core/PathProxy}
  12227. * @readOnly
  12228. */
  12229. this.path = null;
  12230. }
  12231. Path.prototype = {
  12232. constructor: Path,
  12233. type: 'path',
  12234. __dirtyPath: true,
  12235. strokeContainThreshold: 5,
  12236. brush: function (ctx, prevEl) {
  12237. var style = this.style;
  12238. var path = this.path || pathProxyForDraw;
  12239. var hasStroke = style.hasStroke();
  12240. var hasFill = style.hasFill();
  12241. var fill = style.fill;
  12242. var stroke = style.stroke;
  12243. var hasFillGradient = hasFill && !!(fill.colorStops);
  12244. var hasStrokeGradient = hasStroke && !!(stroke.colorStops);
  12245. var hasFillPattern = hasFill && !!(fill.image);
  12246. var hasStrokePattern = hasStroke && !!(stroke.image);
  12247. style.bind(ctx, this, prevEl);
  12248. this.setTransform(ctx);
  12249. if (this.__dirty) {
  12250. var rect;
  12251. // Update gradient because bounding rect may changed
  12252. if (hasFillGradient) {
  12253. rect = rect || this.getBoundingRect();
  12254. this._fillGradient = style.getGradient(ctx, fill, rect);
  12255. }
  12256. if (hasStrokeGradient) {
  12257. rect = rect || this.getBoundingRect();
  12258. this._strokeGradient = style.getGradient(ctx, stroke, rect);
  12259. }
  12260. }
  12261. // Use the gradient or pattern
  12262. if (hasFillGradient) {
  12263. // PENDING If may have affect the state
  12264. ctx.fillStyle = this._fillGradient;
  12265. }
  12266. else if (hasFillPattern) {
  12267. ctx.fillStyle = getCanvasPattern.call(fill, ctx);
  12268. }
  12269. if (hasStrokeGradient) {
  12270. ctx.strokeStyle = this._strokeGradient;
  12271. }
  12272. else if (hasStrokePattern) {
  12273. ctx.strokeStyle = getCanvasPattern.call(stroke, ctx);
  12274. }
  12275. var lineDash = style.lineDash;
  12276. var lineDashOffset = style.lineDashOffset;
  12277. var ctxLineDash = !!ctx.setLineDash;
  12278. // Update path sx, sy
  12279. var scale = this.getGlobalScale();
  12280. path.setScale(scale[0], scale[1]);
  12281. // Proxy context
  12282. // Rebuild path in following 2 cases
  12283. // 1. Path is dirty
  12284. // 2. Path needs javascript implemented lineDash stroking.
  12285. // In this case, lineDash information will not be saved in PathProxy
  12286. if (this.__dirtyPath
  12287. || (lineDash && !ctxLineDash && hasStroke)
  12288. ) {
  12289. path.beginPath(ctx);
  12290. // Setting line dash before build path
  12291. if (lineDash && !ctxLineDash) {
  12292. path.setLineDash(lineDash);
  12293. path.setLineDashOffset(lineDashOffset);
  12294. }
  12295. this.buildPath(path, this.shape, false);
  12296. // Clear path dirty flag
  12297. if (this.path) {
  12298. this.__dirtyPath = false;
  12299. }
  12300. }
  12301. else {
  12302. // Replay path building
  12303. ctx.beginPath();
  12304. this.path.rebuildPath(ctx);
  12305. }
  12306. hasFill && path.fill(ctx);
  12307. if (lineDash && ctxLineDash) {
  12308. ctx.setLineDash(lineDash);
  12309. ctx.lineDashOffset = lineDashOffset;
  12310. }
  12311. hasStroke && path.stroke(ctx);
  12312. if (lineDash && ctxLineDash) {
  12313. // PENDING
  12314. // Remove lineDash
  12315. ctx.setLineDash([]);
  12316. }
  12317. // Draw rect text
  12318. if (style.text != null) {
  12319. // Only restore transform when needs draw text.
  12320. this.restoreTransform(ctx);
  12321. this.drawRectText(ctx, this.getBoundingRect());
  12322. }
  12323. },
  12324. // When bundling path, some shape may decide if use moveTo to begin a new subpath or closePath
  12325. // Like in circle
  12326. buildPath: function (ctx, shapeCfg, inBundle) {},
  12327. createPathProxy: function () {
  12328. this.path = new PathProxy();
  12329. },
  12330. getBoundingRect: function () {
  12331. var rect = this._rect;
  12332. var style = this.style;
  12333. var needsUpdateRect = !rect;
  12334. if (needsUpdateRect) {
  12335. var path = this.path;
  12336. if (!path) {
  12337. // Create path on demand.
  12338. path = this.path = new PathProxy();
  12339. }
  12340. if (this.__dirtyPath) {
  12341. path.beginPath();
  12342. this.buildPath(path, this.shape, false);
  12343. }
  12344. rect = path.getBoundingRect();
  12345. }
  12346. this._rect = rect;
  12347. if (style.hasStroke()) {
  12348. // Needs update rect with stroke lineWidth when
  12349. // 1. Element changes scale or lineWidth
  12350. // 2. Shape is changed
  12351. var rectWithStroke = this._rectWithStroke || (this._rectWithStroke = rect.clone());
  12352. if (this.__dirty || needsUpdateRect) {
  12353. rectWithStroke.copy(rect);
  12354. // FIXME Must after updateTransform
  12355. var w = style.lineWidth;
  12356. // PENDING, Min line width is needed when line is horizontal or vertical
  12357. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  12358. // Only add extra hover lineWidth when there are no fill
  12359. if (!style.hasFill()) {
  12360. w = Math.max(w, this.strokeContainThreshold || 4);
  12361. }
  12362. // Consider line width
  12363. // Line scale can't be 0;
  12364. if (lineScale > 1e-10) {
  12365. rectWithStroke.width += w / lineScale;
  12366. rectWithStroke.height += w / lineScale;
  12367. rectWithStroke.x -= w / lineScale / 2;
  12368. rectWithStroke.y -= w / lineScale / 2;
  12369. }
  12370. }
  12371. // Return rect with stroke
  12372. return rectWithStroke;
  12373. }
  12374. return rect;
  12375. },
  12376. contain: function (x, y) {
  12377. var localPos = this.transformCoordToLocal(x, y);
  12378. var rect = this.getBoundingRect();
  12379. var style = this.style;
  12380. x = localPos[0];
  12381. y = localPos[1];
  12382. if (rect.contain(x, y)) {
  12383. var pathData = this.path.data;
  12384. if (style.hasStroke()) {
  12385. var lineWidth = style.lineWidth;
  12386. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  12387. // Line scale can't be 0;
  12388. if (lineScale > 1e-10) {
  12389. // Only add extra hover lineWidth when there are no fill
  12390. if (!style.hasFill()) {
  12391. lineWidth = Math.max(lineWidth, this.strokeContainThreshold);
  12392. }
  12393. if (containStroke(
  12394. pathData, lineWidth / lineScale, x, y
  12395. )) {
  12396. return true;
  12397. }
  12398. }
  12399. }
  12400. if (style.hasFill()) {
  12401. return contain(pathData, x, y);
  12402. }
  12403. }
  12404. return false;
  12405. },
  12406. /**
  12407. * @param {boolean} dirtyPath
  12408. */
  12409. dirty: function (dirtyPath) {
  12410. if (dirtyPath == null) {
  12411. dirtyPath = true;
  12412. }
  12413. // Only mark dirty, not mark clean
  12414. if (dirtyPath) {
  12415. this.__dirtyPath = dirtyPath;
  12416. this._rect = null;
  12417. }
  12418. this.__dirty = true;
  12419. this.__zr && this.__zr.refresh();
  12420. // Used as a clipping path
  12421. if (this.__clipTarget) {
  12422. this.__clipTarget.dirty();
  12423. }
  12424. },
  12425. /**
  12426. * Alias for animate('shape')
  12427. * @param {boolean} loop
  12428. */
  12429. animateShape: function (loop) {
  12430. return this.animate('shape', loop);
  12431. },
  12432. // Overwrite attrKV
  12433. attrKV: function (key, value) {
  12434. // FIXME
  12435. if (key === 'shape') {
  12436. this.setShape(value);
  12437. this.__dirtyPath = true;
  12438. this._rect = null;
  12439. }
  12440. else {
  12441. Displayable.prototype.attrKV.call(this, key, value);
  12442. }
  12443. },
  12444. /**
  12445. * @param {Object|string} key
  12446. * @param {*} value
  12447. */
  12448. setShape: function (key, value) {
  12449. var shape = this.shape;
  12450. // Path from string may not have shape
  12451. if (shape) {
  12452. if (isObject$1(key)) {
  12453. for (var name in key) {
  12454. if (key.hasOwnProperty(name)) {
  12455. shape[name] = key[name];
  12456. }
  12457. }
  12458. }
  12459. else {
  12460. shape[key] = value;
  12461. }
  12462. this.dirty(true);
  12463. }
  12464. return this;
  12465. },
  12466. getLineScale: function () {
  12467. var m = this.transform;
  12468. // Get the line scale.
  12469. // Determinant of `m` means how much the area is enlarged by the
  12470. // transformation. So its square root can be used as a scale factor
  12471. // for width.
  12472. return m && abs(m[0] - 1) > 1e-10 && abs(m[3] - 1) > 1e-10
  12473. ? Math.sqrt(abs(m[0] * m[3] - m[2] * m[1]))
  12474. : 1;
  12475. }
  12476. };
  12477. /**
  12478. * 扩展一个 Path element, 比如星形,圆等。
  12479. * Extend a path element
  12480. * @param {Object} props
  12481. * @param {string} props.type Path type
  12482. * @param {Function} props.init Initialize
  12483. * @param {Function} props.buildPath Overwrite buildPath method
  12484. * @param {Object} [props.style] Extended default style config
  12485. * @param {Object} [props.shape] Extended default shape config
  12486. */
  12487. Path.extend = function (defaults$$1) {
  12488. var Sub = function (opts) {
  12489. Path.call(this, opts);
  12490. if (defaults$$1.style) {
  12491. // Extend default style
  12492. this.style.extendFrom(defaults$$1.style, false);
  12493. }
  12494. // Extend default shape
  12495. var defaultShape = defaults$$1.shape;
  12496. if (defaultShape) {
  12497. this.shape = this.shape || {};
  12498. var thisShape = this.shape;
  12499. for (var name in defaultShape) {
  12500. if (
  12501. ! thisShape.hasOwnProperty(name)
  12502. && defaultShape.hasOwnProperty(name)
  12503. ) {
  12504. thisShape[name] = defaultShape[name];
  12505. }
  12506. }
  12507. }
  12508. defaults$$1.init && defaults$$1.init.call(this, opts);
  12509. };
  12510. inherits(Sub, Path);
  12511. // FIXME 不能 extend position, rotation 等引用对象
  12512. for (var name in defaults$$1) {
  12513. // Extending prototype values and methods
  12514. if (name !== 'style' && name !== 'shape') {
  12515. Sub.prototype[name] = defaults$$1[name];
  12516. }
  12517. }
  12518. return Sub;
  12519. };
  12520. inherits(Path, Displayable);
  12521. var CMD$2 = PathProxy.CMD;
  12522. var points = [[], [], []];
  12523. var mathSqrt$3 = Math.sqrt;
  12524. var mathAtan2 = Math.atan2;
  12525. var transformPath = function (path, m) {
  12526. var data = path.data;
  12527. var cmd;
  12528. var nPoint;
  12529. var i;
  12530. var j;
  12531. var k;
  12532. var p;
  12533. var M = CMD$2.M;
  12534. var C = CMD$2.C;
  12535. var L = CMD$2.L;
  12536. var R = CMD$2.R;
  12537. var A = CMD$2.A;
  12538. var Q = CMD$2.Q;
  12539. for (i = 0, j = 0; i < data.length;) {
  12540. cmd = data[i++];
  12541. j = i;
  12542. nPoint = 0;
  12543. switch (cmd) {
  12544. case M:
  12545. nPoint = 1;
  12546. break;
  12547. case L:
  12548. nPoint = 1;
  12549. break;
  12550. case C:
  12551. nPoint = 3;
  12552. break;
  12553. case Q:
  12554. nPoint = 2;
  12555. break;
  12556. case A:
  12557. var x = m[4];
  12558. var y = m[5];
  12559. var sx = mathSqrt$3(m[0] * m[0] + m[1] * m[1]);
  12560. var sy = mathSqrt$3(m[2] * m[2] + m[3] * m[3]);
  12561. var angle = mathAtan2(-m[1] / sy, m[0] / sx);
  12562. // cx
  12563. data[i] *= sx;
  12564. data[i++] += x;
  12565. // cy
  12566. data[i] *= sy;
  12567. data[i++] += y;
  12568. // Scale rx and ry
  12569. // FIXME Assume psi is 0 here
  12570. data[i++] *= sx;
  12571. data[i++] *= sy;
  12572. // Start angle
  12573. data[i++] += angle;
  12574. // end angle
  12575. data[i++] += angle;
  12576. // FIXME psi
  12577. i += 2;
  12578. j = i;
  12579. break;
  12580. case R:
  12581. // x0, y0
  12582. p[0] = data[i++];
  12583. p[1] = data[i++];
  12584. applyTransform(p, p, m);
  12585. data[j++] = p[0];
  12586. data[j++] = p[1];
  12587. // x1, y1
  12588. p[0] += data[i++];
  12589. p[1] += data[i++];
  12590. applyTransform(p, p, m);
  12591. data[j++] = p[0];
  12592. data[j++] = p[1];
  12593. }
  12594. for (k = 0; k < nPoint; k++) {
  12595. var p = points[k];
  12596. p[0] = data[i++];
  12597. p[1] = data[i++];
  12598. applyTransform(p, p, m);
  12599. // Write back
  12600. data[j++] = p[0];
  12601. data[j++] = p[1];
  12602. }
  12603. }
  12604. };
  12605. // command chars
  12606. var cc = [
  12607. 'm', 'M', 'l', 'L', 'v', 'V', 'h', 'H', 'z', 'Z',
  12608. 'c', 'C', 'q', 'Q', 't', 'T', 's', 'S', 'a', 'A'
  12609. ];
  12610. var mathSqrt = Math.sqrt;
  12611. var mathSin = Math.sin;
  12612. var mathCos = Math.cos;
  12613. var PI = Math.PI;
  12614. var vMag = function(v) {
  12615. return Math.sqrt(v[0] * v[0] + v[1] * v[1]);
  12616. };
  12617. var vRatio = function(u, v) {
  12618. return (u[0] * v[0] + u[1] * v[1]) / (vMag(u) * vMag(v));
  12619. };
  12620. var vAngle = function(u, v) {
  12621. return (u[0] * v[1] < u[1] * v[0] ? -1 : 1)
  12622. * Math.acos(vRatio(u, v));
  12623. };
  12624. function processArc(x1, y1, x2, y2, fa, fs, rx, ry, psiDeg, cmd, path) {
  12625. var psi = psiDeg * (PI / 180.0);
  12626. var xp = mathCos(psi) * (x1 - x2) / 2.0
  12627. + mathSin(psi) * (y1 - y2) / 2.0;
  12628. var yp = -1 * mathSin(psi) * (x1 - x2) / 2.0
  12629. + mathCos(psi) * (y1 - y2) / 2.0;
  12630. var lambda = (xp * xp) / (rx * rx) + (yp * yp) / (ry * ry);
  12631. if (lambda > 1) {
  12632. rx *= mathSqrt(lambda);
  12633. ry *= mathSqrt(lambda);
  12634. }
  12635. var f = (fa === fs ? -1 : 1)
  12636. * mathSqrt((((rx * rx) * (ry * ry))
  12637. - ((rx * rx) * (yp * yp))
  12638. - ((ry * ry) * (xp * xp))) / ((rx * rx) * (yp * yp)
  12639. + (ry * ry) * (xp * xp))
  12640. ) || 0;
  12641. var cxp = f * rx * yp / ry;
  12642. var cyp = f * -ry * xp / rx;
  12643. var cx = (x1 + x2) / 2.0
  12644. + mathCos(psi) * cxp
  12645. - mathSin(psi) * cyp;
  12646. var cy = (y1 + y2) / 2.0
  12647. + mathSin(psi) * cxp
  12648. + mathCos(psi) * cyp;
  12649. var theta = vAngle([ 1, 0 ], [ (xp - cxp) / rx, (yp - cyp) / ry ]);
  12650. var u = [ (xp - cxp) / rx, (yp - cyp) / ry ];
  12651. var v = [ (-1 * xp - cxp) / rx, (-1 * yp - cyp) / ry ];
  12652. var dTheta = vAngle(u, v);
  12653. if (vRatio(u, v) <= -1) {
  12654. dTheta = PI;
  12655. }
  12656. if (vRatio(u, v) >= 1) {
  12657. dTheta = 0;
  12658. }
  12659. if (fs === 0 && dTheta > 0) {
  12660. dTheta = dTheta - 2 * PI;
  12661. }
  12662. if (fs === 1 && dTheta < 0) {
  12663. dTheta = dTheta + 2 * PI;
  12664. }
  12665. path.addData(cmd, cx, cy, rx, ry, theta, dTheta, psi, fs);
  12666. }
  12667. function createPathProxyFromString(data) {
  12668. if (!data) {
  12669. return [];
  12670. }
  12671. // command string
  12672. var cs = data.replace(/-/g, ' -')
  12673. .replace(/ /g, ' ')
  12674. .replace(/ /g, ',')
  12675. .replace(/,,/g, ',');
  12676. var n;
  12677. // create pipes so that we can split the data
  12678. for (n = 0; n < cc.length; n++) {
  12679. cs = cs.replace(new RegExp(cc[n], 'g'), '|' + cc[n]);
  12680. }
  12681. // create array
  12682. var arr = cs.split('|');
  12683. // init context point
  12684. var cpx = 0;
  12685. var cpy = 0;
  12686. var path = new PathProxy();
  12687. var CMD = PathProxy.CMD;
  12688. var prevCmd;
  12689. for (n = 1; n < arr.length; n++) {
  12690. var str = arr[n];
  12691. var c = str.charAt(0);
  12692. var off = 0;
  12693. var p = str.slice(1).replace(/e,-/g, 'e-').split(',');
  12694. var cmd;
  12695. if (p.length > 0 && p[0] === '') {
  12696. p.shift();
  12697. }
  12698. for (var i = 0; i < p.length; i++) {
  12699. p[i] = parseFloat(p[i]);
  12700. }
  12701. while (off < p.length && !isNaN(p[off])) {
  12702. if (isNaN(p[0])) {
  12703. break;
  12704. }
  12705. var ctlPtx;
  12706. var ctlPty;
  12707. var rx;
  12708. var ry;
  12709. var psi;
  12710. var fa;
  12711. var fs;
  12712. var x1 = cpx;
  12713. var y1 = cpy;
  12714. // convert l, H, h, V, and v to L
  12715. switch (c) {
  12716. case 'l':
  12717. cpx += p[off++];
  12718. cpy += p[off++];
  12719. cmd = CMD.L;
  12720. path.addData(cmd, cpx, cpy);
  12721. break;
  12722. case 'L':
  12723. cpx = p[off++];
  12724. cpy = p[off++];
  12725. cmd = CMD.L;
  12726. path.addData(cmd, cpx, cpy);
  12727. break;
  12728. case 'm':
  12729. cpx += p[off++];
  12730. cpy += p[off++];
  12731. cmd = CMD.M;
  12732. path.addData(cmd, cpx, cpy);
  12733. c = 'l';
  12734. break;
  12735. case 'M':
  12736. cpx = p[off++];
  12737. cpy = p[off++];
  12738. cmd = CMD.M;
  12739. path.addData(cmd, cpx, cpy);
  12740. c = 'L';
  12741. break;
  12742. case 'h':
  12743. cpx += p[off++];
  12744. cmd = CMD.L;
  12745. path.addData(cmd, cpx, cpy);
  12746. break;
  12747. case 'H':
  12748. cpx = p[off++];
  12749. cmd = CMD.L;
  12750. path.addData(cmd, cpx, cpy);
  12751. break;
  12752. case 'v':
  12753. cpy += p[off++];
  12754. cmd = CMD.L;
  12755. path.addData(cmd, cpx, cpy);
  12756. break;
  12757. case 'V':
  12758. cpy = p[off++];
  12759. cmd = CMD.L;
  12760. path.addData(cmd, cpx, cpy);
  12761. break;
  12762. case 'C':
  12763. cmd = CMD.C;
  12764. path.addData(
  12765. cmd, p[off++], p[off++], p[off++], p[off++], p[off++], p[off++]
  12766. );
  12767. cpx = p[off - 2];
  12768. cpy = p[off - 1];
  12769. break;
  12770. case 'c':
  12771. cmd = CMD.C;
  12772. path.addData(
  12773. cmd,
  12774. p[off++] + cpx, p[off++] + cpy,
  12775. p[off++] + cpx, p[off++] + cpy,
  12776. p[off++] + cpx, p[off++] + cpy
  12777. );
  12778. cpx += p[off - 2];
  12779. cpy += p[off - 1];
  12780. break;
  12781. case 'S':
  12782. ctlPtx = cpx;
  12783. ctlPty = cpy;
  12784. var len = path.len();
  12785. var pathData = path.data;
  12786. if (prevCmd === CMD.C) {
  12787. ctlPtx += cpx - pathData[len - 4];
  12788. ctlPty += cpy - pathData[len - 3];
  12789. }
  12790. cmd = CMD.C;
  12791. x1 = p[off++];
  12792. y1 = p[off++];
  12793. cpx = p[off++];
  12794. cpy = p[off++];
  12795. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  12796. break;
  12797. case 's':
  12798. ctlPtx = cpx;
  12799. ctlPty = cpy;
  12800. var len = path.len();
  12801. var pathData = path.data;
  12802. if (prevCmd === CMD.C) {
  12803. ctlPtx += cpx - pathData[len - 4];
  12804. ctlPty += cpy - pathData[len - 3];
  12805. }
  12806. cmd = CMD.C;
  12807. x1 = cpx + p[off++];
  12808. y1 = cpy + p[off++];
  12809. cpx += p[off++];
  12810. cpy += p[off++];
  12811. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  12812. break;
  12813. case 'Q':
  12814. x1 = p[off++];
  12815. y1 = p[off++];
  12816. cpx = p[off++];
  12817. cpy = p[off++];
  12818. cmd = CMD.Q;
  12819. path.addData(cmd, x1, y1, cpx, cpy);
  12820. break;
  12821. case 'q':
  12822. x1 = p[off++] + cpx;
  12823. y1 = p[off++] + cpy;
  12824. cpx += p[off++];
  12825. cpy += p[off++];
  12826. cmd = CMD.Q;
  12827. path.addData(cmd, x1, y1, cpx, cpy);
  12828. break;
  12829. case 'T':
  12830. ctlPtx = cpx;
  12831. ctlPty = cpy;
  12832. var len = path.len();
  12833. var pathData = path.data;
  12834. if (prevCmd === CMD.Q) {
  12835. ctlPtx += cpx - pathData[len - 4];
  12836. ctlPty += cpy - pathData[len - 3];
  12837. }
  12838. cpx = p[off++];
  12839. cpy = p[off++];
  12840. cmd = CMD.Q;
  12841. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  12842. break;
  12843. case 't':
  12844. ctlPtx = cpx;
  12845. ctlPty = cpy;
  12846. var len = path.len();
  12847. var pathData = path.data;
  12848. if (prevCmd === CMD.Q) {
  12849. ctlPtx += cpx - pathData[len - 4];
  12850. ctlPty += cpy - pathData[len - 3];
  12851. }
  12852. cpx += p[off++];
  12853. cpy += p[off++];
  12854. cmd = CMD.Q;
  12855. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  12856. break;
  12857. case 'A':
  12858. rx = p[off++];
  12859. ry = p[off++];
  12860. psi = p[off++];
  12861. fa = p[off++];
  12862. fs = p[off++];
  12863. x1 = cpx, y1 = cpy;
  12864. cpx = p[off++];
  12865. cpy = p[off++];
  12866. cmd = CMD.A;
  12867. processArc(
  12868. x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path
  12869. );
  12870. break;
  12871. case 'a':
  12872. rx = p[off++];
  12873. ry = p[off++];
  12874. psi = p[off++];
  12875. fa = p[off++];
  12876. fs = p[off++];
  12877. x1 = cpx, y1 = cpy;
  12878. cpx += p[off++];
  12879. cpy += p[off++];
  12880. cmd = CMD.A;
  12881. processArc(
  12882. x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path
  12883. );
  12884. break;
  12885. }
  12886. }
  12887. if (c === 'z' || c === 'Z') {
  12888. cmd = CMD.Z;
  12889. path.addData(cmd);
  12890. }
  12891. prevCmd = cmd;
  12892. }
  12893. path.toStatic();
  12894. return path;
  12895. }
  12896. // TODO Optimize double memory cost problem
  12897. function createPathOptions(str, opts) {
  12898. var pathProxy = createPathProxyFromString(str);
  12899. opts = opts || {};
  12900. opts.buildPath = function (path) {
  12901. if (path.setData) {
  12902. path.setData(pathProxy.data);
  12903. // Svg and vml renderer don't have context
  12904. var ctx = path.getContext();
  12905. if (ctx) {
  12906. path.rebuildPath(ctx);
  12907. }
  12908. }
  12909. else {
  12910. var ctx = path;
  12911. pathProxy.rebuildPath(ctx);
  12912. }
  12913. };
  12914. opts.applyTransform = function (m) {
  12915. transformPath(pathProxy, m);
  12916. this.dirty(true);
  12917. };
  12918. return opts;
  12919. }
  12920. /**
  12921. * Create a Path object from path string data
  12922. * http://www.w3.org/TR/SVG/paths.html#PathData
  12923. * @param {Object} opts Other options
  12924. */
  12925. function createFromString(str, opts) {
  12926. return new Path(createPathOptions(str, opts));
  12927. }
  12928. /**
  12929. * Create a Path class from path string data
  12930. * @param {string} str
  12931. * @param {Object} opts Other options
  12932. */
  12933. function extendFromString(str, opts) {
  12934. return Path.extend(createPathOptions(str, opts));
  12935. }
  12936. /**
  12937. * Merge multiple paths
  12938. */
  12939. // TODO Apply transform
  12940. // TODO stroke dash
  12941. // TODO Optimize double memory cost problem
  12942. function mergePath$1(pathEls, opts) {
  12943. var pathList = [];
  12944. var len = pathEls.length;
  12945. for (var i = 0; i < len; i++) {
  12946. var pathEl = pathEls[i];
  12947. if (!pathEl.path) {
  12948. pathEl.createPathProxy();
  12949. }
  12950. if (pathEl.__dirtyPath) {
  12951. pathEl.buildPath(pathEl.path, pathEl.shape, true);
  12952. }
  12953. pathList.push(pathEl.path);
  12954. }
  12955. var pathBundle = new Path(opts);
  12956. // Need path proxy.
  12957. pathBundle.createPathProxy();
  12958. pathBundle.buildPath = function (path) {
  12959. path.appendPath(pathList);
  12960. // Svg and vml renderer don't have context
  12961. var ctx = path.getContext();
  12962. if (ctx) {
  12963. path.rebuildPath(ctx);
  12964. }
  12965. };
  12966. return pathBundle;
  12967. }
  12968. /**
  12969. * @alias zrender/graphic/Text
  12970. * @extends module:zrender/graphic/Displayable
  12971. * @constructor
  12972. * @param {Object} opts
  12973. */
  12974. var Text = function (opts) { // jshint ignore:line
  12975. Displayable.call(this, opts);
  12976. };
  12977. Text.prototype = {
  12978. constructor: Text,
  12979. type: 'text',
  12980. brush: function (ctx, prevEl) {
  12981. var style = this.style;
  12982. // Optimize, avoid normalize every time.
  12983. this.__dirty && normalizeTextStyle(style, true);
  12984. // Use props with prefix 'text'.
  12985. style.fill = style.stroke = style.shadowBlur = style.shadowColor =
  12986. style.shadowOffsetX = style.shadowOffsetY = null;
  12987. var text = style.text;
  12988. // Convert to string
  12989. text != null && (text += '');
  12990. // Always bind style
  12991. style.bind(ctx, this, prevEl);
  12992. if (!needDrawText(text, style)) {
  12993. return;
  12994. }
  12995. this.setTransform(ctx);
  12996. renderText(this, ctx, text, style);
  12997. this.restoreTransform(ctx);
  12998. },
  12999. getBoundingRect: function () {
  13000. var style = this.style;
  13001. // Optimize, avoid normalize every time.
  13002. this.__dirty && normalizeTextStyle(style, true);
  13003. if (!this._rect) {
  13004. var text = style.text;
  13005. text != null ? (text += '') : (text = '');
  13006. var rect = getBoundingRect(
  13007. style.text + '',
  13008. style.font,
  13009. style.textAlign,
  13010. style.textVerticalAlign,
  13011. style.textPadding,
  13012. style.rich
  13013. );
  13014. rect.x += style.x || 0;
  13015. rect.y += style.y || 0;
  13016. if (getStroke(style.textStroke, style.textStrokeWidth)) {
  13017. var w = style.textStrokeWidth;
  13018. rect.x -= w / 2;
  13019. rect.y -= w / 2;
  13020. rect.width += w;
  13021. rect.height += w;
  13022. }
  13023. this._rect = rect;
  13024. }
  13025. return this._rect;
  13026. }
  13027. };
  13028. inherits(Text, Displayable);
  13029. /**
  13030. * 圆形
  13031. * @module zrender/shape/Circle
  13032. */
  13033. var Circle = Path.extend({
  13034. type: 'circle',
  13035. shape: {
  13036. cx: 0,
  13037. cy: 0,
  13038. r: 0
  13039. },
  13040. buildPath : function (ctx, shape, inBundle) {
  13041. // Better stroking in ShapeBundle
  13042. // Always do it may have performence issue ( fill may be 2x more cost)
  13043. if (inBundle) {
  13044. ctx.moveTo(shape.cx + shape.r, shape.cy);
  13045. }
  13046. // else {
  13047. // if (ctx.allocate && !ctx.data.length) {
  13048. // ctx.allocate(ctx.CMD_MEM_SIZE.A);
  13049. // }
  13050. // }
  13051. // Better stroking in ShapeBundle
  13052. // ctx.moveTo(shape.cx + shape.r, shape.cy);
  13053. ctx.arc(shape.cx, shape.cy, shape.r, 0, Math.PI * 2, true);
  13054. }
  13055. });
  13056. // Fix weird bug in some version of IE11 (like 11.0.9600.178**),
  13057. // where exception "unexpected call to method or property access"
  13058. // might be thrown when calling ctx.fill or ctx.stroke after a path
  13059. // whose area size is zero is drawn and ctx.clip() is called and
  13060. // shadowBlur is set. See #4572, #3112, #5777.
  13061. // (e.g.,
  13062. // ctx.moveTo(10, 10);
  13063. // ctx.lineTo(20, 10);
  13064. // ctx.closePath();
  13065. // ctx.clip();
  13066. // ctx.shadowBlur = 10;
  13067. // ...
  13068. // ctx.fill();
  13069. // )
  13070. var shadowTemp = [
  13071. ['shadowBlur', 0],
  13072. ['shadowColor', '#000'],
  13073. ['shadowOffsetX', 0],
  13074. ['shadowOffsetY', 0]
  13075. ];
  13076. var fixClipWithShadow = function (orignalBrush) {
  13077. // version string can be: '11.0'
  13078. return (env$1.browser.ie && env$1.browser.version >= 11)
  13079. ? function () {
  13080. var clipPaths = this.__clipPaths;
  13081. var style = this.style;
  13082. var modified;
  13083. if (clipPaths) {
  13084. for (var i = 0; i < clipPaths.length; i++) {
  13085. var clipPath = clipPaths[i];
  13086. var shape = clipPath && clipPath.shape;
  13087. var type = clipPath && clipPath.type;
  13088. if (shape && (
  13089. (type === 'sector' && shape.startAngle === shape.endAngle)
  13090. || (type === 'rect' && (!shape.width || !shape.height))
  13091. )) {
  13092. for (var j = 0; j < shadowTemp.length; j++) {
  13093. // It is save to put shadowTemp static, because shadowTemp
  13094. // will be all modified each item brush called.
  13095. shadowTemp[j][2] = style[shadowTemp[j][0]];
  13096. style[shadowTemp[j][0]] = shadowTemp[j][1];
  13097. }
  13098. modified = true;
  13099. break;
  13100. }
  13101. }
  13102. }
  13103. orignalBrush.apply(this, arguments);
  13104. if (modified) {
  13105. for (var j = 0; j < shadowTemp.length; j++) {
  13106. style[shadowTemp[j][0]] = shadowTemp[j][2];
  13107. }
  13108. }
  13109. }
  13110. : orignalBrush;
  13111. };
  13112. /**
  13113. * 扇形
  13114. * @module zrender/graphic/shape/Sector
  13115. */
  13116. var Sector = Path.extend({
  13117. type: 'sector',
  13118. shape: {
  13119. cx: 0,
  13120. cy: 0,
  13121. r0: 0,
  13122. r: 0,
  13123. startAngle: 0,
  13124. endAngle: Math.PI * 2,
  13125. clockwise: true
  13126. },
  13127. brush: fixClipWithShadow(Path.prototype.brush),
  13128. buildPath: function (ctx, shape) {
  13129. var x = shape.cx;
  13130. var y = shape.cy;
  13131. var r0 = Math.max(shape.r0 || 0, 0);
  13132. var r = Math.max(shape.r, 0);
  13133. var startAngle = shape.startAngle;
  13134. var endAngle = shape.endAngle;
  13135. var clockwise = shape.clockwise;
  13136. var unitX = Math.cos(startAngle);
  13137. var unitY = Math.sin(startAngle);
  13138. ctx.moveTo(unitX * r0 + x, unitY * r0 + y);
  13139. ctx.lineTo(unitX * r + x, unitY * r + y);
  13140. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  13141. ctx.lineTo(
  13142. Math.cos(endAngle) * r0 + x,
  13143. Math.sin(endAngle) * r0 + y
  13144. );
  13145. if (r0 !== 0) {
  13146. ctx.arc(x, y, r0, endAngle, startAngle, clockwise);
  13147. }
  13148. ctx.closePath();
  13149. }
  13150. });
  13151. /**
  13152. * 圆环
  13153. * @module zrender/graphic/shape/Ring
  13154. */
  13155. var Ring = Path.extend({
  13156. type: 'ring',
  13157. shape: {
  13158. cx: 0,
  13159. cy: 0,
  13160. r: 0,
  13161. r0: 0
  13162. },
  13163. buildPath: function (ctx, shape) {
  13164. var x = shape.cx;
  13165. var y = shape.cy;
  13166. var PI2 = Math.PI * 2;
  13167. ctx.moveTo(x + shape.r, y);
  13168. ctx.arc(x, y, shape.r, 0, PI2, false);
  13169. ctx.moveTo(x + shape.r0, y);
  13170. ctx.arc(x, y, shape.r0, 0, PI2, true);
  13171. }
  13172. });
  13173. /**
  13174. * Catmull-Rom spline 插值折线
  13175. * @module zrender/shape/util/smoothSpline
  13176. * @author pissang (https://www.github.com/pissang)
  13177. * Kener (@Kener-林峰, kener.linfeng@gmail.com)
  13178. * errorrik (errorrik@gmail.com)
  13179. */
  13180. /**
  13181. * @inner
  13182. */
  13183. function interpolate(p0, p1, p2, p3, t, t2, t3) {
  13184. var v0 = (p2 - p0) * 0.5;
  13185. var v1 = (p3 - p1) * 0.5;
  13186. return (2 * (p1 - p2) + v0 + v1) * t3
  13187. + (-3 * (p1 - p2) - 2 * v0 - v1) * t2
  13188. + v0 * t + p1;
  13189. }
  13190. /**
  13191. * @alias module:zrender/shape/util/smoothSpline
  13192. * @param {Array} points 线段顶点数组
  13193. * @param {boolean} isLoop
  13194. * @return {Array}
  13195. */
  13196. var smoothSpline = function (points, isLoop) {
  13197. var len$$1 = points.length;
  13198. var ret = [];
  13199. var distance$$1 = 0;
  13200. for (var i = 1; i < len$$1; i++) {
  13201. distance$$1 += distance(points[i - 1], points[i]);
  13202. }
  13203. var segs = distance$$1 / 2;
  13204. segs = segs < len$$1 ? len$$1 : segs;
  13205. for (var i = 0; i < segs; i++) {
  13206. var pos = i / (segs - 1) * (isLoop ? len$$1 : len$$1 - 1);
  13207. var idx = Math.floor(pos);
  13208. var w = pos - idx;
  13209. var p0;
  13210. var p1 = points[idx % len$$1];
  13211. var p2;
  13212. var p3;
  13213. if (!isLoop) {
  13214. p0 = points[idx === 0 ? idx : idx - 1];
  13215. p2 = points[idx > len$$1 - 2 ? len$$1 - 1 : idx + 1];
  13216. p3 = points[idx > len$$1 - 3 ? len$$1 - 1 : idx + 2];
  13217. }
  13218. else {
  13219. p0 = points[(idx - 1 + len$$1) % len$$1];
  13220. p2 = points[(idx + 1) % len$$1];
  13221. p3 = points[(idx + 2) % len$$1];
  13222. }
  13223. var w2 = w * w;
  13224. var w3 = w * w2;
  13225. ret.push([
  13226. interpolate(p0[0], p1[0], p2[0], p3[0], w, w2, w3),
  13227. interpolate(p0[1], p1[1], p2[1], p3[1], w, w2, w3)
  13228. ]);
  13229. }
  13230. return ret;
  13231. };
  13232. /**
  13233. * 贝塞尔平滑曲线
  13234. * @module zrender/shape/util/smoothBezier
  13235. * @author pissang (https://www.github.com/pissang)
  13236. * Kener (@Kener-林峰, kener.linfeng@gmail.com)
  13237. * errorrik (errorrik@gmail.com)
  13238. */
  13239. /**
  13240. * 贝塞尔平滑曲线
  13241. * @alias module:zrender/shape/util/smoothBezier
  13242. * @param {Array} points 线段顶点数组
  13243. * @param {number} smooth 平滑等级, 0-1
  13244. * @param {boolean} isLoop
  13245. * @param {Array} constraint 将计算出来的控制点约束在一个包围盒内
  13246. * 比如 [[0, 0], [100, 100]], 这个包围盒会与
  13247. * 整个折线的包围盒做一个并集用来约束控制点。
  13248. * @param {Array} 计算出来的控制点数组
  13249. */
  13250. var smoothBezier = function (points, smooth, isLoop, constraint) {
  13251. var cps = [];
  13252. var v = [];
  13253. var v1 = [];
  13254. var v2 = [];
  13255. var prevPoint;
  13256. var nextPoint;
  13257. var min$$1, max$$1;
  13258. if (constraint) {
  13259. min$$1 = [Infinity, Infinity];
  13260. max$$1 = [-Infinity, -Infinity];
  13261. for (var i = 0, len$$1 = points.length; i < len$$1; i++) {
  13262. min(min$$1, min$$1, points[i]);
  13263. max(max$$1, max$$1, points[i]);
  13264. }
  13265. // 与指定的包围盒做并集
  13266. min(min$$1, min$$1, constraint[0]);
  13267. max(max$$1, max$$1, constraint[1]);
  13268. }
  13269. for (var i = 0, len$$1 = points.length; i < len$$1; i++) {
  13270. var point = points[i];
  13271. if (isLoop) {
  13272. prevPoint = points[i ? i - 1 : len$$1 - 1];
  13273. nextPoint = points[(i + 1) % len$$1];
  13274. }
  13275. else {
  13276. if (i === 0 || i === len$$1 - 1) {
  13277. cps.push(clone$1(points[i]));
  13278. continue;
  13279. }
  13280. else {
  13281. prevPoint = points[i - 1];
  13282. nextPoint = points[i + 1];
  13283. }
  13284. }
  13285. sub(v, nextPoint, prevPoint);
  13286. // use degree to scale the handle length
  13287. scale(v, v, smooth);
  13288. var d0 = distance(point, prevPoint);
  13289. var d1 = distance(point, nextPoint);
  13290. var sum = d0 + d1;
  13291. if (sum !== 0) {
  13292. d0 /= sum;
  13293. d1 /= sum;
  13294. }
  13295. scale(v1, v, -d0);
  13296. scale(v2, v, d1);
  13297. var cp0 = add([], point, v1);
  13298. var cp1 = add([], point, v2);
  13299. if (constraint) {
  13300. max(cp0, cp0, min$$1);
  13301. min(cp0, cp0, max$$1);
  13302. max(cp1, cp1, min$$1);
  13303. min(cp1, cp1, max$$1);
  13304. }
  13305. cps.push(cp0);
  13306. cps.push(cp1);
  13307. }
  13308. if (isLoop) {
  13309. cps.push(cps.shift());
  13310. }
  13311. return cps;
  13312. };
  13313. function buildPath$1(ctx, shape, closePath) {
  13314. var points = shape.points;
  13315. var smooth = shape.smooth;
  13316. if (points && points.length >= 2) {
  13317. if (smooth && smooth !== 'spline') {
  13318. var controlPoints = smoothBezier(
  13319. points, smooth, closePath, shape.smoothConstraint
  13320. );
  13321. ctx.moveTo(points[0][0], points[0][1]);
  13322. var len = points.length;
  13323. for (var i = 0; i < (closePath ? len : len - 1); i++) {
  13324. var cp1 = controlPoints[i * 2];
  13325. var cp2 = controlPoints[i * 2 + 1];
  13326. var p = points[(i + 1) % len];
  13327. ctx.bezierCurveTo(
  13328. cp1[0], cp1[1], cp2[0], cp2[1], p[0], p[1]
  13329. );
  13330. }
  13331. }
  13332. else {
  13333. if (smooth === 'spline') {
  13334. points = smoothSpline(points, closePath);
  13335. }
  13336. ctx.moveTo(points[0][0], points[0][1]);
  13337. for (var i = 1, l = points.length; i < l; i++) {
  13338. ctx.lineTo(points[i][0], points[i][1]);
  13339. }
  13340. }
  13341. closePath && ctx.closePath();
  13342. }
  13343. }
  13344. /**
  13345. * 多边形
  13346. * @module zrender/shape/Polygon
  13347. */
  13348. var Polygon = Path.extend({
  13349. type: 'polygon',
  13350. shape: {
  13351. points: null,
  13352. smooth: false,
  13353. smoothConstraint: null
  13354. },
  13355. buildPath: function (ctx, shape) {
  13356. buildPath$1(ctx, shape, true);
  13357. }
  13358. });
  13359. /**
  13360. * @module zrender/graphic/shape/Polyline
  13361. */
  13362. var Polyline = Path.extend({
  13363. type: 'polyline',
  13364. shape: {
  13365. points: null,
  13366. smooth: false,
  13367. smoothConstraint: null
  13368. },
  13369. style: {
  13370. stroke: '#000',
  13371. fill: null
  13372. },
  13373. buildPath: function (ctx, shape) {
  13374. buildPath$1(ctx, shape, false);
  13375. }
  13376. });
  13377. /**
  13378. * 矩形
  13379. * @module zrender/graphic/shape/Rect
  13380. */
  13381. var Rect = Path.extend({
  13382. type: 'rect',
  13383. shape: {
  13384. // 左上、右上、右下、左下角的半径依次为r1、r2、r3、r4
  13385. // r缩写为1 相当于 [1, 1, 1, 1]
  13386. // r缩写为[1] 相当于 [1, 1, 1, 1]
  13387. // r缩写为[1, 2] 相当于 [1, 2, 1, 2]
  13388. // r缩写为[1, 2, 3] 相当于 [1, 2, 3, 2]
  13389. r: 0,
  13390. x: 0,
  13391. y: 0,
  13392. width: 0,
  13393. height: 0
  13394. },
  13395. buildPath: function (ctx, shape) {
  13396. var x = shape.x;
  13397. var y = shape.y;
  13398. var width = shape.width;
  13399. var height = shape.height;
  13400. if (!shape.r) {
  13401. ctx.rect(x, y, width, height);
  13402. }
  13403. else {
  13404. buildPath(ctx, shape);
  13405. }
  13406. ctx.closePath();
  13407. return;
  13408. }
  13409. });
  13410. /**
  13411. * 直线
  13412. * @module zrender/graphic/shape/Line
  13413. */
  13414. var Line = Path.extend({
  13415. type: 'line',
  13416. shape: {
  13417. // Start point
  13418. x1: 0,
  13419. y1: 0,
  13420. // End point
  13421. x2: 0,
  13422. y2: 0,
  13423. percent: 1
  13424. },
  13425. style: {
  13426. stroke: '#000',
  13427. fill: null
  13428. },
  13429. buildPath: function (ctx, shape) {
  13430. var x1 = shape.x1;
  13431. var y1 = shape.y1;
  13432. var x2 = shape.x2;
  13433. var y2 = shape.y2;
  13434. var percent = shape.percent;
  13435. if (percent === 0) {
  13436. return;
  13437. }
  13438. ctx.moveTo(x1, y1);
  13439. if (percent < 1) {
  13440. x2 = x1 * (1 - percent) + x2 * percent;
  13441. y2 = y1 * (1 - percent) + y2 * percent;
  13442. }
  13443. ctx.lineTo(x2, y2);
  13444. },
  13445. /**
  13446. * Get point at percent
  13447. * @param {number} percent
  13448. * @return {Array.<number>}
  13449. */
  13450. pointAt: function (p) {
  13451. var shape = this.shape;
  13452. return [
  13453. shape.x1 * (1 - p) + shape.x2 * p,
  13454. shape.y1 * (1 - p) + shape.y2 * p
  13455. ];
  13456. }
  13457. });
  13458. /**
  13459. * 贝塞尔曲线
  13460. * @module zrender/shape/BezierCurve
  13461. */
  13462. var out = [];
  13463. function someVectorAt(shape, t, isTangent) {
  13464. var cpx2 = shape.cpx2;
  13465. var cpy2 = shape.cpy2;
  13466. if (cpx2 === null || cpy2 === null) {
  13467. return [
  13468. (isTangent ? cubicDerivativeAt : cubicAt)(shape.x1, shape.cpx1, shape.cpx2, shape.x2, t),
  13469. (isTangent ? cubicDerivativeAt : cubicAt)(shape.y1, shape.cpy1, shape.cpy2, shape.y2, t)
  13470. ];
  13471. }
  13472. else {
  13473. return [
  13474. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.x1, shape.cpx1, shape.x2, t),
  13475. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.y1, shape.cpy1, shape.y2, t)
  13476. ];
  13477. }
  13478. }
  13479. var BezierCurve = Path.extend({
  13480. type: 'bezier-curve',
  13481. shape: {
  13482. x1: 0,
  13483. y1: 0,
  13484. x2: 0,
  13485. y2: 0,
  13486. cpx1: 0,
  13487. cpy1: 0,
  13488. // cpx2: 0,
  13489. // cpy2: 0
  13490. // Curve show percent, for animating
  13491. percent: 1
  13492. },
  13493. style: {
  13494. stroke: '#000',
  13495. fill: null
  13496. },
  13497. buildPath: function (ctx, shape) {
  13498. var x1 = shape.x1;
  13499. var y1 = shape.y1;
  13500. var x2 = shape.x2;
  13501. var y2 = shape.y2;
  13502. var cpx1 = shape.cpx1;
  13503. var cpy1 = shape.cpy1;
  13504. var cpx2 = shape.cpx2;
  13505. var cpy2 = shape.cpy2;
  13506. var percent = shape.percent;
  13507. if (percent === 0) {
  13508. return;
  13509. }
  13510. ctx.moveTo(x1, y1);
  13511. if (cpx2 == null || cpy2 == null) {
  13512. if (percent < 1) {
  13513. quadraticSubdivide(
  13514. x1, cpx1, x2, percent, out
  13515. );
  13516. cpx1 = out[1];
  13517. x2 = out[2];
  13518. quadraticSubdivide(
  13519. y1, cpy1, y2, percent, out
  13520. );
  13521. cpy1 = out[1];
  13522. y2 = out[2];
  13523. }
  13524. ctx.quadraticCurveTo(
  13525. cpx1, cpy1,
  13526. x2, y2
  13527. );
  13528. }
  13529. else {
  13530. if (percent < 1) {
  13531. cubicSubdivide(
  13532. x1, cpx1, cpx2, x2, percent, out
  13533. );
  13534. cpx1 = out[1];
  13535. cpx2 = out[2];
  13536. x2 = out[3];
  13537. cubicSubdivide(
  13538. y1, cpy1, cpy2, y2, percent, out
  13539. );
  13540. cpy1 = out[1];
  13541. cpy2 = out[2];
  13542. y2 = out[3];
  13543. }
  13544. ctx.bezierCurveTo(
  13545. cpx1, cpy1,
  13546. cpx2, cpy2,
  13547. x2, y2
  13548. );
  13549. }
  13550. },
  13551. /**
  13552. * Get point at percent
  13553. * @param {number} t
  13554. * @return {Array.<number>}
  13555. */
  13556. pointAt: function (t) {
  13557. return someVectorAt(this.shape, t, false);
  13558. },
  13559. /**
  13560. * Get tangent at percent
  13561. * @param {number} t
  13562. * @return {Array.<number>}
  13563. */
  13564. tangentAt: function (t) {
  13565. var p = someVectorAt(this.shape, t, true);
  13566. return normalize(p, p);
  13567. }
  13568. });
  13569. /**
  13570. * 圆弧
  13571. * @module zrender/graphic/shape/Arc
  13572. */
  13573. var Arc = Path.extend({
  13574. type: 'arc',
  13575. shape: {
  13576. cx: 0,
  13577. cy: 0,
  13578. r: 0,
  13579. startAngle: 0,
  13580. endAngle: Math.PI * 2,
  13581. clockwise: true
  13582. },
  13583. style: {
  13584. stroke: '#000',
  13585. fill: null
  13586. },
  13587. buildPath: function (ctx, shape) {
  13588. var x = shape.cx;
  13589. var y = shape.cy;
  13590. var r = Math.max(shape.r, 0);
  13591. var startAngle = shape.startAngle;
  13592. var endAngle = shape.endAngle;
  13593. var clockwise = shape.clockwise;
  13594. var unitX = Math.cos(startAngle);
  13595. var unitY = Math.sin(startAngle);
  13596. ctx.moveTo(unitX * r + x, unitY * r + y);
  13597. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  13598. }
  13599. });
  13600. // CompoundPath to improve performance
  13601. var CompoundPath = Path.extend({
  13602. type: 'compound',
  13603. shape: {
  13604. paths: null
  13605. },
  13606. _updatePathDirty: function () {
  13607. var dirtyPath = this.__dirtyPath;
  13608. var paths = this.shape.paths;
  13609. for (var i = 0; i < paths.length; i++) {
  13610. // Mark as dirty if any subpath is dirty
  13611. dirtyPath = dirtyPath || paths[i].__dirtyPath;
  13612. }
  13613. this.__dirtyPath = dirtyPath;
  13614. this.__dirty = this.__dirty || dirtyPath;
  13615. },
  13616. beforeBrush: function () {
  13617. this._updatePathDirty();
  13618. var paths = this.shape.paths || [];
  13619. var scale = this.getGlobalScale();
  13620. // Update path scale
  13621. for (var i = 0; i < paths.length; i++) {
  13622. if (!paths[i].path) {
  13623. paths[i].createPathProxy();
  13624. }
  13625. paths[i].path.setScale(scale[0], scale[1]);
  13626. }
  13627. },
  13628. buildPath: function (ctx, shape) {
  13629. var paths = shape.paths || [];
  13630. for (var i = 0; i < paths.length; i++) {
  13631. paths[i].buildPath(ctx, paths[i].shape, true);
  13632. }
  13633. },
  13634. afterBrush: function () {
  13635. var paths = this.shape.paths || [];
  13636. for (var i = 0; i < paths.length; i++) {
  13637. paths[i].__dirtyPath = false;
  13638. }
  13639. },
  13640. getBoundingRect: function () {
  13641. this._updatePathDirty();
  13642. return Path.prototype.getBoundingRect.call(this);
  13643. }
  13644. });
  13645. /**
  13646. * @param {Array.<Object>} colorStops
  13647. */
  13648. var Gradient = function (colorStops) {
  13649. this.colorStops = colorStops || [];
  13650. };
  13651. Gradient.prototype = {
  13652. constructor: Gradient,
  13653. addColorStop: function (offset, color) {
  13654. this.colorStops.push({
  13655. offset: offset,
  13656. color: color
  13657. });
  13658. }
  13659. };
  13660. /**
  13661. * x, y, x2, y2 are all percent from 0 to 1
  13662. * @param {number} [x=0]
  13663. * @param {number} [y=0]
  13664. * @param {number} [x2=1]
  13665. * @param {number} [y2=0]
  13666. * @param {Array.<Object>} colorStops
  13667. * @param {boolean} [globalCoord=false]
  13668. */
  13669. var LinearGradient = function (x, y, x2, y2, colorStops, globalCoord) {
  13670. // Should do nothing more in this constructor. Because gradient can be
  13671. // declard by `color: {type: 'linear', colorStops: ...}`, where
  13672. // this constructor will not be called.
  13673. this.x = x == null ? 0 : x;
  13674. this.y = y == null ? 0 : y;
  13675. this.x2 = x2 == null ? 1 : x2;
  13676. this.y2 = y2 == null ? 0 : y2;
  13677. // Can be cloned
  13678. this.type = 'linear';
  13679. // If use global coord
  13680. this.global = globalCoord || false;
  13681. Gradient.call(this, colorStops);
  13682. };
  13683. LinearGradient.prototype = {
  13684. constructor: LinearGradient
  13685. };
  13686. inherits(LinearGradient, Gradient);
  13687. /**
  13688. * x, y, r are all percent from 0 to 1
  13689. * @param {number} [x=0.5]
  13690. * @param {number} [y=0.5]
  13691. * @param {number} [r=0.5]
  13692. * @param {Array.<Object>} [colorStops]
  13693. * @param {boolean} [globalCoord=false]
  13694. */
  13695. var RadialGradient = function (x, y, r, colorStops, globalCoord) {
  13696. // Should do nothing more in this constructor. Because gradient can be
  13697. // declard by `color: {type: 'radial', colorStops: ...}`, where
  13698. // this constructor will not be called.
  13699. this.x = x == null ? 0.5 : x;
  13700. this.y = y == null ? 0.5 : y;
  13701. this.r = r == null ? 0.5 : r;
  13702. // Can be cloned
  13703. this.type = 'radial';
  13704. // If use global coord
  13705. this.global = globalCoord || false;
  13706. Gradient.call(this, colorStops);
  13707. };
  13708. RadialGradient.prototype = {
  13709. constructor: RadialGradient
  13710. };
  13711. inherits(RadialGradient, Gradient);
  13712. /**
  13713. * Displayable for incremental rendering. It will be rendered in a separate layer
  13714. * IncrementalDisplay have too main methods. `clearDisplayables` and `addDisplayables`
  13715. * addDisplayables will render the added displayables incremetally.
  13716. *
  13717. * It use a not clearFlag to tell the painter don't clear the layer if it's the first element.
  13718. */
  13719. // TODO Style override ?
  13720. function IncrementalDisplayble(opts) {
  13721. Displayable.call(this, opts);
  13722. this._displayables = [];
  13723. this._temporaryDisplayables = [];
  13724. this._cursor = 0;
  13725. this.notClear = true;
  13726. }
  13727. IncrementalDisplayble.prototype.incremental = true;
  13728. IncrementalDisplayble.prototype.clearDisplaybles = function () {
  13729. this._displayables = [];
  13730. this._temporaryDisplayables = [];
  13731. this._cursor = 0;
  13732. this.dirty();
  13733. this.notClear = false;
  13734. };
  13735. IncrementalDisplayble.prototype.addDisplayable = function (displayable, notPersistent) {
  13736. if (notPersistent) {
  13737. this._temporaryDisplayables.push(displayable);
  13738. }
  13739. else {
  13740. this._displayables.push(displayable);
  13741. }
  13742. this.dirty();
  13743. };
  13744. IncrementalDisplayble.prototype.addDisplayables = function (displayables, notPersistent) {
  13745. notPersistent = notPersistent || false;
  13746. for (var i = 0; i < displayables.length; i++) {
  13747. this.addDisplayable(displayables[i], notPersistent);
  13748. }
  13749. };
  13750. IncrementalDisplayble.prototype.eachPendingDisplayable = function (cb) {
  13751. for (var i = this._cursor; i < this._displayables.length; i++) {
  13752. cb && cb(this._displayables[i]);
  13753. }
  13754. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  13755. cb && cb(this._temporaryDisplayables[i]);
  13756. }
  13757. };
  13758. IncrementalDisplayble.prototype.update = function () {
  13759. this.updateTransform();
  13760. for (var i = this._cursor; i < this._displayables.length; i++) {
  13761. var displayable = this._displayables[i];
  13762. // PENDING
  13763. displayable.parent = this;
  13764. displayable.update();
  13765. displayable.parent = null;
  13766. }
  13767. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  13768. var displayable = this._temporaryDisplayables[i];
  13769. // PENDING
  13770. displayable.parent = this;
  13771. displayable.update();
  13772. displayable.parent = null;
  13773. }
  13774. };
  13775. IncrementalDisplayble.prototype.brush = function (ctx, prevEl) {
  13776. // Render persistant displayables.
  13777. for (var i = this._cursor; i < this._displayables.length; i++) {
  13778. var displayable = this._displayables[i];
  13779. displayable.beforeBrush && displayable.beforeBrush(ctx);
  13780. displayable.brush(ctx, i === this._cursor ? null : this._displayables[i - 1]);
  13781. displayable.afterBrush && displayable.afterBrush(ctx);
  13782. }
  13783. this._cursor = i;
  13784. // Render temporary displayables.
  13785. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  13786. var displayable = this._temporaryDisplayables[i];
  13787. displayable.beforeBrush && displayable.beforeBrush(ctx);
  13788. displayable.brush(ctx, i === 0 ? null : this._temporaryDisplayables[i - 1]);
  13789. displayable.afterBrush && displayable.afterBrush(ctx);
  13790. }
  13791. this._temporaryDisplayables = [];
  13792. this.notClear = true;
  13793. };
  13794. var m = [];
  13795. IncrementalDisplayble.prototype.getBoundingRect = function () {
  13796. if (!this._rect) {
  13797. var rect = new BoundingRect(Infinity, Infinity, -Infinity, -Infinity);
  13798. for (var i = 0; i < this._displayables.length; i++) {
  13799. var displayable = this._displayables[i];
  13800. var childRect = displayable.getBoundingRect().clone();
  13801. if (displayable.needLocalTransform()) {
  13802. childRect.applyTransform(displayable.getLocalTransform(m));
  13803. }
  13804. rect.union(childRect);
  13805. }
  13806. this._rect = rect;
  13807. }
  13808. return this._rect;
  13809. };
  13810. IncrementalDisplayble.prototype.contain = function (x, y) {
  13811. var localPos = this.transformCoordToLocal(x, y);
  13812. var rect = this.getBoundingRect();
  13813. if (rect.contain(localPos[0], localPos[1])) {
  13814. for (var i = 0; i < this._displayables.length; i++) {
  13815. var displayable = this._displayables[i];
  13816. if (displayable.contain(x, y)) {
  13817. return true;
  13818. }
  13819. }
  13820. }
  13821. return false;
  13822. };
  13823. inherits(IncrementalDisplayble, Displayable);
  13824. /*
  13825. * Licensed to the Apache Software Foundation (ASF) under one
  13826. * or more contributor license agreements. See the NOTICE file
  13827. * distributed with this work for additional information
  13828. * regarding copyright ownership. The ASF licenses this file
  13829. * to you under the Apache License, Version 2.0 (the
  13830. * "License"); you may not use this file except in compliance
  13831. * with the License. You may obtain a copy of the License at
  13832. *
  13833. * http://www.apache.org/licenses/LICENSE-2.0
  13834. *
  13835. * Unless required by applicable law or agreed to in writing,
  13836. * software distributed under the License is distributed on an
  13837. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  13838. * KIND, either express or implied. See the License for the
  13839. * specific language governing permissions and limitations
  13840. * under the License.
  13841. */
  13842. var round = Math.round;
  13843. var mathMax$1 = Math.max;
  13844. var mathMin$1 = Math.min;
  13845. var EMPTY_OBJ = {};
  13846. /**
  13847. * Extend shape with parameters
  13848. */
  13849. function extendShape(opts) {
  13850. return Path.extend(opts);
  13851. }
  13852. /**
  13853. * Extend path
  13854. */
  13855. function extendPath(pathData, opts) {
  13856. return extendFromString(pathData, opts);
  13857. }
  13858. /**
  13859. * Create a path element from path data string
  13860. * @param {string} pathData
  13861. * @param {Object} opts
  13862. * @param {module:zrender/core/BoundingRect} rect
  13863. * @param {string} [layout=cover] 'center' or 'cover'
  13864. */
  13865. function makePath(pathData, opts, rect, layout) {
  13866. var path = createFromString(pathData, opts);
  13867. var boundingRect = path.getBoundingRect();
  13868. if (rect) {
  13869. if (layout === 'center') {
  13870. rect = centerGraphic(rect, boundingRect);
  13871. }
  13872. resizePath(path, rect);
  13873. }
  13874. return path;
  13875. }
  13876. /**
  13877. * Create a image element from image url
  13878. * @param {string} imageUrl image url
  13879. * @param {Object} opts options
  13880. * @param {module:zrender/core/BoundingRect} rect constrain rect
  13881. * @param {string} [layout=cover] 'center' or 'cover'
  13882. */
  13883. function makeImage(imageUrl, rect, layout) {
  13884. var path = new ZImage({
  13885. style: {
  13886. image: imageUrl,
  13887. x: rect.x,
  13888. y: rect.y,
  13889. width: rect.width,
  13890. height: rect.height
  13891. },
  13892. onload: function (img) {
  13893. if (layout === 'center') {
  13894. var boundingRect = {
  13895. width: img.width,
  13896. height: img.height
  13897. };
  13898. path.setStyle(centerGraphic(rect, boundingRect));
  13899. }
  13900. }
  13901. });
  13902. return path;
  13903. }
  13904. /**
  13905. * Get position of centered element in bounding box.
  13906. *
  13907. * @param {Object} rect element local bounding box
  13908. * @param {Object} boundingRect constraint bounding box
  13909. * @return {Object} element position containing x, y, width, and height
  13910. */
  13911. function centerGraphic(rect, boundingRect) {
  13912. // Set rect to center, keep width / height ratio.
  13913. var aspect = boundingRect.width / boundingRect.height;
  13914. var width = rect.height * aspect;
  13915. var height;
  13916. if (width <= rect.width) {
  13917. height = rect.height;
  13918. }
  13919. else {
  13920. width = rect.width;
  13921. height = width / aspect;
  13922. }
  13923. var cx = rect.x + rect.width / 2;
  13924. var cy = rect.y + rect.height / 2;
  13925. return {
  13926. x: cx - width / 2,
  13927. y: cy - height / 2,
  13928. width: width,
  13929. height: height
  13930. };
  13931. }
  13932. var mergePath = mergePath$1;
  13933. /**
  13934. * Resize a path to fit the rect
  13935. * @param {module:zrender/graphic/Path} path
  13936. * @param {Object} rect
  13937. */
  13938. function resizePath(path, rect) {
  13939. if (!path.applyTransform) {
  13940. return;
  13941. }
  13942. var pathRect = path.getBoundingRect();
  13943. var m = pathRect.calculateTransform(rect);
  13944. path.applyTransform(m);
  13945. }
  13946. /**
  13947. * Sub pixel optimize line for canvas
  13948. *
  13949. * @param {Object} param
  13950. * @param {Object} [param.shape]
  13951. * @param {number} [param.shape.x1]
  13952. * @param {number} [param.shape.y1]
  13953. * @param {number} [param.shape.x2]
  13954. * @param {number} [param.shape.y2]
  13955. * @param {Object} [param.style]
  13956. * @param {number} [param.style.lineWidth]
  13957. * @return {Object} Modified param
  13958. */
  13959. function subPixelOptimizeLine(param) {
  13960. var shape = param.shape;
  13961. var lineWidth = param.style.lineWidth;
  13962. if (round(shape.x1 * 2) === round(shape.x2 * 2)) {
  13963. shape.x1 = shape.x2 = subPixelOptimize(shape.x1, lineWidth, true);
  13964. }
  13965. if (round(shape.y1 * 2) === round(shape.y2 * 2)) {
  13966. shape.y1 = shape.y2 = subPixelOptimize(shape.y1, lineWidth, true);
  13967. }
  13968. return param;
  13969. }
  13970. /**
  13971. * Sub pixel optimize rect for canvas
  13972. *
  13973. * @param {Object} param
  13974. * @param {Object} [param.shape]
  13975. * @param {number} [param.shape.x]
  13976. * @param {number} [param.shape.y]
  13977. * @param {number} [param.shape.width]
  13978. * @param {number} [param.shape.height]
  13979. * @param {Object} [param.style]
  13980. * @param {number} [param.style.lineWidth]
  13981. * @return {Object} Modified param
  13982. */
  13983. function subPixelOptimizeRect(param) {
  13984. var shape = param.shape;
  13985. var lineWidth = param.style.lineWidth;
  13986. var originX = shape.x;
  13987. var originY = shape.y;
  13988. var originWidth = shape.width;
  13989. var originHeight = shape.height;
  13990. shape.x = subPixelOptimize(shape.x, lineWidth, true);
  13991. shape.y = subPixelOptimize(shape.y, lineWidth, true);
  13992. shape.width = Math.max(
  13993. subPixelOptimize(originX + originWidth, lineWidth, false) - shape.x,
  13994. originWidth === 0 ? 0 : 1
  13995. );
  13996. shape.height = Math.max(
  13997. subPixelOptimize(originY + originHeight, lineWidth, false) - shape.y,
  13998. originHeight === 0 ? 0 : 1
  13999. );
  14000. return param;
  14001. }
  14002. /**
  14003. * Sub pixel optimize for canvas
  14004. *
  14005. * @param {number} position Coordinate, such as x, y
  14006. * @param {number} lineWidth Should be nonnegative integer.
  14007. * @param {boolean=} positiveOrNegative Default false (negative).
  14008. * @return {number} Optimized position.
  14009. */
  14010. function subPixelOptimize(position, lineWidth, positiveOrNegative) {
  14011. // Assure that (position + lineWidth / 2) is near integer edge,
  14012. // otherwise line will be fuzzy in canvas.
  14013. var doubledPosition = round(position * 2);
  14014. return (doubledPosition + round(lineWidth)) % 2 === 0
  14015. ? doubledPosition / 2
  14016. : (doubledPosition + (positiveOrNegative ? 1 : -1)) / 2;
  14017. }
  14018. function hasFillOrStroke(fillOrStroke) {
  14019. return fillOrStroke != null && fillOrStroke != 'none';
  14020. }
  14021. function liftColor(color) {
  14022. return typeof color === 'string' ? lift(color, -0.1) : color;
  14023. }
  14024. /**
  14025. * @private
  14026. */
  14027. function cacheElementStl(el) {
  14028. if (el.__hoverStlDirty) {
  14029. var stroke = el.style.stroke;
  14030. var fill = el.style.fill;
  14031. // Create hoverStyle on mouseover
  14032. var hoverStyle = el.__hoverStl;
  14033. hoverStyle.fill = hoverStyle.fill
  14034. || (hasFillOrStroke(fill) ? liftColor(fill) : null);
  14035. hoverStyle.stroke = hoverStyle.stroke
  14036. || (hasFillOrStroke(stroke) ? liftColor(stroke) : null);
  14037. var normalStyle = {};
  14038. for (var name in hoverStyle) {
  14039. // See comment in `doSingleEnterHover`.
  14040. if (hoverStyle[name] != null) {
  14041. normalStyle[name] = el.style[name];
  14042. }
  14043. }
  14044. el.__normalStl = normalStyle;
  14045. el.__hoverStlDirty = false;
  14046. }
  14047. }
  14048. /**
  14049. * @private
  14050. */
  14051. function doSingleEnterHover(el) {
  14052. if (el.__isHover) {
  14053. return;
  14054. }
  14055. cacheElementStl(el);
  14056. if (el.useHoverLayer) {
  14057. el.__zr && el.__zr.addHover(el, el.__hoverStl);
  14058. }
  14059. else {
  14060. var style = el.style;
  14061. var insideRollbackOpt = style.insideRollbackOpt;
  14062. // Consider case: only `position: 'top'` is set on emphasis, then text
  14063. // color should be returned to `autoColor`, rather than remain '#fff'.
  14064. // So we should rollback then apply again after style merging.
  14065. insideRollbackOpt && rollbackInsideStyle(style);
  14066. // styles can be:
  14067. // {
  14068. // label: {
  14069. // show: false,
  14070. // position: 'outside',
  14071. // fontSize: 18
  14072. // },
  14073. // emphasis: {
  14074. // label: {
  14075. // show: true
  14076. // }
  14077. // }
  14078. // },
  14079. // where properties of `emphasis` may not appear in `normal`. We previously use
  14080. // module:echarts/util/model#defaultEmphasis to merge `normal` to `emphasis`.
  14081. // But consider rich text and setOption in merge mode, it is impossible to cover
  14082. // all properties in merge. So we use merge mode when setting style here, where
  14083. // only properties that is not `null/undefined` can be set. The disadventage:
  14084. // null/undefined can not be used to remove style any more in `emphasis`.
  14085. style.extendFrom(el.__hoverStl);
  14086. // Do not save `insideRollback`.
  14087. if (insideRollbackOpt) {
  14088. applyInsideStyle(style, style.insideOriginalTextPosition, insideRollbackOpt);
  14089. // textFill may be rollbacked to null.
  14090. if (style.textFill == null) {
  14091. style.textFill = insideRollbackOpt.autoColor;
  14092. }
  14093. }
  14094. el.dirty(false);
  14095. el.z2 += 1;
  14096. }
  14097. el.__isHover = true;
  14098. }
  14099. /**
  14100. * @inner
  14101. */
  14102. function doSingleLeaveHover(el) {
  14103. if (!el.__isHover) {
  14104. return;
  14105. }
  14106. var normalStl = el.__normalStl;
  14107. if (el.useHoverLayer) {
  14108. el.__zr && el.__zr.removeHover(el);
  14109. }
  14110. else {
  14111. // Consider null/undefined value, should use
  14112. // `setStyle` but not `extendFrom(stl, true)`.
  14113. normalStl && el.setStyle(normalStl);
  14114. el.z2 -= 1;
  14115. }
  14116. el.__isHover = false;
  14117. }
  14118. /**
  14119. * @inner
  14120. */
  14121. function doEnterHover(el) {
  14122. el.type === 'group'
  14123. ? el.traverse(function (child) {
  14124. if (child.type !== 'group') {
  14125. doSingleEnterHover(child);
  14126. }
  14127. })
  14128. : doSingleEnterHover(el);
  14129. }
  14130. function doLeaveHover(el) {
  14131. el.type === 'group'
  14132. ? el.traverse(function (child) {
  14133. if (child.type !== 'group') {
  14134. doSingleLeaveHover(child);
  14135. }
  14136. })
  14137. : doSingleLeaveHover(el);
  14138. }
  14139. /**
  14140. * @inner
  14141. */
  14142. function setElementHoverStl(el, hoverStl) {
  14143. // If element has sepcified hoverStyle, then use it instead of given hoverStyle
  14144. // Often used when item group has a label element and it's hoverStyle is different
  14145. el.__hoverStl = el.hoverStyle || hoverStl || {};
  14146. el.__hoverStlDirty = true;
  14147. if (el.__isHover) {
  14148. cacheElementStl(el);
  14149. }
  14150. }
  14151. /**
  14152. * @inner
  14153. */
  14154. function onElementMouseOver(e) {
  14155. if (this.__hoverSilentOnTouch && e.zrByTouch) {
  14156. return;
  14157. }
  14158. // Only if element is not in emphasis status
  14159. !this.__isEmphasis && doEnterHover(this);
  14160. }
  14161. /**
  14162. * @inner
  14163. */
  14164. function onElementMouseOut(e) {
  14165. if (this.__hoverSilentOnTouch && e.zrByTouch) {
  14166. return;
  14167. }
  14168. // Only if element is not in emphasis status
  14169. !this.__isEmphasis && doLeaveHover(this);
  14170. }
  14171. /**
  14172. * @inner
  14173. */
  14174. function enterEmphasis() {
  14175. this.__isEmphasis = true;
  14176. doEnterHover(this);
  14177. }
  14178. /**
  14179. * @inner
  14180. */
  14181. function leaveEmphasis() {
  14182. this.__isEmphasis = false;
  14183. doLeaveHover(this);
  14184. }
  14185. /**
  14186. * Set hover style of element.
  14187. * This method can be called repeatly without side-effects.
  14188. * @param {module:zrender/Element} el
  14189. * @param {Object} [hoverStyle]
  14190. * @param {Object} [opt]
  14191. * @param {boolean} [opt.hoverSilentOnTouch=false]
  14192. * In touch device, mouseover event will be trigger on touchstart event
  14193. * (see module:zrender/dom/HandlerProxy). By this mechanism, we can
  14194. * conviniently use hoverStyle when tap on touch screen without additional
  14195. * code for compatibility.
  14196. * But if the chart/component has select feature, which usually also use
  14197. * hoverStyle, there might be conflict between 'select-highlight' and
  14198. * 'hover-highlight' especially when roam is enabled (see geo for example).
  14199. * In this case, hoverSilentOnTouch should be used to disable hover-highlight
  14200. * on touch device.
  14201. */
  14202. function setHoverStyle(el, hoverStyle, opt) {
  14203. el.__hoverSilentOnTouch = opt && opt.hoverSilentOnTouch;
  14204. el.type === 'group'
  14205. ? el.traverse(function (child) {
  14206. if (child.type !== 'group') {
  14207. setElementHoverStl(child, hoverStyle);
  14208. }
  14209. })
  14210. : setElementHoverStl(el, hoverStyle);
  14211. // Duplicated function will be auto-ignored, see Eventful.js.
  14212. el.on('mouseover', onElementMouseOver)
  14213. .on('mouseout', onElementMouseOut);
  14214. // Emphasis, normal can be triggered manually
  14215. el.on('emphasis', enterEmphasis)
  14216. .on('normal', leaveEmphasis);
  14217. }
  14218. /**
  14219. * @param {Object|module:zrender/graphic/Style} normalStyle
  14220. * @param {Object} emphasisStyle
  14221. * @param {module:echarts/model/Model} normalModel
  14222. * @param {module:echarts/model/Model} emphasisModel
  14223. * @param {Object} opt Check `opt` of `setTextStyleCommon` to find other props.
  14224. * @param {string|Function} [opt.defaultText]
  14225. * @param {module:echarts/model/Model} [opt.labelFetcher] Fetch text by
  14226. * `opt.labelFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  14227. * @param {module:echarts/model/Model} [opt.labelDataIndex] Fetch text by
  14228. * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  14229. * @param {module:echarts/model/Model} [opt.labelDimIndex] Fetch text by
  14230. * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  14231. * @param {Object} [normalSpecified]
  14232. * @param {Object} [emphasisSpecified]
  14233. */
  14234. function setLabelStyle(
  14235. normalStyle, emphasisStyle,
  14236. normalModel, emphasisModel,
  14237. opt,
  14238. normalSpecified, emphasisSpecified
  14239. ) {
  14240. opt = opt || EMPTY_OBJ;
  14241. var labelFetcher = opt.labelFetcher;
  14242. var labelDataIndex = opt.labelDataIndex;
  14243. var labelDimIndex = opt.labelDimIndex;
  14244. // This scenario, `label.normal.show = true; label.emphasis.show = false`,
  14245. // is not supported util someone requests.
  14246. var showNormal = normalModel.getShallow('show');
  14247. var showEmphasis = emphasisModel.getShallow('show');
  14248. // Consider performance, only fetch label when necessary.
  14249. // If `normal.show` is `false` and `emphasis.show` is `true` and `emphasis.formatter` is not set,
  14250. // label should be displayed, where text is fetched by `normal.formatter` or `opt.defaultText`.
  14251. var baseText;
  14252. if (showNormal || showEmphasis) {
  14253. if (labelFetcher) {
  14254. baseText = labelFetcher.getFormattedLabel(labelDataIndex, 'normal', null, labelDimIndex);
  14255. }
  14256. if (baseText == null) {
  14257. baseText = isFunction$1(opt.defaultText) ? opt.defaultText(labelDataIndex, opt) : opt.defaultText;
  14258. }
  14259. }
  14260. var normalStyleText = showNormal ? baseText : null;
  14261. var emphasisStyleText = showEmphasis
  14262. ? retrieve2(
  14263. labelFetcher
  14264. ? labelFetcher.getFormattedLabel(labelDataIndex, 'emphasis', null, labelDimIndex)
  14265. : null,
  14266. baseText
  14267. )
  14268. : null;
  14269. // Optimize: If style.text is null, text will not be drawn.
  14270. if (normalStyleText != null || emphasisStyleText != null) {
  14271. // Always set `textStyle` even if `normalStyle.text` is null, because default
  14272. // values have to be set on `normalStyle`.
  14273. // If we set default values on `emphasisStyle`, consider case:
  14274. // Firstly, `setOption(... label: {normal: {text: null}, emphasis: {show: true}} ...);`
  14275. // Secondly, `setOption(... label: {noraml: {show: true, text: 'abc', color: 'red'} ...);`
  14276. // Then the 'red' will not work on emphasis.
  14277. setTextStyle(normalStyle, normalModel, normalSpecified, opt);
  14278. setTextStyle(emphasisStyle, emphasisModel, emphasisSpecified, opt, true);
  14279. }
  14280. normalStyle.text = normalStyleText;
  14281. emphasisStyle.text = emphasisStyleText;
  14282. }
  14283. /**
  14284. * Set basic textStyle properties.
  14285. * @param {Object|module:zrender/graphic/Style} textStyle
  14286. * @param {module:echarts/model/Model} model
  14287. * @param {Object} [specifiedTextStyle] Can be overrided by settings in model.
  14288. * @param {Object} [opt] See `opt` of `setTextStyleCommon`.
  14289. * @param {boolean} [isEmphasis]
  14290. */
  14291. function setTextStyle(
  14292. textStyle, textStyleModel, specifiedTextStyle, opt, isEmphasis
  14293. ) {
  14294. setTextStyleCommon(textStyle, textStyleModel, opt, isEmphasis);
  14295. specifiedTextStyle && extend(textStyle, specifiedTextStyle);
  14296. textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  14297. return textStyle;
  14298. }
  14299. /**
  14300. * Set text option in the style.
  14301. * @deprecated
  14302. * @param {Object} textStyle
  14303. * @param {module:echarts/model/Model} labelModel
  14304. * @param {string|boolean} defaultColor Default text color.
  14305. * If set as false, it will be processed as a emphasis style.
  14306. */
  14307. function setText(textStyle, labelModel, defaultColor) {
  14308. var opt = {isRectText: true};
  14309. var isEmphasis;
  14310. if (defaultColor === false) {
  14311. isEmphasis = true;
  14312. }
  14313. else {
  14314. // Support setting color as 'auto' to get visual color.
  14315. opt.autoColor = defaultColor;
  14316. }
  14317. setTextStyleCommon(textStyle, labelModel, opt, isEmphasis);
  14318. textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  14319. }
  14320. /**
  14321. * {
  14322. * disableBox: boolean, Whether diable drawing box of block (outer most).
  14323. * isRectText: boolean,
  14324. * autoColor: string, specify a color when color is 'auto',
  14325. * for textFill, textStroke, textBackgroundColor, and textBorderColor.
  14326. * If autoColor specified, it is used as default textFill.
  14327. * useInsideStyle:
  14328. * `true`: Use inside style (textFill, textStroke, textStrokeWidth)
  14329. * if `textFill` is not specified.
  14330. * `false`: Do not use inside style.
  14331. * `null/undefined`: use inside style if `isRectText` is true and
  14332. * `textFill` is not specified and textPosition contains `'inside'`.
  14333. * forceRich: boolean
  14334. * }
  14335. */
  14336. function setTextStyleCommon(textStyle, textStyleModel, opt, isEmphasis) {
  14337. // Consider there will be abnormal when merge hover style to normal style if given default value.
  14338. opt = opt || EMPTY_OBJ;
  14339. if (opt.isRectText) {
  14340. var textPosition = textStyleModel.getShallow('position')
  14341. || (isEmphasis ? null : 'inside');
  14342. // 'outside' is not a valid zr textPostion value, but used
  14343. // in bar series, and magric type should be considered.
  14344. textPosition === 'outside' && (textPosition = 'top');
  14345. textStyle.textPosition = textPosition;
  14346. textStyle.textOffset = textStyleModel.getShallow('offset');
  14347. var labelRotate = textStyleModel.getShallow('rotate');
  14348. labelRotate != null && (labelRotate *= Math.PI / 180);
  14349. textStyle.textRotation = labelRotate;
  14350. textStyle.textDistance = retrieve2(
  14351. textStyleModel.getShallow('distance'), isEmphasis ? null : 5
  14352. );
  14353. }
  14354. var ecModel = textStyleModel.ecModel;
  14355. var globalTextStyle = ecModel && ecModel.option.textStyle;
  14356. // Consider case:
  14357. // {
  14358. // data: [{
  14359. // value: 12,
  14360. // label: {
  14361. // rich: {
  14362. // // no 'a' here but using parent 'a'.
  14363. // }
  14364. // }
  14365. // }],
  14366. // rich: {
  14367. // a: { ... }
  14368. // }
  14369. // }
  14370. var richItemNames = getRichItemNames(textStyleModel);
  14371. var richResult;
  14372. if (richItemNames) {
  14373. richResult = {};
  14374. for (var name in richItemNames) {
  14375. if (richItemNames.hasOwnProperty(name)) {
  14376. // Cascade is supported in rich.
  14377. var richTextStyle = textStyleModel.getModel(['rich', name]);
  14378. // In rich, never `disableBox`.
  14379. setTokenTextStyle(richResult[name] = {}, richTextStyle, globalTextStyle, opt, isEmphasis);
  14380. }
  14381. }
  14382. }
  14383. textStyle.rich = richResult;
  14384. setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isEmphasis, true);
  14385. if (opt.forceRich && !opt.textStyle) {
  14386. opt.textStyle = {};
  14387. }
  14388. return textStyle;
  14389. }
  14390. // Consider case:
  14391. // {
  14392. // data: [{
  14393. // value: 12,
  14394. // label: {
  14395. // rich: {
  14396. // // no 'a' here but using parent 'a'.
  14397. // }
  14398. // }
  14399. // }],
  14400. // rich: {
  14401. // a: { ... }
  14402. // }
  14403. // }
  14404. function getRichItemNames(textStyleModel) {
  14405. // Use object to remove duplicated names.
  14406. var richItemNameMap;
  14407. while (textStyleModel && textStyleModel !== textStyleModel.ecModel) {
  14408. var rich = (textStyleModel.option || EMPTY_OBJ).rich;
  14409. if (rich) {
  14410. richItemNameMap = richItemNameMap || {};
  14411. for (var name in rich) {
  14412. if (rich.hasOwnProperty(name)) {
  14413. richItemNameMap[name] = 1;
  14414. }
  14415. }
  14416. }
  14417. textStyleModel = textStyleModel.parentModel;
  14418. }
  14419. return richItemNameMap;
  14420. }
  14421. function setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isEmphasis, isBlock) {
  14422. // In merge mode, default value should not be given.
  14423. globalTextStyle = !isEmphasis && globalTextStyle || EMPTY_OBJ;
  14424. textStyle.textFill = getAutoColor(textStyleModel.getShallow('color'), opt)
  14425. || globalTextStyle.color;
  14426. textStyle.textStroke = getAutoColor(textStyleModel.getShallow('textBorderColor'), opt)
  14427. || globalTextStyle.textBorderColor;
  14428. textStyle.textStrokeWidth = retrieve2(
  14429. textStyleModel.getShallow('textBorderWidth'),
  14430. globalTextStyle.textBorderWidth
  14431. );
  14432. if (!isEmphasis) {
  14433. if (isBlock) {
  14434. // Always set `insideRollback`, for clearing previous.
  14435. var originalTextPosition = textStyle.textPosition;
  14436. textStyle.insideRollback = applyInsideStyle(textStyle, originalTextPosition, opt);
  14437. // Save original textPosition, because style.textPosition will be repalced by
  14438. // real location (like [10, 30]) in zrender.
  14439. textStyle.insideOriginalTextPosition = originalTextPosition;
  14440. textStyle.insideRollbackOpt = opt;
  14441. }
  14442. // Set default finally.
  14443. if (textStyle.textFill == null) {
  14444. textStyle.textFill = opt.autoColor;
  14445. }
  14446. }
  14447. // Do not use `getFont` here, because merge should be supported, where
  14448. // part of these properties may be changed in emphasis style, and the
  14449. // others should remain their original value got from normal style.
  14450. textStyle.fontStyle = textStyleModel.getShallow('fontStyle') || globalTextStyle.fontStyle;
  14451. textStyle.fontWeight = textStyleModel.getShallow('fontWeight') || globalTextStyle.fontWeight;
  14452. textStyle.fontSize = textStyleModel.getShallow('fontSize') || globalTextStyle.fontSize;
  14453. textStyle.fontFamily = textStyleModel.getShallow('fontFamily') || globalTextStyle.fontFamily;
  14454. textStyle.textAlign = textStyleModel.getShallow('align');
  14455. textStyle.textVerticalAlign = textStyleModel.getShallow('verticalAlign')
  14456. || textStyleModel.getShallow('baseline');
  14457. textStyle.textLineHeight = textStyleModel.getShallow('lineHeight');
  14458. textStyle.textWidth = textStyleModel.getShallow('width');
  14459. textStyle.textHeight = textStyleModel.getShallow('height');
  14460. textStyle.textTag = textStyleModel.getShallow('tag');
  14461. if (!isBlock || !opt.disableBox) {
  14462. textStyle.textBackgroundColor = getAutoColor(textStyleModel.getShallow('backgroundColor'), opt);
  14463. textStyle.textPadding = textStyleModel.getShallow('padding');
  14464. textStyle.textBorderColor = getAutoColor(textStyleModel.getShallow('borderColor'), opt);
  14465. textStyle.textBorderWidth = textStyleModel.getShallow('borderWidth');
  14466. textStyle.textBorderRadius = textStyleModel.getShallow('borderRadius');
  14467. textStyle.textBoxShadowColor = textStyleModel.getShallow('shadowColor');
  14468. textStyle.textBoxShadowBlur = textStyleModel.getShallow('shadowBlur');
  14469. textStyle.textBoxShadowOffsetX = textStyleModel.getShallow('shadowOffsetX');
  14470. textStyle.textBoxShadowOffsetY = textStyleModel.getShallow('shadowOffsetY');
  14471. }
  14472. textStyle.textShadowColor = textStyleModel.getShallow('textShadowColor')
  14473. || globalTextStyle.textShadowColor;
  14474. textStyle.textShadowBlur = textStyleModel.getShallow('textShadowBlur')
  14475. || globalTextStyle.textShadowBlur;
  14476. textStyle.textShadowOffsetX = textStyleModel.getShallow('textShadowOffsetX')
  14477. || globalTextStyle.textShadowOffsetX;
  14478. textStyle.textShadowOffsetY = textStyleModel.getShallow('textShadowOffsetY')
  14479. || globalTextStyle.textShadowOffsetY;
  14480. }
  14481. function getAutoColor(color, opt) {
  14482. return color !== 'auto' ? color : (opt && opt.autoColor) ? opt.autoColor : null;
  14483. }
  14484. function applyInsideStyle(textStyle, textPosition, opt) {
  14485. var useInsideStyle = opt.useInsideStyle;
  14486. var insideRollback;
  14487. if (textStyle.textFill == null
  14488. && useInsideStyle !== false
  14489. && (useInsideStyle === true
  14490. || (opt.isRectText
  14491. && textPosition
  14492. // textPosition can be [10, 30]
  14493. && typeof textPosition === 'string'
  14494. && textPosition.indexOf('inside') >= 0
  14495. )
  14496. )
  14497. ) {
  14498. insideRollback = {
  14499. textFill: null,
  14500. textStroke: textStyle.textStroke,
  14501. textStrokeWidth: textStyle.textStrokeWidth
  14502. };
  14503. textStyle.textFill = '#fff';
  14504. // Consider text with #fff overflow its container.
  14505. if (textStyle.textStroke == null) {
  14506. textStyle.textStroke = opt.autoColor;
  14507. textStyle.textStrokeWidth == null && (textStyle.textStrokeWidth = 2);
  14508. }
  14509. }
  14510. return insideRollback;
  14511. }
  14512. function rollbackInsideStyle(style) {
  14513. var insideRollback = style.insideRollback;
  14514. if (insideRollback) {
  14515. style.textFill = insideRollback.textFill;
  14516. style.textStroke = insideRollback.textStroke;
  14517. style.textStrokeWidth = insideRollback.textStrokeWidth;
  14518. }
  14519. }
  14520. function getFont(opt, ecModel) {
  14521. // ecModel or default text style model.
  14522. var gTextStyleModel = ecModel || ecModel.getModel('textStyle');
  14523. return trim([
  14524. // FIXME in node-canvas fontWeight is before fontStyle
  14525. opt.fontStyle || gTextStyleModel && gTextStyleModel.getShallow('fontStyle') || '',
  14526. opt.fontWeight || gTextStyleModel && gTextStyleModel.getShallow('fontWeight') || '',
  14527. (opt.fontSize || gTextStyleModel && gTextStyleModel.getShallow('fontSize') || 12) + 'px',
  14528. opt.fontFamily || gTextStyleModel && gTextStyleModel.getShallow('fontFamily') || 'sans-serif'
  14529. ].join(' '));
  14530. }
  14531. function animateOrSetProps(isUpdate, el, props, animatableModel, dataIndex, cb) {
  14532. if (typeof dataIndex === 'function') {
  14533. cb = dataIndex;
  14534. dataIndex = null;
  14535. }
  14536. // Do not check 'animation' property directly here. Consider this case:
  14537. // animation model is an `itemModel`, whose does not have `isAnimationEnabled`
  14538. // but its parent model (`seriesModel`) does.
  14539. var animationEnabled = animatableModel && animatableModel.isAnimationEnabled();
  14540. if (animationEnabled) {
  14541. var postfix = isUpdate ? 'Update' : '';
  14542. var duration = animatableModel.getShallow('animationDuration' + postfix);
  14543. var animationEasing = animatableModel.getShallow('animationEasing' + postfix);
  14544. var animationDelay = animatableModel.getShallow('animationDelay' + postfix);
  14545. if (typeof animationDelay === 'function') {
  14546. animationDelay = animationDelay(
  14547. dataIndex,
  14548. animatableModel.getAnimationDelayParams
  14549. ? animatableModel.getAnimationDelayParams(el, dataIndex)
  14550. : null
  14551. );
  14552. }
  14553. if (typeof duration === 'function') {
  14554. duration = duration(dataIndex);
  14555. }
  14556. duration > 0
  14557. ? el.animateTo(props, duration, animationDelay || 0, animationEasing, cb, !!cb)
  14558. : (el.stopAnimation(), el.attr(props), cb && cb());
  14559. }
  14560. else {
  14561. el.stopAnimation();
  14562. el.attr(props);
  14563. cb && cb();
  14564. }
  14565. }
  14566. /**
  14567. * Update graphic element properties with or without animation according to the
  14568. * configuration in series.
  14569. *
  14570. * Caution: this method will stop previous animation.
  14571. * So if do not use this method to one element twice before
  14572. * animation starts, unless you know what you are doing.
  14573. *
  14574. * @param {module:zrender/Element} el
  14575. * @param {Object} props
  14576. * @param {module:echarts/model/Model} [animatableModel]
  14577. * @param {number} [dataIndex]
  14578. * @param {Function} [cb]
  14579. * @example
  14580. * graphic.updateProps(el, {
  14581. * position: [100, 100]
  14582. * }, seriesModel, dataIndex, function () { console.log('Animation done!'); });
  14583. * // Or
  14584. * graphic.updateProps(el, {
  14585. * position: [100, 100]
  14586. * }, seriesModel, function () { console.log('Animation done!'); });
  14587. */
  14588. function updateProps(el, props, animatableModel, dataIndex, cb) {
  14589. animateOrSetProps(true, el, props, animatableModel, dataIndex, cb);
  14590. }
  14591. /**
  14592. * Init graphic element properties with or without animation according to the
  14593. * configuration in series.
  14594. *
  14595. * Caution: this method will stop previous animation.
  14596. * So if do not use this method to one element twice before
  14597. * animation starts, unless you know what you are doing.
  14598. *
  14599. * @param {module:zrender/Element} el
  14600. * @param {Object} props
  14601. * @param {module:echarts/model/Model} [animatableModel]
  14602. * @param {number} [dataIndex]
  14603. * @param {Function} cb
  14604. */
  14605. function initProps(el, props, animatableModel, dataIndex, cb) {
  14606. animateOrSetProps(false, el, props, animatableModel, dataIndex, cb);
  14607. }
  14608. /**
  14609. * Get transform matrix of target (param target),
  14610. * in coordinate of its ancestor (param ancestor)
  14611. *
  14612. * @param {module:zrender/mixin/Transformable} target
  14613. * @param {module:zrender/mixin/Transformable} [ancestor]
  14614. */
  14615. function getTransform(target, ancestor) {
  14616. var mat = identity([]);
  14617. while (target && target !== ancestor) {
  14618. mul$1(mat, target.getLocalTransform(), mat);
  14619. target = target.parent;
  14620. }
  14621. return mat;
  14622. }
  14623. /**
  14624. * Apply transform to an vertex.
  14625. * @param {Array.<number>} target [x, y]
  14626. * @param {Array.<number>|TypedArray.<number>|Object} transform Can be:
  14627. * + Transform matrix: like [1, 0, 0, 1, 0, 0]
  14628. * + {position, rotation, scale}, the same as `zrender/Transformable`.
  14629. * @param {boolean=} invert Whether use invert matrix.
  14630. * @return {Array.<number>} [x, y]
  14631. */
  14632. function applyTransform$1(target, transform, invert$$1) {
  14633. if (transform && !isArrayLike(transform)) {
  14634. transform = Transformable.getLocalTransform(transform);
  14635. }
  14636. if (invert$$1) {
  14637. transform = invert([], transform);
  14638. }
  14639. return applyTransform([], target, transform);
  14640. }
  14641. /**
  14642. * @param {string} direction 'left' 'right' 'top' 'bottom'
  14643. * @param {Array.<number>} transform Transform matrix: like [1, 0, 0, 1, 0, 0]
  14644. * @param {boolean=} invert Whether use invert matrix.
  14645. * @return {string} Transformed direction. 'left' 'right' 'top' 'bottom'
  14646. */
  14647. function transformDirection(direction, transform, invert$$1) {
  14648. // Pick a base, ensure that transform result will not be (0, 0).
  14649. var hBase = (transform[4] === 0 || transform[5] === 0 || transform[0] === 0)
  14650. ? 1 : Math.abs(2 * transform[4] / transform[0]);
  14651. var vBase = (transform[4] === 0 || transform[5] === 0 || transform[2] === 0)
  14652. ? 1 : Math.abs(2 * transform[4] / transform[2]);
  14653. var vertex = [
  14654. direction === 'left' ? -hBase : direction === 'right' ? hBase : 0,
  14655. direction === 'top' ? -vBase : direction === 'bottom' ? vBase : 0
  14656. ];
  14657. vertex = applyTransform$1(vertex, transform, invert$$1);
  14658. return Math.abs(vertex[0]) > Math.abs(vertex[1])
  14659. ? (vertex[0] > 0 ? 'right' : 'left')
  14660. : (vertex[1] > 0 ? 'bottom' : 'top');
  14661. }
  14662. /**
  14663. * Apply group transition animation from g1 to g2.
  14664. * If no animatableModel, no animation.
  14665. */
  14666. function groupTransition(g1, g2, animatableModel, cb) {
  14667. if (!g1 || !g2) {
  14668. return;
  14669. }
  14670. function getElMap(g) {
  14671. var elMap = {};
  14672. g.traverse(function (el) {
  14673. if (!el.isGroup && el.anid) {
  14674. elMap[el.anid] = el;
  14675. }
  14676. });
  14677. return elMap;
  14678. }
  14679. function getAnimatableProps(el) {
  14680. var obj = {
  14681. position: clone$1(el.position),
  14682. rotation: el.rotation
  14683. };
  14684. if (el.shape) {
  14685. obj.shape = extend({}, el.shape);
  14686. }
  14687. return obj;
  14688. }
  14689. var elMap1 = getElMap(g1);
  14690. g2.traverse(function (el) {
  14691. if (!el.isGroup && el.anid) {
  14692. var oldEl = elMap1[el.anid];
  14693. if (oldEl) {
  14694. var newProp = getAnimatableProps(el);
  14695. el.attr(getAnimatableProps(oldEl));
  14696. updateProps(el, newProp, animatableModel, el.dataIndex);
  14697. }
  14698. // else {
  14699. // if (el.previousProps) {
  14700. // graphic.updateProps
  14701. // }
  14702. // }
  14703. }
  14704. });
  14705. }
  14706. /**
  14707. * @param {Array.<Array.<number>>} points Like: [[23, 44], [53, 66], ...]
  14708. * @param {Object} rect {x, y, width, height}
  14709. * @return {Array.<Array.<number>>} A new clipped points.
  14710. */
  14711. function clipPointsByRect(points, rect) {
  14712. return map(points, function (point) {
  14713. var x = point[0];
  14714. x = mathMax$1(x, rect.x);
  14715. x = mathMin$1(x, rect.x + rect.width);
  14716. var y = point[1];
  14717. y = mathMax$1(y, rect.y);
  14718. y = mathMin$1(y, rect.y + rect.height);
  14719. return [x, y];
  14720. });
  14721. }
  14722. /**
  14723. * @param {Object} targetRect {x, y, width, height}
  14724. * @param {Object} rect {x, y, width, height}
  14725. * @return {Object} A new clipped rect. If rect size are negative, return undefined.
  14726. */
  14727. function clipRectByRect(targetRect, rect) {
  14728. var x = mathMax$1(targetRect.x, rect.x);
  14729. var x2 = mathMin$1(targetRect.x + targetRect.width, rect.x + rect.width);
  14730. var y = mathMax$1(targetRect.y, rect.y);
  14731. var y2 = mathMin$1(targetRect.y + targetRect.height, rect.y + rect.height);
  14732. if (x2 >= x && y2 >= y) {
  14733. return {
  14734. x: x,
  14735. y: y,
  14736. width: x2 - x,
  14737. height: y2 - y
  14738. };
  14739. }
  14740. }
  14741. /**
  14742. * @param {string} iconStr Support 'image://' or 'path://' or direct svg path.
  14743. * @param {Object} [opt] Properties of `module:zrender/Element`, except `style`.
  14744. * @param {Object} [rect] {x, y, width, height}
  14745. * @return {module:zrender/Element} Icon path or image element.
  14746. */
  14747. function createIcon(iconStr, opt, rect) {
  14748. opt = extend({rectHover: true}, opt);
  14749. var style = opt.style = {strokeNoScale: true};
  14750. rect = rect || {x: -1, y: -1, width: 2, height: 2};
  14751. if (iconStr) {
  14752. return iconStr.indexOf('image://') === 0
  14753. ? (
  14754. style.image = iconStr.slice(8),
  14755. defaults(style, rect),
  14756. new ZImage(opt)
  14757. )
  14758. : (
  14759. makePath(
  14760. iconStr.replace('path://', ''),
  14761. opt,
  14762. rect,
  14763. 'center'
  14764. )
  14765. );
  14766. }
  14767. }
  14768. var graphic = (Object.freeze || Object)({
  14769. extendShape: extendShape,
  14770. extendPath: extendPath,
  14771. makePath: makePath,
  14772. makeImage: makeImage,
  14773. mergePath: mergePath,
  14774. resizePath: resizePath,
  14775. subPixelOptimizeLine: subPixelOptimizeLine,
  14776. subPixelOptimizeRect: subPixelOptimizeRect,
  14777. subPixelOptimize: subPixelOptimize,
  14778. setHoverStyle: setHoverStyle,
  14779. setLabelStyle: setLabelStyle,
  14780. setTextStyle: setTextStyle,
  14781. setText: setText,
  14782. getFont: getFont,
  14783. updateProps: updateProps,
  14784. initProps: initProps,
  14785. getTransform: getTransform,
  14786. applyTransform: applyTransform$1,
  14787. transformDirection: transformDirection,
  14788. groupTransition: groupTransition,
  14789. clipPointsByRect: clipPointsByRect,
  14790. clipRectByRect: clipRectByRect,
  14791. createIcon: createIcon,
  14792. Group: Group,
  14793. Image: ZImage,
  14794. Text: Text,
  14795. Circle: Circle,
  14796. Sector: Sector,
  14797. Ring: Ring,
  14798. Polygon: Polygon,
  14799. Polyline: Polyline,
  14800. Rect: Rect,
  14801. Line: Line,
  14802. BezierCurve: BezierCurve,
  14803. Arc: Arc,
  14804. IncrementalDisplayable: IncrementalDisplayble,
  14805. CompoundPath: CompoundPath,
  14806. LinearGradient: LinearGradient,
  14807. RadialGradient: RadialGradient,
  14808. BoundingRect: BoundingRect
  14809. });
  14810. /*
  14811. * Licensed to the Apache Software Foundation (ASF) under one
  14812. * or more contributor license agreements. See the NOTICE file
  14813. * distributed with this work for additional information
  14814. * regarding copyright ownership. The ASF licenses this file
  14815. * to you under the Apache License, Version 2.0 (the
  14816. * "License"); you may not use this file except in compliance
  14817. * with the License. You may obtain a copy of the License at
  14818. *
  14819. * http://www.apache.org/licenses/LICENSE-2.0
  14820. *
  14821. * Unless required by applicable law or agreed to in writing,
  14822. * software distributed under the License is distributed on an
  14823. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14824. * KIND, either express or implied. See the License for the
  14825. * specific language governing permissions and limitations
  14826. * under the License.
  14827. */
  14828. var PATH_COLOR = ['textStyle', 'color'];
  14829. var textStyleMixin = {
  14830. /**
  14831. * Get color property or get color from option.textStyle.color
  14832. * @param {boolean} [isEmphasis]
  14833. * @return {string}
  14834. */
  14835. getTextColor: function (isEmphasis) {
  14836. var ecModel = this.ecModel;
  14837. return this.getShallow('color')
  14838. || (
  14839. (!isEmphasis && ecModel) ? ecModel.get(PATH_COLOR) : null
  14840. );
  14841. },
  14842. /**
  14843. * Create font string from fontStyle, fontWeight, fontSize, fontFamily
  14844. * @return {string}
  14845. */
  14846. getFont: function () {
  14847. return getFont({
  14848. fontStyle: this.getShallow('fontStyle'),
  14849. fontWeight: this.getShallow('fontWeight'),
  14850. fontSize: this.getShallow('fontSize'),
  14851. fontFamily: this.getShallow('fontFamily')
  14852. }, this.ecModel);
  14853. },
  14854. getTextRect: function (text) {
  14855. return getBoundingRect(
  14856. text,
  14857. this.getFont(),
  14858. this.getShallow('align'),
  14859. this.getShallow('verticalAlign') || this.getShallow('baseline'),
  14860. this.getShallow('padding'),
  14861. this.getShallow('rich'),
  14862. this.getShallow('truncateText')
  14863. );
  14864. }
  14865. };
  14866. /*
  14867. * Licensed to the Apache Software Foundation (ASF) under one
  14868. * or more contributor license agreements. See the NOTICE file
  14869. * distributed with this work for additional information
  14870. * regarding copyright ownership. The ASF licenses this file
  14871. * to you under the Apache License, Version 2.0 (the
  14872. * "License"); you may not use this file except in compliance
  14873. * with the License. You may obtain a copy of the License at
  14874. *
  14875. * http://www.apache.org/licenses/LICENSE-2.0
  14876. *
  14877. * Unless required by applicable law or agreed to in writing,
  14878. * software distributed under the License is distributed on an
  14879. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14880. * KIND, either express or implied. See the License for the
  14881. * specific language governing permissions and limitations
  14882. * under the License.
  14883. */
  14884. var getItemStyle = makeStyleMapper(
  14885. [
  14886. ['fill', 'color'],
  14887. ['stroke', 'borderColor'],
  14888. ['lineWidth', 'borderWidth'],
  14889. ['opacity'],
  14890. ['shadowBlur'],
  14891. ['shadowOffsetX'],
  14892. ['shadowOffsetY'],
  14893. ['shadowColor'],
  14894. ['textPosition'],
  14895. ['textAlign']
  14896. ]
  14897. );
  14898. var itemStyleMixin = {
  14899. getItemStyle: function (excludes, includes) {
  14900. var style = getItemStyle(this, excludes, includes);
  14901. var lineDash = this.getBorderLineDash();
  14902. lineDash && (style.lineDash = lineDash);
  14903. return style;
  14904. },
  14905. getBorderLineDash: function () {
  14906. var lineType = this.get('borderType');
  14907. return (lineType === 'solid' || lineType == null) ? null
  14908. : (lineType === 'dashed' ? [5, 5] : [1, 1]);
  14909. }
  14910. };
  14911. /*
  14912. * Licensed to the Apache Software Foundation (ASF) under one
  14913. * or more contributor license agreements. See the NOTICE file
  14914. * distributed with this work for additional information
  14915. * regarding copyright ownership. The ASF licenses this file
  14916. * to you under the Apache License, Version 2.0 (the
  14917. * "License"); you may not use this file except in compliance
  14918. * with the License. You may obtain a copy of the License at
  14919. *
  14920. * http://www.apache.org/licenses/LICENSE-2.0
  14921. *
  14922. * Unless required by applicable law or agreed to in writing,
  14923. * software distributed under the License is distributed on an
  14924. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14925. * KIND, either express or implied. See the License for the
  14926. * specific language governing permissions and limitations
  14927. * under the License.
  14928. */
  14929. /**
  14930. * @module echarts/model/Model
  14931. */
  14932. var mixin$1 = mixin;
  14933. var inner = makeInner();
  14934. /**
  14935. * @alias module:echarts/model/Model
  14936. * @constructor
  14937. * @param {Object} option
  14938. * @param {module:echarts/model/Model} [parentModel]
  14939. * @param {module:echarts/model/Global} [ecModel]
  14940. */
  14941. function Model(option, parentModel, ecModel) {
  14942. /**
  14943. * @type {module:echarts/model/Model}
  14944. * @readOnly
  14945. */
  14946. this.parentModel = parentModel;
  14947. /**
  14948. * @type {module:echarts/model/Global}
  14949. * @readOnly
  14950. */
  14951. this.ecModel = ecModel;
  14952. /**
  14953. * @type {Object}
  14954. * @protected
  14955. */
  14956. this.option = option;
  14957. // Simple optimization
  14958. // if (this.init) {
  14959. // if (arguments.length <= 4) {
  14960. // this.init(option, parentModel, ecModel, extraOpt);
  14961. // }
  14962. // else {
  14963. // this.init.apply(this, arguments);
  14964. // }
  14965. // }
  14966. }
  14967. Model.prototype = {
  14968. constructor: Model,
  14969. /**
  14970. * Model 的初始化函数
  14971. * @param {Object} option
  14972. */
  14973. init: null,
  14974. /**
  14975. * 从新的 Option merge
  14976. */
  14977. mergeOption: function (option) {
  14978. merge(this.option, option, true);
  14979. },
  14980. /**
  14981. * @param {string|Array.<string>} path
  14982. * @param {boolean} [ignoreParent=false]
  14983. * @return {*}
  14984. */
  14985. get: function (path, ignoreParent) {
  14986. if (path == null) {
  14987. return this.option;
  14988. }
  14989. return doGet(
  14990. this.option,
  14991. this.parsePath(path),
  14992. !ignoreParent && getParent(this, path)
  14993. );
  14994. },
  14995. /**
  14996. * @param {string} key
  14997. * @param {boolean} [ignoreParent=false]
  14998. * @return {*}
  14999. */
  15000. getShallow: function (key, ignoreParent) {
  15001. var option = this.option;
  15002. var val = option == null ? option : option[key];
  15003. var parentModel = !ignoreParent && getParent(this, key);
  15004. if (val == null && parentModel) {
  15005. val = parentModel.getShallow(key);
  15006. }
  15007. return val;
  15008. },
  15009. /**
  15010. * @param {string|Array.<string>} [path]
  15011. * @param {module:echarts/model/Model} [parentModel]
  15012. * @return {module:echarts/model/Model}
  15013. */
  15014. getModel: function (path, parentModel) {
  15015. var obj = path == null
  15016. ? this.option
  15017. : doGet(this.option, path = this.parsePath(path));
  15018. var thisParentModel;
  15019. parentModel = parentModel || (
  15020. (thisParentModel = getParent(this, path))
  15021. && thisParentModel.getModel(path)
  15022. );
  15023. return new Model(obj, parentModel, this.ecModel);
  15024. },
  15025. /**
  15026. * If model has option
  15027. */
  15028. isEmpty: function () {
  15029. return this.option == null;
  15030. },
  15031. restoreData: function () {},
  15032. // Pending
  15033. clone: function () {
  15034. var Ctor = this.constructor;
  15035. return new Ctor(clone(this.option));
  15036. },
  15037. setReadOnly: function (properties) {
  15038. // clazzUtil.setReadOnly(this, properties);
  15039. },
  15040. // If path is null/undefined, return null/undefined.
  15041. parsePath: function(path) {
  15042. if (typeof path === 'string') {
  15043. path = path.split('.');
  15044. }
  15045. return path;
  15046. },
  15047. /**
  15048. * @param {Function} getParentMethod
  15049. * param {Array.<string>|string} path
  15050. * return {module:echarts/model/Model}
  15051. */
  15052. customizeGetParent: function (getParentMethod) {
  15053. inner(this).getParent = getParentMethod;
  15054. },
  15055. isAnimationEnabled: function () {
  15056. if (!env$1.node) {
  15057. if (this.option.animation != null) {
  15058. return !!this.option.animation;
  15059. }
  15060. else if (this.parentModel) {
  15061. return this.parentModel.isAnimationEnabled();
  15062. }
  15063. }
  15064. }
  15065. };
  15066. function doGet(obj, pathArr, parentModel) {
  15067. for (var i = 0; i < pathArr.length; i++) {
  15068. // Ignore empty
  15069. if (!pathArr[i]) {
  15070. continue;
  15071. }
  15072. // obj could be number/string/... (like 0)
  15073. obj = (obj && typeof obj === 'object') ? obj[pathArr[i]] : null;
  15074. if (obj == null) {
  15075. break;
  15076. }
  15077. }
  15078. if (obj == null && parentModel) {
  15079. obj = parentModel.get(pathArr);
  15080. }
  15081. return obj;
  15082. }
  15083. // `path` can be null/undefined
  15084. function getParent(model, path) {
  15085. var getParentMethod = inner(model).getParent;
  15086. return getParentMethod ? getParentMethod.call(model, path) : model.parentModel;
  15087. }
  15088. // Enable Model.extend.
  15089. enableClassExtend(Model);
  15090. enableClassCheck(Model);
  15091. mixin$1(Model, lineStyleMixin);
  15092. mixin$1(Model, areaStyleMixin);
  15093. mixin$1(Model, textStyleMixin);
  15094. mixin$1(Model, itemStyleMixin);
  15095. /*
  15096. * Licensed to the Apache Software Foundation (ASF) under one
  15097. * or more contributor license agreements. See the NOTICE file
  15098. * distributed with this work for additional information
  15099. * regarding copyright ownership. The ASF licenses this file
  15100. * to you under the Apache License, Version 2.0 (the
  15101. * "License"); you may not use this file except in compliance
  15102. * with the License. You may obtain a copy of the License at
  15103. *
  15104. * http://www.apache.org/licenses/LICENSE-2.0
  15105. *
  15106. * Unless required by applicable law or agreed to in writing,
  15107. * software distributed under the License is distributed on an
  15108. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15109. * KIND, either express or implied. See the License for the
  15110. * specific language governing permissions and limitations
  15111. * under the License.
  15112. */
  15113. var base = 0;
  15114. /**
  15115. * @public
  15116. * @param {string} type
  15117. * @return {string}
  15118. */
  15119. function getUID(type) {
  15120. // Considering the case of crossing js context,
  15121. // use Math.random to make id as unique as possible.
  15122. return [(type || ''), base++, Math.random().toFixed(5)].join('_');
  15123. }
  15124. /**
  15125. * @inner
  15126. */
  15127. function enableSubTypeDefaulter(entity) {
  15128. var subTypeDefaulters = {};
  15129. entity.registerSubTypeDefaulter = function (componentType, defaulter) {
  15130. componentType = parseClassType$1(componentType);
  15131. subTypeDefaulters[componentType.main] = defaulter;
  15132. };
  15133. entity.determineSubType = function (componentType, option) {
  15134. var type = option.type;
  15135. if (!type) {
  15136. var componentTypeMain = parseClassType$1(componentType).main;
  15137. if (entity.hasSubTypes(componentType) && subTypeDefaulters[componentTypeMain]) {
  15138. type = subTypeDefaulters[componentTypeMain](option);
  15139. }
  15140. }
  15141. return type;
  15142. };
  15143. return entity;
  15144. }
  15145. /**
  15146. * Topological travel on Activity Network (Activity On Vertices).
  15147. * Dependencies is defined in Model.prototype.dependencies, like ['xAxis', 'yAxis'].
  15148. *
  15149. * If 'xAxis' or 'yAxis' is absent in componentTypeList, just ignore it in topology.
  15150. *
  15151. * If there is circle dependencey, Error will be thrown.
  15152. *
  15153. */
  15154. function enableTopologicalTravel(entity, dependencyGetter) {
  15155. /**
  15156. * @public
  15157. * @param {Array.<string>} targetNameList Target Component type list.
  15158. * Can be ['aa', 'bb', 'aa.xx']
  15159. * @param {Array.<string>} fullNameList By which we can build dependency graph.
  15160. * @param {Function} callback Params: componentType, dependencies.
  15161. * @param {Object} context Scope of callback.
  15162. */
  15163. entity.topologicalTravel = function (targetNameList, fullNameList, callback, context) {
  15164. if (!targetNameList.length) {
  15165. return;
  15166. }
  15167. var result = makeDepndencyGraph(fullNameList);
  15168. var graph = result.graph;
  15169. var stack = result.noEntryList;
  15170. var targetNameSet = {};
  15171. each$1(targetNameList, function (name) {
  15172. targetNameSet[name] = true;
  15173. });
  15174. while (stack.length) {
  15175. var currComponentType = stack.pop();
  15176. var currVertex = graph[currComponentType];
  15177. var isInTargetNameSet = !!targetNameSet[currComponentType];
  15178. if (isInTargetNameSet) {
  15179. callback.call(context, currComponentType, currVertex.originalDeps.slice());
  15180. delete targetNameSet[currComponentType];
  15181. }
  15182. each$1(
  15183. currVertex.successor,
  15184. isInTargetNameSet ? removeEdgeAndAdd : removeEdge
  15185. );
  15186. }
  15187. each$1(targetNameSet, function () {
  15188. throw new Error('Circle dependency may exists');
  15189. });
  15190. function removeEdge(succComponentType) {
  15191. graph[succComponentType].entryCount--;
  15192. if (graph[succComponentType].entryCount === 0) {
  15193. stack.push(succComponentType);
  15194. }
  15195. }
  15196. // Consider this case: legend depends on series, and we call
  15197. // chart.setOption({series: [...]}), where only series is in option.
  15198. // If we do not have 'removeEdgeAndAdd', legendModel.mergeOption will
  15199. // not be called, but only sereis.mergeOption is called. Thus legend
  15200. // have no chance to update its local record about series (like which
  15201. // name of series is available in legend).
  15202. function removeEdgeAndAdd(succComponentType) {
  15203. targetNameSet[succComponentType] = true;
  15204. removeEdge(succComponentType);
  15205. }
  15206. };
  15207. /**
  15208. * DepndencyGraph: {Object}
  15209. * key: conponentType,
  15210. * value: {
  15211. * successor: [conponentTypes...],
  15212. * originalDeps: [conponentTypes...],
  15213. * entryCount: {number}
  15214. * }
  15215. */
  15216. function makeDepndencyGraph(fullNameList) {
  15217. var graph = {};
  15218. var noEntryList = [];
  15219. each$1(fullNameList, function (name) {
  15220. var thisItem = createDependencyGraphItem(graph, name);
  15221. var originalDeps = thisItem.originalDeps = dependencyGetter(name);
  15222. var availableDeps = getAvailableDependencies(originalDeps, fullNameList);
  15223. thisItem.entryCount = availableDeps.length;
  15224. if (thisItem.entryCount === 0) {
  15225. noEntryList.push(name);
  15226. }
  15227. each$1(availableDeps, function (dependentName) {
  15228. if (indexOf(thisItem.predecessor, dependentName) < 0) {
  15229. thisItem.predecessor.push(dependentName);
  15230. }
  15231. var thatItem = createDependencyGraphItem(graph, dependentName);
  15232. if (indexOf(thatItem.successor, dependentName) < 0) {
  15233. thatItem.successor.push(name);
  15234. }
  15235. });
  15236. });
  15237. return {graph: graph, noEntryList: noEntryList};
  15238. }
  15239. function createDependencyGraphItem(graph, name) {
  15240. if (!graph[name]) {
  15241. graph[name] = {predecessor: [], successor: []};
  15242. }
  15243. return graph[name];
  15244. }
  15245. function getAvailableDependencies(originalDeps, fullNameList) {
  15246. var availableDeps = [];
  15247. each$1(originalDeps, function (dep) {
  15248. indexOf(fullNameList, dep) >= 0 && availableDeps.push(dep);
  15249. });
  15250. return availableDeps;
  15251. }
  15252. }
  15253. /*
  15254. * Licensed to the Apache Software Foundation (ASF) under one
  15255. * or more contributor license agreements. See the NOTICE file
  15256. * distributed with this work for additional information
  15257. * regarding copyright ownership. The ASF licenses this file
  15258. * to you under the Apache License, Version 2.0 (the
  15259. * "License"); you may not use this file except in compliance
  15260. * with the License. You may obtain a copy of the License at
  15261. *
  15262. * http://www.apache.org/licenses/LICENSE-2.0
  15263. *
  15264. * Unless required by applicable law or agreed to in writing,
  15265. * software distributed under the License is distributed on an
  15266. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15267. * KIND, either express or implied. See the License for the
  15268. * specific language governing permissions and limitations
  15269. * under the License.
  15270. */
  15271. var RADIAN_EPSILON = 1e-4;
  15272. function _trim(str) {
  15273. return str.replace(/^\s+/, '').replace(/\s+$/, '');
  15274. }
  15275. /**
  15276. * Linear mapping a value from domain to range
  15277. * @memberOf module:echarts/util/number
  15278. * @param {(number|Array.<number>)} val
  15279. * @param {Array.<number>} domain Domain extent domain[0] can be bigger than domain[1]
  15280. * @param {Array.<number>} range Range extent range[0] can be bigger than range[1]
  15281. * @param {boolean} clamp
  15282. * @return {(number|Array.<number>}
  15283. */
  15284. function linearMap(val, domain, range, clamp) {
  15285. var subDomain = domain[1] - domain[0];
  15286. var subRange = range[1] - range[0];
  15287. if (subDomain === 0) {
  15288. return subRange === 0
  15289. ? range[0]
  15290. : (range[0] + range[1]) / 2;
  15291. }
  15292. // Avoid accuracy problem in edge, such as
  15293. // 146.39 - 62.83 === 83.55999999999999.
  15294. // See echarts/test/ut/spec/util/number.js#linearMap#accuracyError
  15295. // It is a little verbose for efficiency considering this method
  15296. // is a hotspot.
  15297. if (clamp) {
  15298. if (subDomain > 0) {
  15299. if (val <= domain[0]) {
  15300. return range[0];
  15301. }
  15302. else if (val >= domain[1]) {
  15303. return range[1];
  15304. }
  15305. }
  15306. else {
  15307. if (val >= domain[0]) {
  15308. return range[0];
  15309. }
  15310. else if (val <= domain[1]) {
  15311. return range[1];
  15312. }
  15313. }
  15314. }
  15315. else {
  15316. if (val === domain[0]) {
  15317. return range[0];
  15318. }
  15319. if (val === domain[1]) {
  15320. return range[1];
  15321. }
  15322. }
  15323. return (val - domain[0]) / subDomain * subRange + range[0];
  15324. }
  15325. /**
  15326. * Convert a percent string to absolute number.
  15327. * Returns NaN if percent is not a valid string or number
  15328. * @memberOf module:echarts/util/number
  15329. * @param {string|number} percent
  15330. * @param {number} all
  15331. * @return {number}
  15332. */
  15333. function parsePercent$1(percent, all) {
  15334. switch (percent) {
  15335. case 'center':
  15336. case 'middle':
  15337. percent = '50%';
  15338. break;
  15339. case 'left':
  15340. case 'top':
  15341. percent = '0%';
  15342. break;
  15343. case 'right':
  15344. case 'bottom':
  15345. percent = '100%';
  15346. break;
  15347. }
  15348. if (typeof percent === 'string') {
  15349. if (_trim(percent).match(/%$/)) {
  15350. return parseFloat(percent) / 100 * all;
  15351. }
  15352. return parseFloat(percent);
  15353. }
  15354. return percent == null ? NaN : +percent;
  15355. }
  15356. /**
  15357. * (1) Fix rounding error of float numbers.
  15358. * (2) Support return string to avoid scientific notation like '3.5e-7'.
  15359. *
  15360. * @param {number} x
  15361. * @param {number} [precision]
  15362. * @param {boolean} [returnStr]
  15363. * @return {number|string}
  15364. */
  15365. function round$1(x, precision, returnStr) {
  15366. if (precision == null) {
  15367. precision = 10;
  15368. }
  15369. // Avoid range error
  15370. precision = Math.min(Math.max(0, precision), 20);
  15371. x = (+x).toFixed(precision);
  15372. return returnStr ? x : +x;
  15373. }
  15374. function asc(arr) {
  15375. arr.sort(function (a, b) {
  15376. return a - b;
  15377. });
  15378. return arr;
  15379. }
  15380. /**
  15381. * Get precision
  15382. * @param {number} val
  15383. */
  15384. function getPrecision(val) {
  15385. val = +val;
  15386. if (isNaN(val)) {
  15387. return 0;
  15388. }
  15389. // It is much faster than methods converting number to string as follows
  15390. // var tmp = val.toString();
  15391. // return tmp.length - 1 - tmp.indexOf('.');
  15392. // especially when precision is low
  15393. var e = 1;
  15394. var count = 0;
  15395. while (Math.round(val * e) / e !== val) {
  15396. e *= 10;
  15397. count++;
  15398. }
  15399. return count;
  15400. }
  15401. /**
  15402. * @param {string|number} val
  15403. * @return {number}
  15404. */
  15405. function getPrecisionSafe(val) {
  15406. var str = val.toString();
  15407. // Consider scientific notation: '3.4e-12' '3.4e+12'
  15408. var eIndex = str.indexOf('e');
  15409. if (eIndex > 0) {
  15410. var precision = +str.slice(eIndex + 1);
  15411. return precision < 0 ? -precision : 0;
  15412. }
  15413. else {
  15414. var dotIndex = str.indexOf('.');
  15415. return dotIndex < 0 ? 0 : str.length - 1 - dotIndex;
  15416. }
  15417. }
  15418. /**
  15419. * Minimal dicernible data precisioin according to a single pixel.
  15420. *
  15421. * @param {Array.<number>} dataExtent
  15422. * @param {Array.<number>} pixelExtent
  15423. * @return {number} precision
  15424. */
  15425. function getPixelPrecision(dataExtent, pixelExtent) {
  15426. var log = Math.log;
  15427. var LN10 = Math.LN10;
  15428. var dataQuantity = Math.floor(log(dataExtent[1] - dataExtent[0]) / LN10);
  15429. var sizeQuantity = Math.round(log(Math.abs(pixelExtent[1] - pixelExtent[0])) / LN10);
  15430. // toFixed() digits argument must be between 0 and 20.
  15431. var precision = Math.min(Math.max(-dataQuantity + sizeQuantity, 0), 20);
  15432. return !isFinite(precision) ? 20 : precision;
  15433. }
  15434. /**
  15435. * Get a data of given precision, assuring the sum of percentages
  15436. * in valueList is 1.
  15437. * The largest remainer method is used.
  15438. * https://en.wikipedia.org/wiki/Largest_remainder_method
  15439. *
  15440. * @param {Array.<number>} valueList a list of all data
  15441. * @param {number} idx index of the data to be processed in valueList
  15442. * @param {number} precision integer number showing digits of precision
  15443. * @return {number} percent ranging from 0 to 100
  15444. */
  15445. function getPercentWithPrecision(valueList, idx, precision) {
  15446. if (!valueList[idx]) {
  15447. return 0;
  15448. }
  15449. var sum = reduce(valueList, function (acc, val) {
  15450. return acc + (isNaN(val) ? 0 : val);
  15451. }, 0);
  15452. if (sum === 0) {
  15453. return 0;
  15454. }
  15455. var digits = Math.pow(10, precision);
  15456. var votesPerQuota = map(valueList, function (val) {
  15457. return (isNaN(val) ? 0 : val) / sum * digits * 100;
  15458. });
  15459. var targetSeats = digits * 100;
  15460. var seats = map(votesPerQuota, function (votes) {
  15461. // Assign automatic seats.
  15462. return Math.floor(votes);
  15463. });
  15464. var currentSum = reduce(seats, function (acc, val) {
  15465. return acc + val;
  15466. }, 0);
  15467. var remainder = map(votesPerQuota, function (votes, idx) {
  15468. return votes - seats[idx];
  15469. });
  15470. // Has remainding votes.
  15471. while (currentSum < targetSeats) {
  15472. // Find next largest remainder.
  15473. var max = Number.NEGATIVE_INFINITY;
  15474. var maxId = null;
  15475. for (var i = 0, len = remainder.length; i < len; ++i) {
  15476. if (remainder[i] > max) {
  15477. max = remainder[i];
  15478. maxId = i;
  15479. }
  15480. }
  15481. // Add a vote to max remainder.
  15482. ++seats[maxId];
  15483. remainder[maxId] = 0;
  15484. ++currentSum;
  15485. }
  15486. return seats[idx] / digits;
  15487. }
  15488. // Number.MAX_SAFE_INTEGER, ie do not support.
  15489. var MAX_SAFE_INTEGER = 9007199254740991;
  15490. /**
  15491. * To 0 - 2 * PI, considering negative radian.
  15492. * @param {number} radian
  15493. * @return {number}
  15494. */
  15495. function remRadian(radian) {
  15496. var pi2 = Math.PI * 2;
  15497. return (radian % pi2 + pi2) % pi2;
  15498. }
  15499. /**
  15500. * @param {type} radian
  15501. * @return {boolean}
  15502. */
  15503. function isRadianAroundZero(val) {
  15504. return val > -RADIAN_EPSILON && val < RADIAN_EPSILON;
  15505. }
  15506. 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
  15507. /**
  15508. * @param {string|Date|number} value These values can be accepted:
  15509. * + An instance of Date, represent a time in its own time zone.
  15510. * + Or string in a subset of ISO 8601, only including:
  15511. * + only year, month, date: '2012-03', '2012-03-01', '2012-03-01 05', '2012-03-01 05:06',
  15512. * + separated with T or space: '2012-03-01T12:22:33.123', '2012-03-01 12:22:33.123',
  15513. * + time zone: '2012-03-01T12:22:33Z', '2012-03-01T12:22:33+8000', '2012-03-01T12:22:33-05:00',
  15514. * all of which will be treated as local time if time zone is not specified
  15515. * (see <https://momentjs.com/>).
  15516. * + Or other string format, including (all of which will be treated as loacal time):
  15517. * '2012', '2012-3-1', '2012/3/1', '2012/03/01',
  15518. * '2009/6/12 2:00', '2009/6/12 2:05:08', '2009/6/12 2:05:08.123'
  15519. * + a timestamp, which represent a time in UTC.
  15520. * @return {Date} date
  15521. */
  15522. function parseDate(value) {
  15523. if (value instanceof Date) {
  15524. return value;
  15525. }
  15526. else if (typeof value === 'string') {
  15527. // Different browsers parse date in different way, so we parse it manually.
  15528. // Some other issues:
  15529. // new Date('1970-01-01') is UTC,
  15530. // new Date('1970/01/01') and new Date('1970-1-01') is local.
  15531. // See issue #3623
  15532. var match = TIME_REG.exec(value);
  15533. if (!match) {
  15534. // return Invalid Date.
  15535. return new Date(NaN);
  15536. }
  15537. // Use local time when no timezone offset specifed.
  15538. if (!match[8]) {
  15539. // match[n] can only be string or undefined.
  15540. // But take care of '12' + 1 => '121'.
  15541. return new Date(
  15542. +match[1],
  15543. +(match[2] || 1) - 1,
  15544. +match[3] || 1,
  15545. +match[4] || 0,
  15546. +(match[5] || 0),
  15547. +match[6] || 0,
  15548. +match[7] || 0
  15549. );
  15550. }
  15551. // Timezoneoffset of Javascript Date has considered DST (Daylight Saving Time,
  15552. // https://tc39.github.io/ecma262/#sec-daylight-saving-time-adjustment).
  15553. // For example, system timezone is set as "Time Zone: America/Toronto",
  15554. // then these code will get different result:
  15555. // `new Date(1478411999999).getTimezoneOffset(); // get 240`
  15556. // `new Date(1478412000000).getTimezoneOffset(); // get 300`
  15557. // So we should not use `new Date`, but use `Date.UTC`.
  15558. else {
  15559. var hour = +match[4] || 0;
  15560. if (match[8].toUpperCase() !== 'Z') {
  15561. hour -= match[8].slice(0, 3);
  15562. }
  15563. return new Date(Date.UTC(
  15564. +match[1],
  15565. +(match[2] || 1) - 1,
  15566. +match[3] || 1,
  15567. hour,
  15568. +(match[5] || 0),
  15569. +match[6] || 0,
  15570. +match[7] || 0
  15571. ));
  15572. }
  15573. }
  15574. else if (value == null) {
  15575. return new Date(NaN);
  15576. }
  15577. return new Date(Math.round(value));
  15578. }
  15579. /**
  15580. * Quantity of a number. e.g. 0.1, 1, 10, 100
  15581. *
  15582. * @param {number} val
  15583. * @return {number}
  15584. */
  15585. function quantity(val) {
  15586. return Math.pow(10, quantityExponent(val));
  15587. }
  15588. function quantityExponent(val) {
  15589. return Math.floor(Math.log(val) / Math.LN10);
  15590. }
  15591. /**
  15592. * find a “nice” number approximately equal to x. Round the number if round = true,
  15593. * take ceiling if round = false. The primary observation is that the “nicest”
  15594. * numbers in decimal are 1, 2, and 5, and all power-of-ten multiples of these numbers.
  15595. *
  15596. * See "Nice Numbers for Graph Labels" of Graphic Gems.
  15597. *
  15598. * @param {number} val Non-negative value.
  15599. * @param {boolean} round
  15600. * @return {number}
  15601. */
  15602. function nice(val, round) {
  15603. var exponent = quantityExponent(val);
  15604. var exp10 = Math.pow(10, exponent);
  15605. var f = val / exp10; // 1 <= f < 10
  15606. var nf;
  15607. if (round) {
  15608. if (f < 1.5) { nf = 1; }
  15609. else if (f < 2.5) { nf = 2; }
  15610. else if (f < 4) { nf = 3; }
  15611. else if (f < 7) { nf = 5; }
  15612. else { nf = 10; }
  15613. }
  15614. else {
  15615. if (f < 1) { nf = 1; }
  15616. else if (f < 2) { nf = 2; }
  15617. else if (f < 3) { nf = 3; }
  15618. else if (f < 5) { nf = 5; }
  15619. else { nf = 10; }
  15620. }
  15621. val = nf * exp10;
  15622. // Fix 3 * 0.1 === 0.30000000000000004 issue (see IEEE 754).
  15623. // 20 is the uppper bound of toFixed.
  15624. return exponent >= -20 ? +val.toFixed(exponent < 0 ? -exponent : 0) : val;
  15625. }
  15626. /**
  15627. * Order intervals asc, and split them when overlap.
  15628. * expect(numberUtil.reformIntervals([
  15629. * {interval: [18, 62], close: [1, 1]},
  15630. * {interval: [-Infinity, -70], close: [0, 0]},
  15631. * {interval: [-70, -26], close: [1, 1]},
  15632. * {interval: [-26, 18], close: [1, 1]},
  15633. * {interval: [62, 150], close: [1, 1]},
  15634. * {interval: [106, 150], close: [1, 1]},
  15635. * {interval: [150, Infinity], close: [0, 0]}
  15636. * ])).toEqual([
  15637. * {interval: [-Infinity, -70], close: [0, 0]},
  15638. * {interval: [-70, -26], close: [1, 1]},
  15639. * {interval: [-26, 18], close: [0, 1]},
  15640. * {interval: [18, 62], close: [0, 1]},
  15641. * {interval: [62, 150], close: [0, 1]},
  15642. * {interval: [150, Infinity], close: [0, 0]}
  15643. * ]);
  15644. * @param {Array.<Object>} list, where `close` mean open or close
  15645. * of the interval, and Infinity can be used.
  15646. * @return {Array.<Object>} The origin list, which has been reformed.
  15647. */
  15648. function reformIntervals(list) {
  15649. list.sort(function (a, b) {
  15650. return littleThan(a, b, 0) ? -1 : 1;
  15651. });
  15652. var curr = -Infinity;
  15653. var currClose = 1;
  15654. for (var i = 0; i < list.length;) {
  15655. var interval = list[i].interval;
  15656. var close = list[i].close;
  15657. for (var lg = 0; lg < 2; lg++) {
  15658. if (interval[lg] <= curr) {
  15659. interval[lg] = curr;
  15660. close[lg] = !lg ? 1 - currClose : 1;
  15661. }
  15662. curr = interval[lg];
  15663. currClose = close[lg];
  15664. }
  15665. if (interval[0] === interval[1] && close[0] * close[1] !== 1) {
  15666. list.splice(i, 1);
  15667. }
  15668. else {
  15669. i++;
  15670. }
  15671. }
  15672. return list;
  15673. function littleThan(a, b, lg) {
  15674. return a.interval[lg] < b.interval[lg]
  15675. || (
  15676. a.interval[lg] === b.interval[lg]
  15677. && (
  15678. (a.close[lg] - b.close[lg] === (!lg ? 1 : -1))
  15679. || (!lg && littleThan(a, b, 1))
  15680. )
  15681. );
  15682. }
  15683. }
  15684. /**
  15685. * parseFloat NaNs numeric-cast false positives (null|true|false|"")
  15686. * ...but misinterprets leading-number strings, particularly hex literals ("0x...")
  15687. * subtraction forces infinities to NaN
  15688. *
  15689. * @param {*} v
  15690. * @return {boolean}
  15691. */
  15692. function isNumeric(v) {
  15693. return v - parseFloat(v) >= 0;
  15694. }
  15695. var number = (Object.freeze || Object)({
  15696. linearMap: linearMap,
  15697. parsePercent: parsePercent$1,
  15698. round: round$1,
  15699. asc: asc,
  15700. getPrecision: getPrecision,
  15701. getPrecisionSafe: getPrecisionSafe,
  15702. getPixelPrecision: getPixelPrecision,
  15703. getPercentWithPrecision: getPercentWithPrecision,
  15704. MAX_SAFE_INTEGER: MAX_SAFE_INTEGER,
  15705. remRadian: remRadian,
  15706. isRadianAroundZero: isRadianAroundZero,
  15707. parseDate: parseDate,
  15708. quantity: quantity,
  15709. nice: nice,
  15710. reformIntervals: reformIntervals,
  15711. isNumeric: isNumeric
  15712. });
  15713. /*
  15714. * Licensed to the Apache Software Foundation (ASF) under one
  15715. * or more contributor license agreements. See the NOTICE file
  15716. * distributed with this work for additional information
  15717. * regarding copyright ownership. The ASF licenses this file
  15718. * to you under the Apache License, Version 2.0 (the
  15719. * "License"); you may not use this file except in compliance
  15720. * with the License. You may obtain a copy of the License at
  15721. *
  15722. * http://www.apache.org/licenses/LICENSE-2.0
  15723. *
  15724. * Unless required by applicable law or agreed to in writing,
  15725. * software distributed under the License is distributed on an
  15726. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15727. * KIND, either express or implied. See the License for the
  15728. * specific language governing permissions and limitations
  15729. * under the License.
  15730. */
  15731. /**
  15732. * 每三位默认加,格式化
  15733. * @param {string|number} x
  15734. * @return {string}
  15735. */
  15736. function addCommas(x) {
  15737. if (isNaN(x)) {
  15738. return '-';
  15739. }
  15740. x = (x + '').split('.');
  15741. return x[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g,'$1,')
  15742. + (x.length > 1 ? ('.' + x[1]) : '');
  15743. }
  15744. /**
  15745. * @param {string} str
  15746. * @param {boolean} [upperCaseFirst=false]
  15747. * @return {string} str
  15748. */
  15749. function toCamelCase(str, upperCaseFirst) {
  15750. str = (str || '').toLowerCase().replace(/-(.)/g, function(match, group1) {
  15751. return group1.toUpperCase();
  15752. });
  15753. if (upperCaseFirst && str) {
  15754. str = str.charAt(0).toUpperCase() + str.slice(1);
  15755. }
  15756. return str;
  15757. }
  15758. var normalizeCssArray$1 = normalizeCssArray;
  15759. var replaceReg = /([&<>"'])/g;
  15760. var replaceMap = {
  15761. '&': '&amp;',
  15762. '<': '&lt;',
  15763. '>': '&gt;',
  15764. '"': '&quot;',
  15765. '\'': '&#39;'
  15766. };
  15767. function encodeHTML(source) {
  15768. return source == null
  15769. ? ''
  15770. : (source + '').replace(replaceReg, function (str, c) {
  15771. return replaceMap[c];
  15772. });
  15773. }
  15774. var TPL_VAR_ALIAS = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
  15775. var wrapVar = function (varName, seriesIdx) {
  15776. return '{' + varName + (seriesIdx == null ? '' : seriesIdx) + '}';
  15777. };
  15778. /**
  15779. * Template formatter
  15780. * @param {string} tpl
  15781. * @param {Array.<Object>|Object} paramsList
  15782. * @param {boolean} [encode=false]
  15783. * @return {string}
  15784. */
  15785. function formatTpl(tpl, paramsList, encode) {
  15786. if (!isArray(paramsList)) {
  15787. paramsList = [paramsList];
  15788. }
  15789. var seriesLen = paramsList.length;
  15790. if (!seriesLen) {
  15791. return '';
  15792. }
  15793. var $vars = paramsList[0].$vars || [];
  15794. for (var i = 0; i < $vars.length; i++) {
  15795. var alias = TPL_VAR_ALIAS[i];
  15796. tpl = tpl.replace(wrapVar(alias), wrapVar(alias, 0));
  15797. }
  15798. for (var seriesIdx = 0; seriesIdx < seriesLen; seriesIdx++) {
  15799. for (var k = 0; k < $vars.length; k++) {
  15800. var val = paramsList[seriesIdx][$vars[k]];
  15801. tpl = tpl.replace(
  15802. wrapVar(TPL_VAR_ALIAS[k], seriesIdx),
  15803. encode ? encodeHTML(val) : val
  15804. );
  15805. }
  15806. }
  15807. return tpl;
  15808. }
  15809. /**
  15810. * simple Template formatter
  15811. *
  15812. * @param {string} tpl
  15813. * @param {Object} param
  15814. * @param {boolean} [encode=false]
  15815. * @return {string}
  15816. */
  15817. function formatTplSimple(tpl, param, encode) {
  15818. each$1(param, function (value, key) {
  15819. tpl = tpl.replace(
  15820. '{' + key + '}',
  15821. encode ? encodeHTML(value) : value
  15822. );
  15823. });
  15824. return tpl;
  15825. }
  15826. /**
  15827. * @param {Object|string} [opt] If string, means color.
  15828. * @param {string} [opt.color]
  15829. * @param {string} [opt.extraCssText]
  15830. * @param {string} [opt.type='item'] 'item' or 'subItem'
  15831. * @return {string}
  15832. */
  15833. function getTooltipMarker(opt, extraCssText) {
  15834. opt = isString(opt) ? {color: opt, extraCssText: extraCssText} : (opt || {});
  15835. var color = opt.color;
  15836. var type = opt.type;
  15837. var extraCssText = opt.extraCssText;
  15838. if (!color) {
  15839. return '';
  15840. }
  15841. return type === 'subItem'
  15842. ? '<span style="display:inline-block;vertical-align:middle;margin-right:8px;margin-left:3px;'
  15843. + 'border-radius:4px;width:4px;height:4px;background-color:'
  15844. + encodeHTML(color) + ';' + (extraCssText || '') + '"></span>'
  15845. : '<span style="display:inline-block;margin-right:5px;'
  15846. + 'border-radius:10px;width:10px;height:10px;background-color:'
  15847. + encodeHTML(color) + ';' + (extraCssText || '') + '"></span>';
  15848. }
  15849. function pad(str, len) {
  15850. str += '';
  15851. return '0000'.substr(0, len - str.length) + str;
  15852. }
  15853. /**
  15854. * ISO Date format
  15855. * @param {string} tpl
  15856. * @param {number} value
  15857. * @param {boolean} [isUTC=false] Default in local time.
  15858. * see `module:echarts/scale/Time`
  15859. * and `module:echarts/util/number#parseDate`.
  15860. * @inner
  15861. */
  15862. function formatTime(tpl, value, isUTC) {
  15863. if (tpl === 'week'
  15864. || tpl === 'month'
  15865. || tpl === 'quarter'
  15866. || tpl === 'half-year'
  15867. || tpl === 'year'
  15868. ) {
  15869. tpl = 'MM-dd\nyyyy';
  15870. }
  15871. var date = parseDate(value);
  15872. var utc = isUTC ? 'UTC' : '';
  15873. var y = date['get' + utc + 'FullYear']();
  15874. var M = date['get' + utc + 'Month']() + 1;
  15875. var d = date['get' + utc + 'Date']();
  15876. var h = date['get' + utc + 'Hours']();
  15877. var m = date['get' + utc + 'Minutes']();
  15878. var s = date['get' + utc + 'Seconds']();
  15879. var S = date['get' + utc + 'Milliseconds']();
  15880. tpl = tpl.replace('MM', pad(M, 2))
  15881. .replace('M', M)
  15882. .replace('yyyy', y)
  15883. .replace('yy', y % 100)
  15884. .replace('dd', pad(d, 2))
  15885. .replace('d', d)
  15886. .replace('hh', pad(h, 2))
  15887. .replace('h', h)
  15888. .replace('mm', pad(m, 2))
  15889. .replace('m', m)
  15890. .replace('ss', pad(s, 2))
  15891. .replace('s', s)
  15892. .replace('SSS', pad(S, 3));
  15893. return tpl;
  15894. }
  15895. /**
  15896. * Capital first
  15897. * @param {string} str
  15898. * @return {string}
  15899. */
  15900. function capitalFirst(str) {
  15901. return str ? str.charAt(0).toUpperCase() + str.substr(1) : str;
  15902. }
  15903. var truncateText$1 = truncateText;
  15904. var getTextRect = getBoundingRect;
  15905. var format = (Object.freeze || Object)({
  15906. addCommas: addCommas,
  15907. toCamelCase: toCamelCase,
  15908. normalizeCssArray: normalizeCssArray$1,
  15909. encodeHTML: encodeHTML,
  15910. formatTpl: formatTpl,
  15911. formatTplSimple: formatTplSimple,
  15912. getTooltipMarker: getTooltipMarker,
  15913. formatTime: formatTime,
  15914. capitalFirst: capitalFirst,
  15915. truncateText: truncateText$1,
  15916. getTextRect: getTextRect
  15917. });
  15918. /*
  15919. * Licensed to the Apache Software Foundation (ASF) under one
  15920. * or more contributor license agreements. See the NOTICE file
  15921. * distributed with this work for additional information
  15922. * regarding copyright ownership. The ASF licenses this file
  15923. * to you under the Apache License, Version 2.0 (the
  15924. * "License"); you may not use this file except in compliance
  15925. * with the License. You may obtain a copy of the License at
  15926. *
  15927. * http://www.apache.org/licenses/LICENSE-2.0
  15928. *
  15929. * Unless required by applicable law or agreed to in writing,
  15930. * software distributed under the License is distributed on an
  15931. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15932. * KIND, either express or implied. See the License for the
  15933. * specific language governing permissions and limitations
  15934. * under the License.
  15935. */
  15936. // Layout helpers for each component positioning
  15937. var each$3 = each$1;
  15938. /**
  15939. * @public
  15940. */
  15941. var LOCATION_PARAMS = [
  15942. 'left', 'right', 'top', 'bottom', 'width', 'height'
  15943. ];
  15944. /**
  15945. * @public
  15946. */
  15947. var HV_NAMES = [
  15948. ['width', 'left', 'right'],
  15949. ['height', 'top', 'bottom']
  15950. ];
  15951. function boxLayout(orient, group, gap, maxWidth, maxHeight) {
  15952. var x = 0;
  15953. var y = 0;
  15954. if (maxWidth == null) {
  15955. maxWidth = Infinity;
  15956. }
  15957. if (maxHeight == null) {
  15958. maxHeight = Infinity;
  15959. }
  15960. var currentLineMaxSize = 0;
  15961. group.eachChild(function (child, idx) {
  15962. var position = child.position;
  15963. var rect = child.getBoundingRect();
  15964. var nextChild = group.childAt(idx + 1);
  15965. var nextChildRect = nextChild && nextChild.getBoundingRect();
  15966. var nextX;
  15967. var nextY;
  15968. if (orient === 'horizontal') {
  15969. var moveX = rect.width + (nextChildRect ? (-nextChildRect.x + rect.x) : 0);
  15970. nextX = x + moveX;
  15971. // Wrap when width exceeds maxWidth or meet a `newline` group
  15972. // FIXME compare before adding gap?
  15973. if (nextX > maxWidth || child.newline) {
  15974. x = 0;
  15975. nextX = moveX;
  15976. y += currentLineMaxSize + gap;
  15977. currentLineMaxSize = rect.height;
  15978. }
  15979. else {
  15980. // FIXME: consider rect.y is not `0`?
  15981. currentLineMaxSize = Math.max(currentLineMaxSize, rect.height);
  15982. }
  15983. }
  15984. else {
  15985. var moveY = rect.height + (nextChildRect ? (-nextChildRect.y + rect.y) : 0);
  15986. nextY = y + moveY;
  15987. // Wrap when width exceeds maxHeight or meet a `newline` group
  15988. if (nextY > maxHeight || child.newline) {
  15989. x += currentLineMaxSize + gap;
  15990. y = 0;
  15991. nextY = moveY;
  15992. currentLineMaxSize = rect.width;
  15993. }
  15994. else {
  15995. currentLineMaxSize = Math.max(currentLineMaxSize, rect.width);
  15996. }
  15997. }
  15998. if (child.newline) {
  15999. return;
  16000. }
  16001. position[0] = x;
  16002. position[1] = y;
  16003. orient === 'horizontal'
  16004. ? (x = nextX + gap)
  16005. : (y = nextY + gap);
  16006. });
  16007. }
  16008. /**
  16009. * VBox or HBox layouting
  16010. * @param {string} orient
  16011. * @param {module:zrender/container/Group} group
  16012. * @param {number} gap
  16013. * @param {number} [width=Infinity]
  16014. * @param {number} [height=Infinity]
  16015. */
  16016. var box = boxLayout;
  16017. /**
  16018. * VBox layouting
  16019. * @param {module:zrender/container/Group} group
  16020. * @param {number} gap
  16021. * @param {number} [width=Infinity]
  16022. * @param {number} [height=Infinity]
  16023. */
  16024. var vbox = curry(boxLayout, 'vertical');
  16025. /**
  16026. * HBox layouting
  16027. * @param {module:zrender/container/Group} group
  16028. * @param {number} gap
  16029. * @param {number} [width=Infinity]
  16030. * @param {number} [height=Infinity]
  16031. */
  16032. var hbox = curry(boxLayout, 'horizontal');
  16033. /**
  16034. * If x or x2 is not specified or 'center' 'left' 'right',
  16035. * the width would be as long as possible.
  16036. * If y or y2 is not specified or 'middle' 'top' 'bottom',
  16037. * the height would be as long as possible.
  16038. *
  16039. * @param {Object} positionInfo
  16040. * @param {number|string} [positionInfo.x]
  16041. * @param {number|string} [positionInfo.y]
  16042. * @param {number|string} [positionInfo.x2]
  16043. * @param {number|string} [positionInfo.y2]
  16044. * @param {Object} containerRect {width, height}
  16045. * @param {string|number} margin
  16046. * @return {Object} {width, height}
  16047. */
  16048. function getAvailableSize(positionInfo, containerRect, margin) {
  16049. var containerWidth = containerRect.width;
  16050. var containerHeight = containerRect.height;
  16051. var x = parsePercent$1(positionInfo.x, containerWidth);
  16052. var y = parsePercent$1(positionInfo.y, containerHeight);
  16053. var x2 = parsePercent$1(positionInfo.x2, containerWidth);
  16054. var y2 = parsePercent$1(positionInfo.y2, containerHeight);
  16055. (isNaN(x) || isNaN(parseFloat(positionInfo.x))) && (x = 0);
  16056. (isNaN(x2) || isNaN(parseFloat(positionInfo.x2))) && (x2 = containerWidth);
  16057. (isNaN(y) || isNaN(parseFloat(positionInfo.y))) && (y = 0);
  16058. (isNaN(y2) || isNaN(parseFloat(positionInfo.y2))) && (y2 = containerHeight);
  16059. margin = normalizeCssArray$1(margin || 0);
  16060. return {
  16061. width: Math.max(x2 - x - margin[1] - margin[3], 0),
  16062. height: Math.max(y2 - y - margin[0] - margin[2], 0)
  16063. };
  16064. }
  16065. /**
  16066. * Parse position info.
  16067. *
  16068. * @param {Object} positionInfo
  16069. * @param {number|string} [positionInfo.left]
  16070. * @param {number|string} [positionInfo.top]
  16071. * @param {number|string} [positionInfo.right]
  16072. * @param {number|string} [positionInfo.bottom]
  16073. * @param {number|string} [positionInfo.width]
  16074. * @param {number|string} [positionInfo.height]
  16075. * @param {number|string} [positionInfo.aspect] Aspect is width / height
  16076. * @param {Object} containerRect
  16077. * @param {string|number} [margin]
  16078. *
  16079. * @return {module:zrender/core/BoundingRect}
  16080. */
  16081. function getLayoutRect(
  16082. positionInfo, containerRect, margin
  16083. ) {
  16084. margin = normalizeCssArray$1(margin || 0);
  16085. var containerWidth = containerRect.width;
  16086. var containerHeight = containerRect.height;
  16087. var left = parsePercent$1(positionInfo.left, containerWidth);
  16088. var top = parsePercent$1(positionInfo.top, containerHeight);
  16089. var right = parsePercent$1(positionInfo.right, containerWidth);
  16090. var bottom = parsePercent$1(positionInfo.bottom, containerHeight);
  16091. var width = parsePercent$1(positionInfo.width, containerWidth);
  16092. var height = parsePercent$1(positionInfo.height, containerHeight);
  16093. var verticalMargin = margin[2] + margin[0];
  16094. var horizontalMargin = margin[1] + margin[3];
  16095. var aspect = positionInfo.aspect;
  16096. // If width is not specified, calculate width from left and right
  16097. if (isNaN(width)) {
  16098. width = containerWidth - right - horizontalMargin - left;
  16099. }
  16100. if (isNaN(height)) {
  16101. height = containerHeight - bottom - verticalMargin - top;
  16102. }
  16103. if (aspect != null) {
  16104. // If width and height are not given
  16105. // 1. Graph should not exceeds the container
  16106. // 2. Aspect must be keeped
  16107. // 3. Graph should take the space as more as possible
  16108. // FIXME
  16109. // Margin is not considered, because there is no case that both
  16110. // using margin and aspect so far.
  16111. if (isNaN(width) && isNaN(height)) {
  16112. if (aspect > containerWidth / containerHeight) {
  16113. width = containerWidth * 0.8;
  16114. }
  16115. else {
  16116. height = containerHeight * 0.8;
  16117. }
  16118. }
  16119. // Calculate width or height with given aspect
  16120. if (isNaN(width)) {
  16121. width = aspect * height;
  16122. }
  16123. if (isNaN(height)) {
  16124. height = width / aspect;
  16125. }
  16126. }
  16127. // If left is not specified, calculate left from right and width
  16128. if (isNaN(left)) {
  16129. left = containerWidth - right - width - horizontalMargin;
  16130. }
  16131. if (isNaN(top)) {
  16132. top = containerHeight - bottom - height - verticalMargin;
  16133. }
  16134. // Align left and top
  16135. switch (positionInfo.left || positionInfo.right) {
  16136. case 'center':
  16137. left = containerWidth / 2 - width / 2 - margin[3];
  16138. break;
  16139. case 'right':
  16140. left = containerWidth - width - horizontalMargin;
  16141. break;
  16142. }
  16143. switch (positionInfo.top || positionInfo.bottom) {
  16144. case 'middle':
  16145. case 'center':
  16146. top = containerHeight / 2 - height / 2 - margin[0];
  16147. break;
  16148. case 'bottom':
  16149. top = containerHeight - height - verticalMargin;
  16150. break;
  16151. }
  16152. // If something is wrong and left, top, width, height are calculated as NaN
  16153. left = left || 0;
  16154. top = top || 0;
  16155. if (isNaN(width)) {
  16156. // Width may be NaN if only one value is given except width
  16157. width = containerWidth - horizontalMargin - left - (right || 0);
  16158. }
  16159. if (isNaN(height)) {
  16160. // Height may be NaN if only one value is given except height
  16161. height = containerHeight - verticalMargin - top - (bottom || 0);
  16162. }
  16163. var rect = new BoundingRect(left + margin[3], top + margin[0], width, height);
  16164. rect.margin = margin;
  16165. return rect;
  16166. }
  16167. /**
  16168. * Position a zr element in viewport
  16169. * Group position is specified by either
  16170. * {left, top}, {right, bottom}
  16171. * If all properties exists, right and bottom will be igonred.
  16172. *
  16173. * Logic:
  16174. * 1. Scale (against origin point in parent coord)
  16175. * 2. Rotate (against origin point in parent coord)
  16176. * 3. Traslate (with el.position by this method)
  16177. * So this method only fixes the last step 'Traslate', which does not affect
  16178. * scaling and rotating.
  16179. *
  16180. * If be called repeatly with the same input el, the same result will be gotten.
  16181. *
  16182. * @param {module:zrender/Element} el Should have `getBoundingRect` method.
  16183. * @param {Object} positionInfo
  16184. * @param {number|string} [positionInfo.left]
  16185. * @param {number|string} [positionInfo.top]
  16186. * @param {number|string} [positionInfo.right]
  16187. * @param {number|string} [positionInfo.bottom]
  16188. * @param {number|string} [positionInfo.width] Only for opt.boundingModel: 'raw'
  16189. * @param {number|string} [positionInfo.height] Only for opt.boundingModel: 'raw'
  16190. * @param {Object} containerRect
  16191. * @param {string|number} margin
  16192. * @param {Object} [opt]
  16193. * @param {Array.<number>} [opt.hv=[1,1]] Only horizontal or only vertical.
  16194. * @param {Array.<number>} [opt.boundingMode='all']
  16195. * Specify how to calculate boundingRect when locating.
  16196. * 'all': Position the boundingRect that is transformed and uioned
  16197. * both itself and its descendants.
  16198. * This mode simplies confine the elements in the bounding
  16199. * of their container (e.g., using 'right: 0').
  16200. * 'raw': Position the boundingRect that is not transformed and only itself.
  16201. * This mode is useful when you want a element can overflow its
  16202. * container. (Consider a rotated circle needs to be located in a corner.)
  16203. * In this mode positionInfo.width/height can only be number.
  16204. */
  16205. function positionElement(el, positionInfo, containerRect, margin, opt) {
  16206. var h = !opt || !opt.hv || opt.hv[0];
  16207. var v = !opt || !opt.hv || opt.hv[1];
  16208. var boundingMode = opt && opt.boundingMode || 'all';
  16209. if (!h && !v) {
  16210. return;
  16211. }
  16212. var rect;
  16213. if (boundingMode === 'raw') {
  16214. rect = el.type === 'group'
  16215. ? new BoundingRect(0, 0, +positionInfo.width || 0, +positionInfo.height || 0)
  16216. : el.getBoundingRect();
  16217. }
  16218. else {
  16219. rect = el.getBoundingRect();
  16220. if (el.needLocalTransform()) {
  16221. var transform = el.getLocalTransform();
  16222. // Notice: raw rect may be inner object of el,
  16223. // which should not be modified.
  16224. rect = rect.clone();
  16225. rect.applyTransform(transform);
  16226. }
  16227. }
  16228. // The real width and height can not be specified but calculated by the given el.
  16229. positionInfo = getLayoutRect(
  16230. defaults(
  16231. {width: rect.width, height: rect.height},
  16232. positionInfo
  16233. ),
  16234. containerRect,
  16235. margin
  16236. );
  16237. // Because 'tranlate' is the last step in transform
  16238. // (see zrender/core/Transformable#getLocalTransform),
  16239. // we can just only modify el.position to get final result.
  16240. var elPos = el.position;
  16241. var dx = h ? positionInfo.x - rect.x : 0;
  16242. var dy = v ? positionInfo.y - rect.y : 0;
  16243. el.attr('position', boundingMode === 'raw' ? [dx, dy] : [elPos[0] + dx, elPos[1] + dy]);
  16244. }
  16245. /**
  16246. * @param {Object} option Contains some of the properties in HV_NAMES.
  16247. * @param {number} hvIdx 0: horizontal; 1: vertical.
  16248. */
  16249. function sizeCalculable(option, hvIdx) {
  16250. return option[HV_NAMES[hvIdx][0]] != null
  16251. || (option[HV_NAMES[hvIdx][1]] != null && option[HV_NAMES[hvIdx][2]] != null);
  16252. }
  16253. /**
  16254. * Consider Case:
  16255. * When defulat option has {left: 0, width: 100}, and we set {right: 0}
  16256. * through setOption or media query, using normal zrUtil.merge will cause
  16257. * {right: 0} does not take effect.
  16258. *
  16259. * @example
  16260. * ComponentModel.extend({
  16261. * init: function () {
  16262. * ...
  16263. * var inputPositionParams = layout.getLayoutParams(option);
  16264. * this.mergeOption(inputPositionParams);
  16265. * },
  16266. * mergeOption: function (newOption) {
  16267. * newOption && zrUtil.merge(thisOption, newOption, true);
  16268. * layout.mergeLayoutParam(thisOption, newOption);
  16269. * }
  16270. * });
  16271. *
  16272. * @param {Object} targetOption
  16273. * @param {Object} newOption
  16274. * @param {Object|string} [opt]
  16275. * @param {boolean|Array.<boolean>} [opt.ignoreSize=false] Used for the components
  16276. * that width (or height) should not be calculated by left and right (or top and bottom).
  16277. */
  16278. function mergeLayoutParam(targetOption, newOption, opt) {
  16279. !isObject$1(opt) && (opt = {});
  16280. var ignoreSize = opt.ignoreSize;
  16281. !isArray(ignoreSize) && (ignoreSize = [ignoreSize, ignoreSize]);
  16282. var hResult = merge$$1(HV_NAMES[0], 0);
  16283. var vResult = merge$$1(HV_NAMES[1], 1);
  16284. copy(HV_NAMES[0], targetOption, hResult);
  16285. copy(HV_NAMES[1], targetOption, vResult);
  16286. function merge$$1(names, hvIdx) {
  16287. var newParams = {};
  16288. var newValueCount = 0;
  16289. var merged = {};
  16290. var mergedValueCount = 0;
  16291. var enoughParamNumber = 2;
  16292. each$3(names, function (name) {
  16293. merged[name] = targetOption[name];
  16294. });
  16295. each$3(names, function (name) {
  16296. // Consider case: newOption.width is null, which is
  16297. // set by user for removing width setting.
  16298. hasProp(newOption, name) && (newParams[name] = merged[name] = newOption[name]);
  16299. hasValue(newParams, name) && newValueCount++;
  16300. hasValue(merged, name) && mergedValueCount++;
  16301. });
  16302. if (ignoreSize[hvIdx]) {
  16303. // Only one of left/right is premitted to exist.
  16304. if (hasValue(newOption, names[1])) {
  16305. merged[names[2]] = null;
  16306. }
  16307. else if (hasValue(newOption, names[2])) {
  16308. merged[names[1]] = null;
  16309. }
  16310. return merged;
  16311. }
  16312. // Case: newOption: {width: ..., right: ...},
  16313. // or targetOption: {right: ...} and newOption: {width: ...},
  16314. // There is no conflict when merged only has params count
  16315. // little than enoughParamNumber.
  16316. if (mergedValueCount === enoughParamNumber || !newValueCount) {
  16317. return merged;
  16318. }
  16319. // Case: newOption: {width: ..., right: ...},
  16320. // Than we can make sure user only want those two, and ignore
  16321. // all origin params in targetOption.
  16322. else if (newValueCount >= enoughParamNumber) {
  16323. return newParams;
  16324. }
  16325. else {
  16326. // Chose another param from targetOption by priority.
  16327. for (var i = 0; i < names.length; i++) {
  16328. var name = names[i];
  16329. if (!hasProp(newParams, name) && hasProp(targetOption, name)) {
  16330. newParams[name] = targetOption[name];
  16331. break;
  16332. }
  16333. }
  16334. return newParams;
  16335. }
  16336. }
  16337. function hasProp(obj, name) {
  16338. return obj.hasOwnProperty(name);
  16339. }
  16340. function hasValue(obj, name) {
  16341. return obj[name] != null && obj[name] !== 'auto';
  16342. }
  16343. function copy(names, target, source) {
  16344. each$3(names, function (name) {
  16345. target[name] = source[name];
  16346. });
  16347. }
  16348. }
  16349. /**
  16350. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  16351. * @param {Object} source
  16352. * @return {Object} Result contains those props.
  16353. */
  16354. function getLayoutParams(source) {
  16355. return copyLayoutParams({}, source);
  16356. }
  16357. /**
  16358. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  16359. * @param {Object} source
  16360. * @return {Object} Result contains those props.
  16361. */
  16362. function copyLayoutParams(target, source) {
  16363. source && target && each$3(LOCATION_PARAMS, function (name) {
  16364. source.hasOwnProperty(name) && (target[name] = source[name]);
  16365. });
  16366. return target;
  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 boxLayoutMixin = {
  16387. getBoxLayoutParams: function () {
  16388. return {
  16389. left: this.get('left'),
  16390. top: this.get('top'),
  16391. right: this.get('right'),
  16392. bottom: this.get('bottom'),
  16393. width: this.get('width'),
  16394. height: this.get('height')
  16395. };
  16396. }
  16397. };
  16398. /*
  16399. * Licensed to the Apache Software Foundation (ASF) under one
  16400. * or more contributor license agreements. See the NOTICE file
  16401. * distributed with this work for additional information
  16402. * regarding copyright ownership. The ASF licenses this file
  16403. * to you under the Apache License, Version 2.0 (the
  16404. * "License"); you may not use this file except in compliance
  16405. * with the License. You may obtain a copy of the License at
  16406. *
  16407. * http://www.apache.org/licenses/LICENSE-2.0
  16408. *
  16409. * Unless required by applicable law or agreed to in writing,
  16410. * software distributed under the License is distributed on an
  16411. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16412. * KIND, either express or implied. See the License for the
  16413. * specific language governing permissions and limitations
  16414. * under the License.
  16415. */
  16416. /**
  16417. * Component model
  16418. *
  16419. * @module echarts/model/Component
  16420. */
  16421. var inner$1 = makeInner();
  16422. /**
  16423. * @alias module:echarts/model/Component
  16424. * @constructor
  16425. * @param {Object} option
  16426. * @param {module:echarts/model/Model} parentModel
  16427. * @param {module:echarts/model/Model} ecModel
  16428. */
  16429. var ComponentModel = Model.extend({
  16430. type: 'component',
  16431. /**
  16432. * @readOnly
  16433. * @type {string}
  16434. */
  16435. id: '',
  16436. /**
  16437. * Because simplified concept is probably better, series.name (or component.name)
  16438. * has been having too many resposibilities:
  16439. * (1) Generating id (which requires name in option should not be modified).
  16440. * (2) As an index to mapping series when merging option or calling API (a name
  16441. * can refer to more then one components, which is convinient is some case).
  16442. * (3) Display.
  16443. * @readOnly
  16444. */
  16445. name: '',
  16446. /**
  16447. * @readOnly
  16448. * @type {string}
  16449. */
  16450. mainType: '',
  16451. /**
  16452. * @readOnly
  16453. * @type {string}
  16454. */
  16455. subType: '',
  16456. /**
  16457. * @readOnly
  16458. * @type {number}
  16459. */
  16460. componentIndex: 0,
  16461. /**
  16462. * @type {Object}
  16463. * @protected
  16464. */
  16465. defaultOption: null,
  16466. /**
  16467. * @type {module:echarts/model/Global}
  16468. * @readOnly
  16469. */
  16470. ecModel: null,
  16471. /**
  16472. * key: componentType
  16473. * value: Component model list, can not be null.
  16474. * @type {Object.<string, Array.<module:echarts/model/Model>>}
  16475. * @readOnly
  16476. */
  16477. dependentModels: [],
  16478. /**
  16479. * @type {string}
  16480. * @readOnly
  16481. */
  16482. uid: null,
  16483. /**
  16484. * Support merge layout params.
  16485. * Only support 'box' now (left/right/top/bottom/width/height).
  16486. * @type {string|Object} Object can be {ignoreSize: true}
  16487. * @readOnly
  16488. */
  16489. layoutMode: null,
  16490. $constructor: function (option, parentModel, ecModel, extraOpt) {
  16491. Model.call(this, option, parentModel, ecModel, extraOpt);
  16492. this.uid = getUID('ec_cpt_model');
  16493. },
  16494. init: function (option, parentModel, ecModel, extraOpt) {
  16495. this.mergeDefaultAndTheme(option, ecModel);
  16496. },
  16497. mergeDefaultAndTheme: function (option, ecModel) {
  16498. var layoutMode = this.layoutMode;
  16499. var inputPositionParams = layoutMode
  16500. ? getLayoutParams(option) : {};
  16501. var themeModel = ecModel.getTheme();
  16502. merge(option, themeModel.get(this.mainType));
  16503. merge(option, this.getDefaultOption());
  16504. if (layoutMode) {
  16505. mergeLayoutParam(option, inputPositionParams, layoutMode);
  16506. }
  16507. },
  16508. mergeOption: function (option, extraOpt) {
  16509. merge(this.option, option, true);
  16510. var layoutMode = this.layoutMode;
  16511. if (layoutMode) {
  16512. mergeLayoutParam(this.option, option, layoutMode);
  16513. }
  16514. },
  16515. // Hooker after init or mergeOption
  16516. optionUpdated: function (newCptOption, isInit) {},
  16517. getDefaultOption: function () {
  16518. var fields = inner$1(this);
  16519. if (!fields.defaultOption) {
  16520. var optList = [];
  16521. var Class = this.constructor;
  16522. while (Class) {
  16523. var opt = Class.prototype.defaultOption;
  16524. opt && optList.push(opt);
  16525. Class = Class.superClass;
  16526. }
  16527. var defaultOption = {};
  16528. for (var i = optList.length - 1; i >= 0; i--) {
  16529. defaultOption = merge(defaultOption, optList[i], true);
  16530. }
  16531. fields.defaultOption = defaultOption;
  16532. }
  16533. return fields.defaultOption;
  16534. },
  16535. getReferringComponents: function (mainType) {
  16536. return this.ecModel.queryComponents({
  16537. mainType: mainType,
  16538. index: this.get(mainType + 'Index', true),
  16539. id: this.get(mainType + 'Id', true)
  16540. });
  16541. }
  16542. });
  16543. // Reset ComponentModel.extend, add preConstruct.
  16544. // clazzUtil.enableClassExtend(
  16545. // ComponentModel,
  16546. // function (option, parentModel, ecModel, extraOpt) {
  16547. // // Set dependentModels, componentIndex, name, id, mainType, subType.
  16548. // zrUtil.extend(this, extraOpt);
  16549. // this.uid = componentUtil.getUID('componentModel');
  16550. // // this.setReadOnly([
  16551. // // 'type', 'id', 'uid', 'name', 'mainType', 'subType',
  16552. // // 'dependentModels', 'componentIndex'
  16553. // // ]);
  16554. // }
  16555. // );
  16556. // Add capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  16557. enableClassManagement(
  16558. ComponentModel, {registerWhenExtend: true}
  16559. );
  16560. enableSubTypeDefaulter(ComponentModel);
  16561. // Add capability of ComponentModel.topologicalTravel.
  16562. enableTopologicalTravel(ComponentModel, getDependencies);
  16563. function getDependencies(componentType) {
  16564. var deps = [];
  16565. each$1(ComponentModel.getClassesByMainType(componentType), function (Clazz) {
  16566. deps = deps.concat(Clazz.prototype.dependencies || []);
  16567. });
  16568. // Ensure main type.
  16569. deps = map(deps, function (type) {
  16570. return parseClassType$1(type).main;
  16571. });
  16572. // Hack dataset for convenience.
  16573. if (componentType !== 'dataset' && indexOf(deps, 'dataset') <= 0) {
  16574. deps.unshift('dataset');
  16575. }
  16576. return deps;
  16577. }
  16578. mixin(ComponentModel, boxLayoutMixin);
  16579. /*
  16580. * Licensed to the Apache Software Foundation (ASF) under one
  16581. * or more contributor license agreements. See the NOTICE file
  16582. * distributed with this work for additional information
  16583. * regarding copyright ownership. The ASF licenses this file
  16584. * to you under the Apache License, Version 2.0 (the
  16585. * "License"); you may not use this file except in compliance
  16586. * with the License. You may obtain a copy of the License at
  16587. *
  16588. * http://www.apache.org/licenses/LICENSE-2.0
  16589. *
  16590. * Unless required by applicable law or agreed to in writing,
  16591. * software distributed under the License is distributed on an
  16592. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16593. * KIND, either express or implied. See the License for the
  16594. * specific language governing permissions and limitations
  16595. * under the License.
  16596. */
  16597. var platform = '';
  16598. // Navigator not exists in node
  16599. if (typeof navigator !== 'undefined') {
  16600. platform = navigator.platform || '';
  16601. }
  16602. var globalDefault = {
  16603. // backgroundColor: 'rgba(0,0,0,0)',
  16604. // https://dribbble.com/shots/1065960-Infographic-Pie-chart-visualization
  16605. // color: ['#5793f3', '#d14a61', '#fd9c35', '#675bba', '#fec42c', '#dd4444', '#d4df5a', '#cd4870'],
  16606. // Light colors:
  16607. // color: ['#bcd3bb', '#e88f70', '#edc1a5', '#9dc5c8', '#e1e8c8', '#7b7c68', '#e5b5b5', '#f0b489', '#928ea8', '#bda29a'],
  16608. // color: ['#cc5664', '#9bd6ec', '#ea946e', '#8acaaa', '#f1ec64', '#ee8686', '#a48dc1', '#5da6bc', '#b9dcae'],
  16609. // Dark colors:
  16610. color: ['#c23531','#2f4554', '#61a0a8', '#d48265', '#91c7ae','#749f83', '#ca8622', '#bda29a','#6e7074', '#546570', '#c4ccd3'],
  16611. gradientColor: ['#f6efa6', '#d88273', '#bf444c'],
  16612. // If xAxis and yAxis declared, grid is created by default.
  16613. // grid: {},
  16614. textStyle: {
  16615. // color: '#000',
  16616. // decoration: 'none',
  16617. // PENDING
  16618. fontFamily: platform.match(/^Win/) ? 'Microsoft YaHei' : 'sans-serif',
  16619. // fontFamily: 'Arial, Verdana, sans-serif',
  16620. fontSize: 12,
  16621. fontStyle: 'normal',
  16622. fontWeight: 'normal'
  16623. },
  16624. // http://blogs.adobe.com/webplatform/2014/02/24/using-blend-modes-in-html-canvas/
  16625. // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  16626. // Default is source-over
  16627. blendMode: null,
  16628. animation: 'auto',
  16629. animationDuration: 1000,
  16630. animationDurationUpdate: 300,
  16631. animationEasing: 'exponentialOut',
  16632. animationEasingUpdate: 'cubicOut',
  16633. animationThreshold: 2000,
  16634. // Configuration for progressive/incremental rendering
  16635. progressiveThreshold: 3000,
  16636. progressive: 400,
  16637. // Threshold of if use single hover layer to optimize.
  16638. // It is recommended that `hoverLayerThreshold` is equivalent to or less than
  16639. // `progressiveThreshold`, otherwise hover will cause restart of progressive,
  16640. // which is unexpected.
  16641. // see example <echarts/test/heatmap-large.html>.
  16642. hoverLayerThreshold: 3000,
  16643. // See: module:echarts/scale/Time
  16644. useUTC: false
  16645. };
  16646. /*
  16647. * Licensed to the Apache Software Foundation (ASF) under one
  16648. * or more contributor license agreements. See the NOTICE file
  16649. * distributed with this work for additional information
  16650. * regarding copyright ownership. The ASF licenses this file
  16651. * to you under the Apache License, Version 2.0 (the
  16652. * "License"); you may not use this file except in compliance
  16653. * with the License. You may obtain a copy of the License at
  16654. *
  16655. * http://www.apache.org/licenses/LICENSE-2.0
  16656. *
  16657. * Unless required by applicable law or agreed to in writing,
  16658. * software distributed under the License is distributed on an
  16659. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16660. * KIND, either express or implied. See the License for the
  16661. * specific language governing permissions and limitations
  16662. * under the License.
  16663. */
  16664. var inner$2 = makeInner();
  16665. function getNearestColorPalette(colors, requestColorNum) {
  16666. var paletteNum = colors.length;
  16667. // TODO colors must be in order
  16668. for (var i = 0; i < paletteNum; i++) {
  16669. if (colors[i].length > requestColorNum) {
  16670. return colors[i];
  16671. }
  16672. }
  16673. return colors[paletteNum - 1];
  16674. }
  16675. var colorPaletteMixin = {
  16676. clearColorPalette: function () {
  16677. inner$2(this).colorIdx = 0;
  16678. inner$2(this).colorNameMap = {};
  16679. },
  16680. /**
  16681. * @param {string} name MUST NOT be null/undefined. Otherwise call this function
  16682. * twise with the same parameters will get different result.
  16683. * @param {Object} [scope=this]
  16684. * @param {Object} [requestColorNum]
  16685. * @return {string} color string.
  16686. */
  16687. getColorFromPalette: function (name, scope, requestColorNum) {
  16688. scope = scope || this;
  16689. var scopeFields = inner$2(scope);
  16690. var colorIdx = scopeFields.colorIdx || 0;
  16691. var colorNameMap = scopeFields.colorNameMap = scopeFields.colorNameMap || {};
  16692. // Use `hasOwnProperty` to avoid conflict with Object.prototype.
  16693. if (colorNameMap.hasOwnProperty(name)) {
  16694. return colorNameMap[name];
  16695. }
  16696. var defaultColorPalette = normalizeToArray(this.get('color', true));
  16697. var layeredColorPalette = this.get('colorLayer', true);
  16698. var colorPalette = ((requestColorNum == null || !layeredColorPalette)
  16699. ? defaultColorPalette : getNearestColorPalette(layeredColorPalette, requestColorNum));
  16700. // In case can't find in layered color palette.
  16701. colorPalette = colorPalette || defaultColorPalette;
  16702. if (!colorPalette || !colorPalette.length) {
  16703. return;
  16704. }
  16705. var color = colorPalette[colorIdx];
  16706. if (name) {
  16707. colorNameMap[name] = color;
  16708. }
  16709. scopeFields.colorIdx = (colorIdx + 1) % colorPalette.length;
  16710. return color;
  16711. }
  16712. };
  16713. /*
  16714. * Licensed to the Apache Software Foundation (ASF) under one
  16715. * or more contributor license agreements. See the NOTICE file
  16716. * distributed with this work for additional information
  16717. * regarding copyright ownership. The ASF licenses this file
  16718. * to you under the Apache License, Version 2.0 (the
  16719. * "License"); you may not use this file except in compliance
  16720. * with the License. You may obtain a copy of the License at
  16721. *
  16722. * http://www.apache.org/licenses/LICENSE-2.0
  16723. *
  16724. * Unless required by applicable law or agreed to in writing,
  16725. * software distributed under the License is distributed on an
  16726. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16727. * KIND, either express or implied. See the License for the
  16728. * specific language governing permissions and limitations
  16729. * under the License.
  16730. */
  16731. /**
  16732. * Helper for model references.
  16733. * There are many manners to refer axis/coordSys.
  16734. */
  16735. // TODO
  16736. // merge relevant logic to this file?
  16737. // check: "modelHelper" of tooltip and "BrushTargetManager".
  16738. /**
  16739. * @return {Object} For example:
  16740. * {
  16741. * coordSysName: 'cartesian2d',
  16742. * coordSysDims: ['x', 'y', ...],
  16743. * axisMap: HashMap({
  16744. * x: xAxisModel,
  16745. * y: yAxisModel
  16746. * }),
  16747. * categoryAxisMap: HashMap({
  16748. * x: xAxisModel,
  16749. * y: undefined
  16750. * }),
  16751. * // It also indicate that whether there is category axis.
  16752. * firstCategoryDimIndex: 1,
  16753. * // To replace user specified encode.
  16754. * }
  16755. */
  16756. function getCoordSysDefineBySeries(seriesModel) {
  16757. var coordSysName = seriesModel.get('coordinateSystem');
  16758. var result = {
  16759. coordSysName: coordSysName,
  16760. coordSysDims: [],
  16761. axisMap: createHashMap(),
  16762. categoryAxisMap: createHashMap()
  16763. };
  16764. var fetch = fetchers[coordSysName];
  16765. if (fetch) {
  16766. fetch(seriesModel, result, result.axisMap, result.categoryAxisMap);
  16767. return result;
  16768. }
  16769. }
  16770. var fetchers = {
  16771. cartesian2d: function (seriesModel, result, axisMap, categoryAxisMap) {
  16772. var xAxisModel = seriesModel.getReferringComponents('xAxis')[0];
  16773. var yAxisModel = seriesModel.getReferringComponents('yAxis')[0];
  16774. if (__DEV__) {
  16775. if (!xAxisModel) {
  16776. throw new Error('xAxis "' + retrieve(
  16777. seriesModel.get('xAxisIndex'),
  16778. seriesModel.get('xAxisId'),
  16779. 0
  16780. ) + '" not found');
  16781. }
  16782. if (!yAxisModel) {
  16783. throw new Error('yAxis "' + retrieve(
  16784. seriesModel.get('xAxisIndex'),
  16785. seriesModel.get('yAxisId'),
  16786. 0
  16787. ) + '" not found');
  16788. }
  16789. }
  16790. result.coordSysDims = ['x', 'y'];
  16791. axisMap.set('x', xAxisModel);
  16792. axisMap.set('y', yAxisModel);
  16793. if (isCategory(xAxisModel)) {
  16794. categoryAxisMap.set('x', xAxisModel);
  16795. result.firstCategoryDimIndex = 0;
  16796. }
  16797. if (isCategory(yAxisModel)) {
  16798. categoryAxisMap.set('y', yAxisModel);
  16799. result.firstCategoryDimIndex = 1;
  16800. }
  16801. },
  16802. singleAxis: function (seriesModel, result, axisMap, categoryAxisMap) {
  16803. var singleAxisModel = seriesModel.getReferringComponents('singleAxis')[0];
  16804. if (__DEV__) {
  16805. if (!singleAxisModel) {
  16806. throw new Error('singleAxis should be specified.');
  16807. }
  16808. }
  16809. result.coordSysDims = ['single'];
  16810. axisMap.set('single', singleAxisModel);
  16811. if (isCategory(singleAxisModel)) {
  16812. categoryAxisMap.set('single', singleAxisModel);
  16813. result.firstCategoryDimIndex = 0;
  16814. }
  16815. },
  16816. polar: function (seriesModel, result, axisMap, categoryAxisMap) {
  16817. var polarModel = seriesModel.getReferringComponents('polar')[0];
  16818. var radiusAxisModel = polarModel.findAxisModel('radiusAxis');
  16819. var angleAxisModel = polarModel.findAxisModel('angleAxis');
  16820. if (__DEV__) {
  16821. if (!angleAxisModel) {
  16822. throw new Error('angleAxis option not found');
  16823. }
  16824. if (!radiusAxisModel) {
  16825. throw new Error('radiusAxis option not found');
  16826. }
  16827. }
  16828. result.coordSysDims = ['radius', 'angle'];
  16829. axisMap.set('radius', radiusAxisModel);
  16830. axisMap.set('angle', angleAxisModel);
  16831. if (isCategory(radiusAxisModel)) {
  16832. categoryAxisMap.set('radius', radiusAxisModel);
  16833. result.firstCategoryDimIndex = 0;
  16834. }
  16835. if (isCategory(angleAxisModel)) {
  16836. categoryAxisMap.set('angle', angleAxisModel);
  16837. result.firstCategoryDimIndex = 1;
  16838. }
  16839. },
  16840. geo: function (seriesModel, result, axisMap, categoryAxisMap) {
  16841. result.coordSysDims = ['lng', 'lat'];
  16842. },
  16843. parallel: function (seriesModel, result, axisMap, categoryAxisMap) {
  16844. var ecModel = seriesModel.ecModel;
  16845. var parallelModel = ecModel.getComponent(
  16846. 'parallel', seriesModel.get('parallelIndex')
  16847. );
  16848. var coordSysDims = result.coordSysDims = parallelModel.dimensions.slice();
  16849. each$1(parallelModel.parallelAxisIndex, function (axisIndex, index) {
  16850. var axisModel = ecModel.getComponent('parallelAxis', axisIndex);
  16851. var axisDim = coordSysDims[index];
  16852. axisMap.set(axisDim, axisModel);
  16853. if (isCategory(axisModel) && result.firstCategoryDimIndex == null) {
  16854. categoryAxisMap.set(axisDim, axisModel);
  16855. result.firstCategoryDimIndex = index;
  16856. }
  16857. });
  16858. }
  16859. };
  16860. function isCategory(axisModel) {
  16861. return axisModel.get('type') === 'category';
  16862. }
  16863. /*
  16864. * Licensed to the Apache Software Foundation (ASF) under one
  16865. * or more contributor license agreements. See the NOTICE file
  16866. * distributed with this work for additional information
  16867. * regarding copyright ownership. The ASF licenses this file
  16868. * to you under the Apache License, Version 2.0 (the
  16869. * "License"); you may not use this file except in compliance
  16870. * with the License. You may obtain a copy of the License at
  16871. *
  16872. * http://www.apache.org/licenses/LICENSE-2.0
  16873. *
  16874. * Unless required by applicable law or agreed to in writing,
  16875. * software distributed under the License is distributed on an
  16876. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16877. * KIND, either express or implied. See the License for the
  16878. * specific language governing permissions and limitations
  16879. * under the License.
  16880. */
  16881. // Avoid typo.
  16882. var SOURCE_FORMAT_ORIGINAL = 'original';
  16883. var SOURCE_FORMAT_ARRAY_ROWS = 'arrayRows';
  16884. var SOURCE_FORMAT_OBJECT_ROWS = 'objectRows';
  16885. var SOURCE_FORMAT_KEYED_COLUMNS = 'keyedColumns';
  16886. var SOURCE_FORMAT_UNKNOWN = 'unknown';
  16887. // ??? CHANGE A NAME
  16888. var SOURCE_FORMAT_TYPED_ARRAY = 'typedArray';
  16889. var SERIES_LAYOUT_BY_COLUMN = 'column';
  16890. var SERIES_LAYOUT_BY_ROW = 'row';
  16891. /*
  16892. * Licensed to the Apache Software Foundation (ASF) under one
  16893. * or more contributor license agreements. See the NOTICE file
  16894. * distributed with this work for additional information
  16895. * regarding copyright ownership. The ASF licenses this file
  16896. * to you under the Apache License, Version 2.0 (the
  16897. * "License"); you may not use this file except in compliance
  16898. * with the License. You may obtain a copy of the License at
  16899. *
  16900. * http://www.apache.org/licenses/LICENSE-2.0
  16901. *
  16902. * Unless required by applicable law or agreed to in writing,
  16903. * software distributed under the License is distributed on an
  16904. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16905. * KIND, either express or implied. See the License for the
  16906. * specific language governing permissions and limitations
  16907. * under the License.
  16908. */
  16909. /**
  16910. * [sourceFormat]
  16911. *
  16912. * + "original":
  16913. * This format is only used in series.data, where
  16914. * itemStyle can be specified in data item.
  16915. *
  16916. * + "arrayRows":
  16917. * [
  16918. * ['product', 'score', 'amount'],
  16919. * ['Matcha Latte', 89.3, 95.8],
  16920. * ['Milk Tea', 92.1, 89.4],
  16921. * ['Cheese Cocoa', 94.4, 91.2],
  16922. * ['Walnut Brownie', 85.4, 76.9]
  16923. * ]
  16924. *
  16925. * + "objectRows":
  16926. * [
  16927. * {product: 'Matcha Latte', score: 89.3, amount: 95.8},
  16928. * {product: 'Milk Tea', score: 92.1, amount: 89.4},
  16929. * {product: 'Cheese Cocoa', score: 94.4, amount: 91.2},
  16930. * {product: 'Walnut Brownie', score: 85.4, amount: 76.9}
  16931. * ]
  16932. *
  16933. * + "keyedColumns":
  16934. * {
  16935. * 'product': ['Matcha Latte', 'Milk Tea', 'Cheese Cocoa', 'Walnut Brownie'],
  16936. * 'count': [823, 235, 1042, 988],
  16937. * 'score': [95.8, 81.4, 91.2, 76.9]
  16938. * }
  16939. *
  16940. * + "typedArray"
  16941. *
  16942. * + "unknown"
  16943. */
  16944. /**
  16945. * @constructor
  16946. * @param {Object} fields
  16947. * @param {string} fields.sourceFormat
  16948. * @param {Array|Object} fields.fromDataset
  16949. * @param {Array|Object} [fields.data]
  16950. * @param {string} [seriesLayoutBy='column']
  16951. * @param {Array.<Object|string>} [dimensionsDefine]
  16952. * @param {Objet|HashMap} [encodeDefine]
  16953. * @param {number} [startIndex=0]
  16954. * @param {number} [dimensionsDetectCount]
  16955. */
  16956. function Source(fields) {
  16957. /**
  16958. * @type {boolean}
  16959. */
  16960. this.fromDataset = fields.fromDataset;
  16961. /**
  16962. * Not null/undefined.
  16963. * @type {Array|Object}
  16964. */
  16965. this.data = fields.data || (
  16966. fields.sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS ? {} : []
  16967. );
  16968. /**
  16969. * See also "detectSourceFormat".
  16970. * Not null/undefined.
  16971. * @type {string}
  16972. */
  16973. this.sourceFormat = fields.sourceFormat || SOURCE_FORMAT_UNKNOWN;
  16974. /**
  16975. * 'row' or 'column'
  16976. * Not null/undefined.
  16977. * @type {string} seriesLayoutBy
  16978. */
  16979. this.seriesLayoutBy = fields.seriesLayoutBy || SERIES_LAYOUT_BY_COLUMN;
  16980. /**
  16981. * dimensions definition in option.
  16982. * can be null/undefined.
  16983. * @type {Array.<Object|string>}
  16984. */
  16985. this.dimensionsDefine = fields.dimensionsDefine;
  16986. /**
  16987. * encode definition in option.
  16988. * can be null/undefined.
  16989. * @type {Objet|HashMap}
  16990. */
  16991. this.encodeDefine = fields.encodeDefine && createHashMap(fields.encodeDefine);
  16992. /**
  16993. * Not null/undefined, uint.
  16994. * @type {number}
  16995. */
  16996. this.startIndex = fields.startIndex || 0;
  16997. /**
  16998. * Can be null/undefined (when unknown), uint.
  16999. * @type {number}
  17000. */
  17001. this.dimensionsDetectCount = fields.dimensionsDetectCount;
  17002. }
  17003. /**
  17004. * Wrap original series data for some compatibility cases.
  17005. */
  17006. Source.seriesDataToSource = function (data) {
  17007. return new Source({
  17008. data: data,
  17009. sourceFormat: isTypedArray(data)
  17010. ? SOURCE_FORMAT_TYPED_ARRAY
  17011. : SOURCE_FORMAT_ORIGINAL,
  17012. fromDataset: false
  17013. });
  17014. };
  17015. enableClassCheck(Source);
  17016. /*
  17017. * Licensed to the Apache Software Foundation (ASF) under one
  17018. * or more contributor license agreements. See the NOTICE file
  17019. * distributed with this work for additional information
  17020. * regarding copyright ownership. The ASF licenses this file
  17021. * to you under the Apache License, Version 2.0 (the
  17022. * "License"); you may not use this file except in compliance
  17023. * with the License. You may obtain a copy of the License at
  17024. *
  17025. * http://www.apache.org/licenses/LICENSE-2.0
  17026. *
  17027. * Unless required by applicable law or agreed to in writing,
  17028. * software distributed under the License is distributed on an
  17029. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17030. * KIND, either express or implied. See the License for the
  17031. * specific language governing permissions and limitations
  17032. * under the License.
  17033. */
  17034. var inner$3 = makeInner();
  17035. /**
  17036. * @see {module:echarts/data/Source}
  17037. * @param {module:echarts/component/dataset/DatasetModel} datasetModel
  17038. * @return {string} sourceFormat
  17039. */
  17040. function detectSourceFormat(datasetModel) {
  17041. var data = datasetModel.option.source;
  17042. var sourceFormat = SOURCE_FORMAT_UNKNOWN;
  17043. if (isTypedArray(data)) {
  17044. sourceFormat = SOURCE_FORMAT_TYPED_ARRAY;
  17045. }
  17046. else if (isArray(data)) {
  17047. // FIXME Whether tolerate null in top level array?
  17048. for (var i = 0, len = data.length; i < len; i++) {
  17049. var item = data[i];
  17050. if (item == null) {
  17051. continue;
  17052. }
  17053. else if (isArray(item)) {
  17054. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  17055. break;
  17056. }
  17057. else if (isObject$1(item)) {
  17058. sourceFormat = SOURCE_FORMAT_OBJECT_ROWS;
  17059. break;
  17060. }
  17061. }
  17062. }
  17063. else if (isObject$1(data)) {
  17064. for (var key in data) {
  17065. if (data.hasOwnProperty(key) && isArrayLike(data[key])) {
  17066. sourceFormat = SOURCE_FORMAT_KEYED_COLUMNS;
  17067. break;
  17068. }
  17069. }
  17070. }
  17071. else if (data != null) {
  17072. throw new Error('Invalid data');
  17073. }
  17074. inner$3(datasetModel).sourceFormat = sourceFormat;
  17075. }
  17076. /**
  17077. * [Scenarios]:
  17078. * (1) Provide source data directly:
  17079. * series: {
  17080. * encode: {...},
  17081. * dimensions: [...]
  17082. * seriesLayoutBy: 'row',
  17083. * data: [[...]]
  17084. * }
  17085. * (2) Refer to datasetModel.
  17086. * series: [{
  17087. * encode: {...}
  17088. * // Ignore datasetIndex means `datasetIndex: 0`
  17089. * // and the dimensions defination in dataset is used
  17090. * }, {
  17091. * encode: {...},
  17092. * seriesLayoutBy: 'column',
  17093. * datasetIndex: 1
  17094. * }]
  17095. *
  17096. * Get data from series itself or datset.
  17097. * @return {module:echarts/data/Source} source
  17098. */
  17099. function getSource(seriesModel) {
  17100. return inner$3(seriesModel).source;
  17101. }
  17102. /**
  17103. * MUST be called before mergeOption of all series.
  17104. * @param {module:echarts/model/Global} ecModel
  17105. */
  17106. function resetSourceDefaulter(ecModel) {
  17107. // `datasetMap` is used to make default encode.
  17108. inner$3(ecModel).datasetMap = createHashMap();
  17109. }
  17110. /**
  17111. * [Caution]:
  17112. * MUST be called after series option merged and
  17113. * before "series.getInitailData()" called.
  17114. *
  17115. * [The rule of making default encode]:
  17116. * Category axis (if exists) alway map to the first dimension.
  17117. * Each other axis occupies a subsequent dimension.
  17118. *
  17119. * [Why make default encode]:
  17120. * Simplify the typing of encode in option, avoiding the case like that:
  17121. * series: [{encode: {x: 0, y: 1}}, {encode: {x: 0, y: 2}}, {encode: {x: 0, y: 3}}],
  17122. * where the "y" have to be manually typed as "1, 2, 3, ...".
  17123. *
  17124. * @param {module:echarts/model/Series} seriesModel
  17125. */
  17126. function prepareSource(seriesModel) {
  17127. var seriesOption = seriesModel.option;
  17128. var data = seriesOption.data;
  17129. var sourceFormat = isTypedArray(data)
  17130. ? SOURCE_FORMAT_TYPED_ARRAY : SOURCE_FORMAT_ORIGINAL;
  17131. var fromDataset = false;
  17132. var seriesLayoutBy = seriesOption.seriesLayoutBy;
  17133. var sourceHeader = seriesOption.sourceHeader;
  17134. var dimensionsDefine = seriesOption.dimensions;
  17135. var datasetModel = getDatasetModel(seriesModel);
  17136. if (datasetModel) {
  17137. var datasetOption = datasetModel.option;
  17138. data = datasetOption.source;
  17139. sourceFormat = inner$3(datasetModel).sourceFormat;
  17140. fromDataset = true;
  17141. // These settings from series has higher priority.
  17142. seriesLayoutBy = seriesLayoutBy || datasetOption.seriesLayoutBy;
  17143. sourceHeader == null && (sourceHeader = datasetOption.sourceHeader);
  17144. dimensionsDefine = dimensionsDefine || datasetOption.dimensions;
  17145. }
  17146. var completeResult = completeBySourceData(
  17147. data, sourceFormat, seriesLayoutBy, sourceHeader, dimensionsDefine
  17148. );
  17149. // Note: dataset option does not have `encode`.
  17150. var encodeDefine = seriesOption.encode;
  17151. if (!encodeDefine && datasetModel) {
  17152. encodeDefine = makeDefaultEncode(
  17153. seriesModel, datasetModel, data, sourceFormat, seriesLayoutBy, completeResult
  17154. );
  17155. }
  17156. inner$3(seriesModel).source = new Source({
  17157. data: data,
  17158. fromDataset: fromDataset,
  17159. seriesLayoutBy: seriesLayoutBy,
  17160. sourceFormat: sourceFormat,
  17161. dimensionsDefine: completeResult.dimensionsDefine,
  17162. startIndex: completeResult.startIndex,
  17163. dimensionsDetectCount: completeResult.dimensionsDetectCount,
  17164. encodeDefine: encodeDefine
  17165. });
  17166. }
  17167. // return {startIndex, dimensionsDefine, dimensionsCount}
  17168. function completeBySourceData(data, sourceFormat, seriesLayoutBy, sourceHeader, dimensionsDefine) {
  17169. if (!data) {
  17170. return {dimensionsDefine: normalizeDimensionsDefine(dimensionsDefine)};
  17171. }
  17172. var dimensionsDetectCount;
  17173. var startIndex;
  17174. var findPotentialName;
  17175. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  17176. // Rule: Most of the first line are string: it is header.
  17177. // Caution: consider a line with 5 string and 1 number,
  17178. // it still can not be sure it is a head, because the
  17179. // 5 string may be 5 values of category columns.
  17180. if (sourceHeader === 'auto' || sourceHeader == null) {
  17181. arrayRowsTravelFirst(function (val) {
  17182. // '-' is regarded as null/undefined.
  17183. if (val != null && val !== '-') {
  17184. if (isString(val)) {
  17185. startIndex == null && (startIndex = 1);
  17186. }
  17187. else {
  17188. startIndex = 0;
  17189. }
  17190. }
  17191. // 10 is an experience number, avoid long loop.
  17192. }, seriesLayoutBy, data, 10);
  17193. }
  17194. else {
  17195. startIndex = sourceHeader ? 1 : 0;
  17196. }
  17197. if (!dimensionsDefine && startIndex === 1) {
  17198. dimensionsDefine = [];
  17199. arrayRowsTravelFirst(function (val, index) {
  17200. dimensionsDefine[index] = val != null ? val : '';
  17201. }, seriesLayoutBy, data);
  17202. }
  17203. dimensionsDetectCount = dimensionsDefine
  17204. ? dimensionsDefine.length
  17205. : seriesLayoutBy === SERIES_LAYOUT_BY_ROW
  17206. ? data.length
  17207. : data[0]
  17208. ? data[0].length
  17209. : null;
  17210. }
  17211. else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  17212. if (!dimensionsDefine) {
  17213. dimensionsDefine = objectRowsCollectDimensions(data);
  17214. findPotentialName = true;
  17215. }
  17216. }
  17217. else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  17218. if (!dimensionsDefine) {
  17219. dimensionsDefine = [];
  17220. findPotentialName = true;
  17221. each$1(data, function (colArr, key) {
  17222. dimensionsDefine.push(key);
  17223. });
  17224. }
  17225. }
  17226. else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  17227. var value0 = getDataItemValue(data[0]);
  17228. dimensionsDetectCount = isArray(value0) && value0.length || 1;
  17229. }
  17230. else if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  17231. if (__DEV__) {
  17232. assert$1(!!dimensionsDefine, 'dimensions must be given if data is TypedArray.');
  17233. }
  17234. }
  17235. var potentialNameDimIndex;
  17236. if (findPotentialName) {
  17237. each$1(dimensionsDefine, function (dim, idx) {
  17238. if ((isObject$1(dim) ? dim.name : dim) === 'name') {
  17239. potentialNameDimIndex = idx;
  17240. }
  17241. });
  17242. }
  17243. return {
  17244. startIndex: startIndex,
  17245. dimensionsDefine: normalizeDimensionsDefine(dimensionsDefine),
  17246. dimensionsDetectCount: dimensionsDetectCount,
  17247. potentialNameDimIndex: potentialNameDimIndex
  17248. // TODO: potentialIdDimIdx
  17249. };
  17250. }
  17251. // Consider dimensions defined like ['A', 'price', 'B', 'price', 'C', 'price'],
  17252. // which is reasonable. But dimension name is duplicated.
  17253. // Returns undefined or an array contains only object without null/undefiend or string.
  17254. function normalizeDimensionsDefine(dimensionsDefine) {
  17255. if (!dimensionsDefine) {
  17256. // The meaning of null/undefined is different from empty array.
  17257. return;
  17258. }
  17259. var nameMap = createHashMap();
  17260. return map(dimensionsDefine, function (item, index) {
  17261. item = extend({}, isObject$1(item) ? item : {name: item});
  17262. // User can set null in dimensions.
  17263. // We dont auto specify name, othewise a given name may
  17264. // cause it be refered unexpectedly.
  17265. if (item.name == null) {
  17266. return item;
  17267. }
  17268. // Also consider number form like 2012.
  17269. item.name += '';
  17270. // User may also specify displayName.
  17271. // displayName will always exists except user not
  17272. // specified or dim name is not specified or detected.
  17273. // (A auto generated dim name will not be used as
  17274. // displayName).
  17275. if (item.displayName == null) {
  17276. item.displayName = item.name;
  17277. }
  17278. var exist = nameMap.get(item.name);
  17279. if (!exist) {
  17280. nameMap.set(item.name, {count: 1});
  17281. }
  17282. else {
  17283. item.name += '-' + exist.count++;
  17284. }
  17285. return item;
  17286. });
  17287. }
  17288. function arrayRowsTravelFirst(cb, seriesLayoutBy, data, maxLoop) {
  17289. maxLoop == null && (maxLoop = Infinity);
  17290. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  17291. for (var i = 0; i < data.length && i < maxLoop; i++) {
  17292. cb(data[i] ? data[i][0] : null, i);
  17293. }
  17294. }
  17295. else {
  17296. var value0 = data[0] || [];
  17297. for (var i = 0; i < value0.length && i < maxLoop; i++) {
  17298. cb(value0[i], i);
  17299. }
  17300. }
  17301. }
  17302. function objectRowsCollectDimensions(data) {
  17303. var firstIndex = 0;
  17304. var obj;
  17305. while (firstIndex < data.length && !(obj = data[firstIndex++])) {} // jshint ignore: line
  17306. if (obj) {
  17307. var dimensions = [];
  17308. each$1(obj, function (value, key) {
  17309. dimensions.push(key);
  17310. });
  17311. return dimensions;
  17312. }
  17313. }
  17314. // ??? TODO merge to completedimensions, where also has
  17315. // default encode making logic. And the default rule
  17316. // should depends on series? consider 'map'.
  17317. function makeDefaultEncode(
  17318. seriesModel, datasetModel, data, sourceFormat, seriesLayoutBy, completeResult
  17319. ) {
  17320. var coordSysDefine = getCoordSysDefineBySeries(seriesModel);
  17321. var encode = {};
  17322. // var encodeTooltip = [];
  17323. // var encodeLabel = [];
  17324. var encodeItemName = [];
  17325. var encodeSeriesName = [];
  17326. var seriesType = seriesModel.subType;
  17327. // ??? TODO refactor: provide by series itself.
  17328. // Consider the case: 'map' series is based on geo coordSys,
  17329. // 'graph', 'heatmap' can be based on cartesian. But can not
  17330. // give default rule simply here.
  17331. var nSeriesMap = createHashMap(['pie', 'map', 'funnel']);
  17332. var cSeriesMap = createHashMap([
  17333. 'line', 'bar', 'pictorialBar', 'scatter', 'effectScatter', 'candlestick', 'boxplot'
  17334. ]);
  17335. // Usually in this case series will use the first data
  17336. // dimension as the "value" dimension, or other default
  17337. // processes respectively.
  17338. if (coordSysDefine && cSeriesMap.get(seriesType) != null) {
  17339. var ecModel = seriesModel.ecModel;
  17340. var datasetMap = inner$3(ecModel).datasetMap;
  17341. var key = datasetModel.uid + '_' + seriesLayoutBy;
  17342. var datasetRecord = datasetMap.get(key)
  17343. || datasetMap.set(key, {categoryWayDim: 1, valueWayDim: 0});
  17344. // TODO
  17345. // Auto detect first time axis and do arrangement.
  17346. each$1(coordSysDefine.coordSysDims, function (coordDim) {
  17347. // In value way.
  17348. if (coordSysDefine.firstCategoryDimIndex == null) {
  17349. var dataDim = datasetRecord.valueWayDim++;
  17350. encode[coordDim] = dataDim;
  17351. // ??? TODO give a better default series name rule?
  17352. // especially when encode x y specified.
  17353. // consider: when mutiple series share one dimension
  17354. // category axis, series name should better use
  17355. // the other dimsion name. On the other hand, use
  17356. // both dimensions name.
  17357. encodeSeriesName.push(dataDim);
  17358. // encodeTooltip.push(dataDim);
  17359. // encodeLabel.push(dataDim);
  17360. }
  17361. // In category way, category axis.
  17362. else if (coordSysDefine.categoryAxisMap.get(coordDim)) {
  17363. encode[coordDim] = 0;
  17364. encodeItemName.push(0);
  17365. }
  17366. // In category way, non-category axis.
  17367. else {
  17368. var dataDim = datasetRecord.categoryWayDim++;
  17369. encode[coordDim] = dataDim;
  17370. // encodeTooltip.push(dataDim);
  17371. // encodeLabel.push(dataDim);
  17372. encodeSeriesName.push(dataDim);
  17373. }
  17374. });
  17375. }
  17376. // Do not make a complex rule! Hard to code maintain and not necessary.
  17377. // ??? TODO refactor: provide by series itself.
  17378. // [{name: ..., value: ...}, ...] like:
  17379. else if (nSeriesMap.get(seriesType) != null) {
  17380. // Find the first not ordinal. (5 is an experience value)
  17381. var firstNotOrdinal;
  17382. for (var i = 0; i < 5 && firstNotOrdinal == null; i++) {
  17383. if (!doGuessOrdinal(
  17384. data, sourceFormat, seriesLayoutBy,
  17385. completeResult.dimensionsDefine, completeResult.startIndex, i
  17386. )) {
  17387. firstNotOrdinal = i;
  17388. }
  17389. }
  17390. if (firstNotOrdinal != null) {
  17391. encode.value = firstNotOrdinal;
  17392. var nameDimIndex = completeResult.potentialNameDimIndex
  17393. || Math.max(firstNotOrdinal - 1, 0);
  17394. // By default, label use itemName in charts.
  17395. // So we dont set encodeLabel here.
  17396. encodeSeriesName.push(nameDimIndex);
  17397. encodeItemName.push(nameDimIndex);
  17398. // encodeTooltip.push(firstNotOrdinal);
  17399. }
  17400. }
  17401. // encodeTooltip.length && (encode.tooltip = encodeTooltip);
  17402. // encodeLabel.length && (encode.label = encodeLabel);
  17403. encodeItemName.length && (encode.itemName = encodeItemName);
  17404. encodeSeriesName.length && (encode.seriesName = encodeSeriesName);
  17405. return encode;
  17406. }
  17407. /**
  17408. * If return null/undefined, indicate that should not use datasetModel.
  17409. */
  17410. function getDatasetModel(seriesModel) {
  17411. var option = seriesModel.option;
  17412. // Caution: consider the scenario:
  17413. // A dataset is declared and a series is not expected to use the dataset,
  17414. // and at the beginning `setOption({series: { noData })` (just prepare other
  17415. // option but no data), then `setOption({series: {data: [...]}); In this case,
  17416. // the user should set an empty array to avoid that dataset is used by default.
  17417. var thisData = option.data;
  17418. if (!thisData) {
  17419. return seriesModel.ecModel.getComponent('dataset', option.datasetIndex || 0);
  17420. }
  17421. }
  17422. /**
  17423. * The rule should not be complex, otherwise user might not
  17424. * be able to known where the data is wrong.
  17425. * The code is ugly, but how to make it neat?
  17426. *
  17427. * @param {module:echars/data/Source} source
  17428. * @param {number} dimIndex
  17429. * @return {boolean} Whether ordinal.
  17430. */
  17431. function guessOrdinal(source, dimIndex) {
  17432. return doGuessOrdinal(
  17433. source.data,
  17434. source.sourceFormat,
  17435. source.seriesLayoutBy,
  17436. source.dimensionsDefine,
  17437. source.startIndex,
  17438. dimIndex
  17439. );
  17440. }
  17441. // dimIndex may be overflow source data.
  17442. function doGuessOrdinal(
  17443. data, sourceFormat, seriesLayoutBy, dimensionsDefine, startIndex, dimIndex
  17444. ) {
  17445. var result;
  17446. // Experience value.
  17447. var maxLoop = 5;
  17448. if (isTypedArray(data)) {
  17449. return false;
  17450. }
  17451. // When sourceType is 'objectRows' or 'keyedColumns', dimensionsDefine
  17452. // always exists in source.
  17453. var dimName;
  17454. if (dimensionsDefine) {
  17455. dimName = dimensionsDefine[dimIndex];
  17456. dimName = isObject$1(dimName) ? dimName.name : dimName;
  17457. }
  17458. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  17459. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  17460. var sample = data[dimIndex];
  17461. for (var i = 0; i < (sample || []).length && i < maxLoop; i++) {
  17462. if ((result = detectValue(sample[startIndex + i])) != null) {
  17463. return result;
  17464. }
  17465. }
  17466. }
  17467. else {
  17468. for (var i = 0; i < data.length && i < maxLoop; i++) {
  17469. var row = data[startIndex + i];
  17470. if (row && (result = detectValue(row[dimIndex])) != null) {
  17471. return result;
  17472. }
  17473. }
  17474. }
  17475. }
  17476. else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  17477. if (!dimName) {
  17478. return;
  17479. }
  17480. for (var i = 0; i < data.length && i < maxLoop; i++) {
  17481. var item = data[i];
  17482. if (item && (result = detectValue(item[dimName])) != null) {
  17483. return result;
  17484. }
  17485. }
  17486. }
  17487. else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  17488. if (!dimName) {
  17489. return;
  17490. }
  17491. var sample = data[dimName];
  17492. if (!sample || isTypedArray(sample)) {
  17493. return false;
  17494. }
  17495. for (var i = 0; i < sample.length && i < maxLoop; i++) {
  17496. if ((result = detectValue(sample[i])) != null) {
  17497. return result;
  17498. }
  17499. }
  17500. }
  17501. else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  17502. for (var i = 0; i < data.length && i < maxLoop; i++) {
  17503. var item = data[i];
  17504. var val = getDataItemValue(item);
  17505. if (!isArray(val)) {
  17506. return false;
  17507. }
  17508. if ((result = detectValue(val[dimIndex])) != null) {
  17509. return result;
  17510. }
  17511. }
  17512. }
  17513. function detectValue(val) {
  17514. // Consider usage convenience, '1', '2' will be treated as "number".
  17515. // `isFinit('')` get `true`.
  17516. if (val != null && isFinite(val) && val !== '') {
  17517. return false;
  17518. }
  17519. else if (isString(val) && val !== '-') {
  17520. return true;
  17521. }
  17522. }
  17523. return false;
  17524. }
  17525. /*
  17526. * Licensed to the Apache Software Foundation (ASF) under one
  17527. * or more contributor license agreements. See the NOTICE file
  17528. * distributed with this work for additional information
  17529. * regarding copyright ownership. The ASF licenses this file
  17530. * to you under the Apache License, Version 2.0 (the
  17531. * "License"); you may not use this file except in compliance
  17532. * with the License. You may obtain a copy of the License at
  17533. *
  17534. * http://www.apache.org/licenses/LICENSE-2.0
  17535. *
  17536. * Unless required by applicable law or agreed to in writing,
  17537. * software distributed under the License is distributed on an
  17538. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17539. * KIND, either express or implied. See the License for the
  17540. * specific language governing permissions and limitations
  17541. * under the License.
  17542. */
  17543. /**
  17544. * ECharts global model
  17545. *
  17546. * @module {echarts/model/Global}
  17547. */
  17548. /**
  17549. * Caution: If the mechanism should be changed some day, these cases
  17550. * should be considered:
  17551. *
  17552. * (1) In `merge option` mode, if using the same option to call `setOption`
  17553. * many times, the result should be the same (try our best to ensure that).
  17554. * (2) In `merge option` mode, if a component has no id/name specified, it
  17555. * will be merged by index, and the result sequence of the components is
  17556. * consistent to the original sequence.
  17557. * (3) `reset` feature (in toolbox). Find detailed info in comments about
  17558. * `mergeOption` in module:echarts/model/OptionManager.
  17559. */
  17560. var OPTION_INNER_KEY = '\0_ec_inner';
  17561. /**
  17562. * @alias module:echarts/model/Global
  17563. *
  17564. * @param {Object} option
  17565. * @param {module:echarts/model/Model} parentModel
  17566. * @param {Object} theme
  17567. */
  17568. var GlobalModel = Model.extend({
  17569. init: function (option, parentModel, theme, optionManager) {
  17570. theme = theme || {};
  17571. this.option = null; // Mark as not initialized.
  17572. /**
  17573. * @type {module:echarts/model/Model}
  17574. * @private
  17575. */
  17576. this._theme = new Model(theme);
  17577. /**
  17578. * @type {module:echarts/model/OptionManager}
  17579. */
  17580. this._optionManager = optionManager;
  17581. },
  17582. setOption: function (option, optionPreprocessorFuncs) {
  17583. assert$1(
  17584. !(OPTION_INNER_KEY in option),
  17585. 'please use chart.getOption()'
  17586. );
  17587. this._optionManager.setOption(option, optionPreprocessorFuncs);
  17588. this.resetOption(null);
  17589. },
  17590. /**
  17591. * @param {string} type null/undefined: reset all.
  17592. * 'recreate': force recreate all.
  17593. * 'timeline': only reset timeline option
  17594. * 'media': only reset media query option
  17595. * @return {boolean} Whether option changed.
  17596. */
  17597. resetOption: function (type) {
  17598. var optionChanged = false;
  17599. var optionManager = this._optionManager;
  17600. if (!type || type === 'recreate') {
  17601. var baseOption = optionManager.mountOption(type === 'recreate');
  17602. if (!this.option || type === 'recreate') {
  17603. initBase.call(this, baseOption);
  17604. }
  17605. else {
  17606. this.restoreData();
  17607. this.mergeOption(baseOption);
  17608. }
  17609. optionChanged = true;
  17610. }
  17611. if (type === 'timeline' || type === 'media') {
  17612. this.restoreData();
  17613. }
  17614. if (!type || type === 'recreate' || type === 'timeline') {
  17615. var timelineOption = optionManager.getTimelineOption(this);
  17616. timelineOption && (this.mergeOption(timelineOption), optionChanged = true);
  17617. }
  17618. if (!type || type === 'recreate' || type === 'media') {
  17619. var mediaOptions = optionManager.getMediaOption(this, this._api);
  17620. if (mediaOptions.length) {
  17621. each$1(mediaOptions, function (mediaOption) {
  17622. this.mergeOption(mediaOption, optionChanged = true);
  17623. }, this);
  17624. }
  17625. }
  17626. return optionChanged;
  17627. },
  17628. /**
  17629. * @protected
  17630. */
  17631. mergeOption: function (newOption) {
  17632. var option = this.option;
  17633. var componentsMap = this._componentsMap;
  17634. var newCptTypes = [];
  17635. resetSourceDefaulter(this);
  17636. // If no component class, merge directly.
  17637. // For example: color, animaiton options, etc.
  17638. each$1(newOption, function (componentOption, mainType) {
  17639. if (componentOption == null) {
  17640. return;
  17641. }
  17642. if (!ComponentModel.hasClass(mainType)) {
  17643. // globalSettingTask.dirty();
  17644. option[mainType] = option[mainType] == null
  17645. ? clone(componentOption)
  17646. : merge(option[mainType], componentOption, true);
  17647. }
  17648. else if (mainType) {
  17649. newCptTypes.push(mainType);
  17650. }
  17651. });
  17652. ComponentModel.topologicalTravel(
  17653. newCptTypes, ComponentModel.getAllClassMainTypes(), visitComponent, this
  17654. );
  17655. function visitComponent(mainType, dependencies) {
  17656. var newCptOptionList = normalizeToArray(newOption[mainType]);
  17657. var mapResult = mappingToExists(
  17658. componentsMap.get(mainType), newCptOptionList
  17659. );
  17660. makeIdAndName(mapResult);
  17661. // Set mainType and complete subType.
  17662. each$1(mapResult, function (item, index) {
  17663. var opt = item.option;
  17664. if (isObject$1(opt)) {
  17665. item.keyInfo.mainType = mainType;
  17666. item.keyInfo.subType = determineSubType(mainType, opt, item.exist);
  17667. }
  17668. });
  17669. var dependentModels = getComponentsByTypes(
  17670. componentsMap, dependencies
  17671. );
  17672. option[mainType] = [];
  17673. componentsMap.set(mainType, []);
  17674. each$1(mapResult, function (resultItem, index) {
  17675. var componentModel = resultItem.exist;
  17676. var newCptOption = resultItem.option;
  17677. assert$1(
  17678. isObject$1(newCptOption) || componentModel,
  17679. 'Empty component definition'
  17680. );
  17681. // Consider where is no new option and should be merged using {},
  17682. // see removeEdgeAndAdd in topologicalTravel and
  17683. // ComponentModel.getAllClassMainTypes.
  17684. if (!newCptOption) {
  17685. componentModel.mergeOption({}, this);
  17686. componentModel.optionUpdated({}, false);
  17687. }
  17688. else {
  17689. var ComponentModelClass = ComponentModel.getClass(
  17690. mainType, resultItem.keyInfo.subType, true
  17691. );
  17692. if (componentModel && componentModel instanceof ComponentModelClass) {
  17693. componentModel.name = resultItem.keyInfo.name;
  17694. // componentModel.settingTask && componentModel.settingTask.dirty();
  17695. componentModel.mergeOption(newCptOption, this);
  17696. componentModel.optionUpdated(newCptOption, false);
  17697. }
  17698. else {
  17699. // PENDING Global as parent ?
  17700. var extraOpt = extend(
  17701. {
  17702. dependentModels: dependentModels,
  17703. componentIndex: index
  17704. },
  17705. resultItem.keyInfo
  17706. );
  17707. componentModel = new ComponentModelClass(
  17708. newCptOption, this, this, extraOpt
  17709. );
  17710. extend(componentModel, extraOpt);
  17711. componentModel.init(newCptOption, this, this, extraOpt);
  17712. // Call optionUpdated after init.
  17713. // newCptOption has been used as componentModel.option
  17714. // and may be merged with theme and default, so pass null
  17715. // to avoid confusion.
  17716. componentModel.optionUpdated(null, true);
  17717. }
  17718. }
  17719. componentsMap.get(mainType)[index] = componentModel;
  17720. option[mainType][index] = componentModel.option;
  17721. }, this);
  17722. // Backup series for filtering.
  17723. if (mainType === 'series') {
  17724. createSeriesIndices(this, componentsMap.get('series'));
  17725. }
  17726. }
  17727. this._seriesIndicesMap = createHashMap(
  17728. this._seriesIndices = this._seriesIndices || []
  17729. );
  17730. },
  17731. /**
  17732. * Get option for output (cloned option and inner info removed)
  17733. * @public
  17734. * @return {Object}
  17735. */
  17736. getOption: function () {
  17737. var option = clone(this.option);
  17738. each$1(option, function (opts, mainType) {
  17739. if (ComponentModel.hasClass(mainType)) {
  17740. var opts = normalizeToArray(opts);
  17741. for (var i = opts.length - 1; i >= 0; i--) {
  17742. // Remove options with inner id.
  17743. if (isIdInner(opts[i])) {
  17744. opts.splice(i, 1);
  17745. }
  17746. }
  17747. option[mainType] = opts;
  17748. }
  17749. });
  17750. delete option[OPTION_INNER_KEY];
  17751. return option;
  17752. },
  17753. /**
  17754. * @return {module:echarts/model/Model}
  17755. */
  17756. getTheme: function () {
  17757. return this._theme;
  17758. },
  17759. /**
  17760. * @param {string} mainType
  17761. * @param {number} [idx=0]
  17762. * @return {module:echarts/model/Component}
  17763. */
  17764. getComponent: function (mainType, idx) {
  17765. var list = this._componentsMap.get(mainType);
  17766. if (list) {
  17767. return list[idx || 0];
  17768. }
  17769. },
  17770. /**
  17771. * If none of index and id and name used, return all components with mainType.
  17772. * @param {Object} condition
  17773. * @param {string} condition.mainType
  17774. * @param {string} [condition.subType] If ignore, only query by mainType
  17775. * @param {number|Array.<number>} [condition.index] Either input index or id or name.
  17776. * @param {string|Array.<string>} [condition.id] Either input index or id or name.
  17777. * @param {string|Array.<string>} [condition.name] Either input index or id or name.
  17778. * @return {Array.<module:echarts/model/Component>}
  17779. */
  17780. queryComponents: function (condition) {
  17781. var mainType = condition.mainType;
  17782. if (!mainType) {
  17783. return [];
  17784. }
  17785. var index = condition.index;
  17786. var id = condition.id;
  17787. var name = condition.name;
  17788. var cpts = this._componentsMap.get(mainType);
  17789. if (!cpts || !cpts.length) {
  17790. return [];
  17791. }
  17792. var result;
  17793. if (index != null) {
  17794. if (!isArray(index)) {
  17795. index = [index];
  17796. }
  17797. result = filter(map(index, function (idx) {
  17798. return cpts[idx];
  17799. }), function (val) {
  17800. return !!val;
  17801. });
  17802. }
  17803. else if (id != null) {
  17804. var isIdArray = isArray(id);
  17805. result = filter(cpts, function (cpt) {
  17806. return (isIdArray && indexOf(id, cpt.id) >= 0)
  17807. || (!isIdArray && cpt.id === id);
  17808. });
  17809. }
  17810. else if (name != null) {
  17811. var isNameArray = isArray(name);
  17812. result = filter(cpts, function (cpt) {
  17813. return (isNameArray && indexOf(name, cpt.name) >= 0)
  17814. || (!isNameArray && cpt.name === name);
  17815. });
  17816. }
  17817. else {
  17818. // Return all components with mainType
  17819. result = cpts.slice();
  17820. }
  17821. return filterBySubType(result, condition);
  17822. },
  17823. /**
  17824. * The interface is different from queryComponents,
  17825. * which is convenient for inner usage.
  17826. *
  17827. * @usage
  17828. * var result = findComponents(
  17829. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}}
  17830. * );
  17831. * var result = findComponents(
  17832. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}}
  17833. * );
  17834. * var result = findComponents(
  17835. * {mainType: 'series'},
  17836. * function (model, index) {...}
  17837. * );
  17838. * // result like [component0, componnet1, ...]
  17839. *
  17840. * @param {Object} condition
  17841. * @param {string} condition.mainType Mandatory.
  17842. * @param {string} [condition.subType] Optional.
  17843. * @param {Object} [condition.query] like {xxxIndex, xxxId, xxxName},
  17844. * where xxx is mainType.
  17845. * If query attribute is null/undefined or has no index/id/name,
  17846. * do not filtering by query conditions, which is convenient for
  17847. * no-payload situations or when target of action is global.
  17848. * @param {Function} [condition.filter] parameter: component, return boolean.
  17849. * @return {Array.<module:echarts/model/Component>}
  17850. */
  17851. findComponents: function (condition) {
  17852. var query = condition.query;
  17853. var mainType = condition.mainType;
  17854. var queryCond = getQueryCond(query);
  17855. var result = queryCond
  17856. ? this.queryComponents(queryCond)
  17857. : this._componentsMap.get(mainType);
  17858. return doFilter(filterBySubType(result, condition));
  17859. function getQueryCond(q) {
  17860. var indexAttr = mainType + 'Index';
  17861. var idAttr = mainType + 'Id';
  17862. var nameAttr = mainType + 'Name';
  17863. return q && (
  17864. q[indexAttr] != null
  17865. || q[idAttr] != null
  17866. || q[nameAttr] != null
  17867. )
  17868. ? {
  17869. mainType: mainType,
  17870. // subType will be filtered finally.
  17871. index: q[indexAttr],
  17872. id: q[idAttr],
  17873. name: q[nameAttr]
  17874. }
  17875. : null;
  17876. }
  17877. function doFilter(res) {
  17878. return condition.filter
  17879. ? filter(res, condition.filter)
  17880. : res;
  17881. }
  17882. },
  17883. /**
  17884. * @usage
  17885. * eachComponent('legend', function (legendModel, index) {
  17886. * ...
  17887. * });
  17888. * eachComponent(function (componentType, model, index) {
  17889. * // componentType does not include subType
  17890. * // (componentType is 'xxx' but not 'xxx.aa')
  17891. * });
  17892. * eachComponent(
  17893. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}},
  17894. * function (model, index) {...}
  17895. * );
  17896. * eachComponent(
  17897. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}},
  17898. * function (model, index) {...}
  17899. * );
  17900. *
  17901. * @param {string|Object=} mainType When mainType is object, the definition
  17902. * is the same as the method 'findComponents'.
  17903. * @param {Function} cb
  17904. * @param {*} context
  17905. */
  17906. eachComponent: function (mainType, cb, context) {
  17907. var componentsMap = this._componentsMap;
  17908. if (typeof mainType === 'function') {
  17909. context = cb;
  17910. cb = mainType;
  17911. componentsMap.each(function (components, componentType) {
  17912. each$1(components, function (component, index) {
  17913. cb.call(context, componentType, component, index);
  17914. });
  17915. });
  17916. }
  17917. else if (isString(mainType)) {
  17918. each$1(componentsMap.get(mainType), cb, context);
  17919. }
  17920. else if (isObject$1(mainType)) {
  17921. var queryResult = this.findComponents(mainType);
  17922. each$1(queryResult, cb, context);
  17923. }
  17924. },
  17925. /**
  17926. * @param {string} name
  17927. * @return {Array.<module:echarts/model/Series>}
  17928. */
  17929. getSeriesByName: function (name) {
  17930. var series = this._componentsMap.get('series');
  17931. return filter(series, function (oneSeries) {
  17932. return oneSeries.name === name;
  17933. });
  17934. },
  17935. /**
  17936. * @param {number} seriesIndex
  17937. * @return {module:echarts/model/Series}
  17938. */
  17939. getSeriesByIndex: function (seriesIndex) {
  17940. return this._componentsMap.get('series')[seriesIndex];
  17941. },
  17942. /**
  17943. * Get series list before filtered by type.
  17944. * FIXME: rename to getRawSeriesByType?
  17945. *
  17946. * @param {string} subType
  17947. * @return {Array.<module:echarts/model/Series>}
  17948. */
  17949. getSeriesByType: function (subType) {
  17950. var series = this._componentsMap.get('series');
  17951. return filter(series, function (oneSeries) {
  17952. return oneSeries.subType === subType;
  17953. });
  17954. },
  17955. /**
  17956. * @return {Array.<module:echarts/model/Series>}
  17957. */
  17958. getSeries: function () {
  17959. return this._componentsMap.get('series').slice();
  17960. },
  17961. /**
  17962. * @return {number}
  17963. */
  17964. getSeriesCount: function () {
  17965. return this._componentsMap.get('series').length;
  17966. },
  17967. /**
  17968. * After filtering, series may be different
  17969. * frome raw series.
  17970. *
  17971. * @param {Function} cb
  17972. * @param {*} context
  17973. */
  17974. eachSeries: function (cb, context) {
  17975. assertSeriesInitialized(this);
  17976. each$1(this._seriesIndices, function (rawSeriesIndex) {
  17977. var series = this._componentsMap.get('series')[rawSeriesIndex];
  17978. cb.call(context, series, rawSeriesIndex);
  17979. }, this);
  17980. },
  17981. /**
  17982. * Iterate raw series before filtered.
  17983. *
  17984. * @param {Function} cb
  17985. * @param {*} context
  17986. */
  17987. eachRawSeries: function (cb, context) {
  17988. each$1(this._componentsMap.get('series'), cb, context);
  17989. },
  17990. /**
  17991. * After filtering, series may be different.
  17992. * frome raw series.
  17993. *
  17994. * @parma {string} subType
  17995. * @param {Function} cb
  17996. * @param {*} context
  17997. */
  17998. eachSeriesByType: function (subType, cb, context) {
  17999. assertSeriesInitialized(this);
  18000. each$1(this._seriesIndices, function (rawSeriesIndex) {
  18001. var series = this._componentsMap.get('series')[rawSeriesIndex];
  18002. if (series.subType === subType) {
  18003. cb.call(context, series, rawSeriesIndex);
  18004. }
  18005. }, this);
  18006. },
  18007. /**
  18008. * Iterate raw series before filtered of given type.
  18009. *
  18010. * @parma {string} subType
  18011. * @param {Function} cb
  18012. * @param {*} context
  18013. */
  18014. eachRawSeriesByType: function (subType, cb, context) {
  18015. return each$1(this.getSeriesByType(subType), cb, context);
  18016. },
  18017. /**
  18018. * @param {module:echarts/model/Series} seriesModel
  18019. */
  18020. isSeriesFiltered: function (seriesModel) {
  18021. assertSeriesInitialized(this);
  18022. return this._seriesIndicesMap.get(seriesModel.componentIndex) == null;
  18023. },
  18024. /**
  18025. * @return {Array.<number>}
  18026. */
  18027. getCurrentSeriesIndices: function () {
  18028. return (this._seriesIndices || []).slice();
  18029. },
  18030. /**
  18031. * @param {Function} cb
  18032. * @param {*} context
  18033. */
  18034. filterSeries: function (cb, context) {
  18035. assertSeriesInitialized(this);
  18036. var filteredSeries = filter(
  18037. this._componentsMap.get('series'), cb, context
  18038. );
  18039. createSeriesIndices(this, filteredSeries);
  18040. },
  18041. restoreData: function (payload) {
  18042. var componentsMap = this._componentsMap;
  18043. createSeriesIndices(this, componentsMap.get('series'));
  18044. var componentTypes = [];
  18045. componentsMap.each(function (components, componentType) {
  18046. componentTypes.push(componentType);
  18047. });
  18048. ComponentModel.topologicalTravel(
  18049. componentTypes,
  18050. ComponentModel.getAllClassMainTypes(),
  18051. function (componentType, dependencies) {
  18052. each$1(componentsMap.get(componentType), function (component) {
  18053. (componentType !== 'series' || !isNotTargetSeries(component, payload))
  18054. && component.restoreData();
  18055. });
  18056. }
  18057. );
  18058. }
  18059. });
  18060. function isNotTargetSeries(seriesModel, payload) {
  18061. if (payload) {
  18062. var index = payload.seiresIndex;
  18063. var id = payload.seriesId;
  18064. var name = payload.seriesName;
  18065. return (index != null && seriesModel.componentIndex !== index)
  18066. || (id != null && seriesModel.id !== id)
  18067. || (name != null && seriesModel.name !== name);
  18068. }
  18069. }
  18070. /**
  18071. * @inner
  18072. */
  18073. function mergeTheme(option, theme) {
  18074. // PENDING
  18075. // NOT use `colorLayer` in theme if option has `color`
  18076. var notMergeColorLayer = option.color && !option.colorLayer;
  18077. each$1(theme, function (themeItem, name) {
  18078. if (name === 'colorLayer' && notMergeColorLayer) {
  18079. return;
  18080. }
  18081. // 如果有 component model 则把具体的 merge 逻辑交给该 model 处理
  18082. if (!ComponentModel.hasClass(name)) {
  18083. if (typeof themeItem === 'object') {
  18084. option[name] = !option[name]
  18085. ? clone(themeItem)
  18086. : merge(option[name], themeItem, false);
  18087. }
  18088. else {
  18089. if (option[name] == null) {
  18090. option[name] = themeItem;
  18091. }
  18092. }
  18093. }
  18094. });
  18095. }
  18096. function initBase(baseOption) {
  18097. baseOption = baseOption;
  18098. // Using OPTION_INNER_KEY to mark that this option can not be used outside,
  18099. // i.e. `chart.setOption(chart.getModel().option);` is forbiden.
  18100. this.option = {};
  18101. this.option[OPTION_INNER_KEY] = 1;
  18102. /**
  18103. * Init with series: [], in case of calling findSeries method
  18104. * before series initialized.
  18105. * @type {Object.<string, Array.<module:echarts/model/Model>>}
  18106. * @private
  18107. */
  18108. this._componentsMap = createHashMap({series: []});
  18109. /**
  18110. * Mapping between filtered series list and raw series list.
  18111. * key: filtered series indices, value: raw series indices.
  18112. * @type {Array.<nubmer>}
  18113. * @private
  18114. */
  18115. this._seriesIndices;
  18116. this._seriesIndicesMap;
  18117. mergeTheme(baseOption, this._theme.option);
  18118. // TODO Needs clone when merging to the unexisted property
  18119. merge(baseOption, globalDefault, false);
  18120. this.mergeOption(baseOption);
  18121. }
  18122. /**
  18123. * @inner
  18124. * @param {Array.<string>|string} types model types
  18125. * @return {Object} key: {string} type, value: {Array.<Object>} models
  18126. */
  18127. function getComponentsByTypes(componentsMap, types) {
  18128. if (!isArray(types)) {
  18129. types = types ? [types] : [];
  18130. }
  18131. var ret = {};
  18132. each$1(types, function (type) {
  18133. ret[type] = (componentsMap.get(type) || []).slice();
  18134. });
  18135. return ret;
  18136. }
  18137. /**
  18138. * @inner
  18139. */
  18140. function determineSubType(mainType, newCptOption, existComponent) {
  18141. var subType = newCptOption.type
  18142. ? newCptOption.type
  18143. : existComponent
  18144. ? existComponent.subType
  18145. // Use determineSubType only when there is no existComponent.
  18146. : ComponentModel.determineSubType(mainType, newCptOption);
  18147. // tooltip, markline, markpoint may always has no subType
  18148. return subType;
  18149. }
  18150. /**
  18151. * @inner
  18152. */
  18153. function createSeriesIndices(ecModel, seriesModels) {
  18154. ecModel._seriesIndicesMap = createHashMap(
  18155. ecModel._seriesIndices = map(seriesModels, function (series) {
  18156. return series.componentIndex;
  18157. }) || []
  18158. );
  18159. }
  18160. /**
  18161. * @inner
  18162. */
  18163. function filterBySubType(components, condition) {
  18164. // Using hasOwnProperty for restrict. Consider
  18165. // subType is undefined in user payload.
  18166. return condition.hasOwnProperty('subType')
  18167. ? filter(components, function (cpt) {
  18168. return cpt.subType === condition.subType;
  18169. })
  18170. : components;
  18171. }
  18172. /**
  18173. * @inner
  18174. */
  18175. function assertSeriesInitialized(ecModel) {
  18176. // Components that use _seriesIndices should depends on series component,
  18177. // which make sure that their initialization is after series.
  18178. if (__DEV__) {
  18179. if (!ecModel._seriesIndices) {
  18180. throw new Error('Option should contains series.');
  18181. }
  18182. }
  18183. }
  18184. mixin(GlobalModel, colorPaletteMixin);
  18185. /*
  18186. * Licensed to the Apache Software Foundation (ASF) under one
  18187. * or more contributor license agreements. See the NOTICE file
  18188. * distributed with this work for additional information
  18189. * regarding copyright ownership. The ASF licenses this file
  18190. * to you under the Apache License, Version 2.0 (the
  18191. * "License"); you may not use this file except in compliance
  18192. * with the License. You may obtain a copy of the License at
  18193. *
  18194. * http://www.apache.org/licenses/LICENSE-2.0
  18195. *
  18196. * Unless required by applicable law or agreed to in writing,
  18197. * software distributed under the License is distributed on an
  18198. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18199. * KIND, either express or implied. See the License for the
  18200. * specific language governing permissions and limitations
  18201. * under the License.
  18202. */
  18203. var echartsAPIList = [
  18204. 'getDom', 'getZr', 'getWidth', 'getHeight', 'getDevicePixelRatio', 'dispatchAction', 'isDisposed',
  18205. 'on', 'off', 'getDataURL', 'getConnectedDataURL', 'getModel', 'getOption',
  18206. 'getViewOfComponentModel', 'getViewOfSeriesModel'
  18207. ];
  18208. // And `getCoordinateSystems` and `getComponentByElement` will be injected in echarts.js
  18209. function ExtensionAPI(chartInstance) {
  18210. each$1(echartsAPIList, function (name) {
  18211. this[name] = bind(chartInstance[name], chartInstance);
  18212. }, this);
  18213. }
  18214. /*
  18215. * Licensed to the Apache Software Foundation (ASF) under one
  18216. * or more contributor license agreements. See the NOTICE file
  18217. * distributed with this work for additional information
  18218. * regarding copyright ownership. The ASF licenses this file
  18219. * to you under the Apache License, Version 2.0 (the
  18220. * "License"); you may not use this file except in compliance
  18221. * with the License. You may obtain a copy of the License at
  18222. *
  18223. * http://www.apache.org/licenses/LICENSE-2.0
  18224. *
  18225. * Unless required by applicable law or agreed to in writing,
  18226. * software distributed under the License is distributed on an
  18227. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18228. * KIND, either express or implied. See the License for the
  18229. * specific language governing permissions and limitations
  18230. * under the License.
  18231. */
  18232. var coordinateSystemCreators = {};
  18233. function CoordinateSystemManager() {
  18234. this._coordinateSystems = [];
  18235. }
  18236. CoordinateSystemManager.prototype = {
  18237. constructor: CoordinateSystemManager,
  18238. create: function (ecModel, api) {
  18239. var coordinateSystems = [];
  18240. each$1(coordinateSystemCreators, function (creater, type) {
  18241. var list = creater.create(ecModel, api);
  18242. coordinateSystems = coordinateSystems.concat(list || []);
  18243. });
  18244. this._coordinateSystems = coordinateSystems;
  18245. },
  18246. update: function (ecModel, api) {
  18247. each$1(this._coordinateSystems, function (coordSys) {
  18248. coordSys.update && coordSys.update(ecModel, api);
  18249. });
  18250. },
  18251. getCoordinateSystems: function () {
  18252. return this._coordinateSystems.slice();
  18253. }
  18254. };
  18255. CoordinateSystemManager.register = function (type, coordinateSystemCreator) {
  18256. coordinateSystemCreators[type] = coordinateSystemCreator;
  18257. };
  18258. CoordinateSystemManager.get = function (type) {
  18259. return coordinateSystemCreators[type];
  18260. };
  18261. /*
  18262. * Licensed to the Apache Software Foundation (ASF) under one
  18263. * or more contributor license agreements. See the NOTICE file
  18264. * distributed with this work for additional information
  18265. * regarding copyright ownership. The ASF licenses this file
  18266. * to you under the Apache License, Version 2.0 (the
  18267. * "License"); you may not use this file except in compliance
  18268. * with the License. You may obtain a copy of the License at
  18269. *
  18270. * http://www.apache.org/licenses/LICENSE-2.0
  18271. *
  18272. * Unless required by applicable law or agreed to in writing,
  18273. * software distributed under the License is distributed on an
  18274. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18275. * KIND, either express or implied. See the License for the
  18276. * specific language governing permissions and limitations
  18277. * under the License.
  18278. */
  18279. /**
  18280. * ECharts option manager
  18281. *
  18282. * @module {echarts/model/OptionManager}
  18283. */
  18284. var each$4 = each$1;
  18285. var clone$3 = clone;
  18286. var map$1 = map;
  18287. var merge$1 = merge;
  18288. var QUERY_REG = /^(min|max)?(.+)$/;
  18289. /**
  18290. * TERM EXPLANATIONS:
  18291. *
  18292. * [option]:
  18293. *
  18294. * An object that contains definitions of components. For example:
  18295. * var option = {
  18296. * title: {...},
  18297. * legend: {...},
  18298. * visualMap: {...},
  18299. * series: [
  18300. * {data: [...]},
  18301. * {data: [...]},
  18302. * ...
  18303. * ]
  18304. * };
  18305. *
  18306. * [rawOption]:
  18307. *
  18308. * An object input to echarts.setOption. 'rawOption' may be an
  18309. * 'option', or may be an object contains multi-options. For example:
  18310. * var option = {
  18311. * baseOption: {
  18312. * title: {...},
  18313. * legend: {...},
  18314. * series: [
  18315. * {data: [...]},
  18316. * {data: [...]},
  18317. * ...
  18318. * ]
  18319. * },
  18320. * timeline: {...},
  18321. * options: [
  18322. * {title: {...}, series: {data: [...]}},
  18323. * {title: {...}, series: {data: [...]}},
  18324. * ...
  18325. * ],
  18326. * media: [
  18327. * {
  18328. * query: {maxWidth: 320},
  18329. * option: {series: {x: 20}, visualMap: {show: false}}
  18330. * },
  18331. * {
  18332. * query: {minWidth: 320, maxWidth: 720},
  18333. * option: {series: {x: 500}, visualMap: {show: true}}
  18334. * },
  18335. * {
  18336. * option: {series: {x: 1200}, visualMap: {show: true}}
  18337. * }
  18338. * ]
  18339. * };
  18340. *
  18341. * @alias module:echarts/model/OptionManager
  18342. * @param {module:echarts/ExtensionAPI} api
  18343. */
  18344. function OptionManager(api) {
  18345. /**
  18346. * @private
  18347. * @type {module:echarts/ExtensionAPI}
  18348. */
  18349. this._api = api;
  18350. /**
  18351. * @private
  18352. * @type {Array.<number>}
  18353. */
  18354. this._timelineOptions = [];
  18355. /**
  18356. * @private
  18357. * @type {Array.<Object>}
  18358. */
  18359. this._mediaList = [];
  18360. /**
  18361. * @private
  18362. * @type {Object}
  18363. */
  18364. this._mediaDefault;
  18365. /**
  18366. * -1, means default.
  18367. * empty means no media.
  18368. * @private
  18369. * @type {Array.<number>}
  18370. */
  18371. this._currentMediaIndices = [];
  18372. /**
  18373. * @private
  18374. * @type {Object}
  18375. */
  18376. this._optionBackup;
  18377. /**
  18378. * @private
  18379. * @type {Object}
  18380. */
  18381. this._newBaseOption;
  18382. }
  18383. // timeline.notMerge is not supported in ec3. Firstly there is rearly
  18384. // case that notMerge is needed. Secondly supporting 'notMerge' requires
  18385. // rawOption cloned and backuped when timeline changed, which does no
  18386. // good to performance. What's more, that both timeline and setOption
  18387. // method supply 'notMerge' brings complex and some problems.
  18388. // Consider this case:
  18389. // (step1) chart.setOption({timeline: {notMerge: false}, ...}, false);
  18390. // (step2) chart.setOption({timeline: {notMerge: true}, ...}, false);
  18391. OptionManager.prototype = {
  18392. constructor: OptionManager,
  18393. /**
  18394. * @public
  18395. * @param {Object} rawOption Raw option.
  18396. * @param {module:echarts/model/Global} ecModel
  18397. * @param {Array.<Function>} optionPreprocessorFuncs
  18398. * @return {Object} Init option
  18399. */
  18400. setOption: function (rawOption, optionPreprocessorFuncs) {
  18401. if (rawOption) {
  18402. // That set dat primitive is dangerous if user reuse the data when setOption again.
  18403. each$1(normalizeToArray(rawOption.series), function (series) {
  18404. series && series.data && isTypedArray(series.data) && setAsPrimitive(series.data);
  18405. });
  18406. }
  18407. // Caution: some series modify option data, if do not clone,
  18408. // it should ensure that the repeat modify correctly
  18409. // (create a new object when modify itself).
  18410. rawOption = clone$3(rawOption, true);
  18411. // FIXME
  18412. // 如果 timeline options 或者 media 中设置了某个属性,而baseOption中没有设置,则进行警告。
  18413. var oldOptionBackup = this._optionBackup;
  18414. var newParsedOption = parseRawOption.call(
  18415. this, rawOption, optionPreprocessorFuncs, !oldOptionBackup
  18416. );
  18417. this._newBaseOption = newParsedOption.baseOption;
  18418. // For setOption at second time (using merge mode);
  18419. if (oldOptionBackup) {
  18420. // Only baseOption can be merged.
  18421. mergeOption(oldOptionBackup.baseOption, newParsedOption.baseOption);
  18422. // For simplicity, timeline options and media options do not support merge,
  18423. // that is, if you `setOption` twice and both has timeline options, the latter
  18424. // timeline opitons will not be merged to the formers, but just substitude them.
  18425. if (newParsedOption.timelineOptions.length) {
  18426. oldOptionBackup.timelineOptions = newParsedOption.timelineOptions;
  18427. }
  18428. if (newParsedOption.mediaList.length) {
  18429. oldOptionBackup.mediaList = newParsedOption.mediaList;
  18430. }
  18431. if (newParsedOption.mediaDefault) {
  18432. oldOptionBackup.mediaDefault = newParsedOption.mediaDefault;
  18433. }
  18434. }
  18435. else {
  18436. this._optionBackup = newParsedOption;
  18437. }
  18438. },
  18439. /**
  18440. * @param {boolean} isRecreate
  18441. * @return {Object}
  18442. */
  18443. mountOption: function (isRecreate) {
  18444. var optionBackup = this._optionBackup;
  18445. // TODO
  18446. // 如果没有reset功能则不clone。
  18447. this._timelineOptions = map$1(optionBackup.timelineOptions, clone$3);
  18448. this._mediaList = map$1(optionBackup.mediaList, clone$3);
  18449. this._mediaDefault = clone$3(optionBackup.mediaDefault);
  18450. this._currentMediaIndices = [];
  18451. return clone$3(isRecreate
  18452. // this._optionBackup.baseOption, which is created at the first `setOption`
  18453. // called, and is merged into every new option by inner method `mergeOption`
  18454. // each time `setOption` called, can be only used in `isRecreate`, because
  18455. // its reliability is under suspicion. In other cases option merge is
  18456. // performed by `model.mergeOption`.
  18457. ? optionBackup.baseOption : this._newBaseOption
  18458. );
  18459. },
  18460. /**
  18461. * @param {module:echarts/model/Global} ecModel
  18462. * @return {Object}
  18463. */
  18464. getTimelineOption: function (ecModel) {
  18465. var option;
  18466. var timelineOptions = this._timelineOptions;
  18467. if (timelineOptions.length) {
  18468. // getTimelineOption can only be called after ecModel inited,
  18469. // so we can get currentIndex from timelineModel.
  18470. var timelineModel = ecModel.getComponent('timeline');
  18471. if (timelineModel) {
  18472. option = clone$3(
  18473. timelineOptions[timelineModel.getCurrentIndex()],
  18474. true
  18475. );
  18476. }
  18477. }
  18478. return option;
  18479. },
  18480. /**
  18481. * @param {module:echarts/model/Global} ecModel
  18482. * @return {Array.<Object>}
  18483. */
  18484. getMediaOption: function (ecModel) {
  18485. var ecWidth = this._api.getWidth();
  18486. var ecHeight = this._api.getHeight();
  18487. var mediaList = this._mediaList;
  18488. var mediaDefault = this._mediaDefault;
  18489. var indices = [];
  18490. var result = [];
  18491. // No media defined.
  18492. if (!mediaList.length && !mediaDefault) {
  18493. return result;
  18494. }
  18495. // Multi media may be applied, the latter defined media has higher priority.
  18496. for (var i = 0, len = mediaList.length; i < len; i++) {
  18497. if (applyMediaQuery(mediaList[i].query, ecWidth, ecHeight)) {
  18498. indices.push(i);
  18499. }
  18500. }
  18501. // FIXME
  18502. // 是否mediaDefault应该强制用户设置,否则可能修改不能回归。
  18503. if (!indices.length && mediaDefault) {
  18504. indices = [-1];
  18505. }
  18506. if (indices.length && !indicesEquals(indices, this._currentMediaIndices)) {
  18507. result = map$1(indices, function (index) {
  18508. return clone$3(
  18509. index === -1 ? mediaDefault.option : mediaList[index].option
  18510. );
  18511. });
  18512. }
  18513. // Otherwise return nothing.
  18514. this._currentMediaIndices = indices;
  18515. return result;
  18516. }
  18517. };
  18518. function parseRawOption(rawOption, optionPreprocessorFuncs, isNew) {
  18519. var timelineOptions = [];
  18520. var mediaList = [];
  18521. var mediaDefault;
  18522. var baseOption;
  18523. // Compatible with ec2.
  18524. var timelineOpt = rawOption.timeline;
  18525. if (rawOption.baseOption) {
  18526. baseOption = rawOption.baseOption;
  18527. }
  18528. // For timeline
  18529. if (timelineOpt || rawOption.options) {
  18530. baseOption = baseOption || {};
  18531. timelineOptions = (rawOption.options || []).slice();
  18532. }
  18533. // For media query
  18534. if (rawOption.media) {
  18535. baseOption = baseOption || {};
  18536. var media = rawOption.media;
  18537. each$4(media, function (singleMedia) {
  18538. if (singleMedia && singleMedia.option) {
  18539. if (singleMedia.query) {
  18540. mediaList.push(singleMedia);
  18541. }
  18542. else if (!mediaDefault) {
  18543. // Use the first media default.
  18544. mediaDefault = singleMedia;
  18545. }
  18546. }
  18547. });
  18548. }
  18549. // For normal option
  18550. if (!baseOption) {
  18551. baseOption = rawOption;
  18552. }
  18553. // Set timelineOpt to baseOption in ec3,
  18554. // which is convenient for merge option.
  18555. if (!baseOption.timeline) {
  18556. baseOption.timeline = timelineOpt;
  18557. }
  18558. // Preprocess.
  18559. each$4([baseOption].concat(timelineOptions)
  18560. .concat(map(mediaList, function (media) {
  18561. return media.option;
  18562. })),
  18563. function (option) {
  18564. each$4(optionPreprocessorFuncs, function (preProcess) {
  18565. preProcess(option, isNew);
  18566. });
  18567. }
  18568. );
  18569. return {
  18570. baseOption: baseOption,
  18571. timelineOptions: timelineOptions,
  18572. mediaDefault: mediaDefault,
  18573. mediaList: mediaList
  18574. };
  18575. }
  18576. /**
  18577. * @see <http://www.w3.org/TR/css3-mediaqueries/#media1>
  18578. * Support: width, height, aspectRatio
  18579. * Can use max or min as prefix.
  18580. */
  18581. function applyMediaQuery(query, ecWidth, ecHeight) {
  18582. var realMap = {
  18583. width: ecWidth,
  18584. height: ecHeight,
  18585. aspectratio: ecWidth / ecHeight // lowser case for convenientce.
  18586. };
  18587. var applicatable = true;
  18588. each$1(query, function (value, attr) {
  18589. var matched = attr.match(QUERY_REG);
  18590. if (!matched || !matched[1] || !matched[2]) {
  18591. return;
  18592. }
  18593. var operator = matched[1];
  18594. var realAttr = matched[2].toLowerCase();
  18595. if (!compare(realMap[realAttr], value, operator)) {
  18596. applicatable = false;
  18597. }
  18598. });
  18599. return applicatable;
  18600. }
  18601. function compare(real, expect, operator) {
  18602. if (operator === 'min') {
  18603. return real >= expect;
  18604. }
  18605. else if (operator === 'max') {
  18606. return real <= expect;
  18607. }
  18608. else { // Equals
  18609. return real === expect;
  18610. }
  18611. }
  18612. function indicesEquals(indices1, indices2) {
  18613. // indices is always order by asc and has only finite number.
  18614. return indices1.join(',') === indices2.join(',');
  18615. }
  18616. /**
  18617. * Consider case:
  18618. * `chart.setOption(opt1);`
  18619. * Then user do some interaction like dataZoom, dataView changing.
  18620. * `chart.setOption(opt2);`
  18621. * Then user press 'reset button' in toolbox.
  18622. *
  18623. * After doing that all of the interaction effects should be reset, the
  18624. * chart should be the same as the result of invoke
  18625. * `chart.setOption(opt1); chart.setOption(opt2);`.
  18626. *
  18627. * Although it is not able ensure that
  18628. * `chart.setOption(opt1); chart.setOption(opt2);` is equivalents to
  18629. * `chart.setOption(merge(opt1, opt2));` exactly,
  18630. * this might be the only simple way to implement that feature.
  18631. *
  18632. * MEMO: We've considered some other approaches:
  18633. * 1. Each model handle its self restoration but not uniform treatment.
  18634. * (Too complex in logic and error-prone)
  18635. * 2. Use a shadow ecModel. (Performace expensive)
  18636. */
  18637. function mergeOption(oldOption, newOption) {
  18638. newOption = newOption || {};
  18639. each$4(newOption, function (newCptOpt, mainType) {
  18640. if (newCptOpt == null) {
  18641. return;
  18642. }
  18643. var oldCptOpt = oldOption[mainType];
  18644. if (!ComponentModel.hasClass(mainType)) {
  18645. oldOption[mainType] = merge$1(oldCptOpt, newCptOpt, true);
  18646. }
  18647. else {
  18648. newCptOpt = normalizeToArray(newCptOpt);
  18649. oldCptOpt = normalizeToArray(oldCptOpt);
  18650. var mapResult = mappingToExists(oldCptOpt, newCptOpt);
  18651. oldOption[mainType] = map$1(mapResult, function (item) {
  18652. return (item.option && item.exist)
  18653. ? merge$1(item.exist, item.option, true)
  18654. : (item.exist || item.option);
  18655. });
  18656. }
  18657. });
  18658. }
  18659. /*
  18660. * Licensed to the Apache Software Foundation (ASF) under one
  18661. * or more contributor license agreements. See the NOTICE file
  18662. * distributed with this work for additional information
  18663. * regarding copyright ownership. The ASF licenses this file
  18664. * to you under the Apache License, Version 2.0 (the
  18665. * "License"); you may not use this file except in compliance
  18666. * with the License. You may obtain a copy of the License at
  18667. *
  18668. * http://www.apache.org/licenses/LICENSE-2.0
  18669. *
  18670. * Unless required by applicable law or agreed to in writing,
  18671. * software distributed under the License is distributed on an
  18672. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18673. * KIND, either express or implied. See the License for the
  18674. * specific language governing permissions and limitations
  18675. * under the License.
  18676. */
  18677. var each$5 = each$1;
  18678. var isObject$3 = isObject$1;
  18679. var POSSIBLE_STYLES = [
  18680. 'areaStyle', 'lineStyle', 'nodeStyle', 'linkStyle',
  18681. 'chordStyle', 'label', 'labelLine'
  18682. ];
  18683. function compatEC2ItemStyle(opt) {
  18684. var itemStyleOpt = opt && opt.itemStyle;
  18685. if (!itemStyleOpt) {
  18686. return;
  18687. }
  18688. for (var i = 0, len = POSSIBLE_STYLES.length; i < len; i++) {
  18689. var styleName = POSSIBLE_STYLES[i];
  18690. var normalItemStyleOpt = itemStyleOpt.normal;
  18691. var emphasisItemStyleOpt = itemStyleOpt.emphasis;
  18692. if (normalItemStyleOpt && normalItemStyleOpt[styleName]) {
  18693. opt[styleName] = opt[styleName] || {};
  18694. if (!opt[styleName].normal) {
  18695. opt[styleName].normal = normalItemStyleOpt[styleName];
  18696. }
  18697. else {
  18698. merge(opt[styleName].normal, normalItemStyleOpt[styleName]);
  18699. }
  18700. normalItemStyleOpt[styleName] = null;
  18701. }
  18702. if (emphasisItemStyleOpt && emphasisItemStyleOpt[styleName]) {
  18703. opt[styleName] = opt[styleName] || {};
  18704. if (!opt[styleName].emphasis) {
  18705. opt[styleName].emphasis = emphasisItemStyleOpt[styleName];
  18706. }
  18707. else {
  18708. merge(opt[styleName].emphasis, emphasisItemStyleOpt[styleName]);
  18709. }
  18710. emphasisItemStyleOpt[styleName] = null;
  18711. }
  18712. }
  18713. }
  18714. function convertNormalEmphasis(opt, optType, useExtend) {
  18715. if (opt && opt[optType] && (opt[optType].normal || opt[optType].emphasis)) {
  18716. var normalOpt = opt[optType].normal;
  18717. var emphasisOpt = opt[optType].emphasis;
  18718. if (normalOpt) {
  18719. // Timeline controlStyle has other properties besides normal and emphasis
  18720. if (useExtend) {
  18721. opt[optType].normal = opt[optType].emphasis = null;
  18722. defaults(opt[optType], normalOpt);
  18723. }
  18724. else {
  18725. opt[optType] = normalOpt;
  18726. }
  18727. }
  18728. if (emphasisOpt) {
  18729. opt.emphasis = opt.emphasis || {};
  18730. opt.emphasis[optType] = emphasisOpt;
  18731. }
  18732. }
  18733. }
  18734. function removeEC3NormalStatus(opt) {
  18735. convertNormalEmphasis(opt, 'itemStyle');
  18736. convertNormalEmphasis(opt, 'lineStyle');
  18737. convertNormalEmphasis(opt, 'areaStyle');
  18738. convertNormalEmphasis(opt, 'label');
  18739. convertNormalEmphasis(opt, 'labelLine');
  18740. // treemap
  18741. convertNormalEmphasis(opt, 'upperLabel');
  18742. // graph
  18743. convertNormalEmphasis(opt, 'edgeLabel');
  18744. }
  18745. function compatTextStyle(opt, propName) {
  18746. // Check whether is not object (string\null\undefined ...)
  18747. var labelOptSingle = isObject$3(opt) && opt[propName];
  18748. var textStyle = isObject$3(labelOptSingle) && labelOptSingle.textStyle;
  18749. if (textStyle) {
  18750. for (var i = 0, len = TEXT_STYLE_OPTIONS.length; i < len; i++) {
  18751. var propName = TEXT_STYLE_OPTIONS[i];
  18752. if (textStyle.hasOwnProperty(propName)) {
  18753. labelOptSingle[propName] = textStyle[propName];
  18754. }
  18755. }
  18756. }
  18757. }
  18758. function compatEC3CommonStyles(opt) {
  18759. if (opt) {
  18760. removeEC3NormalStatus(opt);
  18761. compatTextStyle(opt, 'label');
  18762. opt.emphasis && compatTextStyle(opt.emphasis, 'label');
  18763. }
  18764. }
  18765. function processSeries(seriesOpt) {
  18766. if (!isObject$3(seriesOpt)) {
  18767. return;
  18768. }
  18769. compatEC2ItemStyle(seriesOpt);
  18770. removeEC3NormalStatus(seriesOpt);
  18771. compatTextStyle(seriesOpt, 'label');
  18772. // treemap
  18773. compatTextStyle(seriesOpt, 'upperLabel');
  18774. // graph
  18775. compatTextStyle(seriesOpt, 'edgeLabel');
  18776. if (seriesOpt.emphasis) {
  18777. compatTextStyle(seriesOpt.emphasis, 'label');
  18778. // treemap
  18779. compatTextStyle(seriesOpt.emphasis, 'upperLabel');
  18780. // graph
  18781. compatTextStyle(seriesOpt.emphasis, 'edgeLabel');
  18782. }
  18783. var markPoint = seriesOpt.markPoint;
  18784. if (markPoint) {
  18785. compatEC2ItemStyle(markPoint);
  18786. compatEC3CommonStyles(markPoint);
  18787. }
  18788. var markLine = seriesOpt.markLine;
  18789. if (markLine) {
  18790. compatEC2ItemStyle(markLine);
  18791. compatEC3CommonStyles(markLine);
  18792. }
  18793. var markArea = seriesOpt.markArea;
  18794. if (markArea) {
  18795. compatEC3CommonStyles(markArea);
  18796. }
  18797. var data = seriesOpt.data;
  18798. // Break with ec3: if `setOption` again, there may be no `type` in option,
  18799. // then the backward compat based on option type will not be performed.
  18800. if (seriesOpt.type === 'graph') {
  18801. data = data || seriesOpt.nodes;
  18802. var edgeData = seriesOpt.links || seriesOpt.edges;
  18803. if (edgeData && !isTypedArray(edgeData)) {
  18804. for (var i = 0; i < edgeData.length; i++) {
  18805. compatEC3CommonStyles(edgeData[i]);
  18806. }
  18807. }
  18808. each$1(seriesOpt.categories, function (opt) {
  18809. removeEC3NormalStatus(opt);
  18810. });
  18811. }
  18812. if (data && !isTypedArray(data)) {
  18813. for (var i = 0; i < data.length; i++) {
  18814. compatEC3CommonStyles(data[i]);
  18815. }
  18816. }
  18817. // mark point data
  18818. var markPoint = seriesOpt.markPoint;
  18819. if (markPoint && markPoint.data) {
  18820. var mpData = markPoint.data;
  18821. for (var i = 0; i < mpData.length; i++) {
  18822. compatEC3CommonStyles(mpData[i]);
  18823. }
  18824. }
  18825. // mark line data
  18826. var markLine = seriesOpt.markLine;
  18827. if (markLine && markLine.data) {
  18828. var mlData = markLine.data;
  18829. for (var i = 0; i < mlData.length; i++) {
  18830. if (isArray(mlData[i])) {
  18831. compatEC3CommonStyles(mlData[i][0]);
  18832. compatEC3CommonStyles(mlData[i][1]);
  18833. }
  18834. else {
  18835. compatEC3CommonStyles(mlData[i]);
  18836. }
  18837. }
  18838. }
  18839. // Series
  18840. if (seriesOpt.type === 'gauge') {
  18841. compatTextStyle(seriesOpt, 'axisLabel');
  18842. compatTextStyle(seriesOpt, 'title');
  18843. compatTextStyle(seriesOpt, 'detail');
  18844. }
  18845. else if (seriesOpt.type === 'treemap') {
  18846. convertNormalEmphasis(seriesOpt.breadcrumb, 'itemStyle');
  18847. each$1(seriesOpt.levels, function (opt) {
  18848. removeEC3NormalStatus(opt);
  18849. });
  18850. }
  18851. else if (seriesOpt.type === 'tree') {
  18852. removeEC3NormalStatus(seriesOpt.leaves);
  18853. }
  18854. // sunburst starts from ec4, so it does not need to compat levels.
  18855. }
  18856. function toArr(o) {
  18857. return isArray(o) ? o : o ? [o] : [];
  18858. }
  18859. function toObj(o) {
  18860. return (isArray(o) ? o[0] : o) || {};
  18861. }
  18862. var compatStyle = function (option, isTheme) {
  18863. each$5(toArr(option.series), function (seriesOpt) {
  18864. isObject$3(seriesOpt) && processSeries(seriesOpt);
  18865. });
  18866. var axes = ['xAxis', 'yAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'parallelAxis', 'radar'];
  18867. isTheme && axes.push('valueAxis', 'categoryAxis', 'logAxis', 'timeAxis');
  18868. each$5(
  18869. axes,
  18870. function (axisName) {
  18871. each$5(toArr(option[axisName]), function (axisOpt) {
  18872. if (axisOpt) {
  18873. compatTextStyle(axisOpt, 'axisLabel');
  18874. compatTextStyle(axisOpt.axisPointer, 'label');
  18875. }
  18876. });
  18877. }
  18878. );
  18879. each$5(toArr(option.parallel), function (parallelOpt) {
  18880. var parallelAxisDefault = parallelOpt && parallelOpt.parallelAxisDefault;
  18881. compatTextStyle(parallelAxisDefault, 'axisLabel');
  18882. compatTextStyle(parallelAxisDefault && parallelAxisDefault.axisPointer, 'label');
  18883. });
  18884. each$5(toArr(option.calendar), function (calendarOpt) {
  18885. convertNormalEmphasis(calendarOpt, 'itemStyle');
  18886. compatTextStyle(calendarOpt, 'dayLabel');
  18887. compatTextStyle(calendarOpt, 'monthLabel');
  18888. compatTextStyle(calendarOpt, 'yearLabel');
  18889. });
  18890. // radar.name.textStyle
  18891. each$5(toArr(option.radar), function (radarOpt) {
  18892. compatTextStyle(radarOpt, 'name');
  18893. });
  18894. each$5(toArr(option.geo), function (geoOpt) {
  18895. if (isObject$3(geoOpt)) {
  18896. compatEC3CommonStyles(geoOpt);
  18897. each$5(toArr(geoOpt.regions), function (regionObj) {
  18898. compatEC3CommonStyles(regionObj);
  18899. });
  18900. }
  18901. });
  18902. each$5(toArr(option.timeline), function (timelineOpt) {
  18903. compatEC3CommonStyles(timelineOpt);
  18904. convertNormalEmphasis(timelineOpt, 'label');
  18905. convertNormalEmphasis(timelineOpt, 'itemStyle');
  18906. convertNormalEmphasis(timelineOpt, 'controlStyle', true);
  18907. var data = timelineOpt.data;
  18908. isArray(data) && each$1(data, function (item) {
  18909. if (isObject$1(item)) {
  18910. convertNormalEmphasis(item, 'label');
  18911. convertNormalEmphasis(item, 'itemStyle');
  18912. }
  18913. });
  18914. });
  18915. each$5(toArr(option.toolbox), function (toolboxOpt) {
  18916. convertNormalEmphasis(toolboxOpt, 'iconStyle');
  18917. each$5(toolboxOpt.feature, function (featureOpt) {
  18918. convertNormalEmphasis(featureOpt, 'iconStyle');
  18919. });
  18920. });
  18921. compatTextStyle(toObj(option.axisPointer), 'label');
  18922. compatTextStyle(toObj(option.tooltip).axisPointer, 'label');
  18923. };
  18924. /*
  18925. * Licensed to the Apache Software Foundation (ASF) under one
  18926. * or more contributor license agreements. See the NOTICE file
  18927. * distributed with this work for additional information
  18928. * regarding copyright ownership. The ASF licenses this file
  18929. * to you under the Apache License, Version 2.0 (the
  18930. * "License"); you may not use this file except in compliance
  18931. * with the License. You may obtain a copy of the License at
  18932. *
  18933. * http://www.apache.org/licenses/LICENSE-2.0
  18934. *
  18935. * Unless required by applicable law or agreed to in writing,
  18936. * software distributed under the License is distributed on an
  18937. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18938. * KIND, either express or implied. See the License for the
  18939. * specific language governing permissions and limitations
  18940. * under the License.
  18941. */
  18942. // Compatitable with 2.0
  18943. function get(opt, path) {
  18944. path = path.split(',');
  18945. var obj = opt;
  18946. for (var i = 0; i < path.length; i++) {
  18947. obj = obj && obj[path[i]];
  18948. if (obj == null) {
  18949. break;
  18950. }
  18951. }
  18952. return obj;
  18953. }
  18954. function set$1(opt, path, val, overwrite) {
  18955. path = path.split(',');
  18956. var obj = opt;
  18957. var key;
  18958. for (var i = 0; i < path.length - 1; i++) {
  18959. key = path[i];
  18960. if (obj[key] == null) {
  18961. obj[key] = {};
  18962. }
  18963. obj = obj[key];
  18964. }
  18965. if (overwrite || obj[path[i]] == null) {
  18966. obj[path[i]] = val;
  18967. }
  18968. }
  18969. function compatLayoutProperties(option) {
  18970. each$1(LAYOUT_PROPERTIES, function (prop) {
  18971. if (prop[0] in option && !(prop[1] in option)) {
  18972. option[prop[1]] = option[prop[0]];
  18973. }
  18974. });
  18975. }
  18976. var LAYOUT_PROPERTIES = [
  18977. ['x', 'left'], ['y', 'top'], ['x2', 'right'], ['y2', 'bottom']
  18978. ];
  18979. var COMPATITABLE_COMPONENTS = [
  18980. 'grid', 'geo', 'parallel', 'legend', 'toolbox', 'title', 'visualMap', 'dataZoom', 'timeline'
  18981. ];
  18982. var backwardCompat = function (option, isTheme) {
  18983. compatStyle(option, isTheme);
  18984. // Make sure series array for model initialization.
  18985. option.series = normalizeToArray(option.series);
  18986. each$1(option.series, function (seriesOpt) {
  18987. if (!isObject$1(seriesOpt)) {
  18988. return;
  18989. }
  18990. var seriesType = seriesOpt.type;
  18991. if (seriesType === 'pie' || seriesType === 'gauge') {
  18992. if (seriesOpt.clockWise != null) {
  18993. seriesOpt.clockwise = seriesOpt.clockWise;
  18994. }
  18995. }
  18996. if (seriesType === 'gauge') {
  18997. var pointerColor = get(seriesOpt, 'pointer.color');
  18998. pointerColor != null
  18999. && set$1(seriesOpt, 'itemStyle.normal.color', pointerColor);
  19000. }
  19001. compatLayoutProperties(seriesOpt);
  19002. });
  19003. // dataRange has changed to visualMap
  19004. if (option.dataRange) {
  19005. option.visualMap = option.dataRange;
  19006. }
  19007. each$1(COMPATITABLE_COMPONENTS, function (componentName) {
  19008. var options = option[componentName];
  19009. if (options) {
  19010. if (!isArray(options)) {
  19011. options = [options];
  19012. }
  19013. each$1(options, function (option) {
  19014. compatLayoutProperties(option);
  19015. });
  19016. }
  19017. });
  19018. };
  19019. /*
  19020. * Licensed to the Apache Software Foundation (ASF) under one
  19021. * or more contributor license agreements. See the NOTICE file
  19022. * distributed with this work for additional information
  19023. * regarding copyright ownership. The ASF licenses this file
  19024. * to you under the Apache License, Version 2.0 (the
  19025. * "License"); you may not use this file except in compliance
  19026. * with the License. You may obtain a copy of the License at
  19027. *
  19028. * http://www.apache.org/licenses/LICENSE-2.0
  19029. *
  19030. * Unless required by applicable law or agreed to in writing,
  19031. * software distributed under the License is distributed on an
  19032. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19033. * KIND, either express or implied. See the License for the
  19034. * specific language governing permissions and limitations
  19035. * under the License.
  19036. */
  19037. // (1) [Caution]: the logic is correct based on the premises:
  19038. // data processing stage is blocked in stream.
  19039. // See <module:echarts/stream/Scheduler#performDataProcessorTasks>
  19040. // (2) Only register once when import repeatly.
  19041. // Should be executed before after series filtered and before stack calculation.
  19042. var dataStack = function (ecModel) {
  19043. var stackInfoMap = createHashMap();
  19044. ecModel.eachSeries(function (seriesModel) {
  19045. var stack = seriesModel.get('stack');
  19046. // Compatibal: when `stack` is set as '', do not stack.
  19047. if (stack) {
  19048. var stackInfoList = stackInfoMap.get(stack) || stackInfoMap.set(stack, []);
  19049. var data = seriesModel.getData();
  19050. var stackInfo = {
  19051. // Used for calculate axis extent automatically.
  19052. stackResultDimension: data.getCalculationInfo('stackResultDimension'),
  19053. stackedOverDimension: data.getCalculationInfo('stackedOverDimension'),
  19054. stackedDimension: data.getCalculationInfo('stackedDimension'),
  19055. stackedByDimension: data.getCalculationInfo('stackedByDimension'),
  19056. isStackedByIndex: data.getCalculationInfo('isStackedByIndex'),
  19057. data: data,
  19058. seriesModel: seriesModel
  19059. };
  19060. // If stacked on axis that do not support data stack.
  19061. if (!stackInfo.stackedDimension
  19062. || !(stackInfo.isStackedByIndex || stackInfo.stackedByDimension)
  19063. ) {
  19064. return;
  19065. }
  19066. stackInfoList.length && data.setCalculationInfo(
  19067. 'stackedOnSeries', stackInfoList[stackInfoList.length - 1].seriesModel
  19068. );
  19069. stackInfoList.push(stackInfo);
  19070. }
  19071. });
  19072. stackInfoMap.each(calculateStack);
  19073. };
  19074. function calculateStack(stackInfoList) {
  19075. each$1(stackInfoList, function (targetStackInfo, idxInStack) {
  19076. var resultVal = [];
  19077. var resultNaN = [NaN, NaN];
  19078. var dims = [targetStackInfo.stackResultDimension, targetStackInfo.stackedOverDimension];
  19079. var targetData = targetStackInfo.data;
  19080. var isStackedByIndex = targetStackInfo.isStackedByIndex;
  19081. // Should not write on raw data, because stack series model list changes
  19082. // depending on legend selection.
  19083. var newData = targetData.map(dims, function (v0, v1, dataIndex) {
  19084. var sum = targetData.get(targetStackInfo.stackedDimension, dataIndex);
  19085. // Consider `connectNulls` of line area, if value is NaN, stackedOver
  19086. // should also be NaN, to draw a appropriate belt area.
  19087. if (isNaN(sum)) {
  19088. return resultNaN;
  19089. }
  19090. var byValue;
  19091. var stackedDataRawIndex;
  19092. if (isStackedByIndex) {
  19093. stackedDataRawIndex = targetData.getRawIndex(dataIndex);
  19094. }
  19095. else {
  19096. byValue = targetData.get(targetStackInfo.stackedByDimension, dataIndex);
  19097. }
  19098. // If stackOver is NaN, chart view will render point on value start.
  19099. var stackedOver = NaN;
  19100. for (var j = idxInStack - 1; j >= 0; j--) {
  19101. var stackInfo = stackInfoList[j];
  19102. // Has been optimized by inverted indices on `stackedByDimension`.
  19103. if (!isStackedByIndex) {
  19104. stackedDataRawIndex = stackInfo.data.rawIndexOf(stackInfo.stackedByDimension, byValue);
  19105. }
  19106. if (stackedDataRawIndex >= 0) {
  19107. var val = stackInfo.data.getByRawIndex(stackInfo.stackResultDimension, stackedDataRawIndex);
  19108. // Considering positive stack, negative stack and empty data
  19109. if ((sum >= 0 && val > 0) // Positive stack
  19110. || (sum <= 0 && val < 0) // Negative stack
  19111. ) {
  19112. sum += val;
  19113. stackedOver = val;
  19114. break;
  19115. }
  19116. }
  19117. }
  19118. resultVal[0] = sum;
  19119. resultVal[1] = stackedOver;
  19120. return resultVal;
  19121. });
  19122. targetData.hostModel.setData(newData);
  19123. // Update for consequent calculation
  19124. targetStackInfo.data = newData;
  19125. });
  19126. }
  19127. /*
  19128. * Licensed to the Apache Software Foundation (ASF) under one
  19129. * or more contributor license agreements. See the NOTICE file
  19130. * distributed with this work for additional information
  19131. * regarding copyright ownership. The ASF licenses this file
  19132. * to you under the Apache License, Version 2.0 (the
  19133. * "License"); you may not use this file except in compliance
  19134. * with the License. You may obtain a copy of the License at
  19135. *
  19136. * http://www.apache.org/licenses/LICENSE-2.0
  19137. *
  19138. * Unless required by applicable law or agreed to in writing,
  19139. * software distributed under the License is distributed on an
  19140. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19141. * KIND, either express or implied. See the License for the
  19142. * specific language governing permissions and limitations
  19143. * under the License.
  19144. */
  19145. // TODO
  19146. // ??? refactor? check the outer usage of data provider.
  19147. // merge with defaultDimValueGetter?
  19148. /**
  19149. * If normal array used, mutable chunk size is supported.
  19150. * If typed array used, chunk size must be fixed.
  19151. */
  19152. function DefaultDataProvider(source, dimSize) {
  19153. if (!Source.isInstance(source)) {
  19154. source = Source.seriesDataToSource(source);
  19155. }
  19156. this._source = source;
  19157. var data = this._data = source.data;
  19158. var sourceFormat = source.sourceFormat;
  19159. // Typed array. TODO IE10+?
  19160. if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  19161. if (__DEV__) {
  19162. if (dimSize == null) {
  19163. throw new Error('Typed array data must specify dimension size');
  19164. }
  19165. }
  19166. this._offset = 0;
  19167. this._dimSize = dimSize;
  19168. this._data = data;
  19169. }
  19170. var methods = providerMethods[
  19171. sourceFormat === SOURCE_FORMAT_ARRAY_ROWS
  19172. ? sourceFormat + '_' + source.seriesLayoutBy
  19173. : sourceFormat
  19174. ];
  19175. if (__DEV__) {
  19176. assert$1(methods, 'Invalide sourceFormat: ' + sourceFormat);
  19177. }
  19178. extend(this, methods);
  19179. }
  19180. var providerProto = DefaultDataProvider.prototype;
  19181. // If data is pure without style configuration
  19182. providerProto.pure = false;
  19183. // If data is persistent and will not be released after use.
  19184. providerProto.persistent = true;
  19185. // ???! FIXME legacy data provider do not has method getSource
  19186. providerProto.getSource = function () {
  19187. return this._source;
  19188. };
  19189. var providerMethods = {
  19190. 'arrayRows_column': {
  19191. pure: true,
  19192. count: function () {
  19193. return Math.max(0, this._data.length - this._source.startIndex);
  19194. },
  19195. getItem: function (idx) {
  19196. return this._data[idx + this._source.startIndex];
  19197. },
  19198. appendData: appendDataSimply
  19199. },
  19200. 'arrayRows_row': {
  19201. pure: true,
  19202. count: function () {
  19203. var row = this._data[0];
  19204. return row ? Math.max(0, row.length - this._source.startIndex) : 0;
  19205. },
  19206. getItem: function (idx) {
  19207. idx += this._source.startIndex;
  19208. var item = [];
  19209. var data = this._data;
  19210. for (var i = 0; i < data.length; i++) {
  19211. var row = data[i];
  19212. item.push(row ? row[idx] : null);
  19213. }
  19214. return item;
  19215. },
  19216. appendData: function () {
  19217. throw new Error('Do not support appendData when set seriesLayoutBy: "row".');
  19218. }
  19219. },
  19220. 'objectRows': {
  19221. pure: true,
  19222. count: countSimply,
  19223. getItem: getItemSimply,
  19224. appendData: appendDataSimply
  19225. },
  19226. 'keyedColumns': {
  19227. pure: true,
  19228. count: function () {
  19229. var dimName = this._source.dimensionsDefine[0].name;
  19230. var col = this._data[dimName];
  19231. return col ? col.length : 0;
  19232. },
  19233. getItem: function (idx) {
  19234. var item = [];
  19235. var dims = this._source.dimensionsDefine;
  19236. for (var i = 0; i < dims.length; i++) {
  19237. var col = this._data[dims[i].name];
  19238. item.push(col ? col[idx] : null);
  19239. }
  19240. return item;
  19241. },
  19242. appendData: function (newData) {
  19243. var data = this._data;
  19244. each$1(newData, function (newCol, key) {
  19245. var oldCol = data[key] || (data[key] = []);
  19246. for (var i = 0; i < (newCol || []).length; i++) {
  19247. oldCol.push(newCol[i]);
  19248. }
  19249. });
  19250. }
  19251. },
  19252. 'original': {
  19253. count: countSimply,
  19254. getItem: getItemSimply,
  19255. appendData: appendDataSimply
  19256. },
  19257. 'typedArray': {
  19258. persistent: false,
  19259. pure: true,
  19260. count: function () {
  19261. return this._data ? (this._data.length / this._dimSize) : 0;
  19262. },
  19263. getItem: function (idx, out) {
  19264. idx = idx - this._offset;
  19265. out = out || [];
  19266. var offset = this._dimSize * idx;
  19267. for (var i = 0; i < this._dimSize; i++) {
  19268. out[i] = this._data[offset + i];
  19269. }
  19270. return out;
  19271. },
  19272. appendData: function (newData) {
  19273. if (__DEV__) {
  19274. assert$1(
  19275. isTypedArray(newData),
  19276. 'Added data must be TypedArray if data in initialization is TypedArray'
  19277. );
  19278. }
  19279. this._data = newData;
  19280. },
  19281. // Clean self if data is already used.
  19282. clean: function () {
  19283. // PENDING
  19284. this._offset += this.count();
  19285. this._data = null;
  19286. }
  19287. }
  19288. };
  19289. function countSimply() {
  19290. return this._data.length;
  19291. }
  19292. function getItemSimply(idx) {
  19293. return this._data[idx];
  19294. }
  19295. function appendDataSimply(newData) {
  19296. for (var i = 0; i < newData.length; i++) {
  19297. this._data.push(newData[i]);
  19298. }
  19299. }
  19300. var rawValueGetters = {
  19301. arrayRows: getRawValueSimply,
  19302. objectRows: function (dataItem, dataIndex, dimIndex, dimName) {
  19303. return dimIndex != null ? dataItem[dimName] : dataItem;
  19304. },
  19305. keyedColumns: getRawValueSimply,
  19306. original: function (dataItem, dataIndex, dimIndex, dimName) {
  19307. // FIXME
  19308. // In some case (markpoint in geo (geo-map.html)), dataItem
  19309. // is {coord: [...]}
  19310. var value = getDataItemValue(dataItem);
  19311. return (dimIndex == null || !(value instanceof Array))
  19312. ? value
  19313. : value[dimIndex];
  19314. },
  19315. typedArray: getRawValueSimply
  19316. };
  19317. function getRawValueSimply(dataItem, dataIndex, dimIndex, dimName) {
  19318. return dimIndex != null ? dataItem[dimIndex] : dataItem;
  19319. }
  19320. var defaultDimValueGetters = {
  19321. arrayRows: getDimValueSimply,
  19322. objectRows: function (dataItem, dimName, dataIndex, dimIndex) {
  19323. return converDataValue(dataItem[dimName], this._dimensionInfos[dimName]);
  19324. },
  19325. keyedColumns: getDimValueSimply,
  19326. original: function (dataItem, dimName, dataIndex, dimIndex) {
  19327. // Performance sensitive, do not use modelUtil.getDataItemValue.
  19328. // If dataItem is an plain object with no value field, the var `value`
  19329. // will be assigned with the object, but it will be tread correctly
  19330. // in the `convertDataValue`.
  19331. var value = dataItem && (dataItem.value == null ? dataItem : dataItem.value);
  19332. // If any dataItem is like { value: 10 }
  19333. if (!this._rawData.pure && isDataItemOption(dataItem)) {
  19334. this.hasItemOption = true;
  19335. }
  19336. return converDataValue(
  19337. (value instanceof Array)
  19338. ? value[dimIndex]
  19339. // If value is a single number or something else not array.
  19340. : value,
  19341. this._dimensionInfos[dimName]
  19342. );
  19343. },
  19344. typedArray: function (dataItem, dimName, dataIndex, dimIndex) {
  19345. return dataItem[dimIndex];
  19346. }
  19347. };
  19348. function getDimValueSimply(dataItem, dimName, dataIndex, dimIndex) {
  19349. return converDataValue(dataItem[dimIndex], this._dimensionInfos[dimName]);
  19350. }
  19351. /**
  19352. * This helper method convert value in data.
  19353. * @param {string|number|Date} value
  19354. * @param {Object|string} [dimInfo] If string (like 'x'), dimType defaults 'number'.
  19355. * If "dimInfo.ordinalParseAndSave", ordinal value can be parsed.
  19356. */
  19357. function converDataValue(value, dimInfo) {
  19358. // Performance sensitive.
  19359. var dimType = dimInfo && dimInfo.type;
  19360. if (dimType === 'ordinal') {
  19361. // If given value is a category string
  19362. var ordinalMeta = dimInfo && dimInfo.ordinalMeta;
  19363. return ordinalMeta
  19364. ? ordinalMeta.parseAndCollect(value)
  19365. : value;
  19366. }
  19367. if (dimType === 'time'
  19368. // spead up when using timestamp
  19369. && typeof value !== 'number'
  19370. && value != null
  19371. && value !== '-'
  19372. ) {
  19373. value = +parseDate(value);
  19374. }
  19375. // dimType defaults 'number'.
  19376. // If dimType is not ordinal and value is null or undefined or NaN or '-',
  19377. // parse to NaN.
  19378. return (value == null || value === '')
  19379. ? NaN
  19380. // If string (like '-'), using '+' parse to NaN
  19381. // If object, also parse to NaN
  19382. : +value;
  19383. }
  19384. // ??? FIXME can these logic be more neat: getRawValue, getRawDataItem,
  19385. // Consider persistent.
  19386. // Caution: why use raw value to display on label or tooltip?
  19387. // A reason is to avoid format. For example time value we do not know
  19388. // how to format is expected. More over, if stack is used, calculated
  19389. // value may be 0.91000000001, which have brings trouble to display.
  19390. // TODO: consider how to treat null/undefined/NaN when display?
  19391. /**
  19392. * @param {module:echarts/data/List} data
  19393. * @param {number} dataIndex
  19394. * @param {string|number} [dim] dimName or dimIndex
  19395. * @return {Array.<number>|string|number} can be null/undefined.
  19396. */
  19397. function retrieveRawValue(data, dataIndex, dim) {
  19398. if (!data) {
  19399. return;
  19400. }
  19401. // Consider data may be not persistent.
  19402. var dataItem = data.getRawDataItem(dataIndex);
  19403. if (dataItem == null) {
  19404. return;
  19405. }
  19406. var sourceFormat = data.getProvider().getSource().sourceFormat;
  19407. var dimName;
  19408. var dimIndex;
  19409. var dimInfo = data.getDimensionInfo(dim);
  19410. if (dimInfo) {
  19411. dimName = dimInfo.name;
  19412. dimIndex = dimInfo.index;
  19413. }
  19414. return rawValueGetters[sourceFormat](dataItem, dataIndex, dimIndex, dimName);
  19415. }
  19416. /**
  19417. * Compatible with some cases (in pie, map) like:
  19418. * data: [{name: 'xx', value: 5, selected: true}, ...]
  19419. * where only sourceFormat is 'original' and 'objectRows' supported.
  19420. *
  19421. * ??? TODO
  19422. * Supported detail options in data item when using 'arrayRows'.
  19423. *
  19424. * @param {module:echarts/data/List} data
  19425. * @param {number} dataIndex
  19426. * @param {string} attr like 'selected'
  19427. */
  19428. function retrieveRawAttr(data, dataIndex, attr) {
  19429. if (!data) {
  19430. return;
  19431. }
  19432. var sourceFormat = data.getProvider().getSource().sourceFormat;
  19433. if (sourceFormat !== SOURCE_FORMAT_ORIGINAL
  19434. && sourceFormat !== SOURCE_FORMAT_OBJECT_ROWS
  19435. ) {
  19436. return;
  19437. }
  19438. var dataItem = data.getRawDataItem(dataIndex);
  19439. if (sourceFormat === SOURCE_FORMAT_ORIGINAL && !isObject$1(dataItem)) {
  19440. dataItem = null;
  19441. }
  19442. if (dataItem) {
  19443. return dataItem[attr];
  19444. }
  19445. }
  19446. /*
  19447. * Licensed to the Apache Software Foundation (ASF) under one
  19448. * or more contributor license agreements. See the NOTICE file
  19449. * distributed with this work for additional information
  19450. * regarding copyright ownership. The ASF licenses this file
  19451. * to you under the Apache License, Version 2.0 (the
  19452. * "License"); you may not use this file except in compliance
  19453. * with the License. You may obtain a copy of the License at
  19454. *
  19455. * http://www.apache.org/licenses/LICENSE-2.0
  19456. *
  19457. * Unless required by applicable law or agreed to in writing,
  19458. * software distributed under the License is distributed on an
  19459. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19460. * KIND, either express or implied. See the License for the
  19461. * specific language governing permissions and limitations
  19462. * under the License.
  19463. */
  19464. var DIMENSION_LABEL_REG = /\{@(.+?)\}/g;
  19465. // PENDING A little ugly
  19466. var dataFormatMixin = {
  19467. /**
  19468. * Get params for formatter
  19469. * @param {number} dataIndex
  19470. * @param {string} [dataType]
  19471. * @return {Object}
  19472. */
  19473. getDataParams: function (dataIndex, dataType) {
  19474. var data = this.getData(dataType);
  19475. var rawValue = this.getRawValue(dataIndex, dataType);
  19476. var rawDataIndex = data.getRawIndex(dataIndex);
  19477. var name = data.getName(dataIndex);
  19478. var itemOpt = data.getRawDataItem(dataIndex);
  19479. var color = data.getItemVisual(dataIndex, 'color');
  19480. return {
  19481. componentType: this.mainType,
  19482. componentSubType: this.subType,
  19483. seriesType: this.mainType === 'series' ? this.subType : null,
  19484. seriesIndex: this.seriesIndex,
  19485. seriesId: this.id,
  19486. seriesName: this.name,
  19487. name: name,
  19488. dataIndex: rawDataIndex,
  19489. data: itemOpt,
  19490. dataType: dataType,
  19491. value: rawValue,
  19492. color: color,
  19493. marker: getTooltipMarker(color),
  19494. // Param name list for mapping `a`, `b`, `c`, `d`, `e`
  19495. $vars: ['seriesName', 'name', 'value']
  19496. };
  19497. },
  19498. /**
  19499. * Format label
  19500. * @param {number} dataIndex
  19501. * @param {string} [status='normal'] 'normal' or 'emphasis'
  19502. * @param {string} [dataType]
  19503. * @param {number} [dimIndex]
  19504. * @param {string} [labelProp='label']
  19505. * @return {string} If not formatter, return null/undefined
  19506. */
  19507. getFormattedLabel: function (dataIndex, status, dataType, dimIndex, labelProp) {
  19508. status = status || 'normal';
  19509. var data = this.getData(dataType);
  19510. var itemModel = data.getItemModel(dataIndex);
  19511. var params = this.getDataParams(dataIndex, dataType);
  19512. if (dimIndex != null && (params.value instanceof Array)) {
  19513. params.value = params.value[dimIndex];
  19514. }
  19515. var formatter = itemModel.get(
  19516. status === 'normal'
  19517. ? [labelProp || 'label', 'formatter']
  19518. : [status, labelProp || 'label', 'formatter']
  19519. );
  19520. if (typeof formatter === 'function') {
  19521. params.status = status;
  19522. return formatter(params);
  19523. }
  19524. else if (typeof formatter === 'string') {
  19525. var str = formatTpl(formatter, params);
  19526. // Support 'aaa{@[3]}bbb{@product}ccc'.
  19527. // Do not support '}' in dim name util have to.
  19528. return str.replace(DIMENSION_LABEL_REG, function (origin, dim) {
  19529. var len = dim.length;
  19530. if (dim.charAt(0) === '[' && dim.charAt(len - 1) === ']') {
  19531. dim = +dim.slice(1, len - 1); // Also: '[]' => 0
  19532. }
  19533. return retrieveRawValue(data, dataIndex, dim);
  19534. });
  19535. }
  19536. },
  19537. /**
  19538. * Get raw value in option
  19539. * @param {number} idx
  19540. * @param {string} [dataType]
  19541. * @return {Array|number|string}
  19542. */
  19543. getRawValue: function (idx, dataType) {
  19544. return retrieveRawValue(this.getData(dataType), idx);
  19545. },
  19546. /**
  19547. * Should be implemented.
  19548. * @param {number} dataIndex
  19549. * @param {boolean} [multipleSeries=false]
  19550. * @param {number} [dataType]
  19551. * @return {string} tooltip string
  19552. */
  19553. formatTooltip: function () {
  19554. // Empty function
  19555. }
  19556. };
  19557. /*
  19558. * Licensed to the Apache Software Foundation (ASF) under one
  19559. * or more contributor license agreements. See the NOTICE file
  19560. * distributed with this work for additional information
  19561. * regarding copyright ownership. The ASF licenses this file
  19562. * to you under the Apache License, Version 2.0 (the
  19563. * "License"); you may not use this file except in compliance
  19564. * with the License. You may obtain a copy of the License at
  19565. *
  19566. * http://www.apache.org/licenses/LICENSE-2.0
  19567. *
  19568. * Unless required by applicable law or agreed to in writing,
  19569. * software distributed under the License is distributed on an
  19570. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19571. * KIND, either express or implied. See the License for the
  19572. * specific language governing permissions and limitations
  19573. * under the License.
  19574. */
  19575. /**
  19576. * @param {Object} define
  19577. * @return See the return of `createTask`.
  19578. */
  19579. function createTask(define) {
  19580. return new Task(define);
  19581. }
  19582. /**
  19583. * @constructor
  19584. * @param {Object} define
  19585. * @param {Function} define.reset Custom reset
  19586. * @param {Function} [define.plan] Returns 'reset' indicate reset immediately.
  19587. * @param {Function} [define.count] count is used to determin data task.
  19588. * @param {Function} [define.onDirty] count is used to determin data task.
  19589. */
  19590. function Task(define) {
  19591. define = define || {};
  19592. this._reset = define.reset;
  19593. this._plan = define.plan;
  19594. this._count = define.count;
  19595. this._onDirty = define.onDirty;
  19596. this._dirty = true;
  19597. // Context must be specified implicitly, to
  19598. // avoid miss update context when model changed.
  19599. this.context;
  19600. }
  19601. var taskProto = Task.prototype;
  19602. /**
  19603. * @param {Object} performArgs
  19604. * @param {number} [performArgs.step] Specified step.
  19605. * @param {number} [performArgs.skip] Skip customer perform call.
  19606. * @param {number} [performArgs.modBy] Sampling window size.
  19607. * @param {number} [performArgs.modDataCount] Sampling count.
  19608. */
  19609. taskProto.perform = function (performArgs) {
  19610. var upTask = this._upstream;
  19611. var skip = performArgs && performArgs.skip;
  19612. // TODO some refactor.
  19613. // Pull data. Must pull data each time, because context.data
  19614. // may be updated by Series.setData.
  19615. if (this._dirty && upTask) {
  19616. var context = this.context;
  19617. context.data = context.outputData = upTask.context.outputData;
  19618. }
  19619. if (this.__pipeline) {
  19620. this.__pipeline.currentTask = this;
  19621. }
  19622. var planResult;
  19623. if (this._plan && !skip) {
  19624. planResult = this._plan(this.context);
  19625. }
  19626. // Support sharding by mod, which changes the render sequence and makes the rendered graphic
  19627. // elements uniformed distributed when progress, especially when moving or zooming.
  19628. var lastModBy = normalizeModBy(this._modBy);
  19629. var lastModDataCount = this._modDataCount || 0;
  19630. var modBy = normalizeModBy(performArgs && performArgs.modBy);
  19631. var modDataCount = performArgs && performArgs.modDataCount || 0;
  19632. if (lastModBy !== modBy || lastModDataCount !== modDataCount) {
  19633. planResult = 'reset';
  19634. }
  19635. function normalizeModBy(val) {
  19636. !(val >= 1) && (val = 1); // jshint ignore:line
  19637. return val;
  19638. }
  19639. var forceFirstProgress;
  19640. if (this._dirty || planResult === 'reset') {
  19641. this._dirty = false;
  19642. forceFirstProgress = reset(this, skip);
  19643. }
  19644. this._modBy = modBy;
  19645. this._modDataCount = modDataCount;
  19646. var step = performArgs && performArgs.step;
  19647. if (upTask) {
  19648. if (__DEV__) {
  19649. assert$1(upTask._outputDueEnd != null);
  19650. }
  19651. this._dueEnd = upTask._outputDueEnd;
  19652. }
  19653. // DataTask or overallTask
  19654. else {
  19655. if (__DEV__) {
  19656. assert$1(!this._progress || this._count);
  19657. }
  19658. this._dueEnd = this._count ? this._count(this.context) : Infinity;
  19659. }
  19660. // Note: Stubs, that its host overall task let it has progress, has progress.
  19661. // If no progress, pass index from upstream to downstream each time plan called.
  19662. if (this._progress) {
  19663. var start = this._dueIndex;
  19664. var end = Math.min(
  19665. step != null ? this._dueIndex + step : Infinity,
  19666. this._dueEnd
  19667. );
  19668. if (!skip && (forceFirstProgress || start < end)) {
  19669. var progress = this._progress;
  19670. if (isArray(progress)) {
  19671. for (var i = 0; i < progress.length; i++) {
  19672. doProgress(this, progress[i], start, end, modBy, modDataCount);
  19673. }
  19674. }
  19675. else {
  19676. doProgress(this, progress, start, end, modBy, modDataCount);
  19677. }
  19678. }
  19679. this._dueIndex = end;
  19680. // If no `outputDueEnd`, assume that output data and
  19681. // input data is the same, so use `dueIndex` as `outputDueEnd`.
  19682. var outputDueEnd = this._settedOutputEnd != null
  19683. ? this._settedOutputEnd : end;
  19684. if (__DEV__) {
  19685. // ??? Can not rollback.
  19686. assert$1(outputDueEnd >= this._outputDueEnd);
  19687. }
  19688. this._outputDueEnd = outputDueEnd;
  19689. }
  19690. else {
  19691. // (1) Some overall task has no progress.
  19692. // (2) Stubs, that its host overall task do not let it has progress, has no progress.
  19693. // This should always be performed so it can be passed to downstream.
  19694. this._dueIndex = this._outputDueEnd = this._settedOutputEnd != null
  19695. ? this._settedOutputEnd : this._dueEnd;
  19696. }
  19697. return this.unfinished();
  19698. };
  19699. var iterator = (function () {
  19700. var end;
  19701. var current;
  19702. var modBy;
  19703. var modDataCount;
  19704. var winCount;
  19705. var it = {
  19706. reset: function (s, e, sStep, sCount) {
  19707. current = s;
  19708. end = e;
  19709. modBy = sStep;
  19710. modDataCount = sCount;
  19711. winCount = Math.ceil(modDataCount / modBy);
  19712. it.next = (modBy > 1 && modDataCount > 0) ? modNext : sequentialNext;
  19713. }
  19714. };
  19715. return it;
  19716. function sequentialNext() {
  19717. return current < end ? current++ : null;
  19718. }
  19719. function modNext() {
  19720. var dataIndex = (current % winCount) * modBy + Math.ceil(current / winCount);
  19721. var result = current >= end
  19722. ? null
  19723. : dataIndex < modDataCount
  19724. ? dataIndex
  19725. // If modDataCount is smaller than data.count() (consider `appendData` case),
  19726. // Use normal linear rendering mode.
  19727. : current;
  19728. current++;
  19729. return result;
  19730. }
  19731. })();
  19732. taskProto.dirty = function () {
  19733. this._dirty = true;
  19734. this._onDirty && this._onDirty(this.context);
  19735. };
  19736. function doProgress(taskIns, progress, start, end, modBy, modDataCount) {
  19737. iterator.reset(start, end, modBy, modDataCount);
  19738. taskIns._callingProgress = progress;
  19739. taskIns._callingProgress({
  19740. start: start, end: end, count: end - start, next: iterator.next
  19741. }, taskIns.context);
  19742. }
  19743. function reset(taskIns, skip) {
  19744. taskIns._dueIndex = taskIns._outputDueEnd = taskIns._dueEnd = 0;
  19745. taskIns._settedOutputEnd = null;
  19746. var progress;
  19747. var forceFirstProgress;
  19748. if (!skip && taskIns._reset) {
  19749. progress = taskIns._reset(taskIns.context);
  19750. if (progress && progress.progress) {
  19751. forceFirstProgress = progress.forceFirstProgress;
  19752. progress = progress.progress;
  19753. }
  19754. // To simplify no progress checking, array must has item.
  19755. if (isArray(progress) && !progress.length) {
  19756. progress = null;
  19757. }
  19758. }
  19759. taskIns._progress = progress;
  19760. taskIns._modBy = taskIns._modDataCount = null;
  19761. var downstream = taskIns._downstream;
  19762. downstream && downstream.dirty();
  19763. return forceFirstProgress;
  19764. }
  19765. /**
  19766. * @return {boolean}
  19767. */
  19768. taskProto.unfinished = function () {
  19769. return this._progress && this._dueIndex < this._dueEnd;
  19770. };
  19771. /**
  19772. * @param {Object} downTask The downstream task.
  19773. * @return {Object} The downstream task.
  19774. */
  19775. taskProto.pipe = function (downTask) {
  19776. if (__DEV__) {
  19777. assert$1(downTask && !downTask._disposed && downTask !== this);
  19778. }
  19779. // If already downstream, do not dirty downTask.
  19780. if (this._downstream !== downTask || this._dirty) {
  19781. this._downstream = downTask;
  19782. downTask._upstream = this;
  19783. downTask.dirty();
  19784. }
  19785. };
  19786. taskProto.dispose = function () {
  19787. if (this._disposed) {
  19788. return;
  19789. }
  19790. this._upstream && (this._upstream._downstream = null);
  19791. this._downstream && (this._downstream._upstream = null);
  19792. this._dirty = false;
  19793. this._disposed = true;
  19794. };
  19795. taskProto.getUpstream = function () {
  19796. return this._upstream;
  19797. };
  19798. taskProto.getDownstream = function () {
  19799. return this._downstream;
  19800. };
  19801. taskProto.setOutputEnd = function (end) {
  19802. // This only happend in dataTask, dataZoom, map, currently.
  19803. // where dataZoom do not set end each time, but only set
  19804. // when reset. So we should record the setted end, in case
  19805. // that the stub of dataZoom perform again and earse the
  19806. // setted end by upstream.
  19807. this._outputDueEnd = this._settedOutputEnd = end;
  19808. };
  19809. ///////////////////////////////////////////////////////////
  19810. // For stream debug (Should be commented out after used!)
  19811. // Usage: printTask(this, 'begin');
  19812. // Usage: printTask(this, null, {someExtraProp});
  19813. // function printTask(task, prefix, extra) {
  19814. // window.ecTaskUID == null && (window.ecTaskUID = 0);
  19815. // task.uidDebug == null && (task.uidDebug = `task_${window.ecTaskUID++}`);
  19816. // task.agent && task.agent.uidDebug == null && (task.agent.uidDebug = `task_${window.ecTaskUID++}`);
  19817. // var props = [];
  19818. // if (task.__pipeline) {
  19819. // var val = `${task.__idxInPipeline}/${task.__pipeline.tail.__idxInPipeline} ${task.agent ? '(stub)' : ''}`;
  19820. // props.push({text: 'idx', value: val});
  19821. // } else {
  19822. // var stubCount = 0;
  19823. // task.agentStubMap.each(() => stubCount++);
  19824. // props.push({text: 'idx', value: `overall (stubs: ${stubCount})`});
  19825. // }
  19826. // props.push({text: 'uid', value: task.uidDebug});
  19827. // if (task.__pipeline) {
  19828. // props.push({text: 'pid', value: task.__pipeline.id});
  19829. // task.agent && props.push(
  19830. // {text: 'stubFor', value: task.agent.uidDebug}
  19831. // );
  19832. // }
  19833. // props.push(
  19834. // {text: 'dirty', value: task._dirty},
  19835. // {text: 'dueIndex', value: task._dueIndex},
  19836. // {text: 'dueEnd', value: task._dueEnd},
  19837. // {text: 'outputDueEnd', value: task._outputDueEnd}
  19838. // );
  19839. // if (extra) {
  19840. // Object.keys(extra).forEach(key => {
  19841. // props.push({text: key, value: extra[key]});
  19842. // });
  19843. // }
  19844. // var args = ['color: blue'];
  19845. // var msg = `%c[${prefix || 'T'}] %c` + props.map(item => (
  19846. // args.push('color: black', 'color: red'),
  19847. // `${item.text}: %c${item.value}`
  19848. // )).join('%c, ');
  19849. // console.log.apply(console, [msg].concat(args));
  19850. // // console.log(this);
  19851. // }
  19852. /*
  19853. * Licensed to the Apache Software Foundation (ASF) under one
  19854. * or more contributor license agreements. See the NOTICE file
  19855. * distributed with this work for additional information
  19856. * regarding copyright ownership. The ASF licenses this file
  19857. * to you under the Apache License, Version 2.0 (the
  19858. * "License"); you may not use this file except in compliance
  19859. * with the License. You may obtain a copy of the License at
  19860. *
  19861. * http://www.apache.org/licenses/LICENSE-2.0
  19862. *
  19863. * Unless required by applicable law or agreed to in writing,
  19864. * software distributed under the License is distributed on an
  19865. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19866. * KIND, either express or implied. See the License for the
  19867. * specific language governing permissions and limitations
  19868. * under the License.
  19869. */
  19870. var inner$4 = makeInner();
  19871. var SeriesModel = ComponentModel.extend({
  19872. type: 'series.__base__',
  19873. /**
  19874. * @readOnly
  19875. */
  19876. seriesIndex: 0,
  19877. // coodinateSystem will be injected in the echarts/CoordinateSystem
  19878. coordinateSystem: null,
  19879. /**
  19880. * @type {Object}
  19881. * @protected
  19882. */
  19883. defaultOption: null,
  19884. /**
  19885. * Data provided for legend
  19886. * @type {Function}
  19887. */
  19888. // PENDING
  19889. legendDataProvider: null,
  19890. /**
  19891. * Access path of color for visual
  19892. */
  19893. visualColorAccessPath: 'itemStyle.color',
  19894. /**
  19895. * Support merge layout params.
  19896. * Only support 'box' now (left/right/top/bottom/width/height).
  19897. * @type {string|Object} Object can be {ignoreSize: true}
  19898. * @readOnly
  19899. */
  19900. layoutMode: null,
  19901. init: function (option, parentModel, ecModel, extraOpt) {
  19902. /**
  19903. * @type {number}
  19904. * @readOnly
  19905. */
  19906. this.seriesIndex = this.componentIndex;
  19907. this.dataTask = createTask({
  19908. count: dataTaskCount,
  19909. reset: dataTaskReset
  19910. });
  19911. this.dataTask.context = {model: this};
  19912. this.mergeDefaultAndTheme(option, ecModel);
  19913. prepareSource(this);
  19914. var data = this.getInitialData(option, ecModel);
  19915. wrapData(data, this);
  19916. this.dataTask.context.data = data;
  19917. if (__DEV__) {
  19918. assert$1(data, 'getInitialData returned invalid data.');
  19919. }
  19920. /**
  19921. * @type {module:echarts/data/List|module:echarts/data/Tree|module:echarts/data/Graph}
  19922. * @private
  19923. */
  19924. inner$4(this).dataBeforeProcessed = data;
  19925. // If we reverse the order (make data firstly, and then make
  19926. // dataBeforeProcessed by cloneShallow), cloneShallow will
  19927. // cause data.graph.data !== data when using
  19928. // module:echarts/data/Graph or module:echarts/data/Tree.
  19929. // See module:echarts/data/helper/linkList
  19930. // Theoretically, it is unreasonable to call `seriesModel.getData()` in the model
  19931. // init or merge stage, because the data can be restored. So we do not `restoreData`
  19932. // and `setData` here, which forbids calling `seriesModel.getData()` in this stage.
  19933. // Call `seriesModel.getRawData()` instead.
  19934. // this.restoreData();
  19935. autoSeriesName(this);
  19936. },
  19937. /**
  19938. * Util for merge default and theme to option
  19939. * @param {Object} option
  19940. * @param {module:echarts/model/Global} ecModel
  19941. */
  19942. mergeDefaultAndTheme: function (option, ecModel) {
  19943. var layoutMode = this.layoutMode;
  19944. var inputPositionParams = layoutMode
  19945. ? getLayoutParams(option) : {};
  19946. // Backward compat: using subType on theme.
  19947. // But if name duplicate between series subType
  19948. // (for example: parallel) add component mainType,
  19949. // add suffix 'Series'.
  19950. var themeSubType = this.subType;
  19951. if (ComponentModel.hasClass(themeSubType)) {
  19952. themeSubType += 'Series';
  19953. }
  19954. merge(
  19955. option,
  19956. ecModel.getTheme().get(this.subType)
  19957. );
  19958. merge(option, this.getDefaultOption());
  19959. // Default label emphasis `show`
  19960. defaultEmphasis(option, 'label', ['show']);
  19961. this.fillDataTextStyle(option.data);
  19962. if (layoutMode) {
  19963. mergeLayoutParam(option, inputPositionParams, layoutMode);
  19964. }
  19965. },
  19966. mergeOption: function (newSeriesOption, ecModel) {
  19967. // this.settingTask.dirty();
  19968. newSeriesOption = merge(this.option, newSeriesOption, true);
  19969. this.fillDataTextStyle(newSeriesOption.data);
  19970. var layoutMode = this.layoutMode;
  19971. if (layoutMode) {
  19972. mergeLayoutParam(this.option, newSeriesOption, layoutMode);
  19973. }
  19974. prepareSource(this);
  19975. var data = this.getInitialData(newSeriesOption, ecModel);
  19976. wrapData(data, this);
  19977. this.dataTask.dirty();
  19978. this.dataTask.context.data = data;
  19979. inner$4(this).dataBeforeProcessed = data;
  19980. autoSeriesName(this);
  19981. },
  19982. fillDataTextStyle: function (data) {
  19983. // Default data label emphasis `show`
  19984. // FIXME Tree structure data ?
  19985. // FIXME Performance ?
  19986. if (data && !isTypedArray(data)) {
  19987. var props = ['show'];
  19988. for (var i = 0; i < data.length; i++) {
  19989. if (data[i] && data[i].label) {
  19990. defaultEmphasis(data[i], 'label', props);
  19991. }
  19992. }
  19993. }
  19994. },
  19995. /**
  19996. * Init a data structure from data related option in series
  19997. * Must be overwritten
  19998. */
  19999. getInitialData: function () {},
  20000. /**
  20001. * Append data to list
  20002. * @param {Object} params
  20003. * @param {Array|TypedArray} params.data
  20004. */
  20005. appendData: function (params) {
  20006. // FIXME ???
  20007. // (1) If data from dataset, forbidden append.
  20008. // (2) support append data of dataset.
  20009. var data = this.getRawData();
  20010. data.appendData(params.data);
  20011. },
  20012. /**
  20013. * Consider some method like `filter`, `map` need make new data,
  20014. * We should make sure that `seriesModel.getData()` get correct
  20015. * data in the stream procedure. So we fetch data from upstream
  20016. * each time `task.perform` called.
  20017. * @param {string} [dataType]
  20018. * @return {module:echarts/data/List}
  20019. */
  20020. getData: function (dataType) {
  20021. var task = getCurrentTask(this);
  20022. if (task) {
  20023. var data = task.context.data;
  20024. return dataType == null ? data : data.getLinkedData(dataType);
  20025. }
  20026. else {
  20027. // When series is not alive (that may happen when click toolbox
  20028. // restore or setOption with not merge mode), series data may
  20029. // be still need to judge animation or something when graphic
  20030. // elements want to know whether fade out.
  20031. return inner$4(this).data;
  20032. }
  20033. },
  20034. /**
  20035. * @param {module:echarts/data/List} data
  20036. */
  20037. setData: function (data) {
  20038. var task = getCurrentTask(this);
  20039. if (task) {
  20040. var context = task.context;
  20041. // Consider case: filter, data sample.
  20042. if (context.data !== data && task.modifyOutputEnd) {
  20043. task.setOutputEnd(data.count());
  20044. }
  20045. context.outputData = data;
  20046. // Caution: setData should update context.data,
  20047. // Because getData may be called multiply in a
  20048. // single stage and expect to get the data just
  20049. // set. (For example, AxisProxy, x y both call
  20050. // getData and setDate sequentially).
  20051. // So the context.data should be fetched from
  20052. // upstream each time when a stage starts to be
  20053. // performed.
  20054. if (task !== this.dataTask) {
  20055. context.data = data;
  20056. }
  20057. }
  20058. inner$4(this).data = data;
  20059. },
  20060. /**
  20061. * @see {module:echarts/data/helper/sourceHelper#getSource}
  20062. * @return {module:echarts/data/Source} source
  20063. */
  20064. getSource: function () {
  20065. return getSource(this);
  20066. },
  20067. /**
  20068. * Get data before processed
  20069. * @return {module:echarts/data/List}
  20070. */
  20071. getRawData: function () {
  20072. return inner$4(this).dataBeforeProcessed;
  20073. },
  20074. /**
  20075. * Get base axis if has coordinate system and has axis.
  20076. * By default use coordSys.getBaseAxis();
  20077. * Can be overrided for some chart.
  20078. * @return {type} description
  20079. */
  20080. getBaseAxis: function () {
  20081. var coordSys = this.coordinateSystem;
  20082. return coordSys && coordSys.getBaseAxis && coordSys.getBaseAxis();
  20083. },
  20084. // FIXME
  20085. /**
  20086. * Default tooltip formatter
  20087. *
  20088. * @param {number} dataIndex
  20089. * @param {boolean} [multipleSeries=false]
  20090. * @param {number} [dataType]
  20091. */
  20092. formatTooltip: function (dataIndex, multipleSeries, dataType) {
  20093. function formatArrayValue(value) {
  20094. // ??? TODO refactor these logic.
  20095. // check: category-no-encode-has-axis-data in dataset.html
  20096. var vertially = reduce(value, function (vertially, val, idx) {
  20097. var dimItem = data.getDimensionInfo(idx);
  20098. return vertially |= dimItem && dimItem.tooltip !== false && dimItem.displayName != null;
  20099. }, 0);
  20100. var result = [];
  20101. tooltipDims.length
  20102. ? each$1(tooltipDims, function (dim) {
  20103. setEachItem(retrieveRawValue(data, dataIndex, dim), dim);
  20104. })
  20105. // By default, all dims is used on tooltip.
  20106. : each$1(value, setEachItem);
  20107. function setEachItem(val, dim) {
  20108. var dimInfo = data.getDimensionInfo(dim);
  20109. // If `dimInfo.tooltip` is not set, show tooltip.
  20110. if (!dimInfo || dimInfo.otherDims.tooltip === false) {
  20111. return;
  20112. }
  20113. var dimType = dimInfo.type;
  20114. var dimHead = getTooltipMarker({color: color, type: 'subItem'});
  20115. var valStr = (vertially
  20116. ? dimHead + encodeHTML(dimInfo.displayName || '-') + ': '
  20117. : ''
  20118. )
  20119. // FIXME should not format time for raw data?
  20120. + encodeHTML(dimType === 'ordinal'
  20121. ? val + ''
  20122. : dimType === 'time'
  20123. ? (multipleSeries ? '' : formatTime('yyyy/MM/dd hh:mm:ss', val))
  20124. : addCommas(val)
  20125. );
  20126. valStr && result.push(valStr);
  20127. }
  20128. return (vertially ? '<br/>' : '') + result.join(vertially ? '<br/>' : ', ');
  20129. }
  20130. function formatSingleValue(val) {
  20131. return encodeHTML(addCommas(val));
  20132. }
  20133. var data = this.getData();
  20134. var tooltipDims = data.mapDimension('defaultedTooltip', true);
  20135. var tooltipDimLen = tooltipDims.length;
  20136. var value = this.getRawValue(dataIndex);
  20137. var isValueArr = isArray(value);
  20138. var color = data.getItemVisual(dataIndex, 'color');
  20139. if (isObject$1(color) && color.colorStops) {
  20140. color = (color.colorStops[0] || {}).color;
  20141. }
  20142. color = color || 'transparent';
  20143. // Complicated rule for pretty tooltip.
  20144. var formattedValue = (tooltipDimLen > 1 || (isValueArr && !tooltipDimLen))
  20145. ? formatArrayValue(value)
  20146. : tooltipDimLen
  20147. ? formatSingleValue(retrieveRawValue(data, dataIndex, tooltipDims[0]))
  20148. : formatSingleValue(isValueArr ? value[0] : value);
  20149. var colorEl = getTooltipMarker(color);
  20150. var name = data.getName(dataIndex);
  20151. var seriesName = this.name;
  20152. if (!isNameSpecified(this)) {
  20153. seriesName = '';
  20154. }
  20155. seriesName = seriesName
  20156. ? encodeHTML(seriesName) + (!multipleSeries ? '<br/>' : ': ')
  20157. : '';
  20158. return !multipleSeries
  20159. ? seriesName + colorEl
  20160. + (name
  20161. ? encodeHTML(name) + ': ' + formattedValue
  20162. : formattedValue
  20163. )
  20164. : colorEl + seriesName + formattedValue;
  20165. },
  20166. /**
  20167. * @return {boolean}
  20168. */
  20169. isAnimationEnabled: function () {
  20170. if (env$1.node) {
  20171. return false;
  20172. }
  20173. var animationEnabled = this.getShallow('animation');
  20174. if (animationEnabled) {
  20175. if (this.getData().count() > this.getShallow('animationThreshold')) {
  20176. animationEnabled = false;
  20177. }
  20178. }
  20179. return animationEnabled;
  20180. },
  20181. restoreData: function () {
  20182. this.dataTask.dirty();
  20183. },
  20184. getColorFromPalette: function (name, scope, requestColorNum) {
  20185. var ecModel = this.ecModel;
  20186. // PENDING
  20187. var color = colorPaletteMixin.getColorFromPalette.call(this, name, scope, requestColorNum);
  20188. if (!color) {
  20189. color = ecModel.getColorFromPalette(name, scope, requestColorNum);
  20190. }
  20191. return color;
  20192. },
  20193. /**
  20194. * Use `data.mapDimension(coordDim, true)` instead.
  20195. * @deprecated
  20196. */
  20197. coordDimToDataDim: function (coordDim) {
  20198. return this.getRawData().mapDimension(coordDim, true);
  20199. },
  20200. /**
  20201. * Get progressive rendering count each step
  20202. * @return {number}
  20203. */
  20204. getProgressive: function () {
  20205. return this.get('progressive');
  20206. },
  20207. /**
  20208. * Get progressive rendering count each step
  20209. * @return {number}
  20210. */
  20211. getProgressiveThreshold: function () {
  20212. return this.get('progressiveThreshold');
  20213. },
  20214. /**
  20215. * Get data indices for show tooltip content. See tooltip.
  20216. * @abstract
  20217. * @param {Array.<string>|string} dim
  20218. * @param {Array.<number>} value
  20219. * @param {module:echarts/coord/single/SingleAxis} baseAxis
  20220. * @return {Object} {dataIndices, nestestValue}.
  20221. */
  20222. getAxisTooltipData: null,
  20223. /**
  20224. * See tooltip.
  20225. * @abstract
  20226. * @param {number} dataIndex
  20227. * @return {Array.<number>} Point of tooltip. null/undefined can be returned.
  20228. */
  20229. getTooltipPosition: null,
  20230. /**
  20231. * @see {module:echarts/stream/Scheduler}
  20232. */
  20233. pipeTask: null,
  20234. /**
  20235. * Convinient for override in extended class.
  20236. * @protected
  20237. * @type {Function}
  20238. */
  20239. preventIncremental: null,
  20240. /**
  20241. * @public
  20242. * @readOnly
  20243. * @type {Object}
  20244. */
  20245. pipelineContext: null
  20246. });
  20247. mixin(SeriesModel, dataFormatMixin);
  20248. mixin(SeriesModel, colorPaletteMixin);
  20249. /**
  20250. * MUST be called after `prepareSource` called
  20251. * Here we need to make auto series, especially for auto legend. But we
  20252. * do not modify series.name in option to avoid side effects.
  20253. */
  20254. function autoSeriesName(seriesModel) {
  20255. // User specified name has higher priority, otherwise it may cause
  20256. // series can not be queried unexpectedly.
  20257. var name = seriesModel.name;
  20258. if (!isNameSpecified(seriesModel)) {
  20259. seriesModel.name = getSeriesAutoName(seriesModel) || name;
  20260. }
  20261. }
  20262. function getSeriesAutoName(seriesModel) {
  20263. var data = seriesModel.getRawData();
  20264. var dataDims = data.mapDimension('seriesName', true);
  20265. var nameArr = [];
  20266. each$1(dataDims, function (dataDim) {
  20267. var dimInfo = data.getDimensionInfo(dataDim);
  20268. dimInfo.displayName && nameArr.push(dimInfo.displayName);
  20269. });
  20270. return nameArr.join(' ');
  20271. }
  20272. function dataTaskCount(context) {
  20273. return context.model.getRawData().count();
  20274. }
  20275. function dataTaskReset(context) {
  20276. var seriesModel = context.model;
  20277. seriesModel.setData(seriesModel.getRawData().cloneShallow());
  20278. return dataTaskProgress;
  20279. }
  20280. function dataTaskProgress(param, context) {
  20281. // Avoid repead cloneShallow when data just created in reset.
  20282. if (param.end > context.outputData.count()) {
  20283. context.model.getRawData().cloneShallow(context.outputData);
  20284. }
  20285. }
  20286. // TODO refactor
  20287. function wrapData(data, seriesModel) {
  20288. each$1(data.CHANGABLE_METHODS, function (methodName) {
  20289. data.wrapMethod(methodName, curry(onDataSelfChange, seriesModel));
  20290. });
  20291. }
  20292. function onDataSelfChange(seriesModel) {
  20293. var task = getCurrentTask(seriesModel);
  20294. if (task) {
  20295. // Consider case: filter, selectRange
  20296. task.setOutputEnd(this.count());
  20297. }
  20298. }
  20299. function getCurrentTask(seriesModel) {
  20300. var scheduler = (seriesModel.ecModel || {}).scheduler;
  20301. var pipeline = scheduler && scheduler.getPipeline(seriesModel.uid);
  20302. if (pipeline) {
  20303. // When pipline finished, the currrentTask keep the last
  20304. // task (renderTask).
  20305. var task = pipeline.currentTask;
  20306. if (task) {
  20307. var agentStubMap = task.agentStubMap;
  20308. if (agentStubMap) {
  20309. task = agentStubMap.get(seriesModel.uid);
  20310. }
  20311. }
  20312. return task;
  20313. }
  20314. }
  20315. /*
  20316. * Licensed to the Apache Software Foundation (ASF) under one
  20317. * or more contributor license agreements. See the NOTICE file
  20318. * distributed with this work for additional information
  20319. * regarding copyright ownership. The ASF licenses this file
  20320. * to you under the Apache License, Version 2.0 (the
  20321. * "License"); you may not use this file except in compliance
  20322. * with the License. You may obtain a copy of the License at
  20323. *
  20324. * http://www.apache.org/licenses/LICENSE-2.0
  20325. *
  20326. * Unless required by applicable law or agreed to in writing,
  20327. * software distributed under the License is distributed on an
  20328. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20329. * KIND, either express or implied. See the License for the
  20330. * specific language governing permissions and limitations
  20331. * under the License.
  20332. */
  20333. var Component = function () {
  20334. /**
  20335. * @type {module:zrender/container/Group}
  20336. * @readOnly
  20337. */
  20338. this.group = new Group();
  20339. /**
  20340. * @type {string}
  20341. * @readOnly
  20342. */
  20343. this.uid = getUID('viewComponent');
  20344. };
  20345. Component.prototype = {
  20346. constructor: Component,
  20347. init: function (ecModel, api) {},
  20348. render: function (componentModel, ecModel, api, payload) {},
  20349. dispose: function () {}
  20350. };
  20351. var componentProto = Component.prototype;
  20352. componentProto.updateView
  20353. = componentProto.updateLayout
  20354. = componentProto.updateVisual
  20355. = function (seriesModel, ecModel, api, payload) {
  20356. // Do nothing;
  20357. };
  20358. // Enable Component.extend.
  20359. enableClassExtend(Component);
  20360. // Enable capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  20361. enableClassManagement(Component, {registerWhenExtend: true});
  20362. /*
  20363. * Licensed to the Apache Software Foundation (ASF) under one
  20364. * or more contributor license agreements. See the NOTICE file
  20365. * distributed with this work for additional information
  20366. * regarding copyright ownership. The ASF licenses this file
  20367. * to you under the Apache License, Version 2.0 (the
  20368. * "License"); you may not use this file except in compliance
  20369. * with the License. You may obtain a copy of the License at
  20370. *
  20371. * http://www.apache.org/licenses/LICENSE-2.0
  20372. *
  20373. * Unless required by applicable law or agreed to in writing,
  20374. * software distributed under the License is distributed on an
  20375. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20376. * KIND, either express or implied. See the License for the
  20377. * specific language governing permissions and limitations
  20378. * under the License.
  20379. */
  20380. /**
  20381. * @return {string} If large mode changed, return string 'reset';
  20382. */
  20383. var createRenderPlanner = function () {
  20384. var inner = makeInner();
  20385. return function (seriesModel) {
  20386. var fields = inner(seriesModel);
  20387. var pipelineContext = seriesModel.pipelineContext;
  20388. var originalLarge = fields.large;
  20389. var originalProgressive = fields.progressiveRender;
  20390. var large = fields.large = pipelineContext.large;
  20391. var progressive = fields.progressiveRender = pipelineContext.progressiveRender;
  20392. return !!((originalLarge ^ large) || (originalProgressive ^ progressive)) && 'reset';
  20393. };
  20394. };
  20395. /*
  20396. * Licensed to the Apache Software Foundation (ASF) under one
  20397. * or more contributor license agreements. See the NOTICE file
  20398. * distributed with this work for additional information
  20399. * regarding copyright ownership. The ASF licenses this file
  20400. * to you under the Apache License, Version 2.0 (the
  20401. * "License"); you may not use this file except in compliance
  20402. * with the License. You may obtain a copy of the License at
  20403. *
  20404. * http://www.apache.org/licenses/LICENSE-2.0
  20405. *
  20406. * Unless required by applicable law or agreed to in writing,
  20407. * software distributed under the License is distributed on an
  20408. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20409. * KIND, either express or implied. See the License for the
  20410. * specific language governing permissions and limitations
  20411. * under the License.
  20412. */
  20413. var inner$5 = makeInner();
  20414. var renderPlanner = createRenderPlanner();
  20415. function Chart() {
  20416. /**
  20417. * @type {module:zrender/container/Group}
  20418. * @readOnly
  20419. */
  20420. this.group = new Group();
  20421. /**
  20422. * @type {string}
  20423. * @readOnly
  20424. */
  20425. this.uid = getUID('viewChart');
  20426. this.renderTask = createTask({
  20427. plan: renderTaskPlan,
  20428. reset: renderTaskReset
  20429. });
  20430. this.renderTask.context = {view: this};
  20431. }
  20432. Chart.prototype = {
  20433. type: 'chart',
  20434. /**
  20435. * Init the chart.
  20436. * @param {module:echarts/model/Global} ecModel
  20437. * @param {module:echarts/ExtensionAPI} api
  20438. */
  20439. init: function (ecModel, api) {},
  20440. /**
  20441. * Render the chart.
  20442. * @param {module:echarts/model/Series} seriesModel
  20443. * @param {module:echarts/model/Global} ecModel
  20444. * @param {module:echarts/ExtensionAPI} api
  20445. * @param {Object} payload
  20446. */
  20447. render: function (seriesModel, ecModel, api, payload) {},
  20448. /**
  20449. * Highlight series or specified data item.
  20450. * @param {module:echarts/model/Series} seriesModel
  20451. * @param {module:echarts/model/Global} ecModel
  20452. * @param {module:echarts/ExtensionAPI} api
  20453. * @param {Object} payload
  20454. */
  20455. highlight: function (seriesModel, ecModel, api, payload) {
  20456. toggleHighlight(seriesModel.getData(), payload, 'emphasis');
  20457. },
  20458. /**
  20459. * Downplay series or specified data item.
  20460. * @param {module:echarts/model/Series} seriesModel
  20461. * @param {module:echarts/model/Global} ecModel
  20462. * @param {module:echarts/ExtensionAPI} api
  20463. * @param {Object} payload
  20464. */
  20465. downplay: function (seriesModel, ecModel, api, payload) {
  20466. toggleHighlight(seriesModel.getData(), payload, 'normal');
  20467. },
  20468. /**
  20469. * Remove self.
  20470. * @param {module:echarts/model/Global} ecModel
  20471. * @param {module:echarts/ExtensionAPI} api
  20472. */
  20473. remove: function (ecModel, api) {
  20474. this.group.removeAll();
  20475. },
  20476. /**
  20477. * Dispose self.
  20478. * @param {module:echarts/model/Global} ecModel
  20479. * @param {module:echarts/ExtensionAPI} api
  20480. */
  20481. dispose: function () {},
  20482. /**
  20483. * Rendering preparation in progressive mode.
  20484. * @param {module:echarts/model/Series} seriesModel
  20485. * @param {module:echarts/model/Global} ecModel
  20486. * @param {module:echarts/ExtensionAPI} api
  20487. * @param {Object} payload
  20488. */
  20489. incrementalPrepareRender: null,
  20490. /**
  20491. * Render in progressive mode.
  20492. * @param {module:echarts/model/Series} seriesModel
  20493. * @param {module:echarts/model/Global} ecModel
  20494. * @param {module:echarts/ExtensionAPI} api
  20495. * @param {Object} payload
  20496. */
  20497. incrementalRender: null,
  20498. /**
  20499. * Update transform directly.
  20500. * @param {module:echarts/model/Series} seriesModel
  20501. * @param {module:echarts/model/Global} ecModel
  20502. * @param {module:echarts/ExtensionAPI} api
  20503. * @param {Object} payload
  20504. * @return {Object} {update: true}
  20505. */
  20506. updateTransform: null
  20507. /**
  20508. * The view contains the given point.
  20509. * @interface
  20510. * @param {Array.<number>} point
  20511. * @return {boolean}
  20512. */
  20513. // containPoint: function () {}
  20514. };
  20515. var chartProto = Chart.prototype;
  20516. chartProto.updateView
  20517. = chartProto.updateLayout
  20518. = chartProto.updateVisual
  20519. = function (seriesModel, ecModel, api, payload) {
  20520. this.render(seriesModel, ecModel, api, payload);
  20521. };
  20522. /**
  20523. * Set state of single element
  20524. * @param {module:zrender/Element} el
  20525. * @param {string} state
  20526. */
  20527. function elSetState(el, state) {
  20528. if (el) {
  20529. el.trigger(state);
  20530. if (el.type === 'group') {
  20531. for (var i = 0; i < el.childCount(); i++) {
  20532. elSetState(el.childAt(i), state);
  20533. }
  20534. }
  20535. }
  20536. }
  20537. /**
  20538. * @param {module:echarts/data/List} data
  20539. * @param {Object} payload
  20540. * @param {string} state 'normal'|'emphasis'
  20541. */
  20542. function toggleHighlight(data, payload, state) {
  20543. var dataIndex = queryDataIndex(data, payload);
  20544. if (dataIndex != null) {
  20545. each$1(normalizeToArray(dataIndex), function (dataIdx) {
  20546. elSetState(data.getItemGraphicEl(dataIdx), state);
  20547. });
  20548. }
  20549. else {
  20550. data.eachItemGraphicEl(function (el) {
  20551. elSetState(el, state);
  20552. });
  20553. }
  20554. }
  20555. // Enable Chart.extend.
  20556. enableClassExtend(Chart, ['dispose']);
  20557. // Add capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  20558. enableClassManagement(Chart, {registerWhenExtend: true});
  20559. Chart.markUpdateMethod = function (payload, methodName) {
  20560. inner$5(payload).updateMethod = methodName;
  20561. };
  20562. function renderTaskPlan(context) {
  20563. return renderPlanner(context.model);
  20564. }
  20565. function renderTaskReset(context) {
  20566. var seriesModel = context.model;
  20567. var ecModel = context.ecModel;
  20568. var api = context.api;
  20569. var payload = context.payload;
  20570. // ???! remove updateView updateVisual
  20571. var progressiveRender = seriesModel.pipelineContext.progressiveRender;
  20572. var view = context.view;
  20573. var updateMethod = payload && inner$5(payload).updateMethod;
  20574. var methodName = progressiveRender
  20575. ? 'incrementalPrepareRender'
  20576. : (updateMethod && view[updateMethod])
  20577. ? updateMethod
  20578. // `appendData` is also supported when data amount
  20579. // is less than progressive threshold.
  20580. : 'render';
  20581. if (methodName !== 'render') {
  20582. view[methodName](seriesModel, ecModel, api, payload);
  20583. }
  20584. return progressMethodMap[methodName];
  20585. }
  20586. var progressMethodMap = {
  20587. incrementalPrepareRender: {
  20588. progress: function (params, context) {
  20589. context.view.incrementalRender(
  20590. params, context.model, context.ecModel, context.api, context.payload
  20591. );
  20592. }
  20593. },
  20594. render: {
  20595. // Put view.render in `progress` to support appendData. But in this case
  20596. // view.render should not be called in reset, otherwise it will be called
  20597. // twise. Use `forceFirstProgress` to make sure that view.render is called
  20598. // in any cases.
  20599. forceFirstProgress: true,
  20600. progress: function (params, context) {
  20601. context.view.render(
  20602. context.model, context.ecModel, context.api, context.payload
  20603. );
  20604. }
  20605. }
  20606. };
  20607. /*
  20608. * Licensed to the Apache Software Foundation (ASF) under one
  20609. * or more contributor license agreements. See the NOTICE file
  20610. * distributed with this work for additional information
  20611. * regarding copyright ownership. The ASF licenses this file
  20612. * to you under the Apache License, Version 2.0 (the
  20613. * "License"); you may not use this file except in compliance
  20614. * with the License. You may obtain a copy of the License at
  20615. *
  20616. * http://www.apache.org/licenses/LICENSE-2.0
  20617. *
  20618. * Unless required by applicable law or agreed to in writing,
  20619. * software distributed under the License is distributed on an
  20620. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20621. * KIND, either express or implied. See the License for the
  20622. * specific language governing permissions and limitations
  20623. * under the License.
  20624. */
  20625. var ORIGIN_METHOD = '\0__throttleOriginMethod';
  20626. var RATE = '\0__throttleRate';
  20627. var THROTTLE_TYPE = '\0__throttleType';
  20628. /**
  20629. * @public
  20630. * @param {(Function)} fn
  20631. * @param {number} [delay=0] Unit: ms.
  20632. * @param {boolean} [debounce=false]
  20633. * true: If call interval less than `delay`, only the last call works.
  20634. * false: If call interval less than `delay, call works on fixed rate.
  20635. * @return {(Function)} throttled fn.
  20636. */
  20637. function throttle(fn, delay, debounce) {
  20638. var currCall;
  20639. var lastCall = 0;
  20640. var lastExec = 0;
  20641. var timer = null;
  20642. var diff;
  20643. var scope;
  20644. var args;
  20645. var debounceNextCall;
  20646. delay = delay || 0;
  20647. function exec() {
  20648. lastExec = (new Date()).getTime();
  20649. timer = null;
  20650. fn.apply(scope, args || []);
  20651. }
  20652. var cb = function () {
  20653. currCall = (new Date()).getTime();
  20654. scope = this;
  20655. args = arguments;
  20656. var thisDelay = debounceNextCall || delay;
  20657. var thisDebounce = debounceNextCall || debounce;
  20658. debounceNextCall = null;
  20659. diff = currCall - (thisDebounce ? lastCall : lastExec) - thisDelay;
  20660. clearTimeout(timer);
  20661. // Here we should make sure that: the `exec` SHOULD NOT be called later
  20662. // than a new call of `cb`, that is, preserving the command order. Consider
  20663. // calculating "scale rate" when roaming as an example. When a call of `cb`
  20664. // happens, either the `exec` is called dierectly, or the call is delayed.
  20665. // But the delayed call should never be later than next call of `cb`. Under
  20666. // this assurance, we can simply update view state each time `dispatchAction`
  20667. // triggered by user roaming, but not need to add extra code to avoid the
  20668. // state being "rolled-back".
  20669. if (thisDebounce) {
  20670. timer = setTimeout(exec, thisDelay);
  20671. }
  20672. else {
  20673. if (diff >= 0) {
  20674. exec();
  20675. }
  20676. else {
  20677. timer = setTimeout(exec, -diff);
  20678. }
  20679. }
  20680. lastCall = currCall;
  20681. };
  20682. /**
  20683. * Clear throttle.
  20684. * @public
  20685. */
  20686. cb.clear = function () {
  20687. if (timer) {
  20688. clearTimeout(timer);
  20689. timer = null;
  20690. }
  20691. };
  20692. /**
  20693. * Enable debounce once.
  20694. */
  20695. cb.debounceNextCall = function (debounceDelay) {
  20696. debounceNextCall = debounceDelay;
  20697. };
  20698. return cb;
  20699. }
  20700. /**
  20701. * Create throttle method or update throttle rate.
  20702. *
  20703. * @example
  20704. * ComponentView.prototype.render = function () {
  20705. * ...
  20706. * throttle.createOrUpdate(
  20707. * this,
  20708. * '_dispatchAction',
  20709. * this.model.get('throttle'),
  20710. * 'fixRate'
  20711. * );
  20712. * };
  20713. * ComponentView.prototype.remove = function () {
  20714. * throttle.clear(this, '_dispatchAction');
  20715. * };
  20716. * ComponentView.prototype.dispose = function () {
  20717. * throttle.clear(this, '_dispatchAction');
  20718. * };
  20719. *
  20720. * @public
  20721. * @param {Object} obj
  20722. * @param {string} fnAttr
  20723. * @param {number} [rate]
  20724. * @param {string} [throttleType='fixRate'] 'fixRate' or 'debounce'
  20725. * @return {Function} throttled function.
  20726. */
  20727. function createOrUpdate(obj, fnAttr, rate, throttleType) {
  20728. var fn = obj[fnAttr];
  20729. if (!fn) {
  20730. return;
  20731. }
  20732. var originFn = fn[ORIGIN_METHOD] || fn;
  20733. var lastThrottleType = fn[THROTTLE_TYPE];
  20734. var lastRate = fn[RATE];
  20735. if (lastRate !== rate || lastThrottleType !== throttleType) {
  20736. if (rate == null || !throttleType) {
  20737. return (obj[fnAttr] = originFn);
  20738. }
  20739. fn = obj[fnAttr] = throttle(
  20740. originFn, rate, throttleType === 'debounce'
  20741. );
  20742. fn[ORIGIN_METHOD] = originFn;
  20743. fn[THROTTLE_TYPE] = throttleType;
  20744. fn[RATE] = rate;
  20745. }
  20746. return fn;
  20747. }
  20748. /**
  20749. * Clear throttle. Example see throttle.createOrUpdate.
  20750. *
  20751. * @public
  20752. * @param {Object} obj
  20753. * @param {string} fnAttr
  20754. */
  20755. function clear(obj, fnAttr) {
  20756. var fn = obj[fnAttr];
  20757. if (fn && fn[ORIGIN_METHOD]) {
  20758. obj[fnAttr] = fn[ORIGIN_METHOD];
  20759. }
  20760. }
  20761. /*
  20762. * Licensed to the Apache Software Foundation (ASF) under one
  20763. * or more contributor license agreements. See the NOTICE file
  20764. * distributed with this work for additional information
  20765. * regarding copyright ownership. The ASF licenses this file
  20766. * to you under the Apache License, Version 2.0 (the
  20767. * "License"); you may not use this file except in compliance
  20768. * with the License. You may obtain a copy of the License at
  20769. *
  20770. * http://www.apache.org/licenses/LICENSE-2.0
  20771. *
  20772. * Unless required by applicable law or agreed to in writing,
  20773. * software distributed under the License is distributed on an
  20774. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20775. * KIND, either express or implied. See the License for the
  20776. * specific language governing permissions and limitations
  20777. * under the License.
  20778. */
  20779. var seriesColor = {
  20780. createOnAllSeries: true,
  20781. performRawSeries: true,
  20782. reset: function (seriesModel, ecModel) {
  20783. var data = seriesModel.getData();
  20784. var colorAccessPath = (seriesModel.visualColorAccessPath || 'itemStyle.color').split('.');
  20785. var color = seriesModel.get(colorAccessPath) // Set in itemStyle
  20786. || seriesModel.getColorFromPalette(
  20787. // TODO series count changed.
  20788. seriesModel.name, null, ecModel.getSeriesCount()
  20789. ); // Default color
  20790. // FIXME Set color function or use the platte color
  20791. data.setVisual('color', color);
  20792. // Only visible series has each data be visual encoded
  20793. if (!ecModel.isSeriesFiltered(seriesModel)) {
  20794. if (typeof color === 'function' && !(color instanceof Gradient)) {
  20795. data.each(function (idx) {
  20796. data.setItemVisual(
  20797. idx, 'color', color(seriesModel.getDataParams(idx))
  20798. );
  20799. });
  20800. }
  20801. // itemStyle in each data item
  20802. var dataEach = function (data, idx) {
  20803. var itemModel = data.getItemModel(idx);
  20804. var color = itemModel.get(colorAccessPath, true);
  20805. if (color != null) {
  20806. data.setItemVisual(idx, 'color', color);
  20807. }
  20808. };
  20809. return { dataEach: data.hasItemOption ? dataEach : null };
  20810. }
  20811. }
  20812. };
  20813. /*
  20814. * Licensed to the Apache Software Foundation (ASF) under one
  20815. * or more contributor license agreements. See the NOTICE file
  20816. * distributed with this work for additional information
  20817. * regarding copyright ownership. The ASF licenses this file
  20818. * to you under the Apache License, Version 2.0 (the
  20819. * "License"); you may not use this file except in compliance
  20820. * with the License. You may obtain a copy of the License at
  20821. *
  20822. * http://www.apache.org/licenses/LICENSE-2.0
  20823. *
  20824. * Unless required by applicable law or agreed to in writing,
  20825. * software distributed under the License is distributed on an
  20826. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20827. * KIND, either express or implied. See the License for the
  20828. * specific language governing permissions and limitations
  20829. * under the License.
  20830. */
  20831. var lang = {
  20832. toolbox: {
  20833. brush: {
  20834. title: {
  20835. rect: '矩形选择',
  20836. polygon: '圈选',
  20837. lineX: '横向选择',
  20838. lineY: '纵向选择',
  20839. keep: '保持选择',
  20840. clear: '清除选择'
  20841. }
  20842. },
  20843. dataView: {
  20844. title: '数据视图',
  20845. lang: ['数据视图', '关闭', '刷新']
  20846. },
  20847. dataZoom: {
  20848. title: {
  20849. zoom: '区域缩放',
  20850. back: '区域缩放还原'
  20851. }
  20852. },
  20853. magicType: {
  20854. title: {
  20855. line: '切换为折线图',
  20856. bar: '切换为柱状图',
  20857. stack: '切换为堆叠',
  20858. tiled: '切换为平铺'
  20859. }
  20860. },
  20861. restore: {
  20862. title: '还原'
  20863. },
  20864. saveAsImage: {
  20865. title: '保存为图片',
  20866. lang: ['右键另存为图片']
  20867. }
  20868. },
  20869. series: {
  20870. typeNames: {
  20871. pie: '饼图',
  20872. bar: '柱状图',
  20873. line: '折线图',
  20874. scatter: '散点图',
  20875. effectScatter: '涟漪散点图',
  20876. radar: '雷达图',
  20877. tree: '树图',
  20878. treemap: '矩形树图',
  20879. boxplot: '箱型图',
  20880. candlestick: 'K线图',
  20881. k: 'K线图',
  20882. heatmap: '热力图',
  20883. map: '地图',
  20884. parallel: '平行坐标图',
  20885. lines: '线图',
  20886. graph: '关系图',
  20887. sankey: '桑基图',
  20888. funnel: '漏斗图',
  20889. gauge: '仪表盘图',
  20890. pictorialBar: '象形柱图',
  20891. themeRiver: '主题河流图',
  20892. sunburst: '旭日图'
  20893. }
  20894. },
  20895. aria: {
  20896. general: {
  20897. withTitle: '这是一个关于“{title}”的图表。',
  20898. withoutTitle: '这是一个图表,'
  20899. },
  20900. series: {
  20901. single: {
  20902. prefix: '',
  20903. withName: '图表类型是{seriesType},表示{seriesName}。',
  20904. withoutName: '图表类型是{seriesType}。'
  20905. },
  20906. multiple: {
  20907. prefix: '它由{seriesCount}个图表系列组成。',
  20908. withName: '第{seriesId}个系列是一个表示{seriesName}的{seriesType},',
  20909. withoutName: '第{seriesId}个系列是一个{seriesType},',
  20910. separator: {
  20911. middle: ';',
  20912. end: '。'
  20913. }
  20914. }
  20915. },
  20916. data: {
  20917. allData: '其数据是——',
  20918. partialData: '其中,前{displayCnt}项是——',
  20919. withName: '{name}的数据是{value}',
  20920. withoutName: '{value}',
  20921. separator: {
  20922. middle: ',',
  20923. end: ''
  20924. }
  20925. }
  20926. }
  20927. };
  20928. /*
  20929. * Licensed to the Apache Software Foundation (ASF) under one
  20930. * or more contributor license agreements. See the NOTICE file
  20931. * distributed with this work for additional information
  20932. * regarding copyright ownership. The ASF licenses this file
  20933. * to you under the Apache License, Version 2.0 (the
  20934. * "License"); you may not use this file except in compliance
  20935. * with the License. You may obtain a copy of the License at
  20936. *
  20937. * http://www.apache.org/licenses/LICENSE-2.0
  20938. *
  20939. * Unless required by applicable law or agreed to in writing,
  20940. * software distributed under the License is distributed on an
  20941. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20942. * KIND, either express or implied. See the License for the
  20943. * specific language governing permissions and limitations
  20944. * under the License.
  20945. */
  20946. var aria = function (dom, ecModel) {
  20947. var ariaModel = ecModel.getModel('aria');
  20948. if (!ariaModel.get('show')) {
  20949. return;
  20950. }
  20951. else if (ariaModel.get('description')) {
  20952. dom.setAttribute('aria-label', ariaModel.get('description'));
  20953. return;
  20954. }
  20955. var seriesCnt = 0;
  20956. ecModel.eachSeries(function (seriesModel, idx) {
  20957. ++seriesCnt;
  20958. }, this);
  20959. var maxDataCnt = ariaModel.get('data.maxCount') || 10;
  20960. var maxSeriesCnt = ariaModel.get('series.maxCount') || 10;
  20961. var displaySeriesCnt = Math.min(seriesCnt, maxSeriesCnt);
  20962. var ariaLabel;
  20963. if (seriesCnt < 1) {
  20964. // No series, no aria label
  20965. return;
  20966. }
  20967. else {
  20968. var title = getTitle();
  20969. if (title) {
  20970. ariaLabel = replace(getConfig('general.withTitle'), {
  20971. title: title
  20972. });
  20973. }
  20974. else {
  20975. ariaLabel = getConfig('general.withoutTitle');
  20976. }
  20977. var seriesLabels = [];
  20978. var prefix = seriesCnt > 1
  20979. ? 'series.multiple.prefix'
  20980. : 'series.single.prefix';
  20981. ariaLabel += replace(getConfig(prefix), { seriesCount: seriesCnt });
  20982. ecModel.eachSeries(function (seriesModel, idx) {
  20983. if (idx < displaySeriesCnt) {
  20984. var seriesLabel;
  20985. var seriesName = seriesModel.get('name');
  20986. var seriesTpl = 'series.'
  20987. + (seriesCnt > 1 ? 'multiple' : 'single') + '.';
  20988. seriesLabel = getConfig(seriesName
  20989. ? seriesTpl + 'withName'
  20990. : seriesTpl + 'withoutName');
  20991. seriesLabel = replace(seriesLabel, {
  20992. seriesId: seriesModel.seriesIndex,
  20993. seriesName: seriesModel.get('name'),
  20994. seriesType: getSeriesTypeName(seriesModel.subType)
  20995. });
  20996. var data = seriesModel.getData();
  20997. window.data = data;
  20998. if (data.count() > maxDataCnt) {
  20999. // Show part of data
  21000. seriesLabel += replace(getConfig('data.partialData'), {
  21001. displayCnt: maxDataCnt
  21002. });
  21003. }
  21004. else {
  21005. seriesLabel += getConfig('data.allData');
  21006. }
  21007. var dataLabels = [];
  21008. for (var i = 0; i < data.count(); i++) {
  21009. if (i < maxDataCnt) {
  21010. var name = data.getName(i);
  21011. var value = retrieveRawValue(data, i);
  21012. dataLabels.push(
  21013. replace(
  21014. name
  21015. ? getConfig('data.withName')
  21016. : getConfig('data.withoutName'),
  21017. {
  21018. name: name,
  21019. value: value
  21020. }
  21021. )
  21022. );
  21023. }
  21024. }
  21025. seriesLabel += dataLabels
  21026. .join(getConfig('data.separator.middle'))
  21027. + getConfig('data.separator.end');
  21028. seriesLabels.push(seriesLabel);
  21029. }
  21030. });
  21031. ariaLabel += seriesLabels
  21032. .join(getConfig('series.multiple.separator.middle'))
  21033. + getConfig('series.multiple.separator.end');
  21034. dom.setAttribute('aria-label', ariaLabel);
  21035. }
  21036. function replace(str, keyValues) {
  21037. if (typeof str !== 'string') {
  21038. return str;
  21039. }
  21040. var result = str;
  21041. each$1(keyValues, function (value, key) {
  21042. result = result.replace(
  21043. new RegExp('\\{\\s*' + key + '\\s*\\}', 'g'),
  21044. value
  21045. );
  21046. });
  21047. return result;
  21048. }
  21049. function getConfig(path) {
  21050. var userConfig = ariaModel.get(path);
  21051. if (userConfig == null) {
  21052. var pathArr = path.split('.');
  21053. var result = lang.aria;
  21054. for (var i = 0; i < pathArr.length; ++i) {
  21055. result = result[pathArr[i]];
  21056. }
  21057. return result;
  21058. }
  21059. else {
  21060. return userConfig;
  21061. }
  21062. }
  21063. function getTitle() {
  21064. var title = ecModel.getModel('title').option;
  21065. if (title && title.length) {
  21066. title = title[0];
  21067. }
  21068. return title && title.text;
  21069. }
  21070. function getSeriesTypeName(type) {
  21071. return lang.series.typeNames[type] || '自定义图';
  21072. }
  21073. };
  21074. /*
  21075. * Licensed to the Apache Software Foundation (ASF) under one
  21076. * or more contributor license agreements. See the NOTICE file
  21077. * distributed with this work for additional information
  21078. * regarding copyright ownership. The ASF licenses this file
  21079. * to you under the Apache License, Version 2.0 (the
  21080. * "License"); you may not use this file except in compliance
  21081. * with the License. You may obtain a copy of the License at
  21082. *
  21083. * http://www.apache.org/licenses/LICENSE-2.0
  21084. *
  21085. * Unless required by applicable law or agreed to in writing,
  21086. * software distributed under the License is distributed on an
  21087. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21088. * KIND, either express or implied. See the License for the
  21089. * specific language governing permissions and limitations
  21090. * under the License.
  21091. */
  21092. var PI$1 = Math.PI;
  21093. /**
  21094. * @param {module:echarts/ExtensionAPI} api
  21095. * @param {Object} [opts]
  21096. * @param {string} [opts.text]
  21097. * @param {string} [opts.color]
  21098. * @param {string} [opts.textColor]
  21099. * @return {module:zrender/Element}
  21100. */
  21101. var loadingDefault = function (api, opts) {
  21102. opts = opts || {};
  21103. defaults(opts, {
  21104. text: 'loading',
  21105. color: '#c23531',
  21106. textColor: '#000',
  21107. maskColor: 'rgba(255, 255, 255, 0.8)',
  21108. zlevel: 0
  21109. });
  21110. var mask = new Rect({
  21111. style: {
  21112. fill: opts.maskColor
  21113. },
  21114. zlevel: opts.zlevel,
  21115. z: 10000
  21116. });
  21117. var arc = new Arc({
  21118. shape: {
  21119. startAngle: -PI$1 / 2,
  21120. endAngle: -PI$1 / 2 + 0.1,
  21121. r: 10
  21122. },
  21123. style: {
  21124. stroke: opts.color,
  21125. lineCap: 'round',
  21126. lineWidth: 5
  21127. },
  21128. zlevel: opts.zlevel,
  21129. z: 10001
  21130. });
  21131. var labelRect = new Rect({
  21132. style: {
  21133. fill: 'none',
  21134. text: opts.text,
  21135. textPosition: 'right',
  21136. textDistance: 10,
  21137. textFill: opts.textColor
  21138. },
  21139. zlevel: opts.zlevel,
  21140. z: 10001
  21141. });
  21142. arc.animateShape(true)
  21143. .when(1000, {
  21144. endAngle: PI$1 * 3 / 2
  21145. })
  21146. .start('circularInOut');
  21147. arc.animateShape(true)
  21148. .when(1000, {
  21149. startAngle: PI$1 * 3 / 2
  21150. })
  21151. .delay(300)
  21152. .start('circularInOut');
  21153. var group = new Group();
  21154. group.add(arc);
  21155. group.add(labelRect);
  21156. group.add(mask);
  21157. // Inject resize
  21158. group.resize = function () {
  21159. var cx = api.getWidth() / 2;
  21160. var cy = api.getHeight() / 2;
  21161. arc.setShape({
  21162. cx: cx,
  21163. cy: cy
  21164. });
  21165. var r = arc.shape.r;
  21166. labelRect.setShape({
  21167. x: cx - r,
  21168. y: cy - r,
  21169. width: r * 2,
  21170. height: r * 2
  21171. });
  21172. mask.setShape({
  21173. x: 0,
  21174. y: 0,
  21175. width: api.getWidth(),
  21176. height: api.getHeight()
  21177. });
  21178. };
  21179. group.resize();
  21180. return group;
  21181. };
  21182. /*
  21183. * Licensed to the Apache Software Foundation (ASF) under one
  21184. * or more contributor license agreements. See the NOTICE file
  21185. * distributed with this work for additional information
  21186. * regarding copyright ownership. The ASF licenses this file
  21187. * to you under the Apache License, Version 2.0 (the
  21188. * "License"); you may not use this file except in compliance
  21189. * with the License. You may obtain a copy of the License at
  21190. *
  21191. * http://www.apache.org/licenses/LICENSE-2.0
  21192. *
  21193. * Unless required by applicable law or agreed to in writing,
  21194. * software distributed under the License is distributed on an
  21195. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21196. * KIND, either express or implied. See the License for the
  21197. * specific language governing permissions and limitations
  21198. * under the License.
  21199. */
  21200. /**
  21201. * @module echarts/stream/Scheduler
  21202. */
  21203. /**
  21204. * @constructor
  21205. */
  21206. function Scheduler(ecInstance, api, dataProcessorHandlers, visualHandlers) {
  21207. this.ecInstance = ecInstance;
  21208. this.api = api;
  21209. this.unfinished;
  21210. // Fix current processors in case that in some rear cases that
  21211. // processors might be registered after echarts instance created.
  21212. // Register processors incrementally for a echarts instance is
  21213. // not supported by this stream architecture.
  21214. var dataProcessorHandlers = this._dataProcessorHandlers = dataProcessorHandlers.slice();
  21215. var visualHandlers = this._visualHandlers = visualHandlers.slice();
  21216. this._allHandlers = dataProcessorHandlers.concat(visualHandlers);
  21217. /**
  21218. * @private
  21219. * @type {
  21220. * [handlerUID: string]: {
  21221. * seriesTaskMap?: {
  21222. * [seriesUID: string]: Task
  21223. * },
  21224. * overallTask?: Task
  21225. * }
  21226. * }
  21227. */
  21228. this._stageTaskMap = createHashMap();
  21229. }
  21230. var proto = Scheduler.prototype;
  21231. /**
  21232. * @param {module:echarts/model/Global} ecModel
  21233. * @param {Object} payload
  21234. */
  21235. proto.restoreData = function (ecModel, payload) {
  21236. // TODO: Only restroe needed series and components, but not all components.
  21237. // Currently `restoreData` of all of the series and component will be called.
  21238. // But some independent components like `title`, `legend`, `graphic`, `toolbox`,
  21239. // `tooltip`, `axisPointer`, etc, do not need series refresh when `setOption`,
  21240. // and some components like coordinate system, axes, dataZoom, visualMap only
  21241. // need their target series refresh.
  21242. // (1) If we are implementing this feature some day, we should consider these cases:
  21243. // if a data processor depends on a component (e.g., dataZoomProcessor depends
  21244. // on the settings of `dataZoom`), it should be re-performed if the component
  21245. // is modified by `setOption`.
  21246. // (2) If a processor depends on sevral series, speicified by its `getTargetSeries`,
  21247. // it should be re-performed when the result array of `getTargetSeries` changed.
  21248. // We use `dependencies` to cover these issues.
  21249. // (3) How to update target series when coordinate system related components modified.
  21250. // TODO: simply the dirty mechanism? Check whether only the case here can set tasks dirty,
  21251. // and this case all of the tasks will be set as dirty.
  21252. ecModel.restoreData(payload);
  21253. // Theoretically an overall task not only depends on each of its target series, but also
  21254. // depends on all of the series.
  21255. // The overall task is not in pipeline, and `ecModel.restoreData` only set pipeline tasks
  21256. // dirty. If `getTargetSeries` of an overall task returns nothing, we should also ensure
  21257. // that the overall task is set as dirty and to be performed, otherwise it probably cause
  21258. // state chaos. So we have to set dirty of all of the overall tasks manually, otherwise it
  21259. // probably cause state chaos (consider `dataZoomProcessor`).
  21260. this._stageTaskMap.each(function (taskRecord) {
  21261. var overallTask = taskRecord.overallTask;
  21262. overallTask && overallTask.dirty();
  21263. });
  21264. };
  21265. // If seriesModel provided, incremental threshold is check by series data.
  21266. proto.getPerformArgs = function (task, isBlock) {
  21267. // For overall task
  21268. if (!task.__pipeline) {
  21269. return;
  21270. }
  21271. var pipeline = this._pipelineMap.get(task.__pipeline.id);
  21272. var pCtx = pipeline.context;
  21273. var incremental = !isBlock
  21274. && pipeline.progressiveEnabled
  21275. && (!pCtx || pCtx.progressiveRender)
  21276. && task.__idxInPipeline > pipeline.blockIndex;
  21277. var step = incremental ? pipeline.step : null;
  21278. var modDataCount = pCtx && pCtx.modDataCount;
  21279. var modBy = modDataCount != null ? Math.ceil(modDataCount / step): null;
  21280. return {step: step, modBy: modBy, modDataCount: modDataCount};
  21281. };
  21282. proto.getPipeline = function (pipelineId) {
  21283. return this._pipelineMap.get(pipelineId);
  21284. };
  21285. /**
  21286. * Current, progressive rendering starts from visual and layout.
  21287. * Always detect render mode in the same stage, avoiding that incorrect
  21288. * detection caused by data filtering.
  21289. * Caution:
  21290. * `updateStreamModes` use `seriesModel.getData()`.
  21291. */
  21292. proto.updateStreamModes = function (seriesModel, view) {
  21293. var pipeline = this._pipelineMap.get(seriesModel.uid);
  21294. var data = seriesModel.getData();
  21295. var dataLen = data.count();
  21296. // `progressiveRender` means that can render progressively in each
  21297. // animation frame. Note that some types of series do not provide
  21298. // `view.incrementalPrepareRender` but support `chart.appendData`. We
  21299. // use the term `incremental` but not `progressive` to describe the
  21300. // case that `chart.appendData`.
  21301. var progressiveRender = pipeline.progressiveEnabled
  21302. && view.incrementalPrepareRender
  21303. && dataLen >= pipeline.threshold;
  21304. var large = seriesModel.get('large') && dataLen >= seriesModel.get('largeThreshold');
  21305. // TODO: modDataCount should not updated if `appendData`, otherwise cause whole repaint.
  21306. // see `test/candlestick-large3.html`
  21307. var modDataCount = seriesModel.get('progressiveChunkMode') === 'mod' ? dataLen : null;
  21308. seriesModel.pipelineContext = pipeline.context = {
  21309. progressiveRender: progressiveRender,
  21310. modDataCount: modDataCount,
  21311. large: large
  21312. };
  21313. };
  21314. proto.restorePipelines = function (ecModel) {
  21315. var scheduler = this;
  21316. var pipelineMap = scheduler._pipelineMap = createHashMap();
  21317. ecModel.eachSeries(function (seriesModel) {
  21318. var progressive = seriesModel.getProgressive();
  21319. var pipelineId = seriesModel.uid;
  21320. pipelineMap.set(pipelineId, {
  21321. id: pipelineId,
  21322. head: null,
  21323. tail: null,
  21324. threshold: seriesModel.getProgressiveThreshold(),
  21325. progressiveEnabled: progressive
  21326. && !(seriesModel.preventIncremental && seriesModel.preventIncremental()),
  21327. blockIndex: -1,
  21328. step: Math.round(progressive || 700),
  21329. count: 0
  21330. });
  21331. pipe(scheduler, seriesModel, seriesModel.dataTask);
  21332. });
  21333. };
  21334. proto.prepareStageTasks = function () {
  21335. var stageTaskMap = this._stageTaskMap;
  21336. var ecModel = this.ecInstance.getModel();
  21337. var api = this.api;
  21338. each$1(this._allHandlers, function (handler) {
  21339. var record = stageTaskMap.get(handler.uid) || stageTaskMap.set(handler.uid, []);
  21340. handler.reset && createSeriesStageTask(this, handler, record, ecModel, api);
  21341. handler.overallReset && createOverallStageTask(this, handler, record, ecModel, api);
  21342. }, this);
  21343. };
  21344. proto.prepareView = function (view, model, ecModel, api) {
  21345. var renderTask = view.renderTask;
  21346. var context = renderTask.context;
  21347. context.model = model;
  21348. context.ecModel = ecModel;
  21349. context.api = api;
  21350. renderTask.__block = !view.incrementalPrepareRender;
  21351. pipe(this, model, renderTask);
  21352. };
  21353. proto.performDataProcessorTasks = function (ecModel, payload) {
  21354. // If we do not use `block` here, it should be considered when to update modes.
  21355. performStageTasks(this, this._dataProcessorHandlers, ecModel, payload, {block: true});
  21356. };
  21357. // opt
  21358. // opt.visualType: 'visual' or 'layout'
  21359. // opt.setDirty
  21360. proto.performVisualTasks = function (ecModel, payload, opt) {
  21361. performStageTasks(this, this._visualHandlers, ecModel, payload, opt);
  21362. };
  21363. function performStageTasks(scheduler, stageHandlers, ecModel, payload, opt) {
  21364. opt = opt || {};
  21365. var unfinished;
  21366. each$1(stageHandlers, function (stageHandler, idx) {
  21367. if (opt.visualType && opt.visualType !== stageHandler.visualType) {
  21368. return;
  21369. }
  21370. var stageHandlerRecord = scheduler._stageTaskMap.get(stageHandler.uid);
  21371. var seriesTaskMap = stageHandlerRecord.seriesTaskMap;
  21372. var overallTask = stageHandlerRecord.overallTask;
  21373. if (overallTask) {
  21374. var overallNeedDirty;
  21375. var agentStubMap = overallTask.agentStubMap;
  21376. agentStubMap.each(function (stub) {
  21377. if (needSetDirty(opt, stub)) {
  21378. stub.dirty();
  21379. overallNeedDirty = true;
  21380. }
  21381. });
  21382. overallNeedDirty && overallTask.dirty();
  21383. updatePayload(overallTask, payload);
  21384. var performArgs = scheduler.getPerformArgs(overallTask, opt.block);
  21385. // Execute stubs firstly, which may set the overall task dirty,
  21386. // then execute the overall task. And stub will call seriesModel.setData,
  21387. // which ensures that in the overallTask seriesModel.getData() will not
  21388. // return incorrect data.
  21389. agentStubMap.each(function (stub) {
  21390. stub.perform(performArgs);
  21391. });
  21392. unfinished |= overallTask.perform(performArgs);
  21393. }
  21394. else if (seriesTaskMap) {
  21395. seriesTaskMap.each(function (task, pipelineId) {
  21396. if (needSetDirty(opt, task)) {
  21397. task.dirty();
  21398. }
  21399. var performArgs = scheduler.getPerformArgs(task, opt.block);
  21400. performArgs.skip = !stageHandler.performRawSeries
  21401. && ecModel.isSeriesFiltered(task.context.model);
  21402. updatePayload(task, payload);
  21403. unfinished |= task.perform(performArgs);
  21404. });
  21405. }
  21406. });
  21407. function needSetDirty(opt, task) {
  21408. return opt.setDirty && (!opt.dirtyMap || opt.dirtyMap.get(task.__pipeline.id));
  21409. }
  21410. scheduler.unfinished |= unfinished;
  21411. }
  21412. proto.performSeriesTasks = function (ecModel) {
  21413. var unfinished;
  21414. ecModel.eachSeries(function (seriesModel) {
  21415. // Progress to the end for dataInit and dataRestore.
  21416. unfinished |= seriesModel.dataTask.perform();
  21417. });
  21418. this.unfinished |= unfinished;
  21419. };
  21420. proto.plan = function () {
  21421. // Travel pipelines, check block.
  21422. this._pipelineMap.each(function (pipeline) {
  21423. var task = pipeline.tail;
  21424. do {
  21425. if (task.__block) {
  21426. pipeline.blockIndex = task.__idxInPipeline;
  21427. break;
  21428. }
  21429. task = task.getUpstream();
  21430. }
  21431. while (task);
  21432. });
  21433. };
  21434. var updatePayload = proto.updatePayload = function (task, payload) {
  21435. payload !== 'remain' && (task.context.payload = payload);
  21436. };
  21437. function createSeriesStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) {
  21438. var seriesTaskMap = stageHandlerRecord.seriesTaskMap
  21439. || (stageHandlerRecord.seriesTaskMap = createHashMap());
  21440. var seriesType = stageHandler.seriesType;
  21441. var getTargetSeries = stageHandler.getTargetSeries;
  21442. // If a stageHandler should cover all series, `createOnAllSeries` should be declared mandatorily,
  21443. // to avoid some typo or abuse. Otherwise if an extension do not specify a `seriesType`,
  21444. // it works but it may cause other irrelevant charts blocked.
  21445. if (stageHandler.createOnAllSeries) {
  21446. ecModel.eachRawSeries(create);
  21447. }
  21448. else if (seriesType) {
  21449. ecModel.eachRawSeriesByType(seriesType, create);
  21450. }
  21451. else if (getTargetSeries) {
  21452. getTargetSeries(ecModel, api).each(create);
  21453. }
  21454. function create(seriesModel) {
  21455. var pipelineId = seriesModel.uid;
  21456. // Init tasks for each seriesModel only once.
  21457. // Reuse original task instance.
  21458. var task = seriesTaskMap.get(pipelineId)
  21459. || seriesTaskMap.set(pipelineId, createTask({
  21460. plan: seriesTaskPlan,
  21461. reset: seriesTaskReset,
  21462. count: seriesTaskCount
  21463. }));
  21464. task.context = {
  21465. model: seriesModel,
  21466. ecModel: ecModel,
  21467. api: api,
  21468. useClearVisual: stageHandler.isVisual && !stageHandler.isLayout,
  21469. plan: stageHandler.plan,
  21470. reset: stageHandler.reset,
  21471. scheduler: scheduler
  21472. };
  21473. pipe(scheduler, seriesModel, task);
  21474. }
  21475. // Clear unused series tasks.
  21476. var pipelineMap = scheduler._pipelineMap;
  21477. seriesTaskMap.each(function (task, pipelineId) {
  21478. if (!pipelineMap.get(pipelineId)) {
  21479. task.dispose();
  21480. seriesTaskMap.removeKey(pipelineId);
  21481. }
  21482. });
  21483. }
  21484. function createOverallStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) {
  21485. var overallTask = stageHandlerRecord.overallTask = stageHandlerRecord.overallTask
  21486. // For overall task, the function only be called on reset stage.
  21487. || createTask({reset: overallTaskReset});
  21488. overallTask.context = {
  21489. ecModel: ecModel,
  21490. api: api,
  21491. overallReset: stageHandler.overallReset,
  21492. scheduler: scheduler
  21493. };
  21494. // Reuse orignal stubs.
  21495. var agentStubMap = overallTask.agentStubMap = overallTask.agentStubMap || createHashMap();
  21496. var seriesType = stageHandler.seriesType;
  21497. var getTargetSeries = stageHandler.getTargetSeries;
  21498. var overallProgress = true;
  21499. var modifyOutputEnd = stageHandler.modifyOutputEnd;
  21500. // An overall task with seriesType detected or has `getTargetSeries`, we add
  21501. // stub in each pipelines, it will set the overall task dirty when the pipeline
  21502. // progress. Moreover, to avoid call the overall task each frame (too frequent),
  21503. // we set the pipeline block.
  21504. if (seriesType) {
  21505. ecModel.eachRawSeriesByType(seriesType, createStub);
  21506. }
  21507. else if (getTargetSeries) {
  21508. getTargetSeries(ecModel, api).each(createStub);
  21509. }
  21510. // Otherwise, (usually it is legancy case), the overall task will only be
  21511. // executed when upstream dirty. Otherwise the progressive rendering of all
  21512. // pipelines will be disabled unexpectedly. But it still needs stubs to receive
  21513. // dirty info from upsteam.
  21514. else {
  21515. overallProgress = false;
  21516. each$1(ecModel.getSeries(), createStub);
  21517. }
  21518. function createStub(seriesModel) {
  21519. var pipelineId = seriesModel.uid;
  21520. var stub = agentStubMap.get(pipelineId);
  21521. if (!stub) {
  21522. stub = agentStubMap.set(pipelineId, createTask(
  21523. {reset: stubReset, onDirty: stubOnDirty}
  21524. ));
  21525. // When the result of `getTargetSeries` changed, the overallTask
  21526. // should be set as dirty and re-performed.
  21527. overallTask.dirty();
  21528. }
  21529. stub.context = {
  21530. model: seriesModel,
  21531. overallProgress: overallProgress,
  21532. modifyOutputEnd: modifyOutputEnd
  21533. };
  21534. stub.agent = overallTask;
  21535. stub.__block = overallProgress;
  21536. pipe(scheduler, seriesModel, stub);
  21537. }
  21538. // Clear unused stubs.
  21539. var pipelineMap = scheduler._pipelineMap;
  21540. agentStubMap.each(function (stub, pipelineId) {
  21541. if (!pipelineMap.get(pipelineId)) {
  21542. stub.dispose();
  21543. // When the result of `getTargetSeries` changed, the overallTask
  21544. // should be set as dirty and re-performed.
  21545. overallTask.dirty();
  21546. agentStubMap.removeKey(pipelineId);
  21547. }
  21548. });
  21549. }
  21550. function overallTaskReset(context) {
  21551. context.overallReset(
  21552. context.ecModel, context.api, context.payload
  21553. );
  21554. }
  21555. function stubReset(context, upstreamContext) {
  21556. return context.overallProgress && stubProgress;
  21557. }
  21558. function stubProgress() {
  21559. this.agent.dirty();
  21560. this.getDownstream().dirty();
  21561. }
  21562. function stubOnDirty() {
  21563. this.agent && this.agent.dirty();
  21564. }
  21565. function seriesTaskPlan(context) {
  21566. return context.plan && context.plan(
  21567. context.model, context.ecModel, context.api, context.payload
  21568. );
  21569. }
  21570. function seriesTaskReset(context) {
  21571. if (context.useClearVisual) {
  21572. context.data.clearAllVisual();
  21573. }
  21574. var resetDefines = context.resetDefines = normalizeToArray(context.reset(
  21575. context.model, context.ecModel, context.api, context.payload
  21576. ));
  21577. return resetDefines.length > 1
  21578. ? map(resetDefines, function (v, idx) {
  21579. return makeSeriesTaskProgress(idx);
  21580. })
  21581. : singleSeriesTaskProgress;
  21582. }
  21583. var singleSeriesTaskProgress = makeSeriesTaskProgress(0);
  21584. function makeSeriesTaskProgress(resetDefineIdx) {
  21585. return function (params, context) {
  21586. var data = context.data;
  21587. var resetDefine = context.resetDefines[resetDefineIdx];
  21588. if (resetDefine && resetDefine.dataEach) {
  21589. for (var i = params.start; i < params.end; i++) {
  21590. resetDefine.dataEach(data, i);
  21591. }
  21592. }
  21593. else if (resetDefine && resetDefine.progress) {
  21594. resetDefine.progress(params, data);
  21595. }
  21596. };
  21597. }
  21598. function seriesTaskCount(context) {
  21599. return context.data.count();
  21600. }
  21601. function pipe(scheduler, seriesModel, task) {
  21602. var pipelineId = seriesModel.uid;
  21603. var pipeline = scheduler._pipelineMap.get(pipelineId);
  21604. !pipeline.head && (pipeline.head = task);
  21605. pipeline.tail && pipeline.tail.pipe(task);
  21606. pipeline.tail = task;
  21607. task.__idxInPipeline = pipeline.count++;
  21608. task.__pipeline = pipeline;
  21609. }
  21610. Scheduler.wrapStageHandler = function (stageHandler, visualType) {
  21611. if (isFunction$1(stageHandler)) {
  21612. stageHandler = {
  21613. overallReset: stageHandler,
  21614. seriesType: detectSeriseType(stageHandler)
  21615. };
  21616. }
  21617. stageHandler.uid = getUID('stageHandler');
  21618. visualType && (stageHandler.visualType = visualType);
  21619. return stageHandler;
  21620. };
  21621. /**
  21622. * Only some legacy stage handlers (usually in echarts extensions) are pure function.
  21623. * To ensure that they can work normally, they should work in block mode, that is,
  21624. * they should not be started util the previous tasks finished. So they cause the
  21625. * progressive rendering disabled. We try to detect the series type, to narrow down
  21626. * the block range to only the series type they concern, but not all series.
  21627. */
  21628. function detectSeriseType(legacyFunc) {
  21629. seriesType = null;
  21630. try {
  21631. // Assume there is no async when calling `eachSeriesByType`.
  21632. legacyFunc(ecModelMock, apiMock);
  21633. }
  21634. catch (e) {
  21635. }
  21636. return seriesType;
  21637. }
  21638. var ecModelMock = {};
  21639. var apiMock = {};
  21640. var seriesType;
  21641. mockMethods(ecModelMock, GlobalModel);
  21642. mockMethods(apiMock, ExtensionAPI);
  21643. ecModelMock.eachSeriesByType = ecModelMock.eachRawSeriesByType = function (type) {
  21644. seriesType = type;
  21645. };
  21646. ecModelMock.eachComponent = function (cond) {
  21647. if (cond.mainType === 'series' && cond.subType) {
  21648. seriesType = cond.subType;
  21649. }
  21650. };
  21651. function mockMethods(target, Clz) {
  21652. for (var name in Clz.prototype) {
  21653. // Do not use hasOwnProperty
  21654. target[name] = noop;
  21655. }
  21656. }
  21657. /*
  21658. * Licensed to the Apache Software Foundation (ASF) under one
  21659. * or more contributor license agreements. See the NOTICE file
  21660. * distributed with this work for additional information
  21661. * regarding copyright ownership. The ASF licenses this file
  21662. * to you under the Apache License, Version 2.0 (the
  21663. * "License"); you may not use this file except in compliance
  21664. * with the License. You may obtain a copy of the License at
  21665. *
  21666. * http://www.apache.org/licenses/LICENSE-2.0
  21667. *
  21668. * Unless required by applicable law or agreed to in writing,
  21669. * software distributed under the License is distributed on an
  21670. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21671. * KIND, either express or implied. See the License for the
  21672. * specific language governing permissions and limitations
  21673. * under the License.
  21674. */
  21675. var colorAll = ['#37A2DA', '#32C5E9', '#67E0E3', '#9FE6B8', '#FFDB5C','#ff9f7f', '#fb7293', '#E062AE', '#E690D1', '#e7bcf3', '#9d96f5', '#8378EA', '#96BFFF'];
  21676. var lightTheme = {
  21677. color: colorAll,
  21678. colorLayer: [
  21679. ['#37A2DA', '#ffd85c', '#fd7b5f'],
  21680. ['#37A2DA', '#67E0E3', '#FFDB5C', '#ff9f7f', '#E062AE', '#9d96f5'],
  21681. ['#37A2DA', '#32C5E9', '#9FE6B8', '#FFDB5C', '#ff9f7f', '#fb7293', '#e7bcf3', '#8378EA', '#96BFFF'],
  21682. colorAll
  21683. ]
  21684. };
  21685. /*
  21686. * Licensed to the Apache Software Foundation (ASF) under one
  21687. * or more contributor license agreements. See the NOTICE file
  21688. * distributed with this work for additional information
  21689. * regarding copyright ownership. The ASF licenses this file
  21690. * to you under the Apache License, Version 2.0 (the
  21691. * "License"); you may not use this file except in compliance
  21692. * with the License. You may obtain a copy of the License at
  21693. *
  21694. * http://www.apache.org/licenses/LICENSE-2.0
  21695. *
  21696. * Unless required by applicable law or agreed to in writing,
  21697. * software distributed under the License is distributed on an
  21698. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21699. * KIND, either express or implied. See the License for the
  21700. * specific language governing permissions and limitations
  21701. * under the License.
  21702. */
  21703. var contrastColor = '#eee';
  21704. var axisCommon = function () {
  21705. return {
  21706. axisLine: {
  21707. lineStyle: {
  21708. color: contrastColor
  21709. }
  21710. },
  21711. axisTick: {
  21712. lineStyle: {
  21713. color: contrastColor
  21714. }
  21715. },
  21716. axisLabel: {
  21717. textStyle: {
  21718. color: contrastColor
  21719. }
  21720. },
  21721. splitLine: {
  21722. lineStyle: {
  21723. type: 'dashed',
  21724. color: '#aaa'
  21725. }
  21726. },
  21727. splitArea: {
  21728. areaStyle: {
  21729. color: contrastColor
  21730. }
  21731. }
  21732. };
  21733. };
  21734. var colorPalette = ['#dd6b66','#759aa0','#e69d87','#8dc1a9','#ea7e53','#eedd78','#73a373','#73b9bc','#7289ab', '#91ca8c','#f49f42'];
  21735. var theme = {
  21736. color: colorPalette,
  21737. backgroundColor: '#333',
  21738. tooltip: {
  21739. axisPointer: {
  21740. lineStyle: {
  21741. color: contrastColor
  21742. },
  21743. crossStyle: {
  21744. color: contrastColor
  21745. }
  21746. }
  21747. },
  21748. legend: {
  21749. textStyle: {
  21750. color: contrastColor
  21751. }
  21752. },
  21753. textStyle: {
  21754. color: contrastColor
  21755. },
  21756. title: {
  21757. textStyle: {
  21758. color: contrastColor
  21759. }
  21760. },
  21761. toolbox: {
  21762. iconStyle: {
  21763. normal: {
  21764. borderColor: contrastColor
  21765. }
  21766. }
  21767. },
  21768. dataZoom: {
  21769. textStyle: {
  21770. color: contrastColor
  21771. }
  21772. },
  21773. visualMap: {
  21774. textStyle: {
  21775. color: contrastColor
  21776. }
  21777. },
  21778. timeline: {
  21779. lineStyle: {
  21780. color: contrastColor
  21781. },
  21782. itemStyle: {
  21783. normal: {
  21784. color: colorPalette[1]
  21785. }
  21786. },
  21787. label: {
  21788. normal: {
  21789. textStyle: {
  21790. color: contrastColor
  21791. }
  21792. }
  21793. },
  21794. controlStyle: {
  21795. normal: {
  21796. color: contrastColor,
  21797. borderColor: contrastColor
  21798. }
  21799. }
  21800. },
  21801. timeAxis: axisCommon(),
  21802. logAxis: axisCommon(),
  21803. valueAxis: axisCommon(),
  21804. categoryAxis: axisCommon(),
  21805. line: {
  21806. symbol: 'circle'
  21807. },
  21808. graph: {
  21809. color: colorPalette
  21810. },
  21811. gauge: {
  21812. title: {
  21813. textStyle: {
  21814. color: contrastColor
  21815. }
  21816. }
  21817. },
  21818. candlestick: {
  21819. itemStyle: {
  21820. normal: {
  21821. color: '#FD1050',
  21822. color0: '#0CF49B',
  21823. borderColor: '#FD1050',
  21824. borderColor0: '#0CF49B'
  21825. }
  21826. }
  21827. }
  21828. };
  21829. theme.categoryAxis.splitLine.show = false;
  21830. /*
  21831. * Licensed to the Apache Software Foundation (ASF) under one
  21832. * or more contributor license agreements. See the NOTICE file
  21833. * distributed with this work for additional information
  21834. * regarding copyright ownership. The ASF licenses this file
  21835. * to you under the Apache License, Version 2.0 (the
  21836. * "License"); you may not use this file except in compliance
  21837. * with the License. You may obtain a copy of the License at
  21838. *
  21839. * http://www.apache.org/licenses/LICENSE-2.0
  21840. *
  21841. * Unless required by applicable law or agreed to in writing,
  21842. * software distributed under the License is distributed on an
  21843. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21844. * KIND, either express or implied. See the License for the
  21845. * specific language governing permissions and limitations
  21846. * under the License.
  21847. */
  21848. /**
  21849. * This module is imported by echarts directly.
  21850. *
  21851. * Notice:
  21852. * Always keep this file exists for backward compatibility.
  21853. * Because before 4.1.0, dataset is an optional component,
  21854. * some users may import this module manually.
  21855. */
  21856. ComponentModel.extend({
  21857. type: 'dataset',
  21858. /**
  21859. * @protected
  21860. */
  21861. defaultOption: {
  21862. // 'row', 'column'
  21863. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN,
  21864. // null/'auto': auto detect header, see "module:echarts/data/helper/sourceHelper"
  21865. sourceHeader: null,
  21866. dimensions: null,
  21867. source: null
  21868. },
  21869. optionUpdated: function () {
  21870. detectSourceFormat(this);
  21871. }
  21872. });
  21873. Component.extend({
  21874. type: 'dataset'
  21875. });
  21876. /*
  21877. * Licensed to the Apache Software Foundation (ASF) under one
  21878. * or more contributor license agreements. See the NOTICE file
  21879. * distributed with this work for additional information
  21880. * regarding copyright ownership. The ASF licenses this file
  21881. * to you under the Apache License, Version 2.0 (the
  21882. * "License"); you may not use this file except in compliance
  21883. * with the License. You may obtain a copy of the License at
  21884. *
  21885. * http://www.apache.org/licenses/LICENSE-2.0
  21886. *
  21887. * Unless required by applicable law or agreed to in writing,
  21888. * software distributed under the License is distributed on an
  21889. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21890. * KIND, either express or implied. See the License for the
  21891. * specific language governing permissions and limitations
  21892. * under the License.
  21893. */
  21894. var assert = assert$1;
  21895. var each = each$1;
  21896. var isFunction = isFunction$1;
  21897. var isObject = isObject$1;
  21898. var parseClassType = ComponentModel.parseClassType;
  21899. var version = '4.1.0';
  21900. var dependencies = {
  21901. zrender: '4.0.4'
  21902. };
  21903. var TEST_FRAME_REMAIN_TIME = 1;
  21904. var PRIORITY_PROCESSOR_FILTER = 1000;
  21905. var PRIORITY_PROCESSOR_STATISTIC = 5000;
  21906. var PRIORITY_VISUAL_LAYOUT = 1000;
  21907. var PRIORITY_VISUAL_GLOBAL = 2000;
  21908. var PRIORITY_VISUAL_CHART = 3000;
  21909. var PRIORITY_VISUAL_COMPONENT = 4000;
  21910. // FIXME
  21911. // necessary?
  21912. var PRIORITY_VISUAL_BRUSH = 5000;
  21913. var PRIORITY = {
  21914. PROCESSOR: {
  21915. FILTER: PRIORITY_PROCESSOR_FILTER,
  21916. STATISTIC: PRIORITY_PROCESSOR_STATISTIC
  21917. },
  21918. VISUAL: {
  21919. LAYOUT: PRIORITY_VISUAL_LAYOUT,
  21920. GLOBAL: PRIORITY_VISUAL_GLOBAL,
  21921. CHART: PRIORITY_VISUAL_CHART,
  21922. COMPONENT: PRIORITY_VISUAL_COMPONENT,
  21923. BRUSH: PRIORITY_VISUAL_BRUSH
  21924. }
  21925. };
  21926. // Main process have three entries: `setOption`, `dispatchAction` and `resize`,
  21927. // where they must not be invoked nestedly, except the only case: invoke
  21928. // dispatchAction with updateMethod "none" in main process.
  21929. // This flag is used to carry out this rule.
  21930. // All events will be triggered out side main process (i.e. when !this[IN_MAIN_PROCESS]).
  21931. var IN_MAIN_PROCESS = '__flagInMainProcess';
  21932. var OPTION_UPDATED = '__optionUpdated';
  21933. var ACTION_REG = /^[a-zA-Z0-9_]+$/;
  21934. function createRegisterEventWithLowercaseName(method) {
  21935. return function (eventName, handler, context) {
  21936. // Event name is all lowercase
  21937. eventName = eventName && eventName.toLowerCase();
  21938. Eventful.prototype[method].call(this, eventName, handler, context);
  21939. };
  21940. }
  21941. /**
  21942. * @module echarts~MessageCenter
  21943. */
  21944. function MessageCenter() {
  21945. Eventful.call(this);
  21946. }
  21947. MessageCenter.prototype.on = createRegisterEventWithLowercaseName('on');
  21948. MessageCenter.prototype.off = createRegisterEventWithLowercaseName('off');
  21949. MessageCenter.prototype.one = createRegisterEventWithLowercaseName('one');
  21950. mixin(MessageCenter, Eventful);
  21951. /**
  21952. * @module echarts~ECharts
  21953. */
  21954. function ECharts(dom, theme$$1, opts) {
  21955. opts = opts || {};
  21956. // Get theme by name
  21957. if (typeof theme$$1 === 'string') {
  21958. theme$$1 = themeStorage[theme$$1];
  21959. }
  21960. /**
  21961. * @type {string}
  21962. */
  21963. this.id;
  21964. /**
  21965. * Group id
  21966. * @type {string}
  21967. */
  21968. this.group;
  21969. /**
  21970. * @type {HTMLElement}
  21971. * @private
  21972. */
  21973. this._dom = dom;
  21974. var defaultRenderer = 'canvas';
  21975. if (__DEV__) {
  21976. defaultRenderer = (
  21977. typeof window === 'undefined' ? global : window
  21978. ).__ECHARTS__DEFAULT__RENDERER__ || defaultRenderer;
  21979. }
  21980. /**
  21981. * @type {module:zrender/ZRender}
  21982. * @private
  21983. */
  21984. var zr = this._zr = init$1(dom, {
  21985. renderer: opts.renderer || defaultRenderer,
  21986. devicePixelRatio: opts.devicePixelRatio,
  21987. width: opts.width,
  21988. height: opts.height
  21989. });
  21990. /**
  21991. * Expect 60 pfs.
  21992. * @type {Function}
  21993. * @private
  21994. */
  21995. this._throttledZrFlush = throttle(bind(zr.flush, zr), 17);
  21996. var theme$$1 = clone(theme$$1);
  21997. theme$$1 && backwardCompat(theme$$1, true);
  21998. /**
  21999. * @type {Object}
  22000. * @private
  22001. */
  22002. this._theme = theme$$1;
  22003. /**
  22004. * @type {Array.<module:echarts/view/Chart>}
  22005. * @private
  22006. */
  22007. this._chartsViews = [];
  22008. /**
  22009. * @type {Object.<string, module:echarts/view/Chart>}
  22010. * @private
  22011. */
  22012. this._chartsMap = {};
  22013. /**
  22014. * @type {Array.<module:echarts/view/Component>}
  22015. * @private
  22016. */
  22017. this._componentsViews = [];
  22018. /**
  22019. * @type {Object.<string, module:echarts/view/Component>}
  22020. * @private
  22021. */
  22022. this._componentsMap = {};
  22023. /**
  22024. * @type {module:echarts/CoordinateSystem}
  22025. * @private
  22026. */
  22027. this._coordSysMgr = new CoordinateSystemManager();
  22028. /**
  22029. * @type {module:echarts/ExtensionAPI}
  22030. * @private
  22031. */
  22032. var api = this._api = createExtensionAPI(this);
  22033. // Sort on demand
  22034. function prioritySortFunc(a, b) {
  22035. return a.__prio - b.__prio;
  22036. }
  22037. sort(visualFuncs, prioritySortFunc);
  22038. sort(dataProcessorFuncs, prioritySortFunc);
  22039. /**
  22040. * @type {module:echarts/stream/Scheduler}
  22041. */
  22042. this._scheduler = new Scheduler(this, api, dataProcessorFuncs, visualFuncs);
  22043. Eventful.call(this);
  22044. /**
  22045. * @type {module:echarts~MessageCenter}
  22046. * @private
  22047. */
  22048. this._messageCenter = new MessageCenter();
  22049. // Init mouse events
  22050. this._initEvents();
  22051. // In case some people write `window.onresize = chart.resize`
  22052. this.resize = bind(this.resize, this);
  22053. // Can't dispatch action during rendering procedure
  22054. this._pendingActions = [];
  22055. zr.animation.on('frame', this._onframe, this);
  22056. bindRenderedEvent(zr, this);
  22057. // ECharts instance can be used as value.
  22058. setAsPrimitive(this);
  22059. }
  22060. var echartsProto = ECharts.prototype;
  22061. echartsProto._onframe = function () {
  22062. if (this._disposed) {
  22063. return;
  22064. }
  22065. var scheduler = this._scheduler;
  22066. // Lazy update
  22067. if (this[OPTION_UPDATED]) {
  22068. var silent = this[OPTION_UPDATED].silent;
  22069. this[IN_MAIN_PROCESS] = true;
  22070. prepare(this);
  22071. updateMethods.update.call(this);
  22072. this[IN_MAIN_PROCESS] = false;
  22073. this[OPTION_UPDATED] = false;
  22074. flushPendingActions.call(this, silent);
  22075. triggerUpdatedEvent.call(this, silent);
  22076. }
  22077. // Avoid do both lazy update and progress in one frame.
  22078. else if (scheduler.unfinished) {
  22079. // Stream progress.
  22080. var remainTime = TEST_FRAME_REMAIN_TIME;
  22081. var ecModel = this._model;
  22082. var api = this._api;
  22083. scheduler.unfinished = false;
  22084. do {
  22085. var startTime = +new Date();
  22086. scheduler.performSeriesTasks(ecModel);
  22087. // Currently dataProcessorFuncs do not check threshold.
  22088. scheduler.performDataProcessorTasks(ecModel);
  22089. updateStreamModes(this, ecModel);
  22090. // Do not update coordinate system here. Because that coord system update in
  22091. // each frame is not a good user experience. So we follow the rule that
  22092. // the extent of the coordinate system is determin in the first frame (the
  22093. // frame is executed immedietely after task reset.
  22094. // this._coordSysMgr.update(ecModel, api);
  22095. // console.log('--- ec frame visual ---', remainTime);
  22096. scheduler.performVisualTasks(ecModel);
  22097. renderSeries(this, this._model, api, 'remain');
  22098. remainTime -= (+new Date() - startTime);
  22099. }
  22100. while (remainTime > 0 && scheduler.unfinished);
  22101. // Call flush explicitly for trigger finished event.
  22102. if (!scheduler.unfinished) {
  22103. this._zr.flush();
  22104. }
  22105. // Else, zr flushing be ensue within the same frame,
  22106. // because zr flushing is after onframe event.
  22107. }
  22108. };
  22109. /**
  22110. * @return {HTMLElement}
  22111. */
  22112. echartsProto.getDom = function () {
  22113. return this._dom;
  22114. };
  22115. /**
  22116. * @return {module:zrender~ZRender}
  22117. */
  22118. echartsProto.getZr = function () {
  22119. return this._zr;
  22120. };
  22121. /**
  22122. * Usage:
  22123. * chart.setOption(option, notMerge, lazyUpdate);
  22124. * chart.setOption(option, {
  22125. * notMerge: ...,
  22126. * lazyUpdate: ...,
  22127. * silent: ...
  22128. * });
  22129. *
  22130. * @param {Object} option
  22131. * @param {Object|boolean} [opts] opts or notMerge.
  22132. * @param {boolean} [opts.notMerge=false]
  22133. * @param {boolean} [opts.lazyUpdate=false] Useful when setOption frequently.
  22134. */
  22135. echartsProto.setOption = function (option, notMerge, lazyUpdate) {
  22136. if (__DEV__) {
  22137. assert(!this[IN_MAIN_PROCESS], '`setOption` should not be called during main process.');
  22138. }
  22139. var silent;
  22140. if (isObject(notMerge)) {
  22141. lazyUpdate = notMerge.lazyUpdate;
  22142. silent = notMerge.silent;
  22143. notMerge = notMerge.notMerge;
  22144. }
  22145. this[IN_MAIN_PROCESS] = true;
  22146. if (!this._model || notMerge) {
  22147. var optionManager = new OptionManager(this._api);
  22148. var theme$$1 = this._theme;
  22149. var ecModel = this._model = new GlobalModel(null, null, theme$$1, optionManager);
  22150. ecModel.scheduler = this._scheduler;
  22151. ecModel.init(null, null, theme$$1, optionManager);
  22152. }
  22153. this._model.setOption(option, optionPreprocessorFuncs);
  22154. if (lazyUpdate) {
  22155. this[OPTION_UPDATED] = {silent: silent};
  22156. this[IN_MAIN_PROCESS] = false;
  22157. }
  22158. else {
  22159. prepare(this);
  22160. updateMethods.update.call(this);
  22161. // Ensure zr refresh sychronously, and then pixel in canvas can be
  22162. // fetched after `setOption`.
  22163. this._zr.flush();
  22164. this[OPTION_UPDATED] = false;
  22165. this[IN_MAIN_PROCESS] = false;
  22166. flushPendingActions.call(this, silent);
  22167. triggerUpdatedEvent.call(this, silent);
  22168. }
  22169. };
  22170. /**
  22171. * @DEPRECATED
  22172. */
  22173. echartsProto.setTheme = function () {
  22174. console.log('ECharts#setTheme() is DEPRECATED in ECharts 3.0');
  22175. };
  22176. /**
  22177. * @return {module:echarts/model/Global}
  22178. */
  22179. echartsProto.getModel = function () {
  22180. return this._model;
  22181. };
  22182. /**
  22183. * @return {Object}
  22184. */
  22185. echartsProto.getOption = function () {
  22186. return this._model && this._model.getOption();
  22187. };
  22188. /**
  22189. * @return {number}
  22190. */
  22191. echartsProto.getWidth = function () {
  22192. return this._zr.getWidth();
  22193. };
  22194. /**
  22195. * @return {number}
  22196. */
  22197. echartsProto.getHeight = function () {
  22198. return this._zr.getHeight();
  22199. };
  22200. /**
  22201. * @return {number}
  22202. */
  22203. echartsProto.getDevicePixelRatio = function () {
  22204. return this._zr.painter.dpr || window.devicePixelRatio || 1;
  22205. };
  22206. /**
  22207. * Get canvas which has all thing rendered
  22208. * @param {Object} opts
  22209. * @param {string} [opts.backgroundColor]
  22210. * @return {string}
  22211. */
  22212. echartsProto.getRenderedCanvas = function (opts) {
  22213. if (!env$1.canvasSupported) {
  22214. return;
  22215. }
  22216. opts = opts || {};
  22217. opts.pixelRatio = opts.pixelRatio || 1;
  22218. opts.backgroundColor = opts.backgroundColor
  22219. || this._model.get('backgroundColor');
  22220. var zr = this._zr;
  22221. // var list = zr.storage.getDisplayList();
  22222. // Stop animations
  22223. // Never works before in init animation, so remove it.
  22224. // zrUtil.each(list, function (el) {
  22225. // el.stopAnimation(true);
  22226. // });
  22227. return zr.painter.getRenderedCanvas(opts);
  22228. };
  22229. /**
  22230. * Get svg data url
  22231. * @return {string}
  22232. */
  22233. echartsProto.getSvgDataUrl = function () {
  22234. if (!env$1.svgSupported) {
  22235. return;
  22236. }
  22237. var zr = this._zr;
  22238. var list = zr.storage.getDisplayList();
  22239. // Stop animations
  22240. each$1(list, function (el) {
  22241. el.stopAnimation(true);
  22242. });
  22243. return zr.painter.pathToDataUrl();
  22244. };
  22245. /**
  22246. * @return {string}
  22247. * @param {Object} opts
  22248. * @param {string} [opts.type='png']
  22249. * @param {string} [opts.pixelRatio=1]
  22250. * @param {string} [opts.backgroundColor]
  22251. * @param {string} [opts.excludeComponents]
  22252. */
  22253. echartsProto.getDataURL = function (opts) {
  22254. opts = opts || {};
  22255. var excludeComponents = opts.excludeComponents;
  22256. var ecModel = this._model;
  22257. var excludesComponentViews = [];
  22258. var self = this;
  22259. each(excludeComponents, function (componentType) {
  22260. ecModel.eachComponent({
  22261. mainType: componentType
  22262. }, function (component) {
  22263. var view = self._componentsMap[component.__viewId];
  22264. if (!view.group.ignore) {
  22265. excludesComponentViews.push(view);
  22266. view.group.ignore = true;
  22267. }
  22268. });
  22269. });
  22270. var url = this._zr.painter.getType() === 'svg'
  22271. ? this.getSvgDataUrl()
  22272. : this.getRenderedCanvas(opts).toDataURL(
  22273. 'image/' + (opts && opts.type || 'png')
  22274. );
  22275. each(excludesComponentViews, function (view) {
  22276. view.group.ignore = false;
  22277. });
  22278. return url;
  22279. };
  22280. /**
  22281. * @return {string}
  22282. * @param {Object} opts
  22283. * @param {string} [opts.type='png']
  22284. * @param {string} [opts.pixelRatio=1]
  22285. * @param {string} [opts.backgroundColor]
  22286. */
  22287. echartsProto.getConnectedDataURL = function (opts) {
  22288. if (!env$1.canvasSupported) {
  22289. return;
  22290. }
  22291. var groupId = this.group;
  22292. var mathMin = Math.min;
  22293. var mathMax = Math.max;
  22294. var MAX_NUMBER = Infinity;
  22295. if (connectedGroups[groupId]) {
  22296. var left = MAX_NUMBER;
  22297. var top = MAX_NUMBER;
  22298. var right = -MAX_NUMBER;
  22299. var bottom = -MAX_NUMBER;
  22300. var canvasList = [];
  22301. var dpr = (opts && opts.pixelRatio) || 1;
  22302. each$1(instances, function (chart, id) {
  22303. if (chart.group === groupId) {
  22304. var canvas = chart.getRenderedCanvas(
  22305. clone(opts)
  22306. );
  22307. var boundingRect = chart.getDom().getBoundingClientRect();
  22308. left = mathMin(boundingRect.left, left);
  22309. top = mathMin(boundingRect.top, top);
  22310. right = mathMax(boundingRect.right, right);
  22311. bottom = mathMax(boundingRect.bottom, bottom);
  22312. canvasList.push({
  22313. dom: canvas,
  22314. left: boundingRect.left,
  22315. top: boundingRect.top
  22316. });
  22317. }
  22318. });
  22319. left *= dpr;
  22320. top *= dpr;
  22321. right *= dpr;
  22322. bottom *= dpr;
  22323. var width = right - left;
  22324. var height = bottom - top;
  22325. var targetCanvas = createCanvas();
  22326. targetCanvas.width = width;
  22327. targetCanvas.height = height;
  22328. var zr = init$1(targetCanvas);
  22329. each(canvasList, function (item) {
  22330. var img = new ZImage({
  22331. style: {
  22332. x: item.left * dpr - left,
  22333. y: item.top * dpr - top,
  22334. image: item.dom
  22335. }
  22336. });
  22337. zr.add(img);
  22338. });
  22339. zr.refreshImmediately();
  22340. return targetCanvas.toDataURL('image/' + (opts && opts.type || 'png'));
  22341. }
  22342. else {
  22343. return this.getDataURL(opts);
  22344. }
  22345. };
  22346. /**
  22347. * Convert from logical coordinate system to pixel coordinate system.
  22348. * See CoordinateSystem#convertToPixel.
  22349. * @param {string|Object} finder
  22350. * If string, e.g., 'geo', means {geoIndex: 0}.
  22351. * If Object, could contain some of these properties below:
  22352. * {
  22353. * seriesIndex / seriesId / seriesName,
  22354. * geoIndex / geoId, geoName,
  22355. * bmapIndex / bmapId / bmapName,
  22356. * xAxisIndex / xAxisId / xAxisName,
  22357. * yAxisIndex / yAxisId / yAxisName,
  22358. * gridIndex / gridId / gridName,
  22359. * ... (can be extended)
  22360. * }
  22361. * @param {Array|number} value
  22362. * @return {Array|number} result
  22363. */
  22364. echartsProto.convertToPixel = curry(doConvertPixel, 'convertToPixel');
  22365. /**
  22366. * Convert from pixel coordinate system to logical coordinate system.
  22367. * See CoordinateSystem#convertFromPixel.
  22368. * @param {string|Object} finder
  22369. * If string, e.g., 'geo', means {geoIndex: 0}.
  22370. * If Object, could contain some of these properties below:
  22371. * {
  22372. * seriesIndex / seriesId / seriesName,
  22373. * geoIndex / geoId / geoName,
  22374. * bmapIndex / bmapId / bmapName,
  22375. * xAxisIndex / xAxisId / xAxisName,
  22376. * yAxisIndex / yAxisId / yAxisName
  22377. * gridIndex / gridId / gridName,
  22378. * ... (can be extended)
  22379. * }
  22380. * @param {Array|number} value
  22381. * @return {Array|number} result
  22382. */
  22383. echartsProto.convertFromPixel = curry(doConvertPixel, 'convertFromPixel');
  22384. function doConvertPixel(methodName, finder, value) {
  22385. var ecModel = this._model;
  22386. var coordSysList = this._coordSysMgr.getCoordinateSystems();
  22387. var result;
  22388. finder = parseFinder(ecModel, finder);
  22389. for (var i = 0; i < coordSysList.length; i++) {
  22390. var coordSys = coordSysList[i];
  22391. if (coordSys[methodName]
  22392. && (result = coordSys[methodName](ecModel, finder, value)) != null
  22393. ) {
  22394. return result;
  22395. }
  22396. }
  22397. if (__DEV__) {
  22398. console.warn(
  22399. 'No coordinate system that supports ' + methodName + ' found by the given finder.'
  22400. );
  22401. }
  22402. }
  22403. /**
  22404. * Is the specified coordinate systems or components contain the given pixel point.
  22405. * @param {string|Object} finder
  22406. * If string, e.g., 'geo', means {geoIndex: 0}.
  22407. * If Object, could contain some of these properties below:
  22408. * {
  22409. * seriesIndex / seriesId / seriesName,
  22410. * geoIndex / geoId / geoName,
  22411. * bmapIndex / bmapId / bmapName,
  22412. * xAxisIndex / xAxisId / xAxisName,
  22413. * yAxisIndex / yAxisId / yAxisName,
  22414. * gridIndex / gridId / gridName,
  22415. * ... (can be extended)
  22416. * }
  22417. * @param {Array|number} value
  22418. * @return {boolean} result
  22419. */
  22420. echartsProto.containPixel = function (finder, value) {
  22421. var ecModel = this._model;
  22422. var result;
  22423. finder = parseFinder(ecModel, finder);
  22424. each$1(finder, function (models, key) {
  22425. key.indexOf('Models') >= 0 && each$1(models, function (model) {
  22426. var coordSys = model.coordinateSystem;
  22427. if (coordSys && coordSys.containPoint) {
  22428. result |= !!coordSys.containPoint(value);
  22429. }
  22430. else if (key === 'seriesModels') {
  22431. var view = this._chartsMap[model.__viewId];
  22432. if (view && view.containPoint) {
  22433. result |= view.containPoint(value, model);
  22434. }
  22435. else {
  22436. if (__DEV__) {
  22437. console.warn(key + ': ' + (view
  22438. ? 'The found component do not support containPoint.'
  22439. : 'No view mapping to the found component.'
  22440. ));
  22441. }
  22442. }
  22443. }
  22444. else {
  22445. if (__DEV__) {
  22446. console.warn(key + ': containPoint is not supported');
  22447. }
  22448. }
  22449. }, this);
  22450. }, this);
  22451. return !!result;
  22452. };
  22453. /**
  22454. * Get visual from series or data.
  22455. * @param {string|Object} finder
  22456. * If string, e.g., 'series', means {seriesIndex: 0}.
  22457. * If Object, could contain some of these properties below:
  22458. * {
  22459. * seriesIndex / seriesId / seriesName,
  22460. * dataIndex / dataIndexInside
  22461. * }
  22462. * If dataIndex is not specified, series visual will be fetched,
  22463. * but not data item visual.
  22464. * If all of seriesIndex, seriesId, seriesName are not specified,
  22465. * visual will be fetched from first series.
  22466. * @param {string} visualType 'color', 'symbol', 'symbolSize'
  22467. */
  22468. echartsProto.getVisual = function (finder, visualType) {
  22469. var ecModel = this._model;
  22470. finder = parseFinder(ecModel, finder, {defaultMainType: 'series'});
  22471. var seriesModel = finder.seriesModel;
  22472. if (__DEV__) {
  22473. if (!seriesModel) {
  22474. console.warn('There is no specified seires model');
  22475. }
  22476. }
  22477. var data = seriesModel.getData();
  22478. var dataIndexInside = finder.hasOwnProperty('dataIndexInside')
  22479. ? finder.dataIndexInside
  22480. : finder.hasOwnProperty('dataIndex')
  22481. ? data.indexOfRawIndex(finder.dataIndex)
  22482. : null;
  22483. return dataIndexInside != null
  22484. ? data.getItemVisual(dataIndexInside, visualType)
  22485. : data.getVisual(visualType);
  22486. };
  22487. /**
  22488. * Get view of corresponding component model
  22489. * @param {module:echarts/model/Component} componentModel
  22490. * @return {module:echarts/view/Component}
  22491. */
  22492. echartsProto.getViewOfComponentModel = function (componentModel) {
  22493. return this._componentsMap[componentModel.__viewId];
  22494. };
  22495. /**
  22496. * Get view of corresponding series model
  22497. * @param {module:echarts/model/Series} seriesModel
  22498. * @return {module:echarts/view/Chart}
  22499. */
  22500. echartsProto.getViewOfSeriesModel = function (seriesModel) {
  22501. return this._chartsMap[seriesModel.__viewId];
  22502. };
  22503. var updateMethods = {
  22504. prepareAndUpdate: function (payload) {
  22505. prepare(this);
  22506. updateMethods.update.call(this, payload);
  22507. },
  22508. /**
  22509. * @param {Object} payload
  22510. * @private
  22511. */
  22512. update: function (payload) {
  22513. // console.profile && console.profile('update');
  22514. var ecModel = this._model;
  22515. var api = this._api;
  22516. var zr = this._zr;
  22517. var coordSysMgr = this._coordSysMgr;
  22518. var scheduler = this._scheduler;
  22519. // update before setOption
  22520. if (!ecModel) {
  22521. return;
  22522. }
  22523. scheduler.restoreData(ecModel, payload);
  22524. scheduler.performSeriesTasks(ecModel);
  22525. // TODO
  22526. // Save total ecModel here for undo/redo (after restoring data and before processing data).
  22527. // Undo (restoration of total ecModel) can be carried out in 'action' or outside API call.
  22528. // Create new coordinate system each update
  22529. // In LineView may save the old coordinate system and use it to get the orignal point
  22530. coordSysMgr.create(ecModel, api);
  22531. scheduler.performDataProcessorTasks(ecModel, payload);
  22532. // Current stream render is not supported in data process. So we can update
  22533. // stream modes after data processing, where the filtered data is used to
  22534. // deteming whether use progressive rendering.
  22535. updateStreamModes(this, ecModel);
  22536. // We update stream modes before coordinate system updated, then the modes info
  22537. // can be fetched when coord sys updating (consider the barGrid extent fix). But
  22538. // the drawback is the full coord info can not be fetched. Fortunately this full
  22539. // coord is not requied in stream mode updater currently.
  22540. coordSysMgr.update(ecModel, api);
  22541. clearColorPalette(ecModel);
  22542. scheduler.performVisualTasks(ecModel, payload);
  22543. render(this, ecModel, api, payload);
  22544. // Set background
  22545. var backgroundColor = ecModel.get('backgroundColor') || 'transparent';
  22546. // In IE8
  22547. if (!env$1.canvasSupported) {
  22548. var colorArr = parse(backgroundColor);
  22549. backgroundColor = stringify(colorArr, 'rgb');
  22550. if (colorArr[3] === 0) {
  22551. backgroundColor = 'transparent';
  22552. }
  22553. }
  22554. else {
  22555. zr.setBackgroundColor(backgroundColor);
  22556. }
  22557. performPostUpdateFuncs(ecModel, api);
  22558. // console.profile && console.profileEnd('update');
  22559. },
  22560. /**
  22561. * @param {Object} payload
  22562. * @private
  22563. */
  22564. updateTransform: function (payload) {
  22565. var ecModel = this._model;
  22566. var ecIns = this;
  22567. var api = this._api;
  22568. // update before setOption
  22569. if (!ecModel) {
  22570. return;
  22571. }
  22572. // ChartView.markUpdateMethod(payload, 'updateTransform');
  22573. var componentDirtyList = [];
  22574. ecModel.eachComponent(function (componentType, componentModel) {
  22575. var componentView = ecIns.getViewOfComponentModel(componentModel);
  22576. if (componentView && componentView.__alive) {
  22577. if (componentView.updateTransform) {
  22578. var result = componentView.updateTransform(componentModel, ecModel, api, payload);
  22579. result && result.update && componentDirtyList.push(componentView);
  22580. }
  22581. else {
  22582. componentDirtyList.push(componentView);
  22583. }
  22584. }
  22585. });
  22586. var seriesDirtyMap = createHashMap();
  22587. ecModel.eachSeries(function (seriesModel) {
  22588. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  22589. if (chartView.updateTransform) {
  22590. var result = chartView.updateTransform(seriesModel, ecModel, api, payload);
  22591. result && result.update && seriesDirtyMap.set(seriesModel.uid, 1);
  22592. }
  22593. else {
  22594. seriesDirtyMap.set(seriesModel.uid, 1);
  22595. }
  22596. });
  22597. clearColorPalette(ecModel);
  22598. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  22599. // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  22600. this._scheduler.performVisualTasks(
  22601. ecModel, payload, {setDirty: true, dirtyMap: seriesDirtyMap}
  22602. );
  22603. // Currently, not call render of components. Geo render cost a lot.
  22604. // renderComponents(ecIns, ecModel, api, payload, componentDirtyList);
  22605. renderSeries(ecIns, ecModel, api, payload, seriesDirtyMap);
  22606. performPostUpdateFuncs(ecModel, this._api);
  22607. },
  22608. /**
  22609. * @param {Object} payload
  22610. * @private
  22611. */
  22612. updateView: function (payload) {
  22613. var ecModel = this._model;
  22614. // update before setOption
  22615. if (!ecModel) {
  22616. return;
  22617. }
  22618. Chart.markUpdateMethod(payload, 'updateView');
  22619. clearColorPalette(ecModel);
  22620. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  22621. this._scheduler.performVisualTasks(ecModel, payload, {setDirty: true});
  22622. render(this, this._model, this._api, payload);
  22623. performPostUpdateFuncs(ecModel, this._api);
  22624. },
  22625. /**
  22626. * @param {Object} payload
  22627. * @private
  22628. */
  22629. updateVisual: function (payload) {
  22630. updateMethods.update.call(this, payload);
  22631. // var ecModel = this._model;
  22632. // // update before setOption
  22633. // if (!ecModel) {
  22634. // return;
  22635. // }
  22636. // ChartView.markUpdateMethod(payload, 'updateVisual');
  22637. // clearColorPalette(ecModel);
  22638. // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  22639. // this._scheduler.performVisualTasks(ecModel, payload, {visualType: 'visual', setDirty: true});
  22640. // render(this, this._model, this._api, payload);
  22641. // performPostUpdateFuncs(ecModel, this._api);
  22642. },
  22643. /**
  22644. * @param {Object} payload
  22645. * @private
  22646. */
  22647. updateLayout: function (payload) {
  22648. updateMethods.update.call(this, payload);
  22649. // var ecModel = this._model;
  22650. // // update before setOption
  22651. // if (!ecModel) {
  22652. // return;
  22653. // }
  22654. // ChartView.markUpdateMethod(payload, 'updateLayout');
  22655. // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  22656. // // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  22657. // this._scheduler.performVisualTasks(ecModel, payload, {setDirty: true});
  22658. // render(this, this._model, this._api, payload);
  22659. // performPostUpdateFuncs(ecModel, this._api);
  22660. }
  22661. };
  22662. function prepare(ecIns) {
  22663. var ecModel = ecIns._model;
  22664. var scheduler = ecIns._scheduler;
  22665. scheduler.restorePipelines(ecModel);
  22666. scheduler.prepareStageTasks();
  22667. prepareView(ecIns, 'component', ecModel, scheduler);
  22668. prepareView(ecIns, 'chart', ecModel, scheduler);
  22669. scheduler.plan();
  22670. }
  22671. /**
  22672. * @private
  22673. */
  22674. function updateDirectly(ecIns, method, payload, mainType, subType) {
  22675. var ecModel = ecIns._model;
  22676. // broadcast
  22677. if (!mainType) {
  22678. // FIXME
  22679. // Chart will not be update directly here, except set dirty.
  22680. // But there is no such scenario now.
  22681. each(ecIns._componentsViews.concat(ecIns._chartsViews), callView);
  22682. return;
  22683. }
  22684. var query = {};
  22685. query[mainType + 'Id'] = payload[mainType + 'Id'];
  22686. query[mainType + 'Index'] = payload[mainType + 'Index'];
  22687. query[mainType + 'Name'] = payload[mainType + 'Name'];
  22688. var condition = {mainType: mainType, query: query};
  22689. subType && (condition.subType = subType); // subType may be '' by parseClassType;
  22690. var excludeSeriesId = payload.excludeSeriesId;
  22691. if (excludeSeriesId != null) {
  22692. excludeSeriesId = createHashMap(normalizeToArray(excludeSeriesId));
  22693. }
  22694. // If dispatchAction before setOption, do nothing.
  22695. ecModel && ecModel.eachComponent(condition, function (model) {
  22696. if (!excludeSeriesId || excludeSeriesId.get(model.id) == null) {
  22697. callView(ecIns[
  22698. mainType === 'series' ? '_chartsMap' : '_componentsMap'
  22699. ][model.__viewId]);
  22700. }
  22701. }, ecIns);
  22702. function callView(view) {
  22703. view && view.__alive && view[method] && view[method](
  22704. view.__model, ecModel, ecIns._api, payload
  22705. );
  22706. }
  22707. }
  22708. /**
  22709. * Resize the chart
  22710. * @param {Object} opts
  22711. * @param {number} [opts.width] Can be 'auto' (the same as null/undefined)
  22712. * @param {number} [opts.height] Can be 'auto' (the same as null/undefined)
  22713. * @param {boolean} [opts.silent=false]
  22714. */
  22715. echartsProto.resize = function (opts) {
  22716. if (__DEV__) {
  22717. assert(!this[IN_MAIN_PROCESS], '`resize` should not be called during main process.');
  22718. }
  22719. this._zr.resize(opts);
  22720. var ecModel = this._model;
  22721. // Resize loading effect
  22722. this._loadingFX && this._loadingFX.resize();
  22723. if (!ecModel) {
  22724. return;
  22725. }
  22726. var optionChanged = ecModel.resetOption('media');
  22727. var silent = opts && opts.silent;
  22728. this[IN_MAIN_PROCESS] = true;
  22729. optionChanged && prepare(this);
  22730. updateMethods.update.call(this);
  22731. this[IN_MAIN_PROCESS] = false;
  22732. flushPendingActions.call(this, silent);
  22733. triggerUpdatedEvent.call(this, silent);
  22734. };
  22735. function updateStreamModes(ecIns, ecModel) {
  22736. var chartsMap = ecIns._chartsMap;
  22737. var scheduler = ecIns._scheduler;
  22738. ecModel.eachSeries(function (seriesModel) {
  22739. scheduler.updateStreamModes(seriesModel, chartsMap[seriesModel.__viewId]);
  22740. });
  22741. }
  22742. /**
  22743. * Show loading effect
  22744. * @param {string} [name='default']
  22745. * @param {Object} [cfg]
  22746. */
  22747. echartsProto.showLoading = function (name, cfg) {
  22748. if (isObject(name)) {
  22749. cfg = name;
  22750. name = '';
  22751. }
  22752. name = name || 'default';
  22753. this.hideLoading();
  22754. if (!loadingEffects[name]) {
  22755. if (__DEV__) {
  22756. console.warn('Loading effects ' + name + ' not exists.');
  22757. }
  22758. return;
  22759. }
  22760. var el = loadingEffects[name](this._api, cfg);
  22761. var zr = this._zr;
  22762. this._loadingFX = el;
  22763. zr.add(el);
  22764. };
  22765. /**
  22766. * Hide loading effect
  22767. */
  22768. echartsProto.hideLoading = function () {
  22769. this._loadingFX && this._zr.remove(this._loadingFX);
  22770. this._loadingFX = null;
  22771. };
  22772. /**
  22773. * @param {Object} eventObj
  22774. * @return {Object}
  22775. */
  22776. echartsProto.makeActionFromEvent = function (eventObj) {
  22777. var payload = extend({}, eventObj);
  22778. payload.type = eventActionMap[eventObj.type];
  22779. return payload;
  22780. };
  22781. /**
  22782. * @pubilc
  22783. * @param {Object} payload
  22784. * @param {string} [payload.type] Action type
  22785. * @param {Object|boolean} [opt] If pass boolean, means opt.silent
  22786. * @param {boolean} [opt.silent=false] Whether trigger events.
  22787. * @param {boolean} [opt.flush=undefined]
  22788. * true: Flush immediately, and then pixel in canvas can be fetched
  22789. * immediately. Caution: it might affect performance.
  22790. * false: Not not flush.
  22791. * undefined: Auto decide whether perform flush.
  22792. */
  22793. echartsProto.dispatchAction = function (payload, opt) {
  22794. if (!isObject(opt)) {
  22795. opt = {silent: !!opt};
  22796. }
  22797. if (!actions[payload.type]) {
  22798. return;
  22799. }
  22800. // Avoid dispatch action before setOption. Especially in `connect`.
  22801. if (!this._model) {
  22802. return;
  22803. }
  22804. // May dispatchAction in rendering procedure
  22805. if (this[IN_MAIN_PROCESS]) {
  22806. this._pendingActions.push(payload);
  22807. return;
  22808. }
  22809. doDispatchAction.call(this, payload, opt.silent);
  22810. if (opt.flush) {
  22811. this._zr.flush(true);
  22812. }
  22813. else if (opt.flush !== false && env$1.browser.weChat) {
  22814. // In WeChat embeded browser, `requestAnimationFrame` and `setInterval`
  22815. // hang when sliding page (on touch event), which cause that zr does not
  22816. // refresh util user interaction finished, which is not expected.
  22817. // But `dispatchAction` may be called too frequently when pan on touch
  22818. // screen, which impacts performance if do not throttle them.
  22819. this._throttledZrFlush();
  22820. }
  22821. flushPendingActions.call(this, opt.silent);
  22822. triggerUpdatedEvent.call(this, opt.silent);
  22823. };
  22824. function doDispatchAction(payload, silent) {
  22825. var payloadType = payload.type;
  22826. var escapeConnect = payload.escapeConnect;
  22827. var actionWrap = actions[payloadType];
  22828. var actionInfo = actionWrap.actionInfo;
  22829. var cptType = (actionInfo.update || 'update').split(':');
  22830. var updateMethod = cptType.pop();
  22831. cptType = cptType[0] != null && parseClassType(cptType[0]);
  22832. this[IN_MAIN_PROCESS] = true;
  22833. var payloads = [payload];
  22834. var batched = false;
  22835. // Batch action
  22836. if (payload.batch) {
  22837. batched = true;
  22838. payloads = map(payload.batch, function (item) {
  22839. item = defaults(extend({}, item), payload);
  22840. item.batch = null;
  22841. return item;
  22842. });
  22843. }
  22844. var eventObjBatch = [];
  22845. var eventObj;
  22846. var isHighDown = payloadType === 'highlight' || payloadType === 'downplay';
  22847. each(payloads, function (batchItem) {
  22848. // Action can specify the event by return it.
  22849. eventObj = actionWrap.action(batchItem, this._model, this._api);
  22850. // Emit event outside
  22851. eventObj = eventObj || extend({}, batchItem);
  22852. // Convert type to eventType
  22853. eventObj.type = actionInfo.event || eventObj.type;
  22854. eventObjBatch.push(eventObj);
  22855. // light update does not perform data process, layout and visual.
  22856. if (isHighDown) {
  22857. // method, payload, mainType, subType
  22858. updateDirectly(this, updateMethod, batchItem, 'series');
  22859. }
  22860. else if (cptType) {
  22861. updateDirectly(this, updateMethod, batchItem, cptType.main, cptType.sub);
  22862. }
  22863. }, this);
  22864. if (updateMethod !== 'none' && !isHighDown && !cptType) {
  22865. // Still dirty
  22866. if (this[OPTION_UPDATED]) {
  22867. // FIXME Pass payload ?
  22868. prepare(this);
  22869. updateMethods.update.call(this, payload);
  22870. this[OPTION_UPDATED] = false;
  22871. }
  22872. else {
  22873. updateMethods[updateMethod].call(this, payload);
  22874. }
  22875. }
  22876. // Follow the rule of action batch
  22877. if (batched) {
  22878. eventObj = {
  22879. type: actionInfo.event || payloadType,
  22880. escapeConnect: escapeConnect,
  22881. batch: eventObjBatch
  22882. };
  22883. }
  22884. else {
  22885. eventObj = eventObjBatch[0];
  22886. }
  22887. this[IN_MAIN_PROCESS] = false;
  22888. !silent && this._messageCenter.trigger(eventObj.type, eventObj);
  22889. }
  22890. function flushPendingActions(silent) {
  22891. var pendingActions = this._pendingActions;
  22892. while (pendingActions.length) {
  22893. var payload = pendingActions.shift();
  22894. doDispatchAction.call(this, payload, silent);
  22895. }
  22896. }
  22897. function triggerUpdatedEvent(silent) {
  22898. !silent && this.trigger('updated');
  22899. }
  22900. /**
  22901. * Event `rendered` is triggered when zr
  22902. * rendered. It is useful for realtime
  22903. * snapshot (reflect animation).
  22904. *
  22905. * Event `finished` is triggered when:
  22906. * (1) zrender rendering finished.
  22907. * (2) initial animation finished.
  22908. * (3) progressive rendering finished.
  22909. * (4) no pending action.
  22910. * (5) no delayed setOption needs to be processed.
  22911. */
  22912. function bindRenderedEvent(zr, ecIns) {
  22913. zr.on('rendered', function () {
  22914. ecIns.trigger('rendered');
  22915. // The `finished` event should not be triggered repeatly,
  22916. // so it should only be triggered when rendering indeed happend
  22917. // in zrender. (Consider the case that dipatchAction is keep
  22918. // triggering when mouse move).
  22919. if (
  22920. // Although zr is dirty if initial animation is not finished
  22921. // and this checking is called on frame, we also check
  22922. // animation finished for robustness.
  22923. zr.animation.isFinished()
  22924. && !ecIns[OPTION_UPDATED]
  22925. && !ecIns._scheduler.unfinished
  22926. && !ecIns._pendingActions.length
  22927. ) {
  22928. ecIns.trigger('finished');
  22929. }
  22930. });
  22931. }
  22932. /**
  22933. * @param {Object} params
  22934. * @param {number} params.seriesIndex
  22935. * @param {Array|TypedArray} params.data
  22936. */
  22937. echartsProto.appendData = function (params) {
  22938. var seriesIndex = params.seriesIndex;
  22939. var ecModel = this.getModel();
  22940. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  22941. if (__DEV__) {
  22942. assert(params.data && seriesModel);
  22943. }
  22944. seriesModel.appendData(params);
  22945. // Note: `appendData` does not support that update extent of coordinate
  22946. // system, util some scenario require that. In the expected usage of
  22947. // `appendData`, the initial extent of coordinate system should better
  22948. // be fixed by axis `min`/`max` setting or initial data, otherwise if
  22949. // the extent changed while `appendData`, the location of the painted
  22950. // graphic elements have to be changed, which make the usage of
  22951. // `appendData` meaningless.
  22952. this._scheduler.unfinished = true;
  22953. };
  22954. /**
  22955. * Register event
  22956. * @method
  22957. */
  22958. echartsProto.on = createRegisterEventWithLowercaseName('on');
  22959. echartsProto.off = createRegisterEventWithLowercaseName('off');
  22960. echartsProto.one = createRegisterEventWithLowercaseName('one');
  22961. /**
  22962. * Prepare view instances of charts and components
  22963. * @param {module:echarts/model/Global} ecModel
  22964. * @private
  22965. */
  22966. function prepareView(ecIns, type, ecModel, scheduler) {
  22967. var isComponent = type === 'component';
  22968. var viewList = isComponent ? ecIns._componentsViews : ecIns._chartsViews;
  22969. var viewMap = isComponent ? ecIns._componentsMap : ecIns._chartsMap;
  22970. var zr = ecIns._zr;
  22971. var api = ecIns._api;
  22972. for (var i = 0; i < viewList.length; i++) {
  22973. viewList[i].__alive = false;
  22974. }
  22975. isComponent
  22976. ? ecModel.eachComponent(function (componentType, model) {
  22977. componentType !== 'series' && doPrepare(model);
  22978. })
  22979. : ecModel.eachSeries(doPrepare);
  22980. function doPrepare(model) {
  22981. // Consider: id same and type changed.
  22982. var viewId = '_ec_' + model.id + '_' + model.type;
  22983. var view = viewMap[viewId];
  22984. if (!view) {
  22985. var classType = parseClassType(model.type);
  22986. var Clazz = isComponent
  22987. ? Component.getClass(classType.main, classType.sub)
  22988. : Chart.getClass(classType.sub);
  22989. if (__DEV__) {
  22990. assert(Clazz, classType.sub + ' does not exist.');
  22991. }
  22992. view = new Clazz();
  22993. view.init(ecModel, api);
  22994. viewMap[viewId] = view;
  22995. viewList.push(view);
  22996. zr.add(view.group);
  22997. }
  22998. model.__viewId = view.__id = viewId;
  22999. view.__alive = true;
  23000. view.__model = model;
  23001. view.group.__ecComponentInfo = {
  23002. mainType: model.mainType,
  23003. index: model.componentIndex
  23004. };
  23005. !isComponent && scheduler.prepareView(view, model, ecModel, api);
  23006. }
  23007. for (var i = 0; i < viewList.length;) {
  23008. var view = viewList[i];
  23009. if (!view.__alive) {
  23010. !isComponent && view.renderTask.dispose();
  23011. zr.remove(view.group);
  23012. view.dispose(ecModel, api);
  23013. viewList.splice(i, 1);
  23014. delete viewMap[view.__id];
  23015. view.__id = view.group.__ecComponentInfo = null;
  23016. }
  23017. else {
  23018. i++;
  23019. }
  23020. }
  23021. }
  23022. // /**
  23023. // * Encode visual infomation from data after data processing
  23024. // *
  23025. // * @param {module:echarts/model/Global} ecModel
  23026. // * @param {object} layout
  23027. // * @param {boolean} [layoutFilter] `true`: only layout,
  23028. // * `false`: only not layout,
  23029. // * `null`/`undefined`: all.
  23030. // * @param {string} taskBaseTag
  23031. // * @private
  23032. // */
  23033. // function startVisualEncoding(ecIns, ecModel, api, payload, layoutFilter) {
  23034. // each(visualFuncs, function (visual, index) {
  23035. // var isLayout = visual.isLayout;
  23036. // if (layoutFilter == null
  23037. // || (layoutFilter === false && !isLayout)
  23038. // || (layoutFilter === true && isLayout)
  23039. // ) {
  23040. // visual.func(ecModel, api, payload);
  23041. // }
  23042. // });
  23043. // }
  23044. function clearColorPalette(ecModel) {
  23045. ecModel.clearColorPalette();
  23046. ecModel.eachSeries(function (seriesModel) {
  23047. seriesModel.clearColorPalette();
  23048. });
  23049. }
  23050. function render(ecIns, ecModel, api, payload) {
  23051. renderComponents(ecIns, ecModel, api, payload);
  23052. each(ecIns._chartsViews, function (chart) {
  23053. chart.__alive = false;
  23054. });
  23055. renderSeries(ecIns, ecModel, api, payload);
  23056. // Remove groups of unrendered charts
  23057. each(ecIns._chartsViews, function (chart) {
  23058. if (!chart.__alive) {
  23059. chart.remove(ecModel, api);
  23060. }
  23061. });
  23062. }
  23063. function renderComponents(ecIns, ecModel, api, payload, dirtyList) {
  23064. each(dirtyList || ecIns._componentsViews, function (componentView) {
  23065. var componentModel = componentView.__model;
  23066. componentView.render(componentModel, ecModel, api, payload);
  23067. updateZ(componentModel, componentView);
  23068. });
  23069. }
  23070. /**
  23071. * Render each chart and component
  23072. * @private
  23073. */
  23074. function renderSeries(ecIns, ecModel, api, payload, dirtyMap) {
  23075. // Render all charts
  23076. var scheduler = ecIns._scheduler;
  23077. var unfinished;
  23078. ecModel.eachSeries(function (seriesModel) {
  23079. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  23080. chartView.__alive = true;
  23081. var renderTask = chartView.renderTask;
  23082. scheduler.updatePayload(renderTask, payload);
  23083. if (dirtyMap && dirtyMap.get(seriesModel.uid)) {
  23084. renderTask.dirty();
  23085. }
  23086. unfinished |= renderTask.perform(scheduler.getPerformArgs(renderTask));
  23087. chartView.group.silent = !!seriesModel.get('silent');
  23088. updateZ(seriesModel, chartView);
  23089. updateBlend(seriesModel, chartView);
  23090. });
  23091. scheduler.unfinished |= unfinished;
  23092. // If use hover layer
  23093. updateHoverLayerStatus(ecIns._zr, ecModel);
  23094. // Add aria
  23095. aria(ecIns._zr.dom, ecModel);
  23096. }
  23097. function performPostUpdateFuncs(ecModel, api) {
  23098. each(postUpdateFuncs, function (func) {
  23099. func(ecModel, api);
  23100. });
  23101. }
  23102. var MOUSE_EVENT_NAMES = [
  23103. 'click', 'dblclick', 'mouseover', 'mouseout', 'mousemove',
  23104. 'mousedown', 'mouseup', 'globalout', 'contextmenu'
  23105. ];
  23106. /**
  23107. * @private
  23108. */
  23109. echartsProto._initEvents = function () {
  23110. each(MOUSE_EVENT_NAMES, function (eveName) {
  23111. this._zr.on(eveName, function (e) {
  23112. var ecModel = this.getModel();
  23113. var el = e.target;
  23114. var params;
  23115. // no e.target when 'globalout'.
  23116. if (eveName === 'globalout') {
  23117. params = {};
  23118. }
  23119. else if (el && el.dataIndex != null) {
  23120. var dataModel = el.dataModel || ecModel.getSeriesByIndex(el.seriesIndex);
  23121. params = dataModel && dataModel.getDataParams(el.dataIndex, el.dataType) || {};
  23122. }
  23123. // If element has custom eventData of components
  23124. else if (el && el.eventData) {
  23125. params = extend({}, el.eventData);
  23126. }
  23127. if (params) {
  23128. params.event = e;
  23129. params.type = eveName;
  23130. this.trigger(eveName, params);
  23131. }
  23132. }, this);
  23133. }, this);
  23134. each(eventActionMap, function (actionType, eventType) {
  23135. this._messageCenter.on(eventType, function (event) {
  23136. this.trigger(eventType, event);
  23137. }, this);
  23138. }, this);
  23139. };
  23140. /**
  23141. * @return {boolean}
  23142. */
  23143. echartsProto.isDisposed = function () {
  23144. return this._disposed;
  23145. };
  23146. /**
  23147. * Clear
  23148. */
  23149. echartsProto.clear = function () {
  23150. this.setOption({ series: [] }, true);
  23151. };
  23152. /**
  23153. * Dispose instance
  23154. */
  23155. echartsProto.dispose = function () {
  23156. if (this._disposed) {
  23157. if (__DEV__) {
  23158. console.warn('Instance ' + this.id + ' has been disposed');
  23159. }
  23160. return;
  23161. }
  23162. this._disposed = true;
  23163. setAttribute(this.getDom(), DOM_ATTRIBUTE_KEY, '');
  23164. var api = this._api;
  23165. var ecModel = this._model;
  23166. each(this._componentsViews, function (component) {
  23167. component.dispose(ecModel, api);
  23168. });
  23169. each(this._chartsViews, function (chart) {
  23170. chart.dispose(ecModel, api);
  23171. });
  23172. // Dispose after all views disposed
  23173. this._zr.dispose();
  23174. delete instances[this.id];
  23175. };
  23176. mixin(ECharts, Eventful);
  23177. function updateHoverLayerStatus(zr, ecModel) {
  23178. var storage = zr.storage;
  23179. var elCount = 0;
  23180. storage.traverse(function (el) {
  23181. if (!el.isGroup) {
  23182. elCount++;
  23183. }
  23184. });
  23185. if (elCount > ecModel.get('hoverLayerThreshold') && !env$1.node) {
  23186. storage.traverse(function (el) {
  23187. if (!el.isGroup) {
  23188. // Don't switch back.
  23189. el.useHoverLayer = true;
  23190. }
  23191. });
  23192. }
  23193. }
  23194. /**
  23195. * Update chart progressive and blend.
  23196. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  23197. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  23198. */
  23199. function updateBlend(seriesModel, chartView) {
  23200. var blendMode = seriesModel.get('blendMode') || null;
  23201. if (__DEV__) {
  23202. if (!env$1.canvasSupported && blendMode && blendMode !== 'source-over') {
  23203. console.warn('Only canvas support blendMode');
  23204. }
  23205. }
  23206. chartView.group.traverse(function (el) {
  23207. // FIXME marker and other components
  23208. if (!el.isGroup) {
  23209. // Only set if blendMode is changed. In case element is incremental and don't wan't to rerender.
  23210. if (el.style.blend !== blendMode) {
  23211. el.setStyle('blend', blendMode);
  23212. }
  23213. }
  23214. if (el.eachPendingDisplayable) {
  23215. el.eachPendingDisplayable(function (displayable) {
  23216. displayable.setStyle('blend', blendMode);
  23217. });
  23218. }
  23219. });
  23220. }
  23221. /**
  23222. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  23223. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  23224. */
  23225. function updateZ(model, view) {
  23226. var z = model.get('z');
  23227. var zlevel = model.get('zlevel');
  23228. // Set z and zlevel
  23229. view.group.traverse(function (el) {
  23230. if (el.type !== 'group') {
  23231. z != null && (el.z = z);
  23232. zlevel != null && (el.zlevel = zlevel);
  23233. }
  23234. });
  23235. }
  23236. function createExtensionAPI(ecInstance) {
  23237. var coordSysMgr = ecInstance._coordSysMgr;
  23238. return extend(new ExtensionAPI(ecInstance), {
  23239. // Inject methods
  23240. getCoordinateSystems: bind(
  23241. coordSysMgr.getCoordinateSystems, coordSysMgr
  23242. ),
  23243. getComponentByElement: function (el) {
  23244. while (el) {
  23245. var modelInfo = el.__ecComponentInfo;
  23246. if (modelInfo != null) {
  23247. return ecInstance._model.getComponent(modelInfo.mainType, modelInfo.index);
  23248. }
  23249. el = el.parent;
  23250. }
  23251. }
  23252. });
  23253. }
  23254. /**
  23255. * @type {Object} key: actionType.
  23256. * @inner
  23257. */
  23258. var actions = {};
  23259. /**
  23260. * Map eventType to actionType
  23261. * @type {Object}
  23262. */
  23263. var eventActionMap = {};
  23264. /**
  23265. * Data processor functions of each stage
  23266. * @type {Array.<Object.<string, Function>>}
  23267. * @inner
  23268. */
  23269. var dataProcessorFuncs = [];
  23270. /**
  23271. * @type {Array.<Function>}
  23272. * @inner
  23273. */
  23274. var optionPreprocessorFuncs = [];
  23275. /**
  23276. * @type {Array.<Function>}
  23277. * @inner
  23278. */
  23279. var postUpdateFuncs = [];
  23280. /**
  23281. * Visual encoding functions of each stage
  23282. * @type {Array.<Object.<string, Function>>}
  23283. */
  23284. var visualFuncs = [];
  23285. /**
  23286. * Theme storage
  23287. * @type {Object.<key, Object>}
  23288. */
  23289. var themeStorage = {};
  23290. /**
  23291. * Loading effects
  23292. */
  23293. var loadingEffects = {};
  23294. var instances = {};
  23295. var connectedGroups = {};
  23296. var idBase = new Date() - 0;
  23297. var groupIdBase = new Date() - 0;
  23298. var DOM_ATTRIBUTE_KEY = '_echarts_instance_';
  23299. var mapDataStores = {};
  23300. function enableConnect(chart) {
  23301. var STATUS_PENDING = 0;
  23302. var STATUS_UPDATING = 1;
  23303. var STATUS_UPDATED = 2;
  23304. var STATUS_KEY = '__connectUpdateStatus';
  23305. function updateConnectedChartsStatus(charts, status) {
  23306. for (var i = 0; i < charts.length; i++) {
  23307. var otherChart = charts[i];
  23308. otherChart[STATUS_KEY] = status;
  23309. }
  23310. }
  23311. each(eventActionMap, function (actionType, eventType) {
  23312. chart._messageCenter.on(eventType, function (event) {
  23313. if (connectedGroups[chart.group] && chart[STATUS_KEY] !== STATUS_PENDING) {
  23314. if (event && event.escapeConnect) {
  23315. return;
  23316. }
  23317. var action = chart.makeActionFromEvent(event);
  23318. var otherCharts = [];
  23319. each(instances, function (otherChart) {
  23320. if (otherChart !== chart && otherChart.group === chart.group) {
  23321. otherCharts.push(otherChart);
  23322. }
  23323. });
  23324. updateConnectedChartsStatus(otherCharts, STATUS_PENDING);
  23325. each(otherCharts, function (otherChart) {
  23326. if (otherChart[STATUS_KEY] !== STATUS_UPDATING) {
  23327. otherChart.dispatchAction(action);
  23328. }
  23329. });
  23330. updateConnectedChartsStatus(otherCharts, STATUS_UPDATED);
  23331. }
  23332. });
  23333. });
  23334. }
  23335. /**
  23336. * @param {HTMLElement} dom
  23337. * @param {Object} [theme]
  23338. * @param {Object} opts
  23339. * @param {number} [opts.devicePixelRatio] Use window.devicePixelRatio by default
  23340. * @param {string} [opts.renderer] Currently only 'canvas' is supported.
  23341. * @param {number} [opts.width] Use clientWidth of the input `dom` by default.
  23342. * Can be 'auto' (the same as null/undefined)
  23343. * @param {number} [opts.height] Use clientHeight of the input `dom` by default.
  23344. * Can be 'auto' (the same as null/undefined)
  23345. */
  23346. function init(dom, theme$$1, opts) {
  23347. if (__DEV__) {
  23348. // Check version
  23349. if ((version$1.replace('.', '') - 0) < (dependencies.zrender.replace('.', '') - 0)) {
  23350. throw new Error(
  23351. 'zrender/src ' + version$1
  23352. + ' is too old for ECharts ' + version
  23353. + '. Current version need ZRender '
  23354. + dependencies.zrender + '+'
  23355. );
  23356. }
  23357. if (!dom) {
  23358. throw new Error('Initialize failed: invalid dom.');
  23359. }
  23360. }
  23361. var existInstance = getInstanceByDom(dom);
  23362. if (existInstance) {
  23363. if (__DEV__) {
  23364. console.warn('There is a chart instance already initialized on the dom.');
  23365. }
  23366. return existInstance;
  23367. }
  23368. if (__DEV__) {
  23369. if (isDom(dom)
  23370. && dom.nodeName.toUpperCase() !== 'CANVAS'
  23371. && (
  23372. (!dom.clientWidth && (!opts || opts.width == null))
  23373. || (!dom.clientHeight && (!opts || opts.height == null))
  23374. )
  23375. ) {
  23376. console.warn('Can\'t get dom width or height');
  23377. }
  23378. }
  23379. var chart = new ECharts(dom, theme$$1, opts);
  23380. chart.id = 'ec_' + idBase++;
  23381. instances[chart.id] = chart;
  23382. setAttribute(dom, DOM_ATTRIBUTE_KEY, chart.id);
  23383. enableConnect(chart);
  23384. return chart;
  23385. }
  23386. /**
  23387. * @return {string|Array.<module:echarts~ECharts>} groupId
  23388. */
  23389. function connect(groupId) {
  23390. // Is array of charts
  23391. if (isArray(groupId)) {
  23392. var charts = groupId;
  23393. groupId = null;
  23394. // If any chart has group
  23395. each(charts, function (chart) {
  23396. if (chart.group != null) {
  23397. groupId = chart.group;
  23398. }
  23399. });
  23400. groupId = groupId || ('g_' + groupIdBase++);
  23401. each(charts, function (chart) {
  23402. chart.group = groupId;
  23403. });
  23404. }
  23405. connectedGroups[groupId] = true;
  23406. return groupId;
  23407. }
  23408. /**
  23409. * @DEPRECATED
  23410. * @return {string} groupId
  23411. */
  23412. function disConnect(groupId) {
  23413. connectedGroups[groupId] = false;
  23414. }
  23415. /**
  23416. * @return {string} groupId
  23417. */
  23418. var disconnect = disConnect;
  23419. /**
  23420. * Dispose a chart instance
  23421. * @param {module:echarts~ECharts|HTMLDomElement|string} chart
  23422. */
  23423. function dispose(chart) {
  23424. if (typeof chart === 'string') {
  23425. chart = instances[chart];
  23426. }
  23427. else if (!(chart instanceof ECharts)){
  23428. // Try to treat as dom
  23429. chart = getInstanceByDom(chart);
  23430. }
  23431. if ((chart instanceof ECharts) && !chart.isDisposed()) {
  23432. chart.dispose();
  23433. }
  23434. }
  23435. /**
  23436. * @param {HTMLElement} dom
  23437. * @return {echarts~ECharts}
  23438. */
  23439. function getInstanceByDom(dom) {
  23440. return instances[getAttribute(dom, DOM_ATTRIBUTE_KEY)];
  23441. }
  23442. /**
  23443. * @param {string} key
  23444. * @return {echarts~ECharts}
  23445. */
  23446. function getInstanceById(key) {
  23447. return instances[key];
  23448. }
  23449. /**
  23450. * Register theme
  23451. */
  23452. function registerTheme(name, theme$$1) {
  23453. themeStorage[name] = theme$$1;
  23454. }
  23455. /**
  23456. * Register option preprocessor
  23457. * @param {Function} preprocessorFunc
  23458. */
  23459. function registerPreprocessor(preprocessorFunc) {
  23460. optionPreprocessorFuncs.push(preprocessorFunc);
  23461. }
  23462. /**
  23463. * @param {number} [priority=1000]
  23464. * @param {Object|Function} processor
  23465. */
  23466. function registerProcessor(priority, processor) {
  23467. normalizeRegister(dataProcessorFuncs, priority, processor, PRIORITY_PROCESSOR_FILTER);
  23468. }
  23469. /**
  23470. * Register postUpdater
  23471. * @param {Function} postUpdateFunc
  23472. */
  23473. function registerPostUpdate(postUpdateFunc) {
  23474. postUpdateFuncs.push(postUpdateFunc);
  23475. }
  23476. /**
  23477. * Usage:
  23478. * registerAction('someAction', 'someEvent', function () { ... });
  23479. * registerAction('someAction', function () { ... });
  23480. * registerAction(
  23481. * {type: 'someAction', event: 'someEvent', update: 'updateView'},
  23482. * function () { ... }
  23483. * );
  23484. *
  23485. * @param {(string|Object)} actionInfo
  23486. * @param {string} actionInfo.type
  23487. * @param {string} [actionInfo.event]
  23488. * @param {string} [actionInfo.update]
  23489. * @param {string} [eventName]
  23490. * @param {Function} action
  23491. */
  23492. function registerAction(actionInfo, eventName, action) {
  23493. if (typeof eventName === 'function') {
  23494. action = eventName;
  23495. eventName = '';
  23496. }
  23497. var actionType = isObject(actionInfo)
  23498. ? actionInfo.type
  23499. : ([actionInfo, actionInfo = {
  23500. event: eventName
  23501. }][0]);
  23502. // Event name is all lowercase
  23503. actionInfo.event = (actionInfo.event || actionType).toLowerCase();
  23504. eventName = actionInfo.event;
  23505. // Validate action type and event name.
  23506. assert(ACTION_REG.test(actionType) && ACTION_REG.test(eventName));
  23507. if (!actions[actionType]) {
  23508. actions[actionType] = {action: action, actionInfo: actionInfo};
  23509. }
  23510. eventActionMap[eventName] = actionType;
  23511. }
  23512. /**
  23513. * @param {string} type
  23514. * @param {*} CoordinateSystem
  23515. */
  23516. function registerCoordinateSystem(type, CoordinateSystem$$1) {
  23517. CoordinateSystemManager.register(type, CoordinateSystem$$1);
  23518. }
  23519. /**
  23520. * Get dimensions of specified coordinate system.
  23521. * @param {string} type
  23522. * @return {Array.<string|Object>}
  23523. */
  23524. function getCoordinateSystemDimensions(type) {
  23525. var coordSysCreator = CoordinateSystemManager.get(type);
  23526. if (coordSysCreator) {
  23527. return coordSysCreator.getDimensionsInfo
  23528. ? coordSysCreator.getDimensionsInfo()
  23529. : coordSysCreator.dimensions.slice();
  23530. }
  23531. }
  23532. /**
  23533. * Layout is a special stage of visual encoding
  23534. * Most visual encoding like color are common for different chart
  23535. * But each chart has it's own layout algorithm
  23536. *
  23537. * @param {number} [priority=1000]
  23538. * @param {Function} layoutTask
  23539. */
  23540. function registerLayout(priority, layoutTask) {
  23541. normalizeRegister(visualFuncs, priority, layoutTask, PRIORITY_VISUAL_LAYOUT, 'layout');
  23542. }
  23543. /**
  23544. * @param {number} [priority=3000]
  23545. * @param {module:echarts/stream/Task} visualTask
  23546. */
  23547. function registerVisual(priority, visualTask) {
  23548. normalizeRegister(visualFuncs, priority, visualTask, PRIORITY_VISUAL_CHART, 'visual');
  23549. }
  23550. /**
  23551. * @param {Object|Function} fn: {seriesType, createOnAllSeries, performRawSeries, reset}
  23552. */
  23553. function normalizeRegister(targetList, priority, fn, defaultPriority, visualType) {
  23554. if (isFunction(priority) || isObject(priority)) {
  23555. fn = priority;
  23556. priority = defaultPriority;
  23557. }
  23558. if (__DEV__) {
  23559. if (isNaN(priority) || priority == null) {
  23560. throw new Error('Illegal priority');
  23561. }
  23562. // Check duplicate
  23563. each(targetList, function (wrap) {
  23564. assert(wrap.__raw !== fn);
  23565. });
  23566. }
  23567. var stageHandler = Scheduler.wrapStageHandler(fn, visualType);
  23568. stageHandler.__prio = priority;
  23569. stageHandler.__raw = fn;
  23570. targetList.push(stageHandler);
  23571. return stageHandler;
  23572. }
  23573. /**
  23574. * @param {string} name
  23575. */
  23576. function registerLoading(name, loadingFx) {
  23577. loadingEffects[name] = loadingFx;
  23578. }
  23579. /**
  23580. * @param {Object} opts
  23581. * @param {string} [superClass]
  23582. */
  23583. function extendComponentModel(opts/*, superClass*/) {
  23584. // var Clazz = ComponentModel;
  23585. // if (superClass) {
  23586. // var classType = parseClassType(superClass);
  23587. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  23588. // }
  23589. return ComponentModel.extend(opts);
  23590. }
  23591. /**
  23592. * @param {Object} opts
  23593. * @param {string} [superClass]
  23594. */
  23595. function extendComponentView(opts/*, superClass*/) {
  23596. // var Clazz = ComponentView;
  23597. // if (superClass) {
  23598. // var classType = parseClassType(superClass);
  23599. // Clazz = ComponentView.getClass(classType.main, classType.sub, true);
  23600. // }
  23601. return Component.extend(opts);
  23602. }
  23603. /**
  23604. * @param {Object} opts
  23605. * @param {string} [superClass]
  23606. */
  23607. function extendSeriesModel(opts/*, superClass*/) {
  23608. // var Clazz = SeriesModel;
  23609. // if (superClass) {
  23610. // superClass = 'series.' + superClass.replace('series.', '');
  23611. // var classType = parseClassType(superClass);
  23612. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  23613. // }
  23614. return SeriesModel.extend(opts);
  23615. }
  23616. /**
  23617. * @param {Object} opts
  23618. * @param {string} [superClass]
  23619. */
  23620. function extendChartView(opts/*, superClass*/) {
  23621. // var Clazz = ChartView;
  23622. // if (superClass) {
  23623. // superClass = superClass.replace('series.', '');
  23624. // var classType = parseClassType(superClass);
  23625. // Clazz = ChartView.getClass(classType.main, true);
  23626. // }
  23627. return Chart.extend(opts);
  23628. }
  23629. /**
  23630. * ZRender need a canvas context to do measureText.
  23631. * But in node environment canvas may be created by node-canvas.
  23632. * So we need to specify how to create a canvas instead of using document.createElement('canvas')
  23633. *
  23634. * Be careful of using it in the browser.
  23635. *
  23636. * @param {Function} creator
  23637. * @example
  23638. * var Canvas = require('canvas');
  23639. * var echarts = require('echarts');
  23640. * echarts.setCanvasCreator(function () {
  23641. * // Small size is enough.
  23642. * return new Canvas(32, 32);
  23643. * });
  23644. */
  23645. function setCanvasCreator(creator) {
  23646. $override('createCanvas', creator);
  23647. }
  23648. /**
  23649. * @param {string} mapName
  23650. * @param {Object|string} geoJson
  23651. * @param {Object} [specialAreas]
  23652. *
  23653. * @example
  23654. * $.get('USA.json', function (geoJson) {
  23655. * echarts.registerMap('USA', geoJson);
  23656. * // Or
  23657. * echarts.registerMap('USA', {
  23658. * geoJson: geoJson,
  23659. * specialAreas: {}
  23660. * })
  23661. * });
  23662. */
  23663. function registerMap(mapName, geoJson, specialAreas) {
  23664. if (geoJson.geoJson && !geoJson.features) {
  23665. specialAreas = geoJson.specialAreas;
  23666. geoJson = geoJson.geoJson;
  23667. }
  23668. if (typeof geoJson === 'string') {
  23669. geoJson = (typeof JSON !== 'undefined' && JSON.parse)
  23670. ? JSON.parse(geoJson) : (new Function('return (' + geoJson + ');'))();
  23671. }
  23672. mapDataStores[mapName] = {
  23673. geoJson: geoJson,
  23674. specialAreas: specialAreas
  23675. };
  23676. }
  23677. /**
  23678. * @param {string} mapName
  23679. * @return {Object}
  23680. */
  23681. function getMap(mapName) {
  23682. return mapDataStores[mapName];
  23683. }
  23684. registerVisual(PRIORITY_VISUAL_GLOBAL, seriesColor);
  23685. registerPreprocessor(backwardCompat);
  23686. registerProcessor(PRIORITY_PROCESSOR_STATISTIC, dataStack);
  23687. registerLoading('default', loadingDefault);
  23688. // Default actions
  23689. registerAction({
  23690. type: 'highlight',
  23691. event: 'highlight',
  23692. update: 'highlight'
  23693. }, noop);
  23694. registerAction({
  23695. type: 'downplay',
  23696. event: 'downplay',
  23697. update: 'downplay'
  23698. }, noop);
  23699. // Default theme
  23700. registerTheme('light', lightTheme);
  23701. registerTheme('dark', theme);
  23702. // For backward compatibility, where the namespace `dataTool` will
  23703. // be mounted on `echarts` is the extension `dataTool` is imported.
  23704. var dataTool = {};
  23705. /*
  23706. * Licensed to the Apache Software Foundation (ASF) under one
  23707. * or more contributor license agreements. See the NOTICE file
  23708. * distributed with this work for additional information
  23709. * regarding copyright ownership. The ASF licenses this file
  23710. * to you under the Apache License, Version 2.0 (the
  23711. * "License"); you may not use this file except in compliance
  23712. * with the License. You may obtain a copy of the License at
  23713. *
  23714. * http://www.apache.org/licenses/LICENSE-2.0
  23715. *
  23716. * Unless required by applicable law or agreed to in writing,
  23717. * software distributed under the License is distributed on an
  23718. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23719. * KIND, either express or implied. See the License for the
  23720. * specific language governing permissions and limitations
  23721. * under the License.
  23722. */
  23723. function defaultKeyGetter(item) {
  23724. return item;
  23725. }
  23726. /**
  23727. * @param {Array} oldArr
  23728. * @param {Array} newArr
  23729. * @param {Function} oldKeyGetter
  23730. * @param {Function} newKeyGetter
  23731. * @param {Object} [context] Can be visited by this.context in callback.
  23732. */
  23733. function DataDiffer(oldArr, newArr, oldKeyGetter, newKeyGetter, context) {
  23734. this._old = oldArr;
  23735. this._new = newArr;
  23736. this._oldKeyGetter = oldKeyGetter || defaultKeyGetter;
  23737. this._newKeyGetter = newKeyGetter || defaultKeyGetter;
  23738. this.context = context;
  23739. }
  23740. DataDiffer.prototype = {
  23741. constructor: DataDiffer,
  23742. /**
  23743. * Callback function when add a data
  23744. */
  23745. add: function (func) {
  23746. this._add = func;
  23747. return this;
  23748. },
  23749. /**
  23750. * Callback function when update a data
  23751. */
  23752. update: function (func) {
  23753. this._update = func;
  23754. return this;
  23755. },
  23756. /**
  23757. * Callback function when remove a data
  23758. */
  23759. remove: function (func) {
  23760. this._remove = func;
  23761. return this;
  23762. },
  23763. execute: function () {
  23764. var oldArr = this._old;
  23765. var newArr = this._new;
  23766. var oldDataIndexMap = {};
  23767. var newDataIndexMap = {};
  23768. var oldDataKeyArr = [];
  23769. var newDataKeyArr = [];
  23770. var i;
  23771. initIndexMap(oldArr, oldDataIndexMap, oldDataKeyArr, '_oldKeyGetter', this);
  23772. initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter', this);
  23773. // Travel by inverted order to make sure order consistency
  23774. // when duplicate keys exists (consider newDataIndex.pop() below).
  23775. // For performance consideration, these code below do not look neat.
  23776. for (i = 0; i < oldArr.length; i++) {
  23777. var key = oldDataKeyArr[i];
  23778. var idx = newDataIndexMap[key];
  23779. // idx can never be empty array here. see 'set null' logic below.
  23780. if (idx != null) {
  23781. // Consider there is duplicate key (for example, use dataItem.name as key).
  23782. // We should make sure every item in newArr and oldArr can be visited.
  23783. var len = idx.length;
  23784. if (len) {
  23785. len === 1 && (newDataIndexMap[key] = null);
  23786. idx = idx.unshift();
  23787. }
  23788. else {
  23789. newDataIndexMap[key] = null;
  23790. }
  23791. this._update && this._update(idx, i);
  23792. }
  23793. else {
  23794. this._remove && this._remove(i);
  23795. }
  23796. }
  23797. for (var i = 0; i < newDataKeyArr.length; i++) {
  23798. var key = newDataKeyArr[i];
  23799. if (newDataIndexMap.hasOwnProperty(key)) {
  23800. var idx = newDataIndexMap[key];
  23801. if (idx == null) {
  23802. continue;
  23803. }
  23804. // idx can never be empty array here. see 'set null' logic above.
  23805. if (!idx.length) {
  23806. this._add && this._add(idx);
  23807. }
  23808. else {
  23809. for (var j = 0, len = idx.length; j < len; j++) {
  23810. this._add && this._add(idx[j]);
  23811. }
  23812. }
  23813. }
  23814. }
  23815. }
  23816. };
  23817. function initIndexMap(arr, map, keyArr, keyGetterName, dataDiffer) {
  23818. for (var i = 0; i < arr.length; i++) {
  23819. // Add prefix to avoid conflict with Object.prototype.
  23820. var key = '_ec_' + dataDiffer[keyGetterName](arr[i], i);
  23821. var existence = map[key];
  23822. if (existence == null) {
  23823. keyArr.push(key);
  23824. map[key] = i;
  23825. }
  23826. else {
  23827. if (!existence.length) {
  23828. map[key] = existence = [existence];
  23829. }
  23830. existence.push(i);
  23831. }
  23832. }
  23833. }
  23834. /*
  23835. * Licensed to the Apache Software Foundation (ASF) under one
  23836. * or more contributor license agreements. See the NOTICE file
  23837. * distributed with this work for additional information
  23838. * regarding copyright ownership. The ASF licenses this file
  23839. * to you under the Apache License, Version 2.0 (the
  23840. * "License"); you may not use this file except in compliance
  23841. * with the License. You may obtain a copy of the License at
  23842. *
  23843. * http://www.apache.org/licenses/LICENSE-2.0
  23844. *
  23845. * Unless required by applicable law or agreed to in writing,
  23846. * software distributed under the License is distributed on an
  23847. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23848. * KIND, either express or implied. See the License for the
  23849. * specific language governing permissions and limitations
  23850. * under the License.
  23851. */
  23852. var OTHER_DIMENSIONS = createHashMap([
  23853. 'tooltip', 'label', 'itemName', 'itemId', 'seriesName'
  23854. ]);
  23855. function summarizeDimensions(data) {
  23856. var summary = {};
  23857. var encode = summary.encode = {};
  23858. var notExtraCoordDimMap = createHashMap();
  23859. var defaultedLabel = [];
  23860. var defaultedTooltip = [];
  23861. each$1(data.dimensions, function (dimName) {
  23862. var dimItem = data.getDimensionInfo(dimName);
  23863. var coordDim = dimItem.coordDim;
  23864. if (coordDim) {
  23865. if (__DEV__) {
  23866. assert$1(OTHER_DIMENSIONS.get(coordDim) == null);
  23867. }
  23868. var coordDimArr = encode[coordDim];
  23869. if (!encode.hasOwnProperty(coordDim)) {
  23870. coordDimArr = encode[coordDim] = [];
  23871. }
  23872. coordDimArr[dimItem.coordDimIndex] = dimName;
  23873. if (!dimItem.isExtraCoord) {
  23874. notExtraCoordDimMap.set(coordDim, 1);
  23875. // Use the last coord dim (and label friendly) as default label,
  23876. // because when dataset is used, it is hard to guess which dimension
  23877. // can be value dimension. If both show x, y on label is not look good,
  23878. // and conventionally y axis is focused more.
  23879. if (mayLabelDimType(dimItem.type)) {
  23880. defaultedLabel[0] = dimName;
  23881. }
  23882. }
  23883. if (dimItem.defaultTooltip) {
  23884. defaultedTooltip.push(dimName);
  23885. }
  23886. }
  23887. OTHER_DIMENSIONS.each(function (v, otherDim) {
  23888. var otherDimArr = encode[otherDim];
  23889. if (!encode.hasOwnProperty(otherDim)) {
  23890. otherDimArr = encode[otherDim] = [];
  23891. }
  23892. var dimIndex = dimItem.otherDims[otherDim];
  23893. if (dimIndex != null && dimIndex !== false) {
  23894. otherDimArr[dimIndex] = dimItem.name;
  23895. }
  23896. });
  23897. });
  23898. var dataDimsOnCoord = [];
  23899. var encodeFirstDimNotExtra = {};
  23900. notExtraCoordDimMap.each(function (v, coordDim) {
  23901. var dimArr = encode[coordDim];
  23902. // ??? FIXME extra coord should not be set in dataDimsOnCoord.
  23903. // But should fix the case that radar axes: simplify the logic
  23904. // of `completeDimension`, remove `extraPrefix`.
  23905. encodeFirstDimNotExtra[coordDim] = dimArr[0];
  23906. // Not necessary to remove duplicate, because a data
  23907. // dim canot on more than one coordDim.
  23908. dataDimsOnCoord = dataDimsOnCoord.concat(dimArr);
  23909. });
  23910. summary.dataDimsOnCoord = dataDimsOnCoord;
  23911. summary.encodeFirstDimNotExtra = encodeFirstDimNotExtra;
  23912. var encodeLabel = encode.label;
  23913. // FIXME `encode.label` is not recommanded, because formatter can not be set
  23914. // in this way. Use label.formatter instead. May be remove this approach someday.
  23915. if (encodeLabel && encodeLabel.length) {
  23916. defaultedLabel = encodeLabel.slice();
  23917. }
  23918. var encodeTooltip = encode.tooltip;
  23919. if (encodeTooltip && encodeTooltip.length) {
  23920. defaultedTooltip = encodeTooltip.slice();
  23921. }
  23922. else if (!defaultedTooltip.length) {
  23923. defaultedTooltip = defaultedLabel.slice();
  23924. }
  23925. encode.defaultedLabel = defaultedLabel;
  23926. encode.defaultedTooltip = defaultedTooltip;
  23927. return summary;
  23928. }
  23929. function getDimensionTypeByAxis(axisType) {
  23930. return axisType === 'category'
  23931. ? 'ordinal'
  23932. : axisType === 'time'
  23933. ? 'time'
  23934. : 'float';
  23935. }
  23936. function mayLabelDimType(dimType) {
  23937. // In most cases, ordinal and time do not suitable for label.
  23938. // Ordinal info can be displayed on axis. Time is too long.
  23939. return !(dimType === 'ordinal' || dimType === 'time');
  23940. }
  23941. // function findTheLastDimMayLabel(data) {
  23942. // // Get last value dim
  23943. // var dimensions = data.dimensions.slice();
  23944. // var valueType;
  23945. // var valueDim;
  23946. // while (dimensions.length && (
  23947. // valueDim = dimensions.pop(),
  23948. // valueType = data.getDimensionInfo(valueDim).type,
  23949. // valueType === 'ordinal' || valueType === 'time'
  23950. // )) {} // jshint ignore:line
  23951. // return valueDim;
  23952. // }
  23953. /*
  23954. * Licensed to the Apache Software Foundation (ASF) under one
  23955. * or more contributor license agreements. See the NOTICE file
  23956. * distributed with this work for additional information
  23957. * regarding copyright ownership. The ASF licenses this file
  23958. * to you under the Apache License, Version 2.0 (the
  23959. * "License"); you may not use this file except in compliance
  23960. * with the License. You may obtain a copy of the License at
  23961. *
  23962. * http://www.apache.org/licenses/LICENSE-2.0
  23963. *
  23964. * Unless required by applicable law or agreed to in writing,
  23965. * software distributed under the License is distributed on an
  23966. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23967. * KIND, either express or implied. See the License for the
  23968. * specific language governing permissions and limitations
  23969. * under the License.
  23970. */
  23971. /**
  23972. * List for data storage
  23973. * @module echarts/data/List
  23974. */
  23975. var isObject$4 = isObject$1;
  23976. var UNDEFINED = 'undefined';
  23977. // Use prefix to avoid index to be the same as otherIdList[idx],
  23978. // which will cause weird udpate animation.
  23979. var ID_PREFIX = 'e\0\0';
  23980. var dataCtors = {
  23981. 'float': typeof Float64Array === UNDEFINED
  23982. ? Array : Float64Array,
  23983. 'int': typeof Int32Array === UNDEFINED
  23984. ? Array : Int32Array,
  23985. // Ordinal data type can be string or int
  23986. 'ordinal': Array,
  23987. 'number': Array,
  23988. 'time': Array
  23989. };
  23990. // Caution: MUST not use `new CtorUint32Array(arr, 0, len)`, because the Ctor of array is
  23991. // different from the Ctor of typed array.
  23992. var CtorUint32Array = typeof Uint32Array === UNDEFINED ? Array : Uint32Array;
  23993. var CtorUint16Array = typeof Uint16Array === UNDEFINED ? Array : Uint16Array;
  23994. function getIndicesCtor(list) {
  23995. // The possible max value in this._indicies is always this._rawCount despite of filtering.
  23996. return list._rawCount > 65535 ? CtorUint32Array : CtorUint16Array;
  23997. }
  23998. function cloneChunk(originalChunk) {
  23999. var Ctor = originalChunk.constructor;
  24000. // Only shallow clone is enough when Array.
  24001. return Ctor === Array ? originalChunk.slice() : new Ctor(originalChunk);
  24002. }
  24003. var TRANSFERABLE_PROPERTIES = [
  24004. 'hasItemOption', '_nameList', '_idList', '_invertedIndicesMap',
  24005. '_rawData', '_chunkSize', '_chunkCount', '_dimValueGetter',
  24006. '_count', '_rawCount', '_nameDimIdx', '_idDimIdx'
  24007. ];
  24008. var CLONE_PROPERTIES = [
  24009. '_extent', '_approximateExtent', '_rawExtent'
  24010. ];
  24011. function transferProperties(target, source) {
  24012. each$1(TRANSFERABLE_PROPERTIES.concat(source.__wrappedMethods || []), function (propName) {
  24013. if (source.hasOwnProperty(propName)) {
  24014. target[propName] = source[propName];
  24015. }
  24016. });
  24017. target.__wrappedMethods = source.__wrappedMethods;
  24018. each$1(CLONE_PROPERTIES, function (propName) {
  24019. target[propName] = clone(source[propName]);
  24020. });
  24021. target._calculationInfo = extend(source._calculationInfo);
  24022. }
  24023. /**
  24024. * @constructor
  24025. * @alias module:echarts/data/List
  24026. *
  24027. * @param {Array.<string|Object>} dimensions
  24028. * For example, ['someDimName', {name: 'someDimName', type: 'someDimType'}, ...].
  24029. * Dimensions should be concrete names like x, y, z, lng, lat, angle, radius
  24030. * Spetial fields: {
  24031. * ordinalMeta: <module:echarts/data/OrdinalMeta>
  24032. * createInvertedIndices: <boolean>
  24033. * }
  24034. * @param {module:echarts/model/Model} hostModel
  24035. */
  24036. var List = function (dimensions, hostModel) {
  24037. dimensions = dimensions || ['x', 'y'];
  24038. var dimensionInfos = {};
  24039. var dimensionNames = [];
  24040. var invertedIndicesMap = {};
  24041. for (var i = 0; i < dimensions.length; i++) {
  24042. // Use the original dimensions[i], where other flag props may exists.
  24043. var dimensionInfo = dimensions[i];
  24044. if (isString(dimensionInfo)) {
  24045. dimensionInfo = {name: dimensionInfo};
  24046. }
  24047. var dimensionName = dimensionInfo.name;
  24048. dimensionInfo.type = dimensionInfo.type || 'float';
  24049. if (!dimensionInfo.coordDim) {
  24050. dimensionInfo.coordDim = dimensionName;
  24051. dimensionInfo.coordDimIndex = 0;
  24052. }
  24053. dimensionInfo.otherDims = dimensionInfo.otherDims || {};
  24054. dimensionNames.push(dimensionName);
  24055. dimensionInfos[dimensionName] = dimensionInfo;
  24056. dimensionInfo.index = i;
  24057. if (dimensionInfo.createInvertedIndices) {
  24058. invertedIndicesMap[dimensionName] = [];
  24059. }
  24060. }
  24061. /**
  24062. * @readOnly
  24063. * @type {Array.<string>}
  24064. */
  24065. this.dimensions = dimensionNames;
  24066. /**
  24067. * Infomation of each data dimension, like data type.
  24068. * @type {Object}
  24069. */
  24070. this._dimensionInfos = dimensionInfos;
  24071. /**
  24072. * @type {module:echarts/model/Model}
  24073. */
  24074. this.hostModel = hostModel;
  24075. /**
  24076. * @type {module:echarts/model/Model}
  24077. */
  24078. this.dataType;
  24079. /**
  24080. * Indices stores the indices of data subset after filtered.
  24081. * This data subset will be used in chart.
  24082. * @type {Array.<number>}
  24083. * @readOnly
  24084. */
  24085. this._indices = null;
  24086. this._count = 0;
  24087. this._rawCount = 0;
  24088. /**
  24089. * Data storage
  24090. * @type {Object.<key, Array.<TypedArray|Array>>}
  24091. * @private
  24092. */
  24093. this._storage = {};
  24094. /**
  24095. * @type {Array.<string>}
  24096. */
  24097. this._nameList = [];
  24098. /**
  24099. * @type {Array.<string>}
  24100. */
  24101. this._idList = [];
  24102. /**
  24103. * Models of data option is stored sparse for optimizing memory cost
  24104. * @type {Array.<module:echarts/model/Model>}
  24105. * @private
  24106. */
  24107. this._optionModels = [];
  24108. /**
  24109. * Global visual properties after visual coding
  24110. * @type {Object}
  24111. * @private
  24112. */
  24113. this._visual = {};
  24114. /**
  24115. * Globel layout properties.
  24116. * @type {Object}
  24117. * @private
  24118. */
  24119. this._layout = {};
  24120. /**
  24121. * Item visual properties after visual coding
  24122. * @type {Array.<Object>}
  24123. * @private
  24124. */
  24125. this._itemVisuals = [];
  24126. /**
  24127. * Key: visual type, Value: boolean
  24128. * @type {Object}
  24129. * @readOnly
  24130. */
  24131. this.hasItemVisual = {};
  24132. /**
  24133. * Item layout properties after layout
  24134. * @type {Array.<Object>}
  24135. * @private
  24136. */
  24137. this._itemLayouts = [];
  24138. /**
  24139. * Graphic elemnents
  24140. * @type {Array.<module:zrender/Element>}
  24141. * @private
  24142. */
  24143. this._graphicEls = [];
  24144. /**
  24145. * Max size of each chunk.
  24146. * @type {number}
  24147. * @private
  24148. */
  24149. this._chunkSize = 1e5;
  24150. /**
  24151. * @type {number}
  24152. * @private
  24153. */
  24154. this._chunkCount = 0;
  24155. /**
  24156. * @type {Array.<Array|Object>}
  24157. * @private
  24158. */
  24159. this._rawData;
  24160. /**
  24161. * Raw extent will not be cloned, but only transfered.
  24162. * It will not be calculated util needed.
  24163. * key: dim,
  24164. * value: {end: number, extent: Array.<number>}
  24165. * @type {Object}
  24166. * @private
  24167. */
  24168. this._rawExtent = {};
  24169. /**
  24170. * @type {Object}
  24171. * @private
  24172. */
  24173. this._extent = {};
  24174. /**
  24175. * key: dim
  24176. * value: extent
  24177. * @type {Object}
  24178. * @private
  24179. */
  24180. this._approximateExtent = {};
  24181. /**
  24182. * Cache summary info for fast visit. See "dimensionHelper".
  24183. * @type {Object}
  24184. * @private
  24185. */
  24186. this._dimensionsSummary = summarizeDimensions(this);
  24187. /**
  24188. * @type {Object.<Array|TypedArray>}
  24189. * @private
  24190. */
  24191. this._invertedIndicesMap = invertedIndicesMap;
  24192. /**
  24193. * @type {Object}
  24194. * @private
  24195. */
  24196. this._calculationInfo = {};
  24197. };
  24198. var listProto = List.prototype;
  24199. listProto.type = 'list';
  24200. /**
  24201. * If each data item has it's own option
  24202. * @type {boolean}
  24203. */
  24204. listProto.hasItemOption = true;
  24205. /**
  24206. * Get dimension name
  24207. * @param {string|number} dim
  24208. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  24209. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  24210. * @return {string} Concrete dim name.
  24211. */
  24212. listProto.getDimension = function (dim) {
  24213. if (!isNaN(dim)) {
  24214. dim = this.dimensions[dim] || dim;
  24215. }
  24216. return dim;
  24217. };
  24218. /**
  24219. * Get type and calculation info of particular dimension
  24220. * @param {string|number} dim
  24221. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  24222. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  24223. */
  24224. listProto.getDimensionInfo = function (dim) {
  24225. // Do not clone, because there may be categories in dimInfo.
  24226. return this._dimensionInfos[this.getDimension(dim)];
  24227. };
  24228. /**
  24229. * @return {Array.<string>} concrete dimension name list on coord.
  24230. */
  24231. listProto.getDimensionsOnCoord = function () {
  24232. return this._dimensionsSummary.dataDimsOnCoord.slice();
  24233. };
  24234. /**
  24235. * @param {string} coordDim
  24236. * @param {number} [idx] A coordDim may map to more than one data dim.
  24237. * If idx is `true`, return a array of all mapped dims.
  24238. * If idx is not specified, return the first dim not extra.
  24239. * @return {string|Array.<string>} concrete data dim.
  24240. * If idx is number, and not found, return null/undefined.
  24241. * If idx is `true`, and not found, return empty array (always return array).
  24242. */
  24243. listProto.mapDimension = function (coordDim, idx) {
  24244. var dimensionsSummary = this._dimensionsSummary;
  24245. if (idx == null) {
  24246. return dimensionsSummary.encodeFirstDimNotExtra[coordDim];
  24247. }
  24248. var dims = dimensionsSummary.encode[coordDim];
  24249. return idx === true
  24250. // always return array if idx is `true`
  24251. ? (dims || []).slice()
  24252. : (dims && dims[idx]);
  24253. };
  24254. /**
  24255. * Initialize from data
  24256. * @param {Array.<Object|number|Array>} data source or data or data provider.
  24257. * @param {Array.<string>} [nameLIst] The name of a datum is used on data diff and
  24258. * defualt label/tooltip.
  24259. * A name can be specified in encode.itemName,
  24260. * or dataItem.name (only for series option data),
  24261. * or provided in nameList from outside.
  24262. * @param {Function} [dimValueGetter] (dataItem, dimName, dataIndex, dimIndex) => number
  24263. */
  24264. listProto.initData = function (data, nameList, dimValueGetter) {
  24265. var notProvider = Source.isInstance(data) || isArrayLike(data);
  24266. if (notProvider) {
  24267. data = new DefaultDataProvider(data, this.dimensions.length);
  24268. }
  24269. if (__DEV__) {
  24270. if (!notProvider && (typeof data.getItem != 'function' || typeof data.count != 'function')) {
  24271. throw new Error('Inavlid data provider.');
  24272. }
  24273. }
  24274. this._rawData = data;
  24275. // Clear
  24276. this._storage = {};
  24277. this._indices = null;
  24278. this._nameList = nameList || [];
  24279. this._idList = [];
  24280. this._nameRepeatCount = {};
  24281. if (!dimValueGetter) {
  24282. this.hasItemOption = false;
  24283. }
  24284. /**
  24285. * @readOnly
  24286. */
  24287. this.defaultDimValueGetter = defaultDimValueGetters[
  24288. this._rawData.getSource().sourceFormat
  24289. ];
  24290. // Default dim value getter
  24291. this._dimValueGetter = dimValueGetter = dimValueGetter
  24292. || this.defaultDimValueGetter;
  24293. // Reset raw extent.
  24294. this._rawExtent = {};
  24295. this._initDataFromProvider(0, data.count());
  24296. // If data has no item option.
  24297. if (data.pure) {
  24298. this.hasItemOption = false;
  24299. }
  24300. };
  24301. listProto.getProvider = function () {
  24302. return this._rawData;
  24303. };
  24304. listProto.appendData = function (data) {
  24305. if (__DEV__) {
  24306. assert$1(!this._indices, 'appendData can only be called on raw data.');
  24307. }
  24308. var rawData = this._rawData;
  24309. var start = this.count();
  24310. rawData.appendData(data);
  24311. var end = rawData.count();
  24312. if (!rawData.persistent) {
  24313. end += start;
  24314. }
  24315. this._initDataFromProvider(start, end);
  24316. };
  24317. listProto._initDataFromProvider = function (start, end) {
  24318. // Optimize.
  24319. if (start >= end) {
  24320. return;
  24321. }
  24322. var chunkSize = this._chunkSize;
  24323. var rawData = this._rawData;
  24324. var storage = this._storage;
  24325. var dimensions = this.dimensions;
  24326. var dimLen = dimensions.length;
  24327. var dimensionInfoMap = this._dimensionInfos;
  24328. var nameList = this._nameList;
  24329. var idList = this._idList;
  24330. var rawExtent = this._rawExtent;
  24331. var nameRepeatCount = this._nameRepeatCount = {};
  24332. var nameDimIdx;
  24333. var chunkCount = this._chunkCount;
  24334. var lastChunkIndex = chunkCount - 1;
  24335. for (var i = 0; i < dimLen; i++) {
  24336. var dim = dimensions[i];
  24337. if (!rawExtent[dim]) {
  24338. rawExtent[dim] = getInitialExtent();
  24339. }
  24340. var dimInfo = dimensionInfoMap[dim];
  24341. if (dimInfo.otherDims.itemName === 0) {
  24342. nameDimIdx = this._nameDimIdx = i;
  24343. }
  24344. if (dimInfo.otherDims.itemId === 0) {
  24345. this._idDimIdx = i;
  24346. }
  24347. var DataCtor = dataCtors[dimInfo.type];
  24348. if (!storage[dim]) {
  24349. storage[dim] = [];
  24350. }
  24351. var resizeChunkArray = storage[dim][lastChunkIndex];
  24352. if (resizeChunkArray && resizeChunkArray.length < chunkSize) {
  24353. var newStore = new DataCtor(Math.min(end - lastChunkIndex * chunkSize, chunkSize));
  24354. // The cost of the copy is probably inconsiderable
  24355. // within the initial chunkSize.
  24356. for (var j = 0; j < resizeChunkArray.length; j++) {
  24357. newStore[j] = resizeChunkArray[j];
  24358. }
  24359. storage[dim][lastChunkIndex] = newStore;
  24360. }
  24361. // Create new chunks.
  24362. for (var k = chunkCount * chunkSize; k < end; k += chunkSize) {
  24363. storage[dim].push(new DataCtor(Math.min(end - k, chunkSize)));
  24364. }
  24365. this._chunkCount = storage[dim].length;
  24366. }
  24367. var dataItem = new Array(dimLen);
  24368. for (var idx = start; idx < end; idx++) {
  24369. // NOTICE: Try not to write things into dataItem
  24370. dataItem = rawData.getItem(idx, dataItem);
  24371. // Each data item is value
  24372. // [1, 2]
  24373. // 2
  24374. // Bar chart, line chart which uses category axis
  24375. // only gives the 'y' value. 'x' value is the indices of category
  24376. // Use a tempValue to normalize the value to be a (x, y) value
  24377. var chunkIndex = Math.floor(idx / chunkSize);
  24378. var chunkOffset = idx % chunkSize;
  24379. // Store the data by dimensions
  24380. for (var k = 0; k < dimLen; k++) {
  24381. var dim = dimensions[k];
  24382. var dimStorage = storage[dim][chunkIndex];
  24383. // PENDING NULL is empty or zero
  24384. var val = this._dimValueGetter(dataItem, dim, idx, k);
  24385. dimStorage[chunkOffset] = val;
  24386. var dimRawExtent = rawExtent[dim];
  24387. if (val < dimRawExtent[0]) {
  24388. dimRawExtent[0] = val;
  24389. }
  24390. if (val > dimRawExtent[1]) {
  24391. dimRawExtent[1] = val;
  24392. }
  24393. }
  24394. // ??? FIXME not check by pure but sourceFormat?
  24395. // TODO refactor these logic.
  24396. if (!rawData.pure) {
  24397. var name = nameList[idx];
  24398. if (dataItem && name == null) {
  24399. // If dataItem is {name: ...}, it has highest priority.
  24400. // That is appropriate for many common cases.
  24401. if (dataItem.name != null) {
  24402. // There is no other place to persistent dataItem.name,
  24403. // so save it to nameList.
  24404. nameList[idx] = name = dataItem.name;
  24405. }
  24406. else if (nameDimIdx != null) {
  24407. var nameDim = dimensions[nameDimIdx];
  24408. var nameDimChunk = storage[nameDim][chunkIndex];
  24409. if (nameDimChunk) {
  24410. name = nameDimChunk[chunkOffset];
  24411. var ordinalMeta = dimensionInfoMap[nameDim].ordinalMeta;
  24412. if (ordinalMeta && ordinalMeta.categories.length) {
  24413. name = ordinalMeta.categories[name];
  24414. }
  24415. }
  24416. }
  24417. }
  24418. // Try using the id in option
  24419. // id or name is used on dynamical data, mapping old and new items.
  24420. var id = dataItem == null ? null : dataItem.id;
  24421. if (id == null && name != null) {
  24422. // Use name as id and add counter to avoid same name
  24423. nameRepeatCount[name] = nameRepeatCount[name] || 0;
  24424. id = name;
  24425. if (nameRepeatCount[name] > 0) {
  24426. id += '__ec__' + nameRepeatCount[name];
  24427. }
  24428. nameRepeatCount[name]++;
  24429. }
  24430. id != null && (idList[idx] = id);
  24431. }
  24432. }
  24433. if (!rawData.persistent && rawData.clean) {
  24434. // Clean unused data if data source is typed array.
  24435. rawData.clean();
  24436. }
  24437. this._rawCount = this._count = end;
  24438. // Reset data extent
  24439. this._extent = {};
  24440. prepareInvertedIndex(this);
  24441. };
  24442. function prepareInvertedIndex(list) {
  24443. var invertedIndicesMap = list._invertedIndicesMap;
  24444. each$1(invertedIndicesMap, function (invertedIndices, dim) {
  24445. var dimInfo = list._dimensionInfos[dim];
  24446. // Currently, only dimensions that has ordinalMeta can create inverted indices.
  24447. var ordinalMeta = dimInfo.ordinalMeta;
  24448. if (ordinalMeta) {
  24449. invertedIndices = invertedIndicesMap[dim] = new CtorUint32Array(
  24450. ordinalMeta.categories.length
  24451. );
  24452. // The default value of TypedArray is 0. To avoid miss
  24453. // mapping to 0, we should set it as NaN.
  24454. for (var i = 0; i < invertedIndices.length; i++) {
  24455. invertedIndices[i] = NaN;
  24456. }
  24457. for (var i = 0; i < list._count; i++) {
  24458. // Only support the case that all values are distinct.
  24459. invertedIndices[list.get(dim, i)] = i;
  24460. }
  24461. }
  24462. });
  24463. }
  24464. function getRawValueFromStore(list, dimIndex, rawIndex) {
  24465. var val;
  24466. if (dimIndex != null) {
  24467. var chunkSize = list._chunkSize;
  24468. var chunkIndex = Math.floor(rawIndex / chunkSize);
  24469. var chunkOffset = rawIndex % chunkSize;
  24470. var dim = list.dimensions[dimIndex];
  24471. var chunk = list._storage[dim][chunkIndex];
  24472. if (chunk) {
  24473. val = chunk[chunkOffset];
  24474. var ordinalMeta = list._dimensionInfos[dim].ordinalMeta;
  24475. if (ordinalMeta && ordinalMeta.categories.length) {
  24476. val = ordinalMeta.categories[val];
  24477. }
  24478. }
  24479. }
  24480. return val;
  24481. }
  24482. /**
  24483. * @return {number}
  24484. */
  24485. listProto.count = function () {
  24486. return this._count;
  24487. };
  24488. listProto.getIndices = function () {
  24489. var newIndices;
  24490. var indices = this._indices;
  24491. if (indices) {
  24492. var Ctor = indices.constructor;
  24493. var thisCount = this._count;
  24494. // `new Array(a, b, c)` is different from `new Uint32Array(a, b, c)`.
  24495. if (Ctor === Array) {
  24496. newIndices = new Ctor(thisCount);
  24497. for (var i = 0; i < thisCount; i++) {
  24498. newIndices[i] = indices[i];
  24499. }
  24500. }
  24501. else {
  24502. newIndices = new Ctor(indices.buffer, 0, thisCount);
  24503. }
  24504. }
  24505. else {
  24506. var Ctor = getIndicesCtor(this);
  24507. var newIndices = new Ctor(this.count());
  24508. for (var i = 0; i < newIndices.length; i++) {
  24509. newIndices[i] = i;
  24510. }
  24511. }
  24512. return newIndices;
  24513. };
  24514. /**
  24515. * Get value. Return NaN if idx is out of range.
  24516. * @param {string} dim Dim must be concrete name.
  24517. * @param {number} idx
  24518. * @param {boolean} stack
  24519. * @return {number}
  24520. */
  24521. listProto.get = function (dim, idx /*, stack */) {
  24522. if (!(idx >= 0 && idx < this._count)) {
  24523. return NaN;
  24524. }
  24525. var storage = this._storage;
  24526. if (!storage[dim]) {
  24527. // TODO Warn ?
  24528. return NaN;
  24529. }
  24530. idx = this.getRawIndex(idx);
  24531. var chunkIndex = Math.floor(idx / this._chunkSize);
  24532. var chunkOffset = idx % this._chunkSize;
  24533. var chunkStore = storage[dim][chunkIndex];
  24534. var value = chunkStore[chunkOffset];
  24535. // FIXME ordinal data type is not stackable
  24536. // if (stack) {
  24537. // var dimensionInfo = this._dimensionInfos[dim];
  24538. // if (dimensionInfo && dimensionInfo.stackable) {
  24539. // var stackedOn = this.stackedOn;
  24540. // while (stackedOn) {
  24541. // // Get no stacked data of stacked on
  24542. // var stackedValue = stackedOn.get(dim, idx);
  24543. // // Considering positive stack, negative stack and empty data
  24544. // if ((value >= 0 && stackedValue > 0) // Positive stack
  24545. // || (value <= 0 && stackedValue < 0) // Negative stack
  24546. // ) {
  24547. // value += stackedValue;
  24548. // }
  24549. // stackedOn = stackedOn.stackedOn;
  24550. // }
  24551. // }
  24552. // }
  24553. return value;
  24554. };
  24555. /**
  24556. * @param {string} dim concrete dim
  24557. * @param {number} rawIndex
  24558. * @return {number|string}
  24559. */
  24560. listProto.getByRawIndex = function (dim, rawIdx) {
  24561. if (!(rawIdx >= 0 && rawIdx < this._rawCount)) {
  24562. return NaN;
  24563. }
  24564. var dimStore = this._storage[dim];
  24565. if (!dimStore) {
  24566. // TODO Warn ?
  24567. return NaN;
  24568. }
  24569. var chunkIndex = Math.floor(rawIdx / this._chunkSize);
  24570. var chunkOffset = rawIdx % this._chunkSize;
  24571. var chunkStore = dimStore[chunkIndex];
  24572. return chunkStore[chunkOffset];
  24573. };
  24574. /**
  24575. * FIXME Use `get` on chrome maybe slow(in filterSelf and selectRange).
  24576. * Hack a much simpler _getFast
  24577. * @private
  24578. */
  24579. listProto._getFast = function (dim, rawIdx) {
  24580. var chunkIndex = Math.floor(rawIdx / this._chunkSize);
  24581. var chunkOffset = rawIdx % this._chunkSize;
  24582. var chunkStore = this._storage[dim][chunkIndex];
  24583. return chunkStore[chunkOffset];
  24584. };
  24585. /**
  24586. * Get value for multi dimensions.
  24587. * @param {Array.<string>} [dimensions] If ignored, using all dimensions.
  24588. * @param {number} idx
  24589. * @return {number}
  24590. */
  24591. listProto.getValues = function (dimensions, idx /*, stack */) {
  24592. var values = [];
  24593. if (!isArray(dimensions)) {
  24594. // stack = idx;
  24595. idx = dimensions;
  24596. dimensions = this.dimensions;
  24597. }
  24598. for (var i = 0, len = dimensions.length; i < len; i++) {
  24599. values.push(this.get(dimensions[i], idx /*, stack */));
  24600. }
  24601. return values;
  24602. };
  24603. /**
  24604. * If value is NaN. Inlcuding '-'
  24605. * Only check the coord dimensions.
  24606. * @param {string} dim
  24607. * @param {number} idx
  24608. * @return {number}
  24609. */
  24610. listProto.hasValue = function (idx) {
  24611. var dataDimsOnCoord = this._dimensionsSummary.dataDimsOnCoord;
  24612. var dimensionInfos = this._dimensionInfos;
  24613. for (var i = 0, len = dataDimsOnCoord.length; i < len; i++) {
  24614. if (
  24615. // Ordinal type can be string or number
  24616. dimensionInfos[dataDimsOnCoord[i]].type !== 'ordinal'
  24617. // FIXME check ordinal when using index?
  24618. && isNaN(this.get(dataDimsOnCoord[i], idx))
  24619. ) {
  24620. return false;
  24621. }
  24622. }
  24623. return true;
  24624. };
  24625. /**
  24626. * Get extent of data in one dimension
  24627. * @param {string} dim
  24628. * @param {boolean} stack
  24629. */
  24630. listProto.getDataExtent = function (dim /*, stack */) {
  24631. // Make sure use concrete dim as cache name.
  24632. dim = this.getDimension(dim);
  24633. var dimData = this._storage[dim];
  24634. var initialExtent = getInitialExtent();
  24635. // stack = !!((stack || false) && this.getCalculationInfo(dim));
  24636. if (!dimData) {
  24637. return initialExtent;
  24638. }
  24639. // Make more strict checkings to ensure hitting cache.
  24640. var currEnd = this.count();
  24641. // var cacheName = [dim, !!stack].join('_');
  24642. // var cacheName = dim;
  24643. // Consider the most cases when using data zoom, `getDataExtent`
  24644. // happened before filtering. We cache raw extent, which is not
  24645. // necessary to be cleared and recalculated when restore data.
  24646. var useRaw = !this._indices; // && !stack;
  24647. var dimExtent;
  24648. if (useRaw) {
  24649. return this._rawExtent[dim].slice();
  24650. }
  24651. dimExtent = this._extent[dim];
  24652. if (dimExtent) {
  24653. return dimExtent.slice();
  24654. }
  24655. dimExtent = initialExtent;
  24656. var min = dimExtent[0];
  24657. var max = dimExtent[1];
  24658. for (var i = 0; i < currEnd; i++) {
  24659. // var value = stack ? this.get(dim, i, true) : this._getFast(dim, this.getRawIndex(i));
  24660. var value = this._getFast(dim, this.getRawIndex(i));
  24661. value < min && (min = value);
  24662. value > max && (max = value);
  24663. }
  24664. dimExtent = [min, max];
  24665. this._extent[dim] = dimExtent;
  24666. return dimExtent;
  24667. };
  24668. /**
  24669. * Optimize for the scenario that data is filtered by a given extent.
  24670. * Consider that if data amount is more than hundreds of thousand,
  24671. * extent calculation will cost more than 10ms and the cache will
  24672. * be erased because of the filtering.
  24673. */
  24674. listProto.getApproximateExtent = function (dim /*, stack */) {
  24675. dim = this.getDimension(dim);
  24676. return this._approximateExtent[dim] || this.getDataExtent(dim /*, stack */);
  24677. };
  24678. listProto.setApproximateExtent = function (extent, dim /*, stack */) {
  24679. dim = this.getDimension(dim);
  24680. this._approximateExtent[dim] = extent.slice();
  24681. };
  24682. /**
  24683. * @param {string} key
  24684. * @return {*}
  24685. */
  24686. listProto.getCalculationInfo = function (key) {
  24687. return this._calculationInfo[key];
  24688. };
  24689. /**
  24690. * @param {string|Object} key or k-v object
  24691. * @param {*} [value]
  24692. */
  24693. listProto.setCalculationInfo = function (key, value) {
  24694. isObject$4(key)
  24695. ? extend(this._calculationInfo, key)
  24696. : (this._calculationInfo[key] = value);
  24697. };
  24698. /**
  24699. * Get sum of data in one dimension
  24700. * @param {string} dim
  24701. */
  24702. listProto.getSum = function (dim /*, stack */) {
  24703. var dimData = this._storage[dim];
  24704. var sum = 0;
  24705. if (dimData) {
  24706. for (var i = 0, len = this.count(); i < len; i++) {
  24707. var value = this.get(dim, i /*, stack */);
  24708. if (!isNaN(value)) {
  24709. sum += value;
  24710. }
  24711. }
  24712. }
  24713. return sum;
  24714. };
  24715. /**
  24716. * Get median of data in one dimension
  24717. * @param {string} dim
  24718. */
  24719. listProto.getMedian = function (dim /*, stack */) {
  24720. var dimDataArray = [];
  24721. // map all data of one dimension
  24722. this.each(dim, function (val, idx) {
  24723. if (!isNaN(val)) {
  24724. dimDataArray.push(val);
  24725. }
  24726. });
  24727. // TODO
  24728. // Use quick select?
  24729. // immutability & sort
  24730. var sortedDimDataArray = [].concat(dimDataArray).sort(function(a, b) {
  24731. return a - b;
  24732. });
  24733. var len = this.count();
  24734. // calculate median
  24735. return len === 0 ? 0 :
  24736. len % 2 === 1 ? sortedDimDataArray[(len - 1) / 2] :
  24737. (sortedDimDataArray[len / 2] + sortedDimDataArray[len / 2 - 1]) / 2;
  24738. };
  24739. // /**
  24740. // * Retreive the index with given value
  24741. // * @param {string} dim Concrete dimension.
  24742. // * @param {number} value
  24743. // * @return {number}
  24744. // */
  24745. // Currently incorrect: should return dataIndex but not rawIndex.
  24746. // Do not fix it until this method is to be used somewhere.
  24747. // FIXME Precision of float value
  24748. // listProto.indexOf = function (dim, value) {
  24749. // var storage = this._storage;
  24750. // var dimData = storage[dim];
  24751. // var chunkSize = this._chunkSize;
  24752. // if (dimData) {
  24753. // for (var i = 0, len = this.count(); i < len; i++) {
  24754. // var chunkIndex = Math.floor(i / chunkSize);
  24755. // var chunkOffset = i % chunkSize;
  24756. // if (dimData[chunkIndex][chunkOffset] === value) {
  24757. // return i;
  24758. // }
  24759. // }
  24760. // }
  24761. // return -1;
  24762. // };
  24763. /**
  24764. * Only support the dimension which inverted index created.
  24765. * Do not support other cases until required.
  24766. * @param {string} concrete dim
  24767. * @param {number|string} value
  24768. * @return {number} rawIndex
  24769. */
  24770. listProto.rawIndexOf = function (dim, value) {
  24771. var invertedIndices = dim && this._invertedIndicesMap[dim];
  24772. if (__DEV__) {
  24773. if (!invertedIndices) {
  24774. throw new Error('Do not supported yet');
  24775. }
  24776. }
  24777. var rawIndex = invertedIndices[value];
  24778. if (rawIndex == null || isNaN(rawIndex)) {
  24779. return -1;
  24780. }
  24781. return rawIndex;
  24782. };
  24783. /**
  24784. * Retreive the index with given name
  24785. * @param {number} idx
  24786. * @param {number} name
  24787. * @return {number}
  24788. */
  24789. listProto.indexOfName = function (name) {
  24790. for (var i = 0, len = this.count(); i < len; i++) {
  24791. if (this.getName(i) === name) {
  24792. return i;
  24793. }
  24794. }
  24795. return -1;
  24796. };
  24797. /**
  24798. * Retreive the index with given raw data index
  24799. * @param {number} idx
  24800. * @param {number} name
  24801. * @return {number}
  24802. */
  24803. listProto.indexOfRawIndex = function (rawIndex) {
  24804. if (!this._indices) {
  24805. return rawIndex;
  24806. }
  24807. if (rawIndex >= this._rawCount || rawIndex < 0) {
  24808. return -1;
  24809. }
  24810. // Indices are ascending
  24811. var indices = this._indices;
  24812. // If rawIndex === dataIndex
  24813. var rawDataIndex = indices[rawIndex];
  24814. if (rawDataIndex != null && rawDataIndex < this._count && rawDataIndex === rawIndex) {
  24815. return rawIndex;
  24816. }
  24817. var left = 0;
  24818. var right = this._count - 1;
  24819. while (left <= right) {
  24820. var mid = (left + right) / 2 | 0;
  24821. if (indices[mid] < rawIndex) {
  24822. left = mid + 1;
  24823. }
  24824. else if (indices[mid] > rawIndex) {
  24825. right = mid - 1;
  24826. }
  24827. else {
  24828. return mid;
  24829. }
  24830. }
  24831. return -1;
  24832. };
  24833. /**
  24834. * Retreive the index of nearest value
  24835. * @param {string} dim
  24836. * @param {number} value
  24837. * @param {number} [maxDistance=Infinity]
  24838. * @return {Array.<number>} Considere multiple points has the same value.
  24839. */
  24840. listProto.indicesOfNearest = function (dim, value, maxDistance) {
  24841. var storage = this._storage;
  24842. var dimData = storage[dim];
  24843. var nearestIndices = [];
  24844. if (!dimData) {
  24845. return nearestIndices;
  24846. }
  24847. if (maxDistance == null) {
  24848. maxDistance = Infinity;
  24849. }
  24850. var minDist = Number.MAX_VALUE;
  24851. var minDiff = -1;
  24852. for (var i = 0, len = this.count(); i < len; i++) {
  24853. var diff = value - this.get(dim, i /*, stack */);
  24854. var dist = Math.abs(diff);
  24855. if (diff <= maxDistance && dist <= minDist) {
  24856. // For the case of two data are same on xAxis, which has sequence data.
  24857. // Show the nearest index
  24858. // https://github.com/ecomfe/echarts/issues/2869
  24859. if (dist < minDist || (diff >= 0 && minDiff < 0)) {
  24860. minDist = dist;
  24861. minDiff = diff;
  24862. nearestIndices.length = 0;
  24863. }
  24864. nearestIndices.push(i);
  24865. }
  24866. }
  24867. return nearestIndices;
  24868. };
  24869. /**
  24870. * Get raw data index
  24871. * @param {number} idx
  24872. * @return {number}
  24873. */
  24874. listProto.getRawIndex = getRawIndexWithoutIndices;
  24875. function getRawIndexWithoutIndices(idx) {
  24876. return idx;
  24877. }
  24878. function getRawIndexWithIndices(idx) {
  24879. if (idx < this._count && idx >= 0) {
  24880. return this._indices[idx];
  24881. }
  24882. return -1;
  24883. }
  24884. /**
  24885. * Get raw data item
  24886. * @param {number} idx
  24887. * @return {number}
  24888. */
  24889. listProto.getRawDataItem = function (idx) {
  24890. if (!this._rawData.persistent) {
  24891. var val = [];
  24892. for (var i = 0; i < this.dimensions.length; i++) {
  24893. var dim = this.dimensions[i];
  24894. val.push(this.get(dim, idx));
  24895. }
  24896. return val;
  24897. }
  24898. else {
  24899. return this._rawData.getItem(this.getRawIndex(idx));
  24900. }
  24901. };
  24902. /**
  24903. * @param {number} idx
  24904. * @param {boolean} [notDefaultIdx=false]
  24905. * @return {string}
  24906. */
  24907. listProto.getName = function (idx) {
  24908. var rawIndex = this.getRawIndex(idx);
  24909. return this._nameList[rawIndex]
  24910. || getRawValueFromStore(this, this._nameDimIdx, rawIndex)
  24911. || '';
  24912. };
  24913. /**
  24914. * @param {number} idx
  24915. * @param {boolean} [notDefaultIdx=false]
  24916. * @return {string}
  24917. */
  24918. listProto.getId = function (idx) {
  24919. return getId(this, this.getRawIndex(idx));
  24920. };
  24921. function getId(list, rawIndex) {
  24922. var id = list._idList[rawIndex];
  24923. if (id == null) {
  24924. id = getRawValueFromStore(list, list._idDimIdx, rawIndex);
  24925. }
  24926. if (id == null) {
  24927. // FIXME Check the usage in graph, should not use prefix.
  24928. id = ID_PREFIX + rawIndex;
  24929. }
  24930. return id;
  24931. }
  24932. function normalizeDimensions(dimensions) {
  24933. if (!isArray(dimensions)) {
  24934. dimensions = [dimensions];
  24935. }
  24936. return dimensions;
  24937. }
  24938. function validateDimensions(list, dims) {
  24939. for (var i = 0; i < dims.length; i++) {
  24940. // stroage may be empty when no data, so use
  24941. // dimensionInfos to check.
  24942. if (!list._dimensionInfos[dims[i]]) {
  24943. console.error('Unkown dimension ' + dims[i]);
  24944. }
  24945. }
  24946. }
  24947. /**
  24948. * Data iteration
  24949. * @param {string|Array.<string>}
  24950. * @param {Function} cb
  24951. * @param {*} [context=this]
  24952. *
  24953. * @example
  24954. * list.each('x', function (x, idx) {});
  24955. * list.each(['x', 'y'], function (x, y, idx) {});
  24956. * list.each(function (idx) {})
  24957. */
  24958. listProto.each = function (dims, cb, context, contextCompat) {
  24959. 'use strict';
  24960. if (!this._count) {
  24961. return;
  24962. }
  24963. if (typeof dims === 'function') {
  24964. contextCompat = context;
  24965. context = cb;
  24966. cb = dims;
  24967. dims = [];
  24968. }
  24969. // contextCompat just for compat echarts3
  24970. context = context || contextCompat || this;
  24971. dims = map(normalizeDimensions(dims), this.getDimension, this);
  24972. if (__DEV__) {
  24973. validateDimensions(this, dims);
  24974. }
  24975. var dimSize = dims.length;
  24976. for (var i = 0; i < this.count(); i++) {
  24977. // Simple optimization
  24978. switch (dimSize) {
  24979. case 0:
  24980. cb.call(context, i);
  24981. break;
  24982. case 1:
  24983. cb.call(context, this.get(dims[0], i), i);
  24984. break;
  24985. case 2:
  24986. cb.call(context, this.get(dims[0], i), this.get(dims[1], i), i);
  24987. break;
  24988. default:
  24989. var k = 0;
  24990. var value = [];
  24991. for (; k < dimSize; k++) {
  24992. value[k] = this.get(dims[k], i);
  24993. }
  24994. // Index
  24995. value[k] = i;
  24996. cb.apply(context, value);
  24997. }
  24998. }
  24999. };
  25000. /**
  25001. * Data filter
  25002. * @param {string|Array.<string>}
  25003. * @param {Function} cb
  25004. * @param {*} [context=this]
  25005. */
  25006. listProto.filterSelf = function (dimensions, cb, context, contextCompat) {
  25007. 'use strict';
  25008. if (!this._count) {
  25009. return;
  25010. }
  25011. if (typeof dimensions === 'function') {
  25012. contextCompat = context;
  25013. context = cb;
  25014. cb = dimensions;
  25015. dimensions = [];
  25016. }
  25017. // contextCompat just for compat echarts3
  25018. context = context || contextCompat || this;
  25019. dimensions = map(
  25020. normalizeDimensions(dimensions), this.getDimension, this
  25021. );
  25022. if (__DEV__) {
  25023. validateDimensions(this, dimensions);
  25024. }
  25025. var count = this.count();
  25026. var Ctor = getIndicesCtor(this);
  25027. var newIndices = new Ctor(count);
  25028. var value = [];
  25029. var dimSize = dimensions.length;
  25030. var offset = 0;
  25031. var dim0 = dimensions[0];
  25032. for (var i = 0; i < count; i++) {
  25033. var keep;
  25034. var rawIdx = this.getRawIndex(i);
  25035. // Simple optimization
  25036. if (dimSize === 0) {
  25037. keep = cb.call(context, i);
  25038. }
  25039. else if (dimSize === 1) {
  25040. var val = this._getFast(dim0, rawIdx);
  25041. keep = cb.call(context, val, i);
  25042. }
  25043. else {
  25044. for (var k = 0; k < dimSize; k++) {
  25045. value[k] = this._getFast(dim0, rawIdx);
  25046. }
  25047. value[k] = i;
  25048. keep = cb.apply(context, value);
  25049. }
  25050. if (keep) {
  25051. newIndices[offset++] = rawIdx;
  25052. }
  25053. }
  25054. // Set indices after filtered.
  25055. if (offset < count) {
  25056. this._indices = newIndices;
  25057. }
  25058. this._count = offset;
  25059. // Reset data extent
  25060. this._extent = {};
  25061. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  25062. return this;
  25063. };
  25064. /**
  25065. * Select data in range. (For optimization of filter)
  25066. * (Manually inline code, support 5 million data filtering in data zoom.)
  25067. */
  25068. listProto.selectRange = function (range) {
  25069. 'use strict';
  25070. if (!this._count) {
  25071. return;
  25072. }
  25073. var dimensions = [];
  25074. for (var dim in range) {
  25075. if (range.hasOwnProperty(dim)) {
  25076. dimensions.push(dim);
  25077. }
  25078. }
  25079. if (__DEV__) {
  25080. validateDimensions(this, dimensions);
  25081. }
  25082. var dimSize = dimensions.length;
  25083. if (!dimSize) {
  25084. return;
  25085. }
  25086. var originalCount = this.count();
  25087. var Ctor = getIndicesCtor(this);
  25088. var newIndices = new Ctor(originalCount);
  25089. var offset = 0;
  25090. var dim0 = dimensions[0];
  25091. var min = range[dim0][0];
  25092. var max = range[dim0][1];
  25093. var quickFinished = false;
  25094. if (!this._indices) {
  25095. // Extreme optimization for common case. About 2x faster in chrome.
  25096. var idx = 0;
  25097. if (dimSize === 1) {
  25098. var dimStorage = this._storage[dimensions[0]];
  25099. for (var k = 0; k < this._chunkCount; k++) {
  25100. var chunkStorage = dimStorage[k];
  25101. var len = Math.min(this._count - k * this._chunkSize, this._chunkSize);
  25102. for (var i = 0; i < len; i++) {
  25103. var val = chunkStorage[i];
  25104. // NaN will not be filtered. Consider the case, in line chart, empty
  25105. // value indicates the line should be broken. But for the case like
  25106. // scatter plot, a data item with empty value will not be rendered,
  25107. // but the axis extent may be effected if some other dim of the data
  25108. // item has value. Fortunately it is not a significant negative effect.
  25109. if (
  25110. (val >= min && val <= max) || isNaN(val)
  25111. ) {
  25112. newIndices[offset++] = idx;
  25113. }
  25114. idx++;
  25115. }
  25116. }
  25117. quickFinished = true;
  25118. }
  25119. else if (dimSize === 2) {
  25120. var dimStorage = this._storage[dim0];
  25121. var dimStorage2 = this._storage[dimensions[1]];
  25122. var min2 = range[dimensions[1]][0];
  25123. var max2 = range[dimensions[1]][1];
  25124. for (var k = 0; k < this._chunkCount; k++) {
  25125. var chunkStorage = dimStorage[k];
  25126. var chunkStorage2= dimStorage2[k];
  25127. var len = Math.min(this._count - k * this._chunkSize, this._chunkSize);
  25128. for (var i = 0; i < len; i++) {
  25129. var val = chunkStorage[i];
  25130. var val2 = chunkStorage2[i];
  25131. // Do not filter NaN, see comment above.
  25132. if ((
  25133. (val >= min && val <= max) || isNaN(val)
  25134. )
  25135. && (
  25136. (val2 >= min2 && val2 <= max2) || isNaN(val2)
  25137. )
  25138. ) {
  25139. newIndices[offset++] = idx;
  25140. }
  25141. idx++;
  25142. }
  25143. }
  25144. quickFinished = true;
  25145. }
  25146. }
  25147. if (!quickFinished) {
  25148. if (dimSize === 1) {
  25149. for (var i = 0; i < originalCount; i++) {
  25150. var rawIndex = this.getRawIndex(i);
  25151. var val = this._getFast(dim0, rawIndex);
  25152. // Do not filter NaN, see comment above.
  25153. if (
  25154. (val >= min && val <= max) || isNaN(val)
  25155. ) {
  25156. newIndices[offset++] = rawIndex;
  25157. }
  25158. }
  25159. }
  25160. else {
  25161. for (var i = 0; i < originalCount; i++) {
  25162. var keep = true;
  25163. var rawIndex = this.getRawIndex(i);
  25164. for (var k = 0; k < dimSize; k++) {
  25165. var dimk = dimensions[k];
  25166. var val = this._getFast(dim, rawIndex);
  25167. // Do not filter NaN, see comment above.
  25168. if (val < range[dimk][0] || val > range[dimk][1]) {
  25169. keep = false;
  25170. }
  25171. }
  25172. if (keep) {
  25173. newIndices[offset++] = this.getRawIndex(i);
  25174. }
  25175. }
  25176. }
  25177. }
  25178. // Set indices after filtered.
  25179. if (offset < originalCount) {
  25180. this._indices = newIndices;
  25181. }
  25182. this._count = offset;
  25183. // Reset data extent
  25184. this._extent = {};
  25185. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  25186. return this;
  25187. };
  25188. /**
  25189. * Data mapping to a plain array
  25190. * @param {string|Array.<string>} [dimensions]
  25191. * @param {Function} cb
  25192. * @param {*} [context=this]
  25193. * @return {Array}
  25194. */
  25195. listProto.mapArray = function (dimensions, cb, context, contextCompat) {
  25196. 'use strict';
  25197. if (typeof dimensions === 'function') {
  25198. contextCompat = context;
  25199. context = cb;
  25200. cb = dimensions;
  25201. dimensions = [];
  25202. }
  25203. // contextCompat just for compat echarts3
  25204. context = context || contextCompat || this;
  25205. var result = [];
  25206. this.each(dimensions, function () {
  25207. result.push(cb && cb.apply(this, arguments));
  25208. }, context);
  25209. return result;
  25210. };
  25211. // Data in excludeDimensions is copied, otherwise transfered.
  25212. function cloneListForMapAndSample(original, excludeDimensions) {
  25213. var allDimensions = original.dimensions;
  25214. var list = new List(
  25215. map(allDimensions, original.getDimensionInfo, original),
  25216. original.hostModel
  25217. );
  25218. // FIXME If needs stackedOn, value may already been stacked
  25219. transferProperties(list, original);
  25220. var storage = list._storage = {};
  25221. var originalStorage = original._storage;
  25222. // Init storage
  25223. for (var i = 0; i < allDimensions.length; i++) {
  25224. var dim = allDimensions[i];
  25225. if (originalStorage[dim]) {
  25226. // Notice that we do not reset invertedIndicesMap here, becuase
  25227. // there is no scenario of mapping or sampling ordinal dimension.
  25228. if (indexOf(excludeDimensions, dim) >= 0) {
  25229. storage[dim] = cloneDimStore(originalStorage[dim]);
  25230. list._rawExtent[dim] = getInitialExtent();
  25231. list._extent[dim] = null;
  25232. }
  25233. else {
  25234. // Direct reference for other dimensions
  25235. storage[dim] = originalStorage[dim];
  25236. }
  25237. }
  25238. }
  25239. return list;
  25240. }
  25241. function cloneDimStore(originalDimStore) {
  25242. var newDimStore = new Array(originalDimStore.length);
  25243. for (var j = 0; j < originalDimStore.length; j++) {
  25244. newDimStore[j] = cloneChunk(originalDimStore[j]);
  25245. }
  25246. return newDimStore;
  25247. }
  25248. function getInitialExtent() {
  25249. return [Infinity, -Infinity];
  25250. }
  25251. /**
  25252. * Data mapping to a new List with given dimensions
  25253. * @param {string|Array.<string>} dimensions
  25254. * @param {Function} cb
  25255. * @param {*} [context=this]
  25256. * @return {Array}
  25257. */
  25258. listProto.map = function (dimensions, cb, context, contextCompat) {
  25259. 'use strict';
  25260. // contextCompat just for compat echarts3
  25261. context = context || contextCompat || this;
  25262. dimensions = map(
  25263. normalizeDimensions(dimensions), this.getDimension, this
  25264. );
  25265. if (__DEV__) {
  25266. validateDimensions(this, dimensions);
  25267. }
  25268. var list = cloneListForMapAndSample(this, dimensions);
  25269. // Following properties are all immutable.
  25270. // So we can reference to the same value
  25271. list._indices = this._indices;
  25272. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  25273. var storage = list._storage;
  25274. var tmpRetValue = [];
  25275. var chunkSize = this._chunkSize;
  25276. var dimSize = dimensions.length;
  25277. var dataCount = this.count();
  25278. var values = [];
  25279. var rawExtent = list._rawExtent;
  25280. for (var dataIndex = 0; dataIndex < dataCount; dataIndex++) {
  25281. for (var dimIndex = 0; dimIndex < dimSize; dimIndex++) {
  25282. values[dimIndex] = this.get(dimensions[dimIndex], dataIndex /*, stack */);
  25283. }
  25284. values[dimSize] = dataIndex;
  25285. var retValue = cb && cb.apply(context, values);
  25286. if (retValue != null) {
  25287. // a number or string (in oridinal dimension)?
  25288. if (typeof retValue !== 'object') {
  25289. tmpRetValue[0] = retValue;
  25290. retValue = tmpRetValue;
  25291. }
  25292. var rawIndex = this.getRawIndex(dataIndex);
  25293. var chunkIndex = Math.floor(rawIndex / chunkSize);
  25294. var chunkOffset = rawIndex % chunkSize;
  25295. for (var i = 0; i < retValue.length; i++) {
  25296. var dim = dimensions[i];
  25297. var val = retValue[i];
  25298. var rawExtentOnDim = rawExtent[dim];
  25299. var dimStore = storage[dim];
  25300. if (dimStore) {
  25301. dimStore[chunkIndex][chunkOffset] = val;
  25302. }
  25303. if (val < rawExtentOnDim[0]) {
  25304. rawExtentOnDim[0] = val;
  25305. }
  25306. if (val > rawExtentOnDim[1]) {
  25307. rawExtentOnDim[1] = val;
  25308. }
  25309. }
  25310. }
  25311. }
  25312. return list;
  25313. };
  25314. /**
  25315. * Large data down sampling on given dimension
  25316. * @param {string} dimension
  25317. * @param {number} rate
  25318. * @param {Function} sampleValue
  25319. * @param {Function} sampleIndex Sample index for name and id
  25320. */
  25321. listProto.downSample = function (dimension, rate, sampleValue, sampleIndex) {
  25322. var list = cloneListForMapAndSample(this, [dimension]);
  25323. var targetStorage = list._storage;
  25324. var frameValues = [];
  25325. var frameSize = Math.floor(1 / rate);
  25326. var dimStore = targetStorage[dimension];
  25327. var len = this.count();
  25328. var chunkSize = this._chunkSize;
  25329. var rawExtentOnDim = list._rawExtent[dimension];
  25330. var newIndices = new (getIndicesCtor(this))(len);
  25331. var offset = 0;
  25332. for (var i = 0; i < len; i += frameSize) {
  25333. // Last frame
  25334. if (frameSize > len - i) {
  25335. frameSize = len - i;
  25336. frameValues.length = frameSize;
  25337. }
  25338. for (var k = 0; k < frameSize; k++) {
  25339. var dataIdx = this.getRawIndex(i + k);
  25340. var originalChunkIndex = Math.floor(dataIdx / chunkSize);
  25341. var originalChunkOffset = dataIdx % chunkSize;
  25342. frameValues[k] = dimStore[originalChunkIndex][originalChunkOffset];
  25343. }
  25344. var value = sampleValue(frameValues);
  25345. var sampleFrameIdx = this.getRawIndex(
  25346. Math.min(i + sampleIndex(frameValues, value) || 0, len - 1)
  25347. );
  25348. var sampleChunkIndex = Math.floor(sampleFrameIdx / chunkSize);
  25349. var sampleChunkOffset = sampleFrameIdx % chunkSize;
  25350. // Only write value on the filtered data
  25351. dimStore[sampleChunkIndex][sampleChunkOffset] = value;
  25352. if (value < rawExtentOnDim[0]) {
  25353. rawExtentOnDim[0] = value;
  25354. }
  25355. if (value > rawExtentOnDim[1]) {
  25356. rawExtentOnDim[1] = value;
  25357. }
  25358. newIndices[offset++] = sampleFrameIdx;
  25359. }
  25360. list._count = offset;
  25361. list._indices = newIndices;
  25362. list.getRawIndex = getRawIndexWithIndices;
  25363. return list;
  25364. };
  25365. /**
  25366. * Get model of one data item.
  25367. *
  25368. * @param {number} idx
  25369. */
  25370. // FIXME Model proxy ?
  25371. listProto.getItemModel = function (idx) {
  25372. var hostModel = this.hostModel;
  25373. return new Model(this.getRawDataItem(idx), hostModel, hostModel && hostModel.ecModel);
  25374. };
  25375. /**
  25376. * Create a data differ
  25377. * @param {module:echarts/data/List} otherList
  25378. * @return {module:echarts/data/DataDiffer}
  25379. */
  25380. listProto.diff = function (otherList) {
  25381. var thisList = this;
  25382. return new DataDiffer(
  25383. otherList ? otherList.getIndices() : [],
  25384. this.getIndices(),
  25385. function (idx) {
  25386. return getId(otherList, idx);
  25387. },
  25388. function (idx) {
  25389. return getId(thisList, idx);
  25390. }
  25391. );
  25392. };
  25393. /**
  25394. * Get visual property.
  25395. * @param {string} key
  25396. */
  25397. listProto.getVisual = function (key) {
  25398. var visual = this._visual;
  25399. return visual && visual[key];
  25400. };
  25401. /**
  25402. * Set visual property
  25403. * @param {string|Object} key
  25404. * @param {*} [value]
  25405. *
  25406. * @example
  25407. * setVisual('color', color);
  25408. * setVisual({
  25409. * 'color': color
  25410. * });
  25411. */
  25412. listProto.setVisual = function (key, val) {
  25413. if (isObject$4(key)) {
  25414. for (var name in key) {
  25415. if (key.hasOwnProperty(name)) {
  25416. this.setVisual(name, key[name]);
  25417. }
  25418. }
  25419. return;
  25420. }
  25421. this._visual = this._visual || {};
  25422. this._visual[key] = val;
  25423. };
  25424. /**
  25425. * Set layout property.
  25426. * @param {string|Object} key
  25427. * @param {*} [val]
  25428. */
  25429. listProto.setLayout = function (key, val) {
  25430. if (isObject$4(key)) {
  25431. for (var name in key) {
  25432. if (key.hasOwnProperty(name)) {
  25433. this.setLayout(name, key[name]);
  25434. }
  25435. }
  25436. return;
  25437. }
  25438. this._layout[key] = val;
  25439. };
  25440. /**
  25441. * Get layout property.
  25442. * @param {string} key.
  25443. * @return {*}
  25444. */
  25445. listProto.getLayout = function (key) {
  25446. return this._layout[key];
  25447. };
  25448. /**
  25449. * Get layout of single data item
  25450. * @param {number} idx
  25451. */
  25452. listProto.getItemLayout = function (idx) {
  25453. return this._itemLayouts[idx];
  25454. };
  25455. /**
  25456. * Set layout of single data item
  25457. * @param {number} idx
  25458. * @param {Object} layout
  25459. * @param {boolean=} [merge=false]
  25460. */
  25461. listProto.setItemLayout = function (idx, layout, merge$$1) {
  25462. this._itemLayouts[idx] = merge$$1
  25463. ? extend(this._itemLayouts[idx] || {}, layout)
  25464. : layout;
  25465. };
  25466. /**
  25467. * Clear all layout of single data item
  25468. */
  25469. listProto.clearItemLayouts = function () {
  25470. this._itemLayouts.length = 0;
  25471. };
  25472. /**
  25473. * Get visual property of single data item
  25474. * @param {number} idx
  25475. * @param {string} key
  25476. * @param {boolean} [ignoreParent=false]
  25477. */
  25478. listProto.getItemVisual = function (idx, key, ignoreParent) {
  25479. var itemVisual = this._itemVisuals[idx];
  25480. var val = itemVisual && itemVisual[key];
  25481. if (val == null && !ignoreParent) {
  25482. // Use global visual property
  25483. return this.getVisual(key);
  25484. }
  25485. return val;
  25486. };
  25487. /**
  25488. * Set visual property of single data item
  25489. *
  25490. * @param {number} idx
  25491. * @param {string|Object} key
  25492. * @param {*} [value]
  25493. *
  25494. * @example
  25495. * setItemVisual(0, 'color', color);
  25496. * setItemVisual(0, {
  25497. * 'color': color
  25498. * });
  25499. */
  25500. listProto.setItemVisual = function (idx, key, value) {
  25501. var itemVisual = this._itemVisuals[idx] || {};
  25502. var hasItemVisual = this.hasItemVisual;
  25503. this._itemVisuals[idx] = itemVisual;
  25504. if (isObject$4(key)) {
  25505. for (var name in key) {
  25506. if (key.hasOwnProperty(name)) {
  25507. itemVisual[name] = key[name];
  25508. hasItemVisual[name] = true;
  25509. }
  25510. }
  25511. return;
  25512. }
  25513. itemVisual[key] = value;
  25514. hasItemVisual[key] = true;
  25515. };
  25516. /**
  25517. * Clear itemVisuals and list visual.
  25518. */
  25519. listProto.clearAllVisual = function () {
  25520. this._visual = {};
  25521. this._itemVisuals = [];
  25522. this.hasItemVisual = {};
  25523. };
  25524. var setItemDataAndSeriesIndex = function (child) {
  25525. child.seriesIndex = this.seriesIndex;
  25526. child.dataIndex = this.dataIndex;
  25527. child.dataType = this.dataType;
  25528. };
  25529. /**
  25530. * Set graphic element relative to data. It can be set as null
  25531. * @param {number} idx
  25532. * @param {module:zrender/Element} [el]
  25533. */
  25534. listProto.setItemGraphicEl = function (idx, el) {
  25535. var hostModel = this.hostModel;
  25536. if (el) {
  25537. // Add data index and series index for indexing the data by element
  25538. // Useful in tooltip
  25539. el.dataIndex = idx;
  25540. el.dataType = this.dataType;
  25541. el.seriesIndex = hostModel && hostModel.seriesIndex;
  25542. if (el.type === 'group') {
  25543. el.traverse(setItemDataAndSeriesIndex, el);
  25544. }
  25545. }
  25546. this._graphicEls[idx] = el;
  25547. };
  25548. /**
  25549. * @param {number} idx
  25550. * @return {module:zrender/Element}
  25551. */
  25552. listProto.getItemGraphicEl = function (idx) {
  25553. return this._graphicEls[idx];
  25554. };
  25555. /**
  25556. * @param {Function} cb
  25557. * @param {*} context
  25558. */
  25559. listProto.eachItemGraphicEl = function (cb, context) {
  25560. each$1(this._graphicEls, function (el, idx) {
  25561. if (el) {
  25562. cb && cb.call(context, el, idx);
  25563. }
  25564. });
  25565. };
  25566. /**
  25567. * Shallow clone a new list except visual and layout properties, and graph elements.
  25568. * New list only change the indices.
  25569. */
  25570. listProto.cloneShallow = function (list) {
  25571. if (!list) {
  25572. var dimensionInfoList = map(this.dimensions, this.getDimensionInfo, this);
  25573. list = new List(dimensionInfoList, this.hostModel);
  25574. }
  25575. // FIXME
  25576. list._storage = this._storage;
  25577. transferProperties(list, this);
  25578. // Clone will not change the data extent and indices
  25579. if (this._indices) {
  25580. var Ctor = this._indices.constructor;
  25581. list._indices = new Ctor(this._indices);
  25582. }
  25583. else {
  25584. list._indices = null;
  25585. }
  25586. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  25587. return list;
  25588. };
  25589. /**
  25590. * Wrap some method to add more feature
  25591. * @param {string} methodName
  25592. * @param {Function} injectFunction
  25593. */
  25594. listProto.wrapMethod = function (methodName, injectFunction) {
  25595. var originalMethod = this[methodName];
  25596. if (typeof originalMethod !== 'function') {
  25597. return;
  25598. }
  25599. this.__wrappedMethods = this.__wrappedMethods || [];
  25600. this.__wrappedMethods.push(methodName);
  25601. this[methodName] = function () {
  25602. var res = originalMethod.apply(this, arguments);
  25603. return injectFunction.apply(this, [res].concat(slice(arguments)));
  25604. };
  25605. };
  25606. // Methods that create a new list based on this list should be listed here.
  25607. // Notice that those method should `RETURN` the new list.
  25608. listProto.TRANSFERABLE_METHODS = ['cloneShallow', 'downSample', 'map'];
  25609. // Methods that change indices of this list should be listed here.
  25610. listProto.CHANGABLE_METHODS = ['filterSelf', 'selectRange'];
  25611. /*
  25612. * Licensed to the Apache Software Foundation (ASF) under one
  25613. * or more contributor license agreements. See the NOTICE file
  25614. * distributed with this work for additional information
  25615. * regarding copyright ownership. The ASF licenses this file
  25616. * to you under the Apache License, Version 2.0 (the
  25617. * "License"); you may not use this file except in compliance
  25618. * with the License. You may obtain a copy of the License at
  25619. *
  25620. * http://www.apache.org/licenses/LICENSE-2.0
  25621. *
  25622. * Unless required by applicable law or agreed to in writing,
  25623. * software distributed under the License is distributed on an
  25624. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  25625. * KIND, either express or implied. See the License for the
  25626. * specific language governing permissions and limitations
  25627. * under the License.
  25628. */
  25629. /**
  25630. * @deprecated
  25631. * Use `echarts/data/helper/createDimensions` instead.
  25632. */
  25633. /**
  25634. * @see {module:echarts/test/ut/spec/data/completeDimensions}
  25635. *
  25636. * Complete the dimensions array, by user defined `dimension` and `encode`,
  25637. * and guessing from the data structure.
  25638. * If no 'value' dimension specified, the first no-named dimension will be
  25639. * named as 'value'.
  25640. *
  25641. * @param {Array.<string>} sysDims Necessary dimensions, like ['x', 'y'], which
  25642. * provides not only dim template, but also default order.
  25643. * properties: 'name', 'type', 'displayName'.
  25644. * `name` of each item provides default coord name.
  25645. * [{dimsDef: [string|Object, ...]}, ...] dimsDef of sysDim item provides default dim name, and
  25646. * provide dims count that the sysDim required.
  25647. * [{ordinalMeta}] can be specified.
  25648. * @param {module:echarts/data/Source|Array|Object} source or data (for compatibal with pervious)
  25649. * @param {Object} [opt]
  25650. * @param {Array.<Object|string>} [opt.dimsDef] option.series.dimensions User defined dimensions
  25651. * For example: ['asdf', {name, type}, ...].
  25652. * @param {Object|HashMap} [opt.encodeDef] option.series.encode {x: 2, y: [3, 1], tooltip: [1, 2], label: 3}
  25653. * @param {string} [opt.generateCoord] Generate coord dim with the given name.
  25654. * If not specified, extra dim names will be:
  25655. * 'value', 'value0', 'value1', ...
  25656. * @param {number} [opt.generateCoordCount] By default, the generated dim name is `generateCoord`.
  25657. * If `generateCoordCount` specified, the generated dim names will be:
  25658. * `generateCoord` + 0, `generateCoord` + 1, ...
  25659. * can be Infinity, indicate that use all of the remain columns.
  25660. * @param {number} [opt.dimCount] If not specified, guess by the first data item.
  25661. * @param {number} [opt.encodeDefaulter] If not specified, auto find the next available data dim.
  25662. * @return {Array.<Object>} [{
  25663. * name: string mandatory,
  25664. * displayName: string, the origin name in dimsDef, see source helper.
  25665. * If displayName given, the tooltip will displayed vertically.
  25666. * coordDim: string mandatory,
  25667. * coordDimIndex: number mandatory,
  25668. * type: string optional,
  25669. * otherDims: { never null/undefined
  25670. * tooltip: number optional,
  25671. * label: number optional,
  25672. * itemName: number optional,
  25673. * seriesName: number optional,
  25674. * },
  25675. * isExtraCoord: boolean true if coord is generated
  25676. * (not specified in encode and not series specified)
  25677. * other props ...
  25678. * }]
  25679. */
  25680. function completeDimensions(sysDims, source, opt) {
  25681. if (!Source.isInstance(source)) {
  25682. source = Source.seriesDataToSource(source);
  25683. }
  25684. opt = opt || {};
  25685. sysDims = (sysDims || []).slice();
  25686. var dimsDef = (opt.dimsDef || []).slice();
  25687. var encodeDef = createHashMap(opt.encodeDef);
  25688. var dataDimNameMap = createHashMap();
  25689. var coordDimNameMap = createHashMap();
  25690. // var valueCandidate;
  25691. var result = [];
  25692. var dimCount = getDimCount(source, sysDims, dimsDef, opt.dimCount);
  25693. // Apply user defined dims (`name` and `type`) and init result.
  25694. for (var i = 0; i < dimCount; i++) {
  25695. var dimDefItem = dimsDef[i] = extend(
  25696. {}, isObject$1(dimsDef[i]) ? dimsDef[i] : {name: dimsDef[i]}
  25697. );
  25698. var userDimName = dimDefItem.name;
  25699. var resultItem = result[i] = {otherDims: {}};
  25700. // Name will be applied later for avoiding duplication.
  25701. if (userDimName != null && dataDimNameMap.get(userDimName) == null) {
  25702. // Only if `series.dimensions` is defined in option
  25703. // displayName, will be set, and dimension will be diplayed vertically in
  25704. // tooltip by default.
  25705. resultItem.name = resultItem.displayName = userDimName;
  25706. dataDimNameMap.set(userDimName, i);
  25707. }
  25708. dimDefItem.type != null && (resultItem.type = dimDefItem.type);
  25709. dimDefItem.displayName != null && (resultItem.displayName = dimDefItem.displayName);
  25710. }
  25711. // Set `coordDim` and `coordDimIndex` by `encodeDef` and normalize `encodeDef`.
  25712. encodeDef.each(function (dataDims, coordDim) {
  25713. dataDims = normalizeToArray(dataDims).slice();
  25714. var validDataDims = encodeDef.set(coordDim, []);
  25715. each$1(dataDims, function (resultDimIdx, idx) {
  25716. // The input resultDimIdx can be dim name or index.
  25717. isString(resultDimIdx) && (resultDimIdx = dataDimNameMap.get(resultDimIdx));
  25718. if (resultDimIdx != null && resultDimIdx < dimCount) {
  25719. validDataDims[idx] = resultDimIdx;
  25720. applyDim(result[resultDimIdx], coordDim, idx);
  25721. }
  25722. });
  25723. });
  25724. // Apply templetes and default order from `sysDims`.
  25725. var availDimIdx = 0;
  25726. each$1(sysDims, function (sysDimItem, sysDimIndex) {
  25727. var coordDim;
  25728. var sysDimItem;
  25729. var sysDimItemDimsDef;
  25730. var sysDimItemOtherDims;
  25731. if (isString(sysDimItem)) {
  25732. coordDim = sysDimItem;
  25733. sysDimItem = {};
  25734. }
  25735. else {
  25736. coordDim = sysDimItem.name;
  25737. var ordinalMeta = sysDimItem.ordinalMeta;
  25738. sysDimItem.ordinalMeta = null;
  25739. sysDimItem = clone(sysDimItem);
  25740. sysDimItem.ordinalMeta = ordinalMeta;
  25741. // `coordDimIndex` should not be set directly.
  25742. sysDimItemDimsDef = sysDimItem.dimsDef;
  25743. sysDimItemOtherDims = sysDimItem.otherDims;
  25744. sysDimItem.name = sysDimItem.coordDim = sysDimItem.coordDimIndex
  25745. = sysDimItem.dimsDef = sysDimItem.otherDims = null;
  25746. }
  25747. var dataDims = normalizeToArray(encodeDef.get(coordDim));
  25748. // dimensions provides default dim sequences.
  25749. if (!dataDims.length) {
  25750. for (var i = 0; i < (sysDimItemDimsDef && sysDimItemDimsDef.length || 1); i++) {
  25751. while (availDimIdx < result.length && result[availDimIdx].coordDim != null) {
  25752. availDimIdx++;
  25753. }
  25754. availDimIdx < result.length && dataDims.push(availDimIdx++);
  25755. }
  25756. }
  25757. // Apply templates.
  25758. each$1(dataDims, function (resultDimIdx, coordDimIndex) {
  25759. var resultItem = result[resultDimIdx];
  25760. applyDim(defaults(resultItem, sysDimItem), coordDim, coordDimIndex);
  25761. if (resultItem.name == null && sysDimItemDimsDef) {
  25762. var sysDimItemDimsDefItem = sysDimItemDimsDef[coordDimIndex];
  25763. !isObject$1(sysDimItemDimsDefItem) && (sysDimItemDimsDefItem = {name: sysDimItemDimsDefItem});
  25764. resultItem.name = resultItem.displayName = sysDimItemDimsDefItem.name;
  25765. resultItem.defaultTooltip = sysDimItemDimsDefItem.defaultTooltip;
  25766. }
  25767. // FIXME refactor, currently only used in case: {otherDims: {tooltip: false}}
  25768. sysDimItemOtherDims && defaults(resultItem.otherDims, sysDimItemOtherDims);
  25769. });
  25770. });
  25771. function applyDim(resultItem, coordDim, coordDimIndex) {
  25772. if (OTHER_DIMENSIONS.get(coordDim) != null) {
  25773. resultItem.otherDims[coordDim] = coordDimIndex;
  25774. }
  25775. else {
  25776. resultItem.coordDim = coordDim;
  25777. resultItem.coordDimIndex = coordDimIndex;
  25778. coordDimNameMap.set(coordDim, true);
  25779. }
  25780. }
  25781. // Make sure the first extra dim is 'value'.
  25782. var generateCoord = opt.generateCoord;
  25783. var generateCoordCount = opt.generateCoordCount;
  25784. var fromZero = generateCoordCount != null;
  25785. generateCoordCount = generateCoord ? (generateCoordCount || 1) : 0;
  25786. var extra = generateCoord || 'value';
  25787. // Set dim `name` and other `coordDim` and other props.
  25788. for (var resultDimIdx = 0; resultDimIdx < dimCount; resultDimIdx++) {
  25789. var resultItem = result[resultDimIdx] = result[resultDimIdx] || {};
  25790. var coordDim = resultItem.coordDim;
  25791. if (coordDim == null) {
  25792. resultItem.coordDim = genName(
  25793. extra, coordDimNameMap, fromZero
  25794. );
  25795. resultItem.coordDimIndex = 0;
  25796. if (!generateCoord || generateCoordCount <= 0) {
  25797. resultItem.isExtraCoord = true;
  25798. }
  25799. generateCoordCount--;
  25800. }
  25801. resultItem.name == null && (resultItem.name = genName(
  25802. resultItem.coordDim,
  25803. dataDimNameMap
  25804. ));
  25805. if (resultItem.type == null && guessOrdinal(source, resultDimIdx, resultItem.name)) {
  25806. resultItem.type = 'ordinal';
  25807. }
  25808. }
  25809. return result;
  25810. }
  25811. // ??? TODO
  25812. // Originally detect dimCount by data[0]. Should we
  25813. // optimize it to only by sysDims and dimensions and encode.
  25814. // So only necessary dims will be initialized.
  25815. // But
  25816. // (1) custom series should be considered. where other dims
  25817. // may be visited.
  25818. // (2) sometimes user need to calcualte bubble size or use visualMap
  25819. // on other dimensions besides coordSys needed.
  25820. // So, dims that is not used by system, should be shared in storage?
  25821. function getDimCount(source, sysDims, dimsDef, optDimCount) {
  25822. // Note that the result dimCount should not small than columns count
  25823. // of data, otherwise `dataDimNameMap` checking will be incorrect.
  25824. var dimCount = Math.max(
  25825. source.dimensionsDetectCount || 1,
  25826. sysDims.length,
  25827. dimsDef.length,
  25828. optDimCount || 0
  25829. );
  25830. each$1(sysDims, function (sysDimItem) {
  25831. var sysDimItemDimsDef = sysDimItem.dimsDef;
  25832. sysDimItemDimsDef && (dimCount = Math.max(dimCount, sysDimItemDimsDef.length));
  25833. });
  25834. return dimCount;
  25835. }
  25836. function genName(name, map$$1, fromZero) {
  25837. if (fromZero || map$$1.get(name) != null) {
  25838. var i = 0;
  25839. while (map$$1.get(name + i) != null) {
  25840. i++;
  25841. }
  25842. name += i;
  25843. }
  25844. map$$1.set(name, true);
  25845. return name;
  25846. }
  25847. /*
  25848. * Licensed to the Apache Software Foundation (ASF) under one
  25849. * or more contributor license agreements. See the NOTICE file
  25850. * distributed with this work for additional information
  25851. * regarding copyright ownership. The ASF licenses this file
  25852. * to you under the Apache License, Version 2.0 (the
  25853. * "License"); you may not use this file except in compliance
  25854. * with the License. You may obtain a copy of the License at
  25855. *
  25856. * http://www.apache.org/licenses/LICENSE-2.0
  25857. *
  25858. * Unless required by applicable law or agreed to in writing,
  25859. * software distributed under the License is distributed on an
  25860. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  25861. * KIND, either express or implied. See the License for the
  25862. * specific language governing permissions and limitations
  25863. * under the License.
  25864. */
  25865. /**
  25866. * Substitute `completeDimensions`.
  25867. * `completeDimensions` is to be deprecated.
  25868. */
  25869. /**
  25870. * @param {module:echarts/data/Source|module:echarts/data/List} source or data.
  25871. * @param {Object|Array} [opt]
  25872. * @param {Array.<string|Object>} [opt.coordDimensions=[]]
  25873. * @param {number} [opt.dimensionsCount]
  25874. * @param {string} [opt.generateCoord]
  25875. * @param {string} [opt.generateCoordCount]
  25876. * @param {Array.<string|Object>} [opt.dimensionsDefine=source.dimensionsDefine] Overwrite source define.
  25877. * @param {Object|HashMap} [opt.encodeDefine=source.encodeDefine] Overwrite source define.
  25878. * @return {Array.<Object>} dimensionsInfo
  25879. */
  25880. var createDimensions = function (source, opt) {
  25881. opt = opt || {};
  25882. return completeDimensions(opt.coordDimensions || [], source, {
  25883. dimsDef: opt.dimensionsDefine || source.dimensionsDefine,
  25884. encodeDef: opt.encodeDefine || source.encodeDefine,
  25885. dimCount: opt.dimensionsCount,
  25886. generateCoord: opt.generateCoord,
  25887. generateCoordCount: opt.generateCoordCount
  25888. });
  25889. };
  25890. /*
  25891. * Licensed to the Apache Software Foundation (ASF) under one
  25892. * or more contributor license agreements. See the NOTICE file
  25893. * distributed with this work for additional information
  25894. * regarding copyright ownership. The ASF licenses this file
  25895. * to you under the Apache License, Version 2.0 (the
  25896. * "License"); you may not use this file except in compliance
  25897. * with the License. You may obtain a copy of the License at
  25898. *
  25899. * http://www.apache.org/licenses/LICENSE-2.0
  25900. *
  25901. * Unless required by applicable law or agreed to in writing,
  25902. * software distributed under the License is distributed on an
  25903. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  25904. * KIND, either express or implied. See the License for the
  25905. * specific language governing permissions and limitations
  25906. * under the License.
  25907. */
  25908. /**
  25909. * Note that it is too complicated to support 3d stack by value
  25910. * (have to create two-dimension inverted index), so in 3d case
  25911. * we just support that stacked by index.
  25912. *
  25913. * @param {module:echarts/model/Series} seriesModel
  25914. * @param {Array.<string|Object>} dimensionInfoList The same as the input of <module:echarts/data/List>.
  25915. * The input dimensionInfoList will be modified.
  25916. * @param {Object} [opt]
  25917. * @param {boolean} [opt.stackedCoordDimension=''] Specify a coord dimension if needed.
  25918. * @param {boolean} [opt.byIndex=false]
  25919. * @return {Object} calculationInfo
  25920. * {
  25921. * stackedDimension: string
  25922. * stackedByDimension: string
  25923. * isStackedByIndex: boolean
  25924. * stackedOverDimension: string
  25925. * stackResultDimension: string
  25926. * }
  25927. */
  25928. function enableDataStack(seriesModel, dimensionInfoList, opt) {
  25929. opt = opt || {};
  25930. var byIndex = opt.byIndex;
  25931. var stackedCoordDimension = opt.stackedCoordDimension;
  25932. // Compatibal: when `stack` is set as '', do not stack.
  25933. var mayStack = !!(seriesModel && seriesModel.get('stack'));
  25934. var stackedByDimInfo;
  25935. var stackedDimInfo;
  25936. var stackResultDimension;
  25937. var stackedOverDimension;
  25938. each$1(dimensionInfoList, function (dimensionInfo, index) {
  25939. if (isString(dimensionInfo)) {
  25940. dimensionInfoList[index] = dimensionInfo = {name: dimensionInfo};
  25941. }
  25942. if (mayStack && !dimensionInfo.isExtraCoord) {
  25943. // Find the first ordinal dimension as the stackedByDimInfo.
  25944. if (!byIndex && !stackedByDimInfo && dimensionInfo.ordinalMeta) {
  25945. stackedByDimInfo = dimensionInfo;
  25946. }
  25947. // Find the first stackable dimension as the stackedDimInfo.
  25948. if (!stackedDimInfo
  25949. && dimensionInfo.type !== 'ordinal'
  25950. && dimensionInfo.type !== 'time'
  25951. && (!stackedCoordDimension || stackedCoordDimension === dimensionInfo.coordDim)
  25952. ) {
  25953. stackedDimInfo = dimensionInfo;
  25954. }
  25955. }
  25956. });
  25957. // Add stack dimension, they can be both calculated by coordinate system in `unionExtent`.
  25958. // That put stack logic in List is for using conveniently in echarts extensions, but it
  25959. // might not be a good way.
  25960. if (stackedDimInfo && (byIndex || stackedByDimInfo)) {
  25961. // Use a weird name that not duplicated with other names.
  25962. stackResultDimension = '__\0ecstackresult';
  25963. stackedOverDimension = '__\0ecstackedover';
  25964. // Create inverted index to fast query index by value.
  25965. if (stackedByDimInfo) {
  25966. stackedByDimInfo.createInvertedIndices = true;
  25967. }
  25968. var stackedDimCoordDim = stackedDimInfo.coordDim;
  25969. var stackedDimType = stackedDimInfo.type;
  25970. var stackedDimCoordIndex = 0;
  25971. each$1(dimensionInfoList, function (dimensionInfo) {
  25972. if (dimensionInfo.coordDim === stackedDimCoordDim) {
  25973. stackedDimCoordIndex++;
  25974. }
  25975. });
  25976. dimensionInfoList.push({
  25977. name: stackResultDimension,
  25978. coordDim: stackedDimCoordDim,
  25979. coordDimIndex: stackedDimCoordIndex,
  25980. type: stackedDimType,
  25981. isExtraCoord: true,
  25982. isCalculationCoord: true
  25983. });
  25984. stackedDimCoordIndex++;
  25985. dimensionInfoList.push({
  25986. name: stackedOverDimension,
  25987. // This dimension contains stack base (generally, 0), so do not set it as
  25988. // `stackedDimCoordDim` to avoid extent calculation, consider log scale.
  25989. coordDim: stackedOverDimension,
  25990. coordDimIndex: stackedDimCoordIndex,
  25991. type: stackedDimType,
  25992. isExtraCoord: true,
  25993. isCalculationCoord: true
  25994. });
  25995. }
  25996. return {
  25997. stackedDimension: stackedDimInfo && stackedDimInfo.name,
  25998. stackedByDimension: stackedByDimInfo && stackedByDimInfo.name,
  25999. isStackedByIndex: byIndex,
  26000. stackedOverDimension: stackedOverDimension,
  26001. stackResultDimension: stackResultDimension
  26002. };
  26003. }
  26004. /**
  26005. * @param {module:echarts/data/List} data
  26006. * @param {string} stackedDim
  26007. * @param {string} [stackedByDim] If not input this parameter, check whether
  26008. * stacked by index.
  26009. */
  26010. function isDimensionStacked(data, stackedDim, stackedByDim) {
  26011. return stackedDim
  26012. && stackedDim === data.getCalculationInfo('stackedDimension')
  26013. && (
  26014. stackedByDim != null
  26015. ? stackedByDim === data.getCalculationInfo('stackedByDimension')
  26016. : data.getCalculationInfo('isStackedByIndex')
  26017. );
  26018. }
  26019. /*
  26020. * Licensed to the Apache Software Foundation (ASF) under one
  26021. * or more contributor license agreements. See the NOTICE file
  26022. * distributed with this work for additional information
  26023. * regarding copyright ownership. The ASF licenses this file
  26024. * to you under the Apache License, Version 2.0 (the
  26025. * "License"); you may not use this file except in compliance
  26026. * with the License. You may obtain a copy of the License at
  26027. *
  26028. * http://www.apache.org/licenses/LICENSE-2.0
  26029. *
  26030. * Unless required by applicable law or agreed to in writing,
  26031. * software distributed under the License is distributed on an
  26032. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26033. * KIND, either express or implied. See the License for the
  26034. * specific language governing permissions and limitations
  26035. * under the License.
  26036. */
  26037. /**
  26038. * @param {module:echarts/data/Source|Array} source Or raw data.
  26039. * @param {module:echarts/model/Series} seriesModel
  26040. * @param {Object} [opt]
  26041. * @param {string} [opt.generateCoord]
  26042. */
  26043. function createListFromArray(source, seriesModel, opt) {
  26044. opt = opt || {};
  26045. if (!Source.isInstance(source)) {
  26046. source = Source.seriesDataToSource(source);
  26047. }
  26048. var coordSysName = seriesModel.get('coordinateSystem');
  26049. var registeredCoordSys = CoordinateSystemManager.get(coordSysName);
  26050. var coordSysDefine = getCoordSysDefineBySeries(seriesModel);
  26051. var coordSysDimDefs;
  26052. if (coordSysDefine) {
  26053. coordSysDimDefs = map(coordSysDefine.coordSysDims, function (dim) {
  26054. var dimInfo = {name: dim};
  26055. var axisModel = coordSysDefine.axisMap.get(dim);
  26056. if (axisModel) {
  26057. var axisType = axisModel.get('type');
  26058. dimInfo.type = getDimensionTypeByAxis(axisType);
  26059. // dimInfo.stackable = isStackable(axisType);
  26060. }
  26061. return dimInfo;
  26062. });
  26063. }
  26064. if (!coordSysDimDefs) {
  26065. // Get dimensions from registered coordinate system
  26066. coordSysDimDefs = (registeredCoordSys && (
  26067. registeredCoordSys.getDimensionsInfo
  26068. ? registeredCoordSys.getDimensionsInfo()
  26069. : registeredCoordSys.dimensions.slice()
  26070. )) || ['x', 'y'];
  26071. }
  26072. var dimInfoList = createDimensions(source, {
  26073. coordDimensions: coordSysDimDefs,
  26074. generateCoord: opt.generateCoord
  26075. });
  26076. var firstCategoryDimIndex;
  26077. var hasNameEncode;
  26078. coordSysDefine && each$1(dimInfoList, function (dimInfo, dimIndex) {
  26079. var coordDim = dimInfo.coordDim;
  26080. var categoryAxisModel = coordSysDefine.categoryAxisMap.get(coordDim);
  26081. if (categoryAxisModel) {
  26082. if (firstCategoryDimIndex == null) {
  26083. firstCategoryDimIndex = dimIndex;
  26084. }
  26085. dimInfo.ordinalMeta = categoryAxisModel.getOrdinalMeta();
  26086. }
  26087. if (dimInfo.otherDims.itemName != null) {
  26088. hasNameEncode = true;
  26089. }
  26090. });
  26091. if (!hasNameEncode && firstCategoryDimIndex != null) {
  26092. dimInfoList[firstCategoryDimIndex].otherDims.itemName = 0;
  26093. }
  26094. var stackCalculationInfo = enableDataStack(seriesModel, dimInfoList);
  26095. var list = new List(dimInfoList, seriesModel);
  26096. list.setCalculationInfo(stackCalculationInfo);
  26097. var dimValueGetter = (firstCategoryDimIndex != null && isNeedCompleteOrdinalData(source))
  26098. ? function (itemOpt, dimName, dataIndex, dimIndex) {
  26099. // Use dataIndex as ordinal value in categoryAxis
  26100. return dimIndex === firstCategoryDimIndex
  26101. ? dataIndex
  26102. : this.defaultDimValueGetter(itemOpt, dimName, dataIndex, dimIndex);
  26103. }
  26104. : null;
  26105. list.hasItemOption = false;
  26106. list.initData(source, null, dimValueGetter);
  26107. return list;
  26108. }
  26109. function isNeedCompleteOrdinalData(source) {
  26110. if (source.sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  26111. var sampleItem = firstDataNotNull(source.data || []);
  26112. return sampleItem != null
  26113. && !isArray(getDataItemValue(sampleItem));
  26114. }
  26115. }
  26116. function firstDataNotNull(data) {
  26117. var i = 0;
  26118. while (i < data.length && data[i] == null) {
  26119. i++;
  26120. }
  26121. return data[i];
  26122. }
  26123. /*
  26124. * Licensed to the Apache Software Foundation (ASF) under one
  26125. * or more contributor license agreements. See the NOTICE file
  26126. * distributed with this work for additional information
  26127. * regarding copyright ownership. The ASF licenses this file
  26128. * to you under the Apache License, Version 2.0 (the
  26129. * "License"); you may not use this file except in compliance
  26130. * with the License. You may obtain a copy of the License at
  26131. *
  26132. * http://www.apache.org/licenses/LICENSE-2.0
  26133. *
  26134. * Unless required by applicable law or agreed to in writing,
  26135. * software distributed under the License is distributed on an
  26136. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26137. * KIND, either express or implied. See the License for the
  26138. * specific language governing permissions and limitations
  26139. * under the License.
  26140. */
  26141. /**
  26142. * // Scale class management
  26143. * @module echarts/scale/Scale
  26144. */
  26145. /**
  26146. * @param {Object} [setting]
  26147. */
  26148. function Scale(setting) {
  26149. this._setting = setting || {};
  26150. /**
  26151. * Extent
  26152. * @type {Array.<number>}
  26153. * @protected
  26154. */
  26155. this._extent = [Infinity, -Infinity];
  26156. /**
  26157. * Step is calculated in adjustExtent
  26158. * @type {Array.<number>}
  26159. * @protected
  26160. */
  26161. this._interval = 0;
  26162. this.init && this.init.apply(this, arguments);
  26163. }
  26164. /**
  26165. * Parse input val to valid inner number.
  26166. * @param {*} val
  26167. * @return {number}
  26168. */
  26169. Scale.prototype.parse = function (val) {
  26170. // Notice: This would be a trap here, If the implementation
  26171. // of this method depends on extent, and this method is used
  26172. // before extent set (like in dataZoom), it would be wrong.
  26173. // Nevertheless, parse does not depend on extent generally.
  26174. return val;
  26175. };
  26176. Scale.prototype.getSetting = function (name) {
  26177. return this._setting[name];
  26178. };
  26179. Scale.prototype.contain = function (val) {
  26180. var extent = this._extent;
  26181. return val >= extent[0] && val <= extent[1];
  26182. };
  26183. /**
  26184. * Normalize value to linear [0, 1], return 0.5 if extent span is 0
  26185. * @param {number} val
  26186. * @return {number}
  26187. */
  26188. Scale.prototype.normalize = function (val) {
  26189. var extent = this._extent;
  26190. if (extent[1] === extent[0]) {
  26191. return 0.5;
  26192. }
  26193. return (val - extent[0]) / (extent[1] - extent[0]);
  26194. };
  26195. /**
  26196. * Scale normalized value
  26197. * @param {number} val
  26198. * @return {number}
  26199. */
  26200. Scale.prototype.scale = function (val) {
  26201. var extent = this._extent;
  26202. return val * (extent[1] - extent[0]) + extent[0];
  26203. };
  26204. /**
  26205. * Set extent from data
  26206. * @param {Array.<number>} other
  26207. */
  26208. Scale.prototype.unionExtent = function (other) {
  26209. var extent = this._extent;
  26210. other[0] < extent[0] && (extent[0] = other[0]);
  26211. other[1] > extent[1] && (extent[1] = other[1]);
  26212. // not setExtent because in log axis it may transformed to power
  26213. // this.setExtent(extent[0], extent[1]);
  26214. };
  26215. /**
  26216. * Set extent from data
  26217. * @param {module:echarts/data/List} data
  26218. * @param {string} dim
  26219. */
  26220. Scale.prototype.unionExtentFromData = function (data, dim) {
  26221. this.unionExtent(data.getApproximateExtent(dim));
  26222. };
  26223. /**
  26224. * Get extent
  26225. * @return {Array.<number>}
  26226. */
  26227. Scale.prototype.getExtent = function () {
  26228. return this._extent.slice();
  26229. };
  26230. /**
  26231. * Set extent
  26232. * @param {number} start
  26233. * @param {number} end
  26234. */
  26235. Scale.prototype.setExtent = function (start, end) {
  26236. var thisExtent = this._extent;
  26237. if (!isNaN(start)) {
  26238. thisExtent[0] = start;
  26239. }
  26240. if (!isNaN(end)) {
  26241. thisExtent[1] = end;
  26242. }
  26243. };
  26244. /**
  26245. * When axis extent depends on data and no data exists,
  26246. * axis ticks should not be drawn, which is named 'blank'.
  26247. */
  26248. Scale.prototype.isBlank = function () {
  26249. return this._isBlank;
  26250. },
  26251. /**
  26252. * When axis extent depends on data and no data exists,
  26253. * axis ticks should not be drawn, which is named 'blank'.
  26254. */
  26255. Scale.prototype.setBlank = function (isBlank) {
  26256. this._isBlank = isBlank;
  26257. };
  26258. /**
  26259. * @abstract
  26260. * @param {*} tick
  26261. * @return {string} label of the tick.
  26262. */
  26263. Scale.prototype.getLabel = null;
  26264. enableClassExtend(Scale);
  26265. enableClassManagement(Scale, {
  26266. registerWhenExtend: true
  26267. });
  26268. /*
  26269. * Licensed to the Apache Software Foundation (ASF) under one
  26270. * or more contributor license agreements. See the NOTICE file
  26271. * distributed with this work for additional information
  26272. * regarding copyright ownership. The ASF licenses this file
  26273. * to you under the Apache License, Version 2.0 (the
  26274. * "License"); you may not use this file except in compliance
  26275. * with the License. You may obtain a copy of the License at
  26276. *
  26277. * http://www.apache.org/licenses/LICENSE-2.0
  26278. *
  26279. * Unless required by applicable law or agreed to in writing,
  26280. * software distributed under the License is distributed on an
  26281. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26282. * KIND, either express or implied. See the License for the
  26283. * specific language governing permissions and limitations
  26284. * under the License.
  26285. */
  26286. /**
  26287. * @constructor
  26288. * @param {Object} [opt]
  26289. * @param {Object} [opt.categories=[]]
  26290. * @param {Object} [opt.needCollect=false]
  26291. * @param {Object} [opt.deduplication=false]
  26292. */
  26293. function OrdinalMeta(opt) {
  26294. /**
  26295. * @readOnly
  26296. * @type {Array.<string>}
  26297. */
  26298. this.categories = opt.categories || [];
  26299. /**
  26300. * @private
  26301. * @type {boolean}
  26302. */
  26303. this._needCollect = opt.needCollect;
  26304. /**
  26305. * @private
  26306. * @type {boolean}
  26307. */
  26308. this._deduplication = opt.deduplication;
  26309. /**
  26310. * @private
  26311. * @type {boolean}
  26312. */
  26313. this._map;
  26314. }
  26315. /**
  26316. * @param {module:echarts/model/Model} axisModel
  26317. * @return {module:echarts/data/OrdinalMeta}
  26318. */
  26319. OrdinalMeta.createByAxisModel = function (axisModel) {
  26320. var option = axisModel.option;
  26321. var data = option.data;
  26322. var categories = data && map(data, getName);
  26323. return new OrdinalMeta({
  26324. categories: categories,
  26325. needCollect: !categories,
  26326. // deduplication is default in axis.
  26327. deduplication: option.dedplication !== false
  26328. });
  26329. };
  26330. var proto$1 = OrdinalMeta.prototype;
  26331. /**
  26332. * @param {string} category
  26333. * @return {number} ordinal
  26334. */
  26335. proto$1.getOrdinal = function (category) {
  26336. return getOrCreateMap(this).get(category);
  26337. };
  26338. /**
  26339. * @param {*} category
  26340. * @return {number} The ordinal. If not found, return NaN.
  26341. */
  26342. proto$1.parseAndCollect = function (category) {
  26343. var index;
  26344. var needCollect = this._needCollect;
  26345. // The value of category dim can be the index of the given category set.
  26346. // This feature is only supported when !needCollect, because we should
  26347. // consider a common case: a value is 2017, which is a number but is
  26348. // expected to be tread as a category. This case usually happen in dataset,
  26349. // where it happent to be no need of the index feature.
  26350. if (typeof category !== 'string' && !needCollect) {
  26351. return category;
  26352. }
  26353. // Optimize for the scenario:
  26354. // category is ['2012-01-01', '2012-01-02', ...], where the input
  26355. // data has been ensured not duplicate and is large data.
  26356. // Notice, if a dataset dimension provide categroies, usually echarts
  26357. // should remove duplication except user tell echarts dont do that
  26358. // (set axis.deduplication = false), because echarts do not know whether
  26359. // the values in the category dimension has duplication (consider the
  26360. // parallel-aqi example)
  26361. if (needCollect && !this._deduplication) {
  26362. index = this.categories.length;
  26363. this.categories[index] = category;
  26364. return index;
  26365. }
  26366. var map$$1 = getOrCreateMap(this);
  26367. index = map$$1.get(category);
  26368. if (index == null) {
  26369. if (needCollect) {
  26370. index = this.categories.length;
  26371. this.categories[index] = category;
  26372. map$$1.set(category, index);
  26373. }
  26374. else {
  26375. index = NaN;
  26376. }
  26377. }
  26378. return index;
  26379. };
  26380. // Consider big data, do not create map until needed.
  26381. function getOrCreateMap(ordinalMeta) {
  26382. return ordinalMeta._map || (
  26383. ordinalMeta._map = createHashMap(ordinalMeta.categories)
  26384. );
  26385. }
  26386. function getName(obj) {
  26387. if (isObject$1(obj) && obj.value != null) {
  26388. return obj.value;
  26389. }
  26390. else {
  26391. return obj + '';
  26392. }
  26393. }
  26394. /*
  26395. * Licensed to the Apache Software Foundation (ASF) under one
  26396. * or more contributor license agreements. See the NOTICE file
  26397. * distributed with this work for additional information
  26398. * regarding copyright ownership. The ASF licenses this file
  26399. * to you under the Apache License, Version 2.0 (the
  26400. * "License"); you may not use this file except in compliance
  26401. * with the License. You may obtain a copy of the License at
  26402. *
  26403. * http://www.apache.org/licenses/LICENSE-2.0
  26404. *
  26405. * Unless required by applicable law or agreed to in writing,
  26406. * software distributed under the License is distributed on an
  26407. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26408. * KIND, either express or implied. See the License for the
  26409. * specific language governing permissions and limitations
  26410. * under the License.
  26411. */
  26412. /**
  26413. * Linear continuous scale
  26414. * @module echarts/coord/scale/Ordinal
  26415. *
  26416. * http://en.wikipedia.org/wiki/Level_of_measurement
  26417. */
  26418. // FIXME only one data
  26419. var scaleProto = Scale.prototype;
  26420. var OrdinalScale = Scale.extend({
  26421. type: 'ordinal',
  26422. /**
  26423. * @param {module:echarts/data/OrdianlMeta|Array.<string>} ordinalMeta
  26424. */
  26425. init: function (ordinalMeta, extent) {
  26426. // Caution: Should not use instanceof, consider ec-extensions using
  26427. // import approach to get OrdinalMeta class.
  26428. if (!ordinalMeta || isArray(ordinalMeta)) {
  26429. ordinalMeta = new OrdinalMeta({categories: ordinalMeta});
  26430. }
  26431. this._ordinalMeta = ordinalMeta;
  26432. this._extent = extent || [0, ordinalMeta.categories.length - 1];
  26433. },
  26434. parse: function (val) {
  26435. return typeof val === 'string'
  26436. ? this._ordinalMeta.getOrdinal(val)
  26437. // val might be float.
  26438. : Math.round(val);
  26439. },
  26440. contain: function (rank) {
  26441. rank = this.parse(rank);
  26442. return scaleProto.contain.call(this, rank)
  26443. && this._ordinalMeta.categories[rank] != null;
  26444. },
  26445. /**
  26446. * Normalize given rank or name to linear [0, 1]
  26447. * @param {number|string} [val]
  26448. * @return {number}
  26449. */
  26450. normalize: function (val) {
  26451. return scaleProto.normalize.call(this, this.parse(val));
  26452. },
  26453. scale: function (val) {
  26454. return Math.round(scaleProto.scale.call(this, val));
  26455. },
  26456. /**
  26457. * @return {Array}
  26458. */
  26459. getTicks: function () {
  26460. var ticks = [];
  26461. var extent = this._extent;
  26462. var rank = extent[0];
  26463. while (rank <= extent[1]) {
  26464. ticks.push(rank);
  26465. rank++;
  26466. }
  26467. return ticks;
  26468. },
  26469. /**
  26470. * Get item on rank n
  26471. * @param {number} n
  26472. * @return {string}
  26473. */
  26474. getLabel: function (n) {
  26475. if (!this.isBlank()) {
  26476. // Note that if no data, ordinalMeta.categories is an empty array.
  26477. return this._ordinalMeta.categories[n];
  26478. }
  26479. },
  26480. /**
  26481. * @return {number}
  26482. */
  26483. count: function () {
  26484. return this._extent[1] - this._extent[0] + 1;
  26485. },
  26486. /**
  26487. * @override
  26488. */
  26489. unionExtentFromData: function (data, dim) {
  26490. this.unionExtent(data.getApproximateExtent(dim));
  26491. },
  26492. getOrdinalMeta: function () {
  26493. return this._ordinalMeta;
  26494. },
  26495. niceTicks: noop,
  26496. niceExtent: noop
  26497. });
  26498. /**
  26499. * @return {module:echarts/scale/Time}
  26500. */
  26501. OrdinalScale.create = function () {
  26502. return new OrdinalScale();
  26503. };
  26504. /*
  26505. * Licensed to the Apache Software Foundation (ASF) under one
  26506. * or more contributor license agreements. See the NOTICE file
  26507. * distributed with this work for additional information
  26508. * regarding copyright ownership. The ASF licenses this file
  26509. * to you under the Apache License, Version 2.0 (the
  26510. * "License"); you may not use this file except in compliance
  26511. * with the License. You may obtain a copy of the License at
  26512. *
  26513. * http://www.apache.org/licenses/LICENSE-2.0
  26514. *
  26515. * Unless required by applicable law or agreed to in writing,
  26516. * software distributed under the License is distributed on an
  26517. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26518. * KIND, either express or implied. See the License for the
  26519. * specific language governing permissions and limitations
  26520. * under the License.
  26521. */
  26522. /**
  26523. * For testable.
  26524. */
  26525. var roundNumber$1 = round$1;
  26526. /**
  26527. * @param {Array.<number>} extent Both extent[0] and extent[1] should be valid number.
  26528. * Should be extent[0] < extent[1].
  26529. * @param {number} splitNumber splitNumber should be >= 1.
  26530. * @param {number} [minInterval]
  26531. * @param {number} [maxInterval]
  26532. * @return {Object} {interval, intervalPrecision, niceTickExtent}
  26533. */
  26534. function intervalScaleNiceTicks(extent, splitNumber, minInterval, maxInterval) {
  26535. var result = {};
  26536. var span = extent[1] - extent[0];
  26537. var interval = result.interval = nice(span / splitNumber, true);
  26538. if (minInterval != null && interval < minInterval) {
  26539. interval = result.interval = minInterval;
  26540. }
  26541. if (maxInterval != null && interval > maxInterval) {
  26542. interval = result.interval = maxInterval;
  26543. }
  26544. // Tow more digital for tick.
  26545. var precision = result.intervalPrecision = getIntervalPrecision(interval);
  26546. // Niced extent inside original extent
  26547. var niceTickExtent = result.niceTickExtent = [
  26548. roundNumber$1(Math.ceil(extent[0] / interval) * interval, precision),
  26549. roundNumber$1(Math.floor(extent[1] / interval) * interval, precision)
  26550. ];
  26551. fixExtent(niceTickExtent, extent);
  26552. return result;
  26553. }
  26554. /**
  26555. * @param {number} interval
  26556. * @return {number} interval precision
  26557. */
  26558. function getIntervalPrecision(interval) {
  26559. // Tow more digital for tick.
  26560. return getPrecisionSafe(interval) + 2;
  26561. }
  26562. function clamp(niceTickExtent, idx, extent) {
  26563. niceTickExtent[idx] = Math.max(Math.min(niceTickExtent[idx], extent[1]), extent[0]);
  26564. }
  26565. // In some cases (e.g., splitNumber is 1), niceTickExtent may be out of extent.
  26566. function fixExtent(niceTickExtent, extent) {
  26567. !isFinite(niceTickExtent[0]) && (niceTickExtent[0] = extent[0]);
  26568. !isFinite(niceTickExtent[1]) && (niceTickExtent[1] = extent[1]);
  26569. clamp(niceTickExtent, 0, extent);
  26570. clamp(niceTickExtent, 1, extent);
  26571. if (niceTickExtent[0] > niceTickExtent[1]) {
  26572. niceTickExtent[0] = niceTickExtent[1];
  26573. }
  26574. }
  26575. function intervalScaleGetTicks(interval, extent, niceTickExtent, intervalPrecision) {
  26576. var ticks = [];
  26577. // If interval is 0, return [];
  26578. if (!interval) {
  26579. return ticks;
  26580. }
  26581. // Consider this case: using dataZoom toolbox, zoom and zoom.
  26582. var safeLimit = 10000;
  26583. if (extent[0] < niceTickExtent[0]) {
  26584. ticks.push(extent[0]);
  26585. }
  26586. var tick = niceTickExtent[0];
  26587. while (tick <= niceTickExtent[1]) {
  26588. ticks.push(tick);
  26589. // Avoid rounding error
  26590. tick = roundNumber$1(tick + interval, intervalPrecision);
  26591. if (tick === ticks[ticks.length - 1]) {
  26592. // Consider out of safe float point, e.g.,
  26593. // -3711126.9907707 + 2e-10 === -3711126.9907707
  26594. break;
  26595. }
  26596. if (ticks.length > safeLimit) {
  26597. return [];
  26598. }
  26599. }
  26600. // Consider this case: the last item of ticks is smaller
  26601. // than niceTickExtent[1] and niceTickExtent[1] === extent[1].
  26602. if (extent[1] > (ticks.length ? ticks[ticks.length - 1] : niceTickExtent[1])) {
  26603. ticks.push(extent[1]);
  26604. }
  26605. return ticks;
  26606. }
  26607. /*
  26608. * Licensed to the Apache Software Foundation (ASF) under one
  26609. * or more contributor license agreements. See the NOTICE file
  26610. * distributed with this work for additional information
  26611. * regarding copyright ownership. The ASF licenses this file
  26612. * to you under the Apache License, Version 2.0 (the
  26613. * "License"); you may not use this file except in compliance
  26614. * with the License. You may obtain a copy of the License at
  26615. *
  26616. * http://www.apache.org/licenses/LICENSE-2.0
  26617. *
  26618. * Unless required by applicable law or agreed to in writing,
  26619. * software distributed under the License is distributed on an
  26620. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26621. * KIND, either express or implied. See the License for the
  26622. * specific language governing permissions and limitations
  26623. * under the License.
  26624. */
  26625. /**
  26626. * Interval scale
  26627. * @module echarts/scale/Interval
  26628. */
  26629. var roundNumber = round$1;
  26630. /**
  26631. * @alias module:echarts/coord/scale/Interval
  26632. * @constructor
  26633. */
  26634. var IntervalScale = Scale.extend({
  26635. type: 'interval',
  26636. _interval: 0,
  26637. _intervalPrecision: 2,
  26638. setExtent: function (start, end) {
  26639. var thisExtent = this._extent;
  26640. //start,end may be a Number like '25',so...
  26641. if (!isNaN(start)) {
  26642. thisExtent[0] = parseFloat(start);
  26643. }
  26644. if (!isNaN(end)) {
  26645. thisExtent[1] = parseFloat(end);
  26646. }
  26647. },
  26648. unionExtent: function (other) {
  26649. var extent = this._extent;
  26650. other[0] < extent[0] && (extent[0] = other[0]);
  26651. other[1] > extent[1] && (extent[1] = other[1]);
  26652. // unionExtent may called by it's sub classes
  26653. IntervalScale.prototype.setExtent.call(this, extent[0], extent[1]);
  26654. },
  26655. /**
  26656. * Get interval
  26657. */
  26658. getInterval: function () {
  26659. return this._interval;
  26660. },
  26661. /**
  26662. * Set interval
  26663. */
  26664. setInterval: function (interval) {
  26665. this._interval = interval;
  26666. // Dropped auto calculated niceExtent and use user setted extent
  26667. // We assume user wan't to set both interval, min, max to get a better result
  26668. this._niceExtent = this._extent.slice();
  26669. this._intervalPrecision = getIntervalPrecision(interval);
  26670. },
  26671. /**
  26672. * @return {Array.<number>}
  26673. */
  26674. getTicks: function () {
  26675. return intervalScaleGetTicks(
  26676. this._interval, this._extent, this._niceExtent, this._intervalPrecision
  26677. );
  26678. },
  26679. /**
  26680. * @param {number} data
  26681. * @param {Object} [opt]
  26682. * @param {number|string} [opt.precision] If 'auto', use nice presision.
  26683. * @param {boolean} [opt.pad] returns 1.50 but not 1.5 if precision is 2.
  26684. * @return {string}
  26685. */
  26686. getLabel: function (data, opt) {
  26687. if (data == null) {
  26688. return '';
  26689. }
  26690. var precision = opt && opt.precision;
  26691. if (precision == null) {
  26692. precision = getPrecisionSafe(data) || 0;
  26693. }
  26694. else if (precision === 'auto') {
  26695. // Should be more precise then tick.
  26696. precision = this._intervalPrecision;
  26697. }
  26698. // (1) If `precision` is set, 12.005 should be display as '12.00500'.
  26699. // (2) Use roundNumber (toFixed) to avoid scientific notation like '3.5e-7'.
  26700. data = roundNumber(data, precision, true);
  26701. return addCommas(data);
  26702. },
  26703. /**
  26704. * Update interval and extent of intervals for nice ticks
  26705. *
  26706. * @param {number} [splitNumber = 5] Desired number of ticks
  26707. * @param {number} [minInterval]
  26708. * @param {number} [maxInterval]
  26709. */
  26710. niceTicks: function (splitNumber, minInterval, maxInterval) {
  26711. splitNumber = splitNumber || 5;
  26712. var extent = this._extent;
  26713. var span = extent[1] - extent[0];
  26714. if (!isFinite(span)) {
  26715. return;
  26716. }
  26717. // User may set axis min 0 and data are all negative
  26718. // FIXME If it needs to reverse ?
  26719. if (span < 0) {
  26720. span = -span;
  26721. extent.reverse();
  26722. }
  26723. var result = intervalScaleNiceTicks(
  26724. extent, splitNumber, minInterval, maxInterval
  26725. );
  26726. this._intervalPrecision = result.intervalPrecision;
  26727. this._interval = result.interval;
  26728. this._niceExtent = result.niceTickExtent;
  26729. },
  26730. /**
  26731. * Nice extent.
  26732. * @param {Object} opt
  26733. * @param {number} [opt.splitNumber = 5] Given approx tick number
  26734. * @param {boolean} [opt.fixMin=false]
  26735. * @param {boolean} [opt.fixMax=false]
  26736. * @param {boolean} [opt.minInterval]
  26737. * @param {boolean} [opt.maxInterval]
  26738. */
  26739. niceExtent: function (opt) {
  26740. var extent = this._extent;
  26741. // If extent start and end are same, expand them
  26742. if (extent[0] === extent[1]) {
  26743. if (extent[0] !== 0) {
  26744. // Expand extent
  26745. var expandSize = extent[0];
  26746. // In the fowllowing case
  26747. // Axis has been fixed max 100
  26748. // Plus data are all 100 and axis extent are [100, 100].
  26749. // Extend to the both side will cause expanded max is larger than fixed max.
  26750. // So only expand to the smaller side.
  26751. if (!opt.fixMax) {
  26752. extent[1] += expandSize / 2;
  26753. extent[0] -= expandSize / 2;
  26754. }
  26755. else {
  26756. extent[0] -= expandSize / 2;
  26757. }
  26758. }
  26759. else {
  26760. extent[1] = 1;
  26761. }
  26762. }
  26763. var span = extent[1] - extent[0];
  26764. // If there are no data and extent are [Infinity, -Infinity]
  26765. if (!isFinite(span)) {
  26766. extent[0] = 0;
  26767. extent[1] = 1;
  26768. }
  26769. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  26770. // var extent = this._extent;
  26771. var interval = this._interval;
  26772. if (!opt.fixMin) {
  26773. extent[0] = roundNumber(Math.floor(extent[0] / interval) * interval);
  26774. }
  26775. if (!opt.fixMax) {
  26776. extent[1] = roundNumber(Math.ceil(extent[1] / interval) * interval);
  26777. }
  26778. }
  26779. });
  26780. /**
  26781. * @return {module:echarts/scale/Time}
  26782. */
  26783. IntervalScale.create = function () {
  26784. return new IntervalScale();
  26785. };
  26786. /*
  26787. * Licensed to the Apache Software Foundation (ASF) under one
  26788. * or more contributor license agreements. See the NOTICE file
  26789. * distributed with this work for additional information
  26790. * regarding copyright ownership. The ASF licenses this file
  26791. * to you under the Apache License, Version 2.0 (the
  26792. * "License"); you may not use this file except in compliance
  26793. * with the License. You may obtain a copy of the License at
  26794. *
  26795. * http://www.apache.org/licenses/LICENSE-2.0
  26796. *
  26797. * Unless required by applicable law or agreed to in writing,
  26798. * software distributed under the License is distributed on an
  26799. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26800. * KIND, either express or implied. See the License for the
  26801. * specific language governing permissions and limitations
  26802. * under the License.
  26803. */
  26804. var STACK_PREFIX = '__ec_stack_';
  26805. var LARGE_BAR_MIN_WIDTH = 0.5;
  26806. var LargeArr = typeof Float32Array !== 'undefined' ? Float32Array : Array;
  26807. function getSeriesStackId(seriesModel) {
  26808. return seriesModel.get('stack') || STACK_PREFIX + seriesModel.seriesIndex;
  26809. }
  26810. function getAxisKey(axis) {
  26811. return axis.dim + axis.index;
  26812. }
  26813. /**
  26814. * @param {Object} opt
  26815. * @param {module:echarts/coord/Axis} opt.axis Only support category axis currently.
  26816. * @param {number} opt.count Positive interger.
  26817. * @param {number} [opt.barWidth]
  26818. * @param {number} [opt.barMaxWidth]
  26819. * @param {number} [opt.barGap]
  26820. * @param {number} [opt.barCategoryGap]
  26821. * @return {Object} {width, offset, offsetCenter} If axis.type is not 'category', return undefined.
  26822. */
  26823. function getLayoutOnAxis(opt) {
  26824. var params = [];
  26825. var baseAxis = opt.axis;
  26826. var axisKey = 'axis0';
  26827. if (baseAxis.type !== 'category') {
  26828. return;
  26829. }
  26830. var bandWidth = baseAxis.getBandWidth();
  26831. for (var i = 0; i < opt.count || 0; i++) {
  26832. params.push(defaults({
  26833. bandWidth: bandWidth,
  26834. axisKey: axisKey,
  26835. stackId: STACK_PREFIX + i
  26836. }, opt));
  26837. }
  26838. var widthAndOffsets = doCalBarWidthAndOffset(params);
  26839. var result = [];
  26840. for (var i = 0; i < opt.count; i++) {
  26841. var item = widthAndOffsets[axisKey][STACK_PREFIX + i];
  26842. item.offsetCenter = item.offset + item.width / 2;
  26843. result.push(item);
  26844. }
  26845. return result;
  26846. }
  26847. function prepareLayoutBarSeries(seriesType, ecModel) {
  26848. var seriesModels = [];
  26849. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  26850. // Check series coordinate, do layout for cartesian2d only
  26851. if (isOnCartesian(seriesModel) && !isInLargeMode(seriesModel)) {
  26852. seriesModels.push(seriesModel);
  26853. }
  26854. });
  26855. return seriesModels;
  26856. }
  26857. function makeColumnLayout(barSeries) {
  26858. var seriesInfoList = [];
  26859. each$1(barSeries, function (seriesModel) {
  26860. var data = seriesModel.getData();
  26861. var cartesian = seriesModel.coordinateSystem;
  26862. var baseAxis = cartesian.getBaseAxis();
  26863. var axisExtent = baseAxis.getExtent();
  26864. var bandWidth = baseAxis.type === 'category'
  26865. ? baseAxis.getBandWidth()
  26866. : (Math.abs(axisExtent[1] - axisExtent[0]) / data.count());
  26867. var barWidth = parsePercent$1(
  26868. seriesModel.get('barWidth'), bandWidth
  26869. );
  26870. var barMaxWidth = parsePercent$1(
  26871. seriesModel.get('barMaxWidth'), bandWidth
  26872. );
  26873. var barGap = seriesModel.get('barGap');
  26874. var barCategoryGap = seriesModel.get('barCategoryGap');
  26875. seriesInfoList.push({
  26876. bandWidth: bandWidth,
  26877. barWidth: barWidth,
  26878. barMaxWidth: barMaxWidth,
  26879. barGap: barGap,
  26880. barCategoryGap: barCategoryGap,
  26881. axisKey: getAxisKey(baseAxis),
  26882. stackId: getSeriesStackId(seriesModel)
  26883. });
  26884. });
  26885. return doCalBarWidthAndOffset(seriesInfoList);
  26886. }
  26887. function doCalBarWidthAndOffset(seriesInfoList) {
  26888. // Columns info on each category axis. Key is cartesian name
  26889. var columnsMap = {};
  26890. each$1(seriesInfoList, function (seriesInfo, idx) {
  26891. var axisKey = seriesInfo.axisKey;
  26892. var bandWidth = seriesInfo.bandWidth;
  26893. var columnsOnAxis = columnsMap[axisKey] || {
  26894. bandWidth: bandWidth,
  26895. remainedWidth: bandWidth,
  26896. autoWidthCount: 0,
  26897. categoryGap: '20%',
  26898. gap: '30%',
  26899. stacks: {}
  26900. };
  26901. var stacks = columnsOnAxis.stacks;
  26902. columnsMap[axisKey] = columnsOnAxis;
  26903. var stackId = seriesInfo.stackId;
  26904. if (!stacks[stackId]) {
  26905. columnsOnAxis.autoWidthCount++;
  26906. }
  26907. stacks[stackId] = stacks[stackId] || {
  26908. width: 0,
  26909. maxWidth: 0
  26910. };
  26911. // Caution: In a single coordinate system, these barGrid attributes
  26912. // will be shared by series. Consider that they have default values,
  26913. // only the attributes set on the last series will work.
  26914. // Do not change this fact unless there will be a break change.
  26915. // TODO
  26916. var barWidth = seriesInfo.barWidth;
  26917. if (barWidth && !stacks[stackId].width) {
  26918. // See #6312, do not restrict width.
  26919. stacks[stackId].width = barWidth;
  26920. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  26921. columnsOnAxis.remainedWidth -= barWidth;
  26922. }
  26923. var barMaxWidth = seriesInfo.barMaxWidth;
  26924. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  26925. var barGap = seriesInfo.barGap;
  26926. (barGap != null) && (columnsOnAxis.gap = barGap);
  26927. var barCategoryGap = seriesInfo.barCategoryGap;
  26928. (barCategoryGap != null) && (columnsOnAxis.categoryGap = barCategoryGap);
  26929. });
  26930. var result = {};
  26931. each$1(columnsMap, function (columnsOnAxis, coordSysName) {
  26932. result[coordSysName] = {};
  26933. var stacks = columnsOnAxis.stacks;
  26934. var bandWidth = columnsOnAxis.bandWidth;
  26935. var categoryGap = parsePercent$1(columnsOnAxis.categoryGap, bandWidth);
  26936. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  26937. var remainedWidth = columnsOnAxis.remainedWidth;
  26938. var autoWidthCount = columnsOnAxis.autoWidthCount;
  26939. var autoWidth = (remainedWidth - categoryGap)
  26940. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  26941. autoWidth = Math.max(autoWidth, 0);
  26942. // Find if any auto calculated bar exceeded maxBarWidth
  26943. each$1(stacks, function (column, stack) {
  26944. var maxWidth = column.maxWidth;
  26945. if (maxWidth && maxWidth < autoWidth) {
  26946. maxWidth = Math.min(maxWidth, remainedWidth);
  26947. if (column.width) {
  26948. maxWidth = Math.min(maxWidth, column.width);
  26949. }
  26950. remainedWidth -= maxWidth;
  26951. column.width = maxWidth;
  26952. autoWidthCount--;
  26953. }
  26954. });
  26955. // Recalculate width again
  26956. autoWidth = (remainedWidth - categoryGap)
  26957. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  26958. autoWidth = Math.max(autoWidth, 0);
  26959. var widthSum = 0;
  26960. var lastColumn;
  26961. each$1(stacks, function (column, idx) {
  26962. if (!column.width) {
  26963. column.width = autoWidth;
  26964. }
  26965. lastColumn = column;
  26966. widthSum += column.width * (1 + barGapPercent);
  26967. });
  26968. if (lastColumn) {
  26969. widthSum -= lastColumn.width * barGapPercent;
  26970. }
  26971. var offset = -widthSum / 2;
  26972. each$1(stacks, function (column, stackId) {
  26973. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  26974. offset: offset,
  26975. width: column.width
  26976. };
  26977. offset += column.width * (1 + barGapPercent);
  26978. });
  26979. });
  26980. return result;
  26981. }
  26982. /**
  26983. * @param {Object} barWidthAndOffset The result of makeColumnLayout
  26984. * @param {module:echarts/coord/Axis} axis
  26985. * @param {module:echarts/model/Series} [seriesModel] If not provided, return all.
  26986. * @return {Object} {stackId: {offset, width}} or {offset, width} if seriesModel provided.
  26987. */
  26988. function retrieveColumnLayout(barWidthAndOffset, axis, seriesModel) {
  26989. if (barWidthAndOffset && axis) {
  26990. var result = barWidthAndOffset[getAxisKey(axis)];
  26991. if (result != null && seriesModel != null) {
  26992. result = result[getSeriesStackId(seriesModel)];
  26993. }
  26994. return result;
  26995. }
  26996. }
  26997. /**
  26998. * @param {string} seriesType
  26999. * @param {module:echarts/model/Global} ecModel
  27000. */
  27001. function layout(seriesType, ecModel) {
  27002. var seriesModels = prepareLayoutBarSeries(seriesType, ecModel);
  27003. var barWidthAndOffset = makeColumnLayout(seriesModels);
  27004. var lastStackCoords = {};
  27005. each$1(seriesModels, function (seriesModel) {
  27006. var data = seriesModel.getData();
  27007. var cartesian = seriesModel.coordinateSystem;
  27008. var baseAxis = cartesian.getBaseAxis();
  27009. var stackId = getSeriesStackId(seriesModel);
  27010. var columnLayoutInfo = barWidthAndOffset[getAxisKey(baseAxis)][stackId];
  27011. var columnOffset = columnLayoutInfo.offset;
  27012. var columnWidth = columnLayoutInfo.width;
  27013. var valueAxis = cartesian.getOtherAxis(baseAxis);
  27014. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  27015. lastStackCoords[stackId] = lastStackCoords[stackId] || [];
  27016. data.setLayout({
  27017. offset: columnOffset,
  27018. size: columnWidth
  27019. });
  27020. var valueDim = data.mapDimension(valueAxis.dim);
  27021. var baseDim = data.mapDimension(baseAxis.dim);
  27022. var stacked = isDimensionStacked(data, valueDim, baseDim);
  27023. var isValueAxisH = valueAxis.isHorizontal();
  27024. var valueAxisStart = getValueAxisStart(baseAxis, valueAxis, stacked);
  27025. for (var idx = 0, len = data.count(); idx < len; idx++) {
  27026. var value = data.get(valueDim, idx);
  27027. var baseValue = data.get(baseDim, idx);
  27028. if (isNaN(value)) {
  27029. continue;
  27030. }
  27031. var sign = value >= 0 ? 'p' : 'n';
  27032. var baseCoord = valueAxisStart;
  27033. // Because of the barMinHeight, we can not use the value in
  27034. // stackResultDimension directly.
  27035. if (stacked) {
  27036. // Only ordinal axis can be stacked.
  27037. if (!lastStackCoords[stackId][baseValue]) {
  27038. lastStackCoords[stackId][baseValue] = {
  27039. p: valueAxisStart, // Positive stack
  27040. n: valueAxisStart // Negative stack
  27041. };
  27042. }
  27043. // Should also consider #4243
  27044. baseCoord = lastStackCoords[stackId][baseValue][sign];
  27045. }
  27046. var x;
  27047. var y;
  27048. var width;
  27049. var height;
  27050. if (isValueAxisH) {
  27051. var coord = cartesian.dataToPoint([value, baseValue]);
  27052. x = baseCoord;
  27053. y = coord[1] + columnOffset;
  27054. width = coord[0] - valueAxisStart;
  27055. height = columnWidth;
  27056. if (Math.abs(width) < barMinHeight) {
  27057. width = (width < 0 ? -1 : 1) * barMinHeight;
  27058. }
  27059. stacked && (lastStackCoords[stackId][baseValue][sign] += width);
  27060. }
  27061. else {
  27062. var coord = cartesian.dataToPoint([baseValue, value]);
  27063. x = coord[0] + columnOffset;
  27064. y = baseCoord;
  27065. width = columnWidth;
  27066. height = coord[1] - valueAxisStart;
  27067. if (Math.abs(height) < barMinHeight) {
  27068. // Include zero to has a positive bar
  27069. height = (height <= 0 ? -1 : 1) * barMinHeight;
  27070. }
  27071. stacked && (lastStackCoords[stackId][baseValue][sign] += height);
  27072. }
  27073. data.setItemLayout(idx, {
  27074. x: x,
  27075. y: y,
  27076. width: width,
  27077. height: height
  27078. });
  27079. }
  27080. }, this);
  27081. }
  27082. // TODO: Do not support stack in large mode yet.
  27083. var largeLayout = {
  27084. seriesType: 'bar',
  27085. plan: createRenderPlanner(),
  27086. reset: function (seriesModel) {
  27087. if (!isOnCartesian(seriesModel) || !isInLargeMode(seriesModel)) {
  27088. return;
  27089. }
  27090. var data = seriesModel.getData();
  27091. var cartesian = seriesModel.coordinateSystem;
  27092. var baseAxis = cartesian.getBaseAxis();
  27093. var valueAxis = cartesian.getOtherAxis(baseAxis);
  27094. var valueDim = data.mapDimension(valueAxis.dim);
  27095. var baseDim = data.mapDimension(baseAxis.dim);
  27096. var valueAxisHorizontal = valueAxis.isHorizontal();
  27097. var valueDimIdx = valueAxisHorizontal ? 0 : 1;
  27098. var barWidth = retrieveColumnLayout(
  27099. makeColumnLayout([seriesModel]), baseAxis, seriesModel
  27100. ).width;
  27101. if (!(barWidth > LARGE_BAR_MIN_WIDTH)) { // jshint ignore:line
  27102. barWidth = LARGE_BAR_MIN_WIDTH;
  27103. }
  27104. return {progress: progress};
  27105. function progress(params, data) {
  27106. var largePoints = new LargeArr(params.count * 2);
  27107. var dataIndex;
  27108. var coord = [];
  27109. var valuePair = [];
  27110. var offset = 0;
  27111. while ((dataIndex = params.next()) != null) {
  27112. valuePair[valueDimIdx] = data.get(valueDim, dataIndex);
  27113. valuePair[1 - valueDimIdx] = data.get(baseDim, dataIndex);
  27114. coord = cartesian.dataToPoint(valuePair, null, coord);
  27115. largePoints[offset++] = coord[0];
  27116. largePoints[offset++] = coord[1];
  27117. }
  27118. data.setLayout({
  27119. largePoints: largePoints,
  27120. barWidth: barWidth,
  27121. valueAxisStart: getValueAxisStart(baseAxis, valueAxis, false),
  27122. valueAxisHorizontal: valueAxisHorizontal
  27123. });
  27124. }
  27125. }
  27126. };
  27127. function isOnCartesian(seriesModel) {
  27128. return seriesModel.coordinateSystem && seriesModel.coordinateSystem.type === 'cartesian2d';
  27129. }
  27130. function isInLargeMode(seriesModel) {
  27131. return seriesModel.pipelineContext && seriesModel.pipelineContext.large;
  27132. }
  27133. function getValueAxisStart(baseAxis, valueAxis, stacked) {
  27134. return (
  27135. indexOf(baseAxis.getAxesOnZeroOf(), valueAxis) >= 0
  27136. || stacked
  27137. )
  27138. ? valueAxis.toGlobalCoord(valueAxis.dataToCoord(0))
  27139. : valueAxis.getGlobalExtent()[0];
  27140. }
  27141. /*
  27142. * Licensed to the Apache Software Foundation (ASF) under one
  27143. * or more contributor license agreements. See the NOTICE file
  27144. * distributed with this work for additional information
  27145. * regarding copyright ownership. The ASF licenses this file
  27146. * to you under the Apache License, Version 2.0 (the
  27147. * "License"); you may not use this file except in compliance
  27148. * with the License. You may obtain a copy of the License at
  27149. *
  27150. * http://www.apache.org/licenses/LICENSE-2.0
  27151. *
  27152. * Unless required by applicable law or agreed to in writing,
  27153. * software distributed under the License is distributed on an
  27154. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27155. * KIND, either express or implied. See the License for the
  27156. * specific language governing permissions and limitations
  27157. * under the License.
  27158. */
  27159. // [About UTC and local time zone]:
  27160. // In most cases, `number.parseDate` will treat input data string as local time
  27161. // (except time zone is specified in time string). And `format.formateTime` returns
  27162. // local time by default. option.useUTC is false by default. This design have
  27163. // concidered these common case:
  27164. // (1) Time that is persistent in server is in UTC, but it is needed to be diplayed
  27165. // in local time by default.
  27166. // (2) By default, the input data string (e.g., '2011-01-02') should be displayed
  27167. // as its original time, without any time difference.
  27168. var intervalScaleProto = IntervalScale.prototype;
  27169. var mathCeil = Math.ceil;
  27170. var mathFloor = Math.floor;
  27171. var ONE_SECOND = 1000;
  27172. var ONE_MINUTE = ONE_SECOND * 60;
  27173. var ONE_HOUR = ONE_MINUTE * 60;
  27174. var ONE_DAY = ONE_HOUR * 24;
  27175. // FIXME 公用?
  27176. var bisect = function (a, x, lo, hi) {
  27177. while (lo < hi) {
  27178. var mid = lo + hi >>> 1;
  27179. if (a[mid][1] < x) {
  27180. lo = mid + 1;
  27181. }
  27182. else {
  27183. hi = mid;
  27184. }
  27185. }
  27186. return lo;
  27187. };
  27188. /**
  27189. * @alias module:echarts/coord/scale/Time
  27190. * @constructor
  27191. */
  27192. var TimeScale = IntervalScale.extend({
  27193. type: 'time',
  27194. /**
  27195. * @override
  27196. */
  27197. getLabel: function (val) {
  27198. var stepLvl = this._stepLvl;
  27199. var date = new Date(val);
  27200. return formatTime(stepLvl[0], date, this.getSetting('useUTC'));
  27201. },
  27202. /**
  27203. * @override
  27204. */
  27205. niceExtent: function (opt) {
  27206. var extent = this._extent;
  27207. // If extent start and end are same, expand them
  27208. if (extent[0] === extent[1]) {
  27209. // Expand extent
  27210. extent[0] -= ONE_DAY;
  27211. extent[1] += ONE_DAY;
  27212. }
  27213. // If there are no data and extent are [Infinity, -Infinity]
  27214. if (extent[1] === -Infinity && extent[0] === Infinity) {
  27215. var d = new Date();
  27216. extent[1] = +new Date(d.getFullYear(), d.getMonth(), d.getDate());
  27217. extent[0] = extent[1] - ONE_DAY;
  27218. }
  27219. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  27220. // var extent = this._extent;
  27221. var interval = this._interval;
  27222. if (!opt.fixMin) {
  27223. extent[0] = round$1(mathFloor(extent[0] / interval) * interval);
  27224. }
  27225. if (!opt.fixMax) {
  27226. extent[1] = round$1(mathCeil(extent[1] / interval) * interval);
  27227. }
  27228. },
  27229. /**
  27230. * @override
  27231. */
  27232. niceTicks: function (approxTickNum, minInterval, maxInterval) {
  27233. approxTickNum = approxTickNum || 10;
  27234. var extent = this._extent;
  27235. var span = extent[1] - extent[0];
  27236. var approxInterval = span / approxTickNum;
  27237. if (minInterval != null && approxInterval < minInterval) {
  27238. approxInterval = minInterval;
  27239. }
  27240. if (maxInterval != null && approxInterval > maxInterval) {
  27241. approxInterval = maxInterval;
  27242. }
  27243. var scaleLevelsLen = scaleLevels.length;
  27244. var idx = bisect(scaleLevels, approxInterval, 0, scaleLevelsLen);
  27245. var level = scaleLevels[Math.min(idx, scaleLevelsLen - 1)];
  27246. var interval = level[1];
  27247. // Same with interval scale if span is much larger than 1 year
  27248. if (level[0] === 'year') {
  27249. var yearSpan = span / interval;
  27250. // From "Nice Numbers for Graph Labels" of Graphic Gems
  27251. // var niceYearSpan = numberUtil.nice(yearSpan, false);
  27252. var yearStep = nice(yearSpan / approxTickNum, true);
  27253. interval *= yearStep;
  27254. }
  27255. var timezoneOffset = this.getSetting('useUTC')
  27256. ? 0 : (new Date(+extent[0] || +extent[1])).getTimezoneOffset() * 60 * 1000;
  27257. var niceExtent = [
  27258. Math.round(mathCeil((extent[0] - timezoneOffset) / interval) * interval + timezoneOffset),
  27259. Math.round(mathFloor((extent[1] - timezoneOffset) / interval) * interval + timezoneOffset)
  27260. ];
  27261. fixExtent(niceExtent, extent);
  27262. this._stepLvl = level;
  27263. // Interval will be used in getTicks
  27264. this._interval = interval;
  27265. this._niceExtent = niceExtent;
  27266. },
  27267. parse: function (val) {
  27268. // val might be float.
  27269. return +parseDate(val);
  27270. }
  27271. });
  27272. each$1(['contain', 'normalize'], function (methodName) {
  27273. TimeScale.prototype[methodName] = function (val) {
  27274. return intervalScaleProto[methodName].call(this, this.parse(val));
  27275. };
  27276. });
  27277. // Steps from d3
  27278. var scaleLevels = [
  27279. // Format interval
  27280. ['hh:mm:ss', ONE_SECOND], // 1s
  27281. ['hh:mm:ss', ONE_SECOND * 5], // 5s
  27282. ['hh:mm:ss', ONE_SECOND * 10], // 10s
  27283. ['hh:mm:ss', ONE_SECOND * 15], // 15s
  27284. ['hh:mm:ss', ONE_SECOND * 30], // 30s
  27285. ['hh:mm\nMM-dd', ONE_MINUTE], // 1m
  27286. ['hh:mm\nMM-dd', ONE_MINUTE * 5], // 5m
  27287. ['hh:mm\nMM-dd', ONE_MINUTE * 10], // 10m
  27288. ['hh:mm\nMM-dd', ONE_MINUTE * 15], // 15m
  27289. ['hh:mm\nMM-dd', ONE_MINUTE * 30], // 30m
  27290. ['hh:mm\nMM-dd', ONE_HOUR], // 1h
  27291. ['hh:mm\nMM-dd', ONE_HOUR * 2], // 2h
  27292. ['hh:mm\nMM-dd', ONE_HOUR * 6], // 6h
  27293. ['hh:mm\nMM-dd', ONE_HOUR * 12], // 12h
  27294. ['MM-dd\nyyyy', ONE_DAY], // 1d
  27295. ['MM-dd\nyyyy', ONE_DAY * 2], // 2d
  27296. ['MM-dd\nyyyy', ONE_DAY * 3], // 3d
  27297. ['MM-dd\nyyyy', ONE_DAY * 4], // 4d
  27298. ['MM-dd\nyyyy', ONE_DAY * 5], // 5d
  27299. ['MM-dd\nyyyy', ONE_DAY * 6], // 6d
  27300. ['week', ONE_DAY * 7], // 7d
  27301. ['MM-dd\nyyyy', ONE_DAY * 10], // 10d
  27302. ['week', ONE_DAY * 14], // 2w
  27303. ['week', ONE_DAY * 21], // 3w
  27304. ['month', ONE_DAY * 31], // 1M
  27305. ['week', ONE_DAY * 42], // 6w
  27306. ['month', ONE_DAY * 62], // 2M
  27307. ['week', ONE_DAY * 42], // 10w
  27308. ['quarter', ONE_DAY * 380 / 4], // 3M
  27309. ['month', ONE_DAY * 31 * 4], // 4M
  27310. ['month', ONE_DAY * 31 * 5], // 5M
  27311. ['half-year', ONE_DAY * 380 / 2], // 6M
  27312. ['month', ONE_DAY * 31 * 8], // 8M
  27313. ['month', ONE_DAY * 31 * 10], // 10M
  27314. ['year', ONE_DAY * 380] // 1Y
  27315. ];
  27316. /**
  27317. * @param {module:echarts/model/Model}
  27318. * @return {module:echarts/scale/Time}
  27319. */
  27320. TimeScale.create = function (model) {
  27321. return new TimeScale({useUTC: model.ecModel.get('useUTC')});
  27322. };
  27323. /*
  27324. * Licensed to the Apache Software Foundation (ASF) under one
  27325. * or more contributor license agreements. See the NOTICE file
  27326. * distributed with this work for additional information
  27327. * regarding copyright ownership. The ASF licenses this file
  27328. * to you under the Apache License, Version 2.0 (the
  27329. * "License"); you may not use this file except in compliance
  27330. * with the License. You may obtain a copy of the License at
  27331. *
  27332. * http://www.apache.org/licenses/LICENSE-2.0
  27333. *
  27334. * Unless required by applicable law or agreed to in writing,
  27335. * software distributed under the License is distributed on an
  27336. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27337. * KIND, either express or implied. See the License for the
  27338. * specific language governing permissions and limitations
  27339. * under the License.
  27340. */
  27341. /**
  27342. * Log scale
  27343. * @module echarts/scale/Log
  27344. */
  27345. // Use some method of IntervalScale
  27346. var scaleProto$1 = Scale.prototype;
  27347. var intervalScaleProto$1 = IntervalScale.prototype;
  27348. var getPrecisionSafe$1 = getPrecisionSafe;
  27349. var roundingErrorFix = round$1;
  27350. var mathFloor$1 = Math.floor;
  27351. var mathCeil$1 = Math.ceil;
  27352. var mathPow$1 = Math.pow;
  27353. var mathLog = Math.log;
  27354. var LogScale = Scale.extend({
  27355. type: 'log',
  27356. base: 10,
  27357. $constructor: function () {
  27358. Scale.apply(this, arguments);
  27359. this._originalScale = new IntervalScale();
  27360. },
  27361. /**
  27362. * @return {Array.<number>}
  27363. */
  27364. getTicks: function () {
  27365. var originalScale = this._originalScale;
  27366. var extent = this._extent;
  27367. var originalExtent = originalScale.getExtent();
  27368. return map(intervalScaleProto$1.getTicks.call(this), function (val) {
  27369. var powVal = round$1(mathPow$1(this.base, val));
  27370. // Fix #4158
  27371. powVal = (val === extent[0] && originalScale.__fixMin)
  27372. ? fixRoundingError(powVal, originalExtent[0])
  27373. : powVal;
  27374. powVal = (val === extent[1] && originalScale.__fixMax)
  27375. ? fixRoundingError(powVal, originalExtent[1])
  27376. : powVal;
  27377. return powVal;
  27378. }, this);
  27379. },
  27380. /**
  27381. * @param {number} val
  27382. * @return {string}
  27383. */
  27384. getLabel: intervalScaleProto$1.getLabel,
  27385. /**
  27386. * @param {number} val
  27387. * @return {number}
  27388. */
  27389. scale: function (val) {
  27390. val = scaleProto$1.scale.call(this, val);
  27391. return mathPow$1(this.base, val);
  27392. },
  27393. /**
  27394. * @param {number} start
  27395. * @param {number} end
  27396. */
  27397. setExtent: function (start, end) {
  27398. var base = this.base;
  27399. start = mathLog(start) / mathLog(base);
  27400. end = mathLog(end) / mathLog(base);
  27401. intervalScaleProto$1.setExtent.call(this, start, end);
  27402. },
  27403. /**
  27404. * @return {number} end
  27405. */
  27406. getExtent: function () {
  27407. var base = this.base;
  27408. var extent = scaleProto$1.getExtent.call(this);
  27409. extent[0] = mathPow$1(base, extent[0]);
  27410. extent[1] = mathPow$1(base, extent[1]);
  27411. // Fix #4158
  27412. var originalScale = this._originalScale;
  27413. var originalExtent = originalScale.getExtent();
  27414. originalScale.__fixMin && (extent[0] = fixRoundingError(extent[0], originalExtent[0]));
  27415. originalScale.__fixMax && (extent[1] = fixRoundingError(extent[1], originalExtent[1]));
  27416. return extent;
  27417. },
  27418. /**
  27419. * @param {Array.<number>} extent
  27420. */
  27421. unionExtent: function (extent) {
  27422. this._originalScale.unionExtent(extent);
  27423. var base = this.base;
  27424. extent[0] = mathLog(extent[0]) / mathLog(base);
  27425. extent[1] = mathLog(extent[1]) / mathLog(base);
  27426. scaleProto$1.unionExtent.call(this, extent);
  27427. },
  27428. /**
  27429. * @override
  27430. */
  27431. unionExtentFromData: function (data, dim) {
  27432. // TODO
  27433. // filter value that <= 0
  27434. this.unionExtent(data.getApproximateExtent(dim));
  27435. },
  27436. /**
  27437. * Update interval and extent of intervals for nice ticks
  27438. * @param {number} [approxTickNum = 10] Given approx tick number
  27439. */
  27440. niceTicks: function (approxTickNum) {
  27441. approxTickNum = approxTickNum || 10;
  27442. var extent = this._extent;
  27443. var span = extent[1] - extent[0];
  27444. if (span === Infinity || span <= 0) {
  27445. return;
  27446. }
  27447. var interval = quantity(span);
  27448. var err = approxTickNum / span * interval;
  27449. // Filter ticks to get closer to the desired count.
  27450. if (err <= 0.5) {
  27451. interval *= 10;
  27452. }
  27453. // Interval should be integer
  27454. while (!isNaN(interval) && Math.abs(interval) < 1 && Math.abs(interval) > 0) {
  27455. interval *= 10;
  27456. }
  27457. var niceExtent = [
  27458. round$1(mathCeil$1(extent[0] / interval) * interval),
  27459. round$1(mathFloor$1(extent[1] / interval) * interval)
  27460. ];
  27461. this._interval = interval;
  27462. this._niceExtent = niceExtent;
  27463. },
  27464. /**
  27465. * Nice extent.
  27466. * @override
  27467. */
  27468. niceExtent: function (opt) {
  27469. intervalScaleProto$1.niceExtent.call(this, opt);
  27470. var originalScale = this._originalScale;
  27471. originalScale.__fixMin = opt.fixMin;
  27472. originalScale.__fixMax = opt.fixMax;
  27473. }
  27474. });
  27475. each$1(['contain', 'normalize'], function (methodName) {
  27476. LogScale.prototype[methodName] = function (val) {
  27477. val = mathLog(val) / mathLog(this.base);
  27478. return scaleProto$1[methodName].call(this, val);
  27479. };
  27480. });
  27481. LogScale.create = function () {
  27482. return new LogScale();
  27483. };
  27484. function fixRoundingError(val, originalVal) {
  27485. return roundingErrorFix(val, getPrecisionSafe$1(originalVal));
  27486. }
  27487. /*
  27488. * Licensed to the Apache Software Foundation (ASF) under one
  27489. * or more contributor license agreements. See the NOTICE file
  27490. * distributed with this work for additional information
  27491. * regarding copyright ownership. The ASF licenses this file
  27492. * to you under the Apache License, Version 2.0 (the
  27493. * "License"); you may not use this file except in compliance
  27494. * with the License. You may obtain a copy of the License at
  27495. *
  27496. * http://www.apache.org/licenses/LICENSE-2.0
  27497. *
  27498. * Unless required by applicable law or agreed to in writing,
  27499. * software distributed under the License is distributed on an
  27500. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27501. * KIND, either express or implied. See the License for the
  27502. * specific language governing permissions and limitations
  27503. * under the License.
  27504. */
  27505. /**
  27506. * Get axis scale extent before niced.
  27507. * Item of returned array can only be number (including Infinity and NaN).
  27508. */
  27509. function getScaleExtent(scale, model) {
  27510. var scaleType = scale.type;
  27511. var min = model.getMin();
  27512. var max = model.getMax();
  27513. var fixMin = min != null;
  27514. var fixMax = max != null;
  27515. var originalExtent = scale.getExtent();
  27516. var axisDataLen;
  27517. var boundaryGap;
  27518. var span;
  27519. if (scaleType === 'ordinal') {
  27520. axisDataLen = model.getCategories().length;
  27521. }
  27522. else {
  27523. boundaryGap = model.get('boundaryGap');
  27524. if (!isArray(boundaryGap)) {
  27525. boundaryGap = [boundaryGap || 0, boundaryGap || 0];
  27526. }
  27527. if (typeof boundaryGap[0] === 'boolean') {
  27528. if (__DEV__) {
  27529. console.warn('Boolean type for boundaryGap is only '
  27530. + 'allowed for ordinal axis. Please use string in '
  27531. + 'percentage instead, e.g., "20%". Currently, '
  27532. + 'boundaryGap is set to be 0.');
  27533. }
  27534. boundaryGap = [0, 0];
  27535. }
  27536. boundaryGap[0] = parsePercent$1(boundaryGap[0], 1);
  27537. boundaryGap[1] = parsePercent$1(boundaryGap[1], 1);
  27538. span = (originalExtent[1] - originalExtent[0])
  27539. || Math.abs(originalExtent[0]);
  27540. }
  27541. // Notice: When min/max is not set (that is, when there are null/undefined,
  27542. // which is the most common case), these cases should be ensured:
  27543. // (1) For 'ordinal', show all axis.data.
  27544. // (2) For others:
  27545. // + `boundaryGap` is applied (if min/max set, boundaryGap is
  27546. // disabled).
  27547. // + If `needCrossZero`, min/max should be zero, otherwise, min/max should
  27548. // be the result that originalExtent enlarged by boundaryGap.
  27549. // (3) If no data, it should be ensured that `scale.setBlank` is set.
  27550. // FIXME
  27551. // (1) When min/max is 'dataMin' or 'dataMax', should boundaryGap be able to used?
  27552. // (2) When `needCrossZero` and all data is positive/negative, should it be ensured
  27553. // that the results processed by boundaryGap are positive/negative?
  27554. if (min == null) {
  27555. min = scaleType === 'ordinal'
  27556. ? (axisDataLen ? 0 : NaN)
  27557. : originalExtent[0] - boundaryGap[0] * span;
  27558. }
  27559. if (max == null) {
  27560. max = scaleType === 'ordinal'
  27561. ? (axisDataLen ? axisDataLen - 1 : NaN)
  27562. : originalExtent[1] + boundaryGap[1] * span;
  27563. }
  27564. if (min === 'dataMin') {
  27565. min = originalExtent[0];
  27566. }
  27567. else if (typeof min === 'function') {
  27568. min = min({
  27569. min: originalExtent[0],
  27570. max: originalExtent[1]
  27571. });
  27572. }
  27573. if (max === 'dataMax') {
  27574. max = originalExtent[1];
  27575. }
  27576. else if (typeof max === 'function') {
  27577. max = max({
  27578. min: originalExtent[0],
  27579. max: originalExtent[1]
  27580. });
  27581. }
  27582. (min == null || !isFinite(min)) && (min = NaN);
  27583. (max == null || !isFinite(max)) && (max = NaN);
  27584. scale.setBlank(
  27585. eqNaN(min)
  27586. || eqNaN(max)
  27587. || (scaleType === 'ordinal' && !scale.getOrdinalMeta().categories.length)
  27588. );
  27589. // Evaluate if axis needs cross zero
  27590. if (model.getNeedCrossZero()) {
  27591. // Axis is over zero and min is not set
  27592. if (min > 0 && max > 0 && !fixMin) {
  27593. min = 0;
  27594. }
  27595. // Axis is under zero and max is not set
  27596. if (min < 0 && max < 0 && !fixMax) {
  27597. max = 0;
  27598. }
  27599. }
  27600. // If bars are placed on a base axis of type time or interval account for axis boundary overflow and current axis
  27601. // is base axis
  27602. // FIXME
  27603. // (1) Consider support value axis, where below zero and axis `onZero` should be handled properly.
  27604. // (2) Refactor the logic with `barGrid`. Is it not need to `makeBarWidthAndOffsetInfo` twice with different extent?
  27605. // Should not depend on series type `bar`?
  27606. // (3) Fix that might overlap when using dataZoom.
  27607. // (4) Consider other chart types using `barGrid`?
  27608. // See #6728, #4862, `test/bar-overflow-time-plot.html`
  27609. var ecModel = model.ecModel;
  27610. if (ecModel && (scaleType === 'time' /*|| scaleType === 'interval' */)) {
  27611. var barSeriesModels = prepareLayoutBarSeries('bar', ecModel);
  27612. var isBaseAxisAndHasBarSeries;
  27613. each$1(barSeriesModels, function (seriesModel) {
  27614. isBaseAxisAndHasBarSeries |= seriesModel.getBaseAxis() === model.axis;
  27615. });
  27616. if (isBaseAxisAndHasBarSeries) {
  27617. // Calculate placement of bars on axis
  27618. var barWidthAndOffset = makeColumnLayout(barSeriesModels);
  27619. // Adjust axis min and max to account for overflow
  27620. var adjustedScale = adjustScaleForOverflow(min, max, model, barWidthAndOffset);
  27621. min = adjustedScale.min;
  27622. max = adjustedScale.max;
  27623. }
  27624. }
  27625. return [min, max];
  27626. }
  27627. function adjustScaleForOverflow(min, max, model, barWidthAndOffset) {
  27628. // Get Axis Length
  27629. var axisExtent = model.axis.getExtent();
  27630. var axisLength = axisExtent[1] - axisExtent[0];
  27631. // Get bars on current base axis and calculate min and max overflow
  27632. var barsOnCurrentAxis = retrieveColumnLayout(barWidthAndOffset, model.axis);
  27633. if (barsOnCurrentAxis === undefined) {
  27634. return {min: min, max: max};
  27635. }
  27636. var minOverflow = Infinity;
  27637. each$1(barsOnCurrentAxis, function (item) {
  27638. minOverflow = Math.min(item.offset, minOverflow);
  27639. });
  27640. var maxOverflow = -Infinity;
  27641. each$1(barsOnCurrentAxis, function (item) {
  27642. maxOverflow = Math.max(item.offset + item.width, maxOverflow);
  27643. });
  27644. minOverflow = Math.abs(minOverflow);
  27645. maxOverflow = Math.abs(maxOverflow);
  27646. var totalOverFlow = minOverflow + maxOverflow;
  27647. // Calulate required buffer based on old range and overflow
  27648. var oldRange = max - min;
  27649. var oldRangePercentOfNew = (1 - (minOverflow + maxOverflow) / axisLength);
  27650. var overflowBuffer = ((oldRange / oldRangePercentOfNew) - oldRange);
  27651. max += overflowBuffer * (maxOverflow / totalOverFlow);
  27652. min -= overflowBuffer * (minOverflow / totalOverFlow);
  27653. return {min: min, max: max};
  27654. }
  27655. function niceScaleExtent(scale, model) {
  27656. var extent = getScaleExtent(scale, model);
  27657. var fixMin = model.getMin() != null;
  27658. var fixMax = model.getMax() != null;
  27659. var splitNumber = model.get('splitNumber');
  27660. if (scale.type === 'log') {
  27661. scale.base = model.get('logBase');
  27662. }
  27663. var scaleType = scale.type;
  27664. scale.setExtent(extent[0], extent[1]);
  27665. scale.niceExtent({
  27666. splitNumber: splitNumber,
  27667. fixMin: fixMin,
  27668. fixMax: fixMax,
  27669. minInterval: (scaleType === 'interval' || scaleType === 'time')
  27670. ? model.get('minInterval') : null,
  27671. maxInterval: (scaleType === 'interval' || scaleType === 'time')
  27672. ? model.get('maxInterval') : null
  27673. });
  27674. // If some one specified the min, max. And the default calculated interval
  27675. // is not good enough. He can specify the interval. It is often appeared
  27676. // in angle axis with angle 0 - 360. Interval calculated in interval scale is hard
  27677. // to be 60.
  27678. // FIXME
  27679. var interval = model.get('interval');
  27680. if (interval != null) {
  27681. scale.setInterval && scale.setInterval(interval);
  27682. }
  27683. }
  27684. /**
  27685. * @param {module:echarts/model/Model} model
  27686. * @param {string} [axisType] Default retrieve from model.type
  27687. * @return {module:echarts/scale/*}
  27688. */
  27689. function createScaleByModel(model, axisType) {
  27690. axisType = axisType || model.get('type');
  27691. if (axisType) {
  27692. switch (axisType) {
  27693. // Buildin scale
  27694. case 'category':
  27695. return new OrdinalScale(
  27696. model.getOrdinalMeta
  27697. ? model.getOrdinalMeta()
  27698. : model.getCategories(),
  27699. [Infinity, -Infinity]
  27700. );
  27701. case 'value':
  27702. return new IntervalScale();
  27703. // Extended scale, like time and log
  27704. default:
  27705. return (Scale.getClass(axisType) || IntervalScale).create(model);
  27706. }
  27707. }
  27708. }
  27709. /**
  27710. * Check if the axis corss 0
  27711. */
  27712. function ifAxisCrossZero(axis) {
  27713. var dataExtent = axis.scale.getExtent();
  27714. var min = dataExtent[0];
  27715. var max = dataExtent[1];
  27716. return !((min > 0 && max > 0) || (min < 0 && max < 0));
  27717. }
  27718. /**
  27719. * @param {module:echarts/coord/Axis} axis
  27720. * @return {Function} Label formatter function.
  27721. * param: {number} tickValue,
  27722. * param: {number} idx, the index in all ticks.
  27723. * If category axis, this param is not requied.
  27724. * return: {string} label string.
  27725. */
  27726. function makeLabelFormatter(axis) {
  27727. var labelFormatter = axis.getLabelModel().get('formatter');
  27728. var categoryTickStart = axis.type === 'category' ? axis.scale.getExtent()[0] : null;
  27729. if (typeof labelFormatter === 'string') {
  27730. labelFormatter = (function (tpl) {
  27731. return function (val) {
  27732. return tpl.replace('{value}', val != null ? val : '');
  27733. };
  27734. })(labelFormatter);
  27735. // Consider empty array
  27736. return labelFormatter;
  27737. }
  27738. else if (typeof labelFormatter === 'function') {
  27739. return function (tickValue, idx) {
  27740. // The original intention of `idx` is "the index of the tick in all ticks".
  27741. // But the previous implementation of category axis do not consider the
  27742. // `axisLabel.interval`, which cause that, for example, the `interval` is
  27743. // `1`, then the ticks "name5", "name7", "name9" are displayed, where the
  27744. // corresponding `idx` are `0`, `2`, `4`, but not `0`, `1`, `2`. So we keep
  27745. // the definition here for back compatibility.
  27746. if (categoryTickStart != null) {
  27747. idx = tickValue - categoryTickStart;
  27748. }
  27749. return labelFormatter(getAxisRawValue(axis, tickValue), idx);
  27750. };
  27751. }
  27752. else {
  27753. return function (tick) {
  27754. return axis.scale.getLabel(tick);
  27755. };
  27756. }
  27757. }
  27758. function getAxisRawValue(axis, value) {
  27759. // In category axis with data zoom, tick is not the original
  27760. // index of axis.data. So tick should not be exposed to user
  27761. // in category axis.
  27762. return axis.type === 'category' ? axis.scale.getLabel(value) : value;
  27763. }
  27764. /**
  27765. * @param {module:echarts/coord/Axis} axis
  27766. * @return {module:zrender/core/BoundingRect} Be null/undefined if no labels.
  27767. */
  27768. function estimateLabelUnionRect(axis) {
  27769. var axisModel = axis.model;
  27770. var scale = axis.scale;
  27771. if (!axisModel.get('axisLabel.show') || scale.isBlank()) {
  27772. return;
  27773. }
  27774. var isCategory = axis.type === 'category';
  27775. var realNumberScaleTicks;
  27776. var tickCount;
  27777. var categoryScaleExtent = scale.getExtent();
  27778. // Optimize for large category data, avoid call `getTicks()`.
  27779. if (isCategory) {
  27780. tickCount = scale.count();
  27781. }
  27782. else {
  27783. realNumberScaleTicks = scale.getTicks();
  27784. tickCount = realNumberScaleTicks.length;
  27785. }
  27786. var axisLabelModel = axis.getLabelModel();
  27787. var labelFormatter = makeLabelFormatter(axis);
  27788. var rect;
  27789. var step = 1;
  27790. // Simple optimization for large amount of labels
  27791. if (tickCount > 40) {
  27792. step = Math.ceil(tickCount / 40);
  27793. }
  27794. for (var i = 0; i < tickCount; i += step) {
  27795. var tickValue = realNumberScaleTicks ? realNumberScaleTicks[i] : categoryScaleExtent[0] + i;
  27796. var label = labelFormatter(tickValue);
  27797. var unrotatedSingleRect = axisLabelModel.getTextRect(label);
  27798. var singleRect = rotateTextRect(unrotatedSingleRect, axisLabelModel.get('rotate') || 0);
  27799. rect ? rect.union(singleRect) : (rect = singleRect);
  27800. }
  27801. return rect;
  27802. }
  27803. function rotateTextRect(textRect, rotate) {
  27804. var rotateRadians = rotate * Math.PI / 180;
  27805. var boundingBox = textRect.plain();
  27806. var beforeWidth = boundingBox.width;
  27807. var beforeHeight = boundingBox.height;
  27808. var afterWidth = beforeWidth * Math.cos(rotateRadians) + beforeHeight * Math.sin(rotateRadians);
  27809. var afterHeight = beforeWidth * Math.sin(rotateRadians) + beforeHeight * Math.cos(rotateRadians);
  27810. var rotatedRect = new BoundingRect(boundingBox.x, boundingBox.y, afterWidth, afterHeight);
  27811. return rotatedRect;
  27812. }
  27813. /*
  27814. * Licensed to the Apache Software Foundation (ASF) under one
  27815. * or more contributor license agreements. See the NOTICE file
  27816. * distributed with this work for additional information
  27817. * regarding copyright ownership. The ASF licenses this file
  27818. * to you under the Apache License, Version 2.0 (the
  27819. * "License"); you may not use this file except in compliance
  27820. * with the License. You may obtain a copy of the License at
  27821. *
  27822. * http://www.apache.org/licenses/LICENSE-2.0
  27823. *
  27824. * Unless required by applicable law or agreed to in writing,
  27825. * software distributed under the License is distributed on an
  27826. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27827. * KIND, either express or implied. See the License for the
  27828. * specific language governing permissions and limitations
  27829. * under the License.
  27830. */
  27831. var axisModelCommonMixin = {
  27832. /**
  27833. * @param {boolean} origin
  27834. * @return {number|string} min value or 'dataMin' or null/undefined (means auto) or NaN
  27835. */
  27836. getMin: function (origin) {
  27837. var option = this.option;
  27838. var min = (!origin && option.rangeStart != null)
  27839. ? option.rangeStart : option.min;
  27840. if (this.axis
  27841. && min != null
  27842. && min !== 'dataMin'
  27843. && typeof min !== 'function'
  27844. && !eqNaN(min)
  27845. ) {
  27846. min = this.axis.scale.parse(min);
  27847. }
  27848. return min;
  27849. },
  27850. /**
  27851. * @param {boolean} origin
  27852. * @return {number|string} max value or 'dataMax' or null/undefined (means auto) or NaN
  27853. */
  27854. getMax: function (origin) {
  27855. var option = this.option;
  27856. var max = (!origin && option.rangeEnd != null)
  27857. ? option.rangeEnd : option.max;
  27858. if (this.axis
  27859. && max != null
  27860. && max !== 'dataMax'
  27861. && typeof max !== 'function'
  27862. && !eqNaN(max)
  27863. ) {
  27864. max = this.axis.scale.parse(max);
  27865. }
  27866. return max;
  27867. },
  27868. /**
  27869. * @return {boolean}
  27870. */
  27871. getNeedCrossZero: function () {
  27872. var option = this.option;
  27873. return (option.rangeStart != null || option.rangeEnd != null)
  27874. ? false : !option.scale;
  27875. },
  27876. /**
  27877. * Should be implemented by each axis model if necessary.
  27878. * @return {module:echarts/model/Component} coordinate system model
  27879. */
  27880. getCoordSysModel: noop,
  27881. /**
  27882. * @param {number} rangeStart Can only be finite number or null/undefined or NaN.
  27883. * @param {number} rangeEnd Can only be finite number or null/undefined or NaN.
  27884. */
  27885. setRange: function (rangeStart, rangeEnd) {
  27886. this.option.rangeStart = rangeStart;
  27887. this.option.rangeEnd = rangeEnd;
  27888. },
  27889. /**
  27890. * Reset range
  27891. */
  27892. resetRange: function () {
  27893. // rangeStart and rangeEnd is readonly.
  27894. this.option.rangeStart = this.option.rangeEnd = null;
  27895. }
  27896. };
  27897. /*
  27898. * Licensed to the Apache Software Foundation (ASF) under one
  27899. * or more contributor license agreements. See the NOTICE file
  27900. * distributed with this work for additional information
  27901. * regarding copyright ownership. The ASF licenses this file
  27902. * to you under the Apache License, Version 2.0 (the
  27903. * "License"); you may not use this file except in compliance
  27904. * with the License. You may obtain a copy of the License at
  27905. *
  27906. * http://www.apache.org/licenses/LICENSE-2.0
  27907. *
  27908. * Unless required by applicable law or agreed to in writing,
  27909. * software distributed under the License is distributed on an
  27910. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27911. * KIND, either express or implied. See the License for the
  27912. * specific language governing permissions and limitations
  27913. * under the License.
  27914. */
  27915. // Symbol factory
  27916. /**
  27917. * Triangle shape
  27918. * @inner
  27919. */
  27920. var Triangle = extendShape({
  27921. type: 'triangle',
  27922. shape: {
  27923. cx: 0,
  27924. cy: 0,
  27925. width: 0,
  27926. height: 0
  27927. },
  27928. buildPath: function (path, shape) {
  27929. var cx = shape.cx;
  27930. var cy = shape.cy;
  27931. var width = shape.width / 2;
  27932. var height = shape.height / 2;
  27933. path.moveTo(cx, cy - height);
  27934. path.lineTo(cx + width, cy + height);
  27935. path.lineTo(cx - width, cy + height);
  27936. path.closePath();
  27937. }
  27938. });
  27939. /**
  27940. * Diamond shape
  27941. * @inner
  27942. */
  27943. var Diamond = extendShape({
  27944. type: 'diamond',
  27945. shape: {
  27946. cx: 0,
  27947. cy: 0,
  27948. width: 0,
  27949. height: 0
  27950. },
  27951. buildPath: function (path, shape) {
  27952. var cx = shape.cx;
  27953. var cy = shape.cy;
  27954. var width = shape.width / 2;
  27955. var height = shape.height / 2;
  27956. path.moveTo(cx, cy - height);
  27957. path.lineTo(cx + width, cy);
  27958. path.lineTo(cx, cy + height);
  27959. path.lineTo(cx - width, cy);
  27960. path.closePath();
  27961. }
  27962. });
  27963. /**
  27964. * Pin shape
  27965. * @inner
  27966. */
  27967. var Pin = extendShape({
  27968. type: 'pin',
  27969. shape: {
  27970. // x, y on the cusp
  27971. x: 0,
  27972. y: 0,
  27973. width: 0,
  27974. height: 0
  27975. },
  27976. buildPath: function (path, shape) {
  27977. var x = shape.x;
  27978. var y = shape.y;
  27979. var w = shape.width / 5 * 3;
  27980. // Height must be larger than width
  27981. var h = Math.max(w, shape.height);
  27982. var r = w / 2;
  27983. // Dist on y with tangent point and circle center
  27984. var dy = r * r / (h - r);
  27985. var cy = y - h + r + dy;
  27986. var angle = Math.asin(dy / r);
  27987. // Dist on x with tangent point and circle center
  27988. var dx = Math.cos(angle) * r;
  27989. var tanX = Math.sin(angle);
  27990. var tanY = Math.cos(angle);
  27991. var cpLen = r * 0.6;
  27992. var cpLen2 = r * 0.7;
  27993. path.moveTo(x - dx, cy + dy);
  27994. path.arc(
  27995. x, cy, r,
  27996. Math.PI - angle,
  27997. Math.PI * 2 + angle
  27998. );
  27999. path.bezierCurveTo(
  28000. x + dx - tanX * cpLen, cy + dy + tanY * cpLen,
  28001. x, y - cpLen2,
  28002. x, y
  28003. );
  28004. path.bezierCurveTo(
  28005. x, y - cpLen2,
  28006. x - dx + tanX * cpLen, cy + dy + tanY * cpLen,
  28007. x - dx, cy + dy
  28008. );
  28009. path.closePath();
  28010. }
  28011. });
  28012. /**
  28013. * Arrow shape
  28014. * @inner
  28015. */
  28016. var Arrow = extendShape({
  28017. type: 'arrow',
  28018. shape: {
  28019. x: 0,
  28020. y: 0,
  28021. width: 0,
  28022. height: 0
  28023. },
  28024. buildPath: function (ctx, shape) {
  28025. var height = shape.height;
  28026. var width = shape.width;
  28027. var x = shape.x;
  28028. var y = shape.y;
  28029. var dx = width / 3 * 2;
  28030. ctx.moveTo(x, y);
  28031. ctx.lineTo(x + dx, y + height);
  28032. ctx.lineTo(x, y + height / 4 * 3);
  28033. ctx.lineTo(x - dx, y + height);
  28034. ctx.lineTo(x, y);
  28035. ctx.closePath();
  28036. }
  28037. });
  28038. /**
  28039. * Map of path contructors
  28040. * @type {Object.<string, module:zrender/graphic/Path>}
  28041. */
  28042. var symbolCtors = {
  28043. line: Line,
  28044. rect: Rect,
  28045. roundRect: Rect,
  28046. square: Rect,
  28047. circle: Circle,
  28048. diamond: Diamond,
  28049. pin: Pin,
  28050. arrow: Arrow,
  28051. triangle: Triangle
  28052. };
  28053. var symbolShapeMakers = {
  28054. line: function (x, y, w, h, shape) {
  28055. // FIXME
  28056. shape.x1 = x;
  28057. shape.y1 = y + h / 2;
  28058. shape.x2 = x + w;
  28059. shape.y2 = y + h / 2;
  28060. },
  28061. rect: function (x, y, w, h, shape) {
  28062. shape.x = x;
  28063. shape.y = y;
  28064. shape.width = w;
  28065. shape.height = h;
  28066. },
  28067. roundRect: function (x, y, w, h, shape) {
  28068. shape.x = x;
  28069. shape.y = y;
  28070. shape.width = w;
  28071. shape.height = h;
  28072. shape.r = Math.min(w, h) / 4;
  28073. },
  28074. square: function (x, y, w, h, shape) {
  28075. var size = Math.min(w, h);
  28076. shape.x = x;
  28077. shape.y = y;
  28078. shape.width = size;
  28079. shape.height = size;
  28080. },
  28081. circle: function (x, y, w, h, shape) {
  28082. // Put circle in the center of square
  28083. shape.cx = x + w / 2;
  28084. shape.cy = y + h / 2;
  28085. shape.r = Math.min(w, h) / 2;
  28086. },
  28087. diamond: function (x, y, w, h, shape) {
  28088. shape.cx = x + w / 2;
  28089. shape.cy = y + h / 2;
  28090. shape.width = w;
  28091. shape.height = h;
  28092. },
  28093. pin: function (x, y, w, h, shape) {
  28094. shape.x = x + w / 2;
  28095. shape.y = y + h / 2;
  28096. shape.width = w;
  28097. shape.height = h;
  28098. },
  28099. arrow: function (x, y, w, h, shape) {
  28100. shape.x = x + w / 2;
  28101. shape.y = y + h / 2;
  28102. shape.width = w;
  28103. shape.height = h;
  28104. },
  28105. triangle: function (x, y, w, h, shape) {
  28106. shape.cx = x + w / 2;
  28107. shape.cy = y + h / 2;
  28108. shape.width = w;
  28109. shape.height = h;
  28110. }
  28111. };
  28112. var symbolBuildProxies = {};
  28113. each$1(symbolCtors, function (Ctor, name) {
  28114. symbolBuildProxies[name] = new Ctor();
  28115. });
  28116. var SymbolClz = extendShape({
  28117. type: 'symbol',
  28118. shape: {
  28119. symbolType: '',
  28120. x: 0,
  28121. y: 0,
  28122. width: 0,
  28123. height: 0
  28124. },
  28125. beforeBrush: function () {
  28126. var style = this.style;
  28127. var shape = this.shape;
  28128. // FIXME
  28129. if (shape.symbolType === 'pin' && style.textPosition === 'inside') {
  28130. style.textPosition = ['50%', '40%'];
  28131. style.textAlign = 'center';
  28132. style.textVerticalAlign = 'middle';
  28133. }
  28134. },
  28135. buildPath: function (ctx, shape, inBundle) {
  28136. var symbolType = shape.symbolType;
  28137. var proxySymbol = symbolBuildProxies[symbolType];
  28138. if (shape.symbolType !== 'none') {
  28139. if (!proxySymbol) {
  28140. // Default rect
  28141. symbolType = 'rect';
  28142. proxySymbol = symbolBuildProxies[symbolType];
  28143. }
  28144. symbolShapeMakers[symbolType](
  28145. shape.x, shape.y, shape.width, shape.height, proxySymbol.shape
  28146. );
  28147. proxySymbol.buildPath(ctx, proxySymbol.shape, inBundle);
  28148. }
  28149. }
  28150. });
  28151. // Provide setColor helper method to avoid determine if set the fill or stroke outside
  28152. function symbolPathSetColor(color, innerColor) {
  28153. if (this.type !== 'image') {
  28154. var symbolStyle = this.style;
  28155. var symbolShape = this.shape;
  28156. if (symbolShape && symbolShape.symbolType === 'line') {
  28157. symbolStyle.stroke = color;
  28158. }
  28159. else if (this.__isEmptyBrush) {
  28160. symbolStyle.stroke = color;
  28161. symbolStyle.fill = innerColor || '#fff';
  28162. }
  28163. else {
  28164. // FIXME 判断图形默认是填充还是描边,使用 onlyStroke ?
  28165. symbolStyle.fill && (symbolStyle.fill = color);
  28166. symbolStyle.stroke && (symbolStyle.stroke = color);
  28167. }
  28168. this.dirty(false);
  28169. }
  28170. }
  28171. /**
  28172. * Create a symbol element with given symbol configuration: shape, x, y, width, height, color
  28173. * @param {string} symbolType
  28174. * @param {number} x
  28175. * @param {number} y
  28176. * @param {number} w
  28177. * @param {number} h
  28178. * @param {string} color
  28179. * @param {boolean} [keepAspect=false] whether to keep the ratio of w/h,
  28180. * for path and image only.
  28181. */
  28182. function createSymbol(symbolType, x, y, w, h, color, keepAspect) {
  28183. // TODO Support image object, DynamicImage.
  28184. var isEmpty = symbolType.indexOf('empty') === 0;
  28185. if (isEmpty) {
  28186. symbolType = symbolType.substr(5, 1).toLowerCase() + symbolType.substr(6);
  28187. }
  28188. var symbolPath;
  28189. if (symbolType.indexOf('image://') === 0) {
  28190. symbolPath = makeImage(
  28191. symbolType.slice(8),
  28192. new BoundingRect(x, y, w, h),
  28193. keepAspect ? 'center' : 'cover'
  28194. );
  28195. }
  28196. else if (symbolType.indexOf('path://') === 0) {
  28197. symbolPath = makePath(
  28198. symbolType.slice(7),
  28199. {},
  28200. new BoundingRect(x, y, w, h),
  28201. keepAspect ? 'center' : 'cover'
  28202. );
  28203. }
  28204. else {
  28205. symbolPath = new SymbolClz({
  28206. shape: {
  28207. symbolType: symbolType,
  28208. x: x,
  28209. y: y,
  28210. width: w,
  28211. height: h
  28212. }
  28213. });
  28214. }
  28215. symbolPath.__isEmptyBrush = isEmpty;
  28216. symbolPath.setColor = symbolPathSetColor;
  28217. symbolPath.setColor(color);
  28218. return symbolPath;
  28219. }
  28220. /*
  28221. * Licensed to the Apache Software Foundation (ASF) under one
  28222. * or more contributor license agreements. See the NOTICE file
  28223. * distributed with this work for additional information
  28224. * regarding copyright ownership. The ASF licenses this file
  28225. * to you under the Apache License, Version 2.0 (the
  28226. * "License"); you may not use this file except in compliance
  28227. * with the License. You may obtain a copy of the License at
  28228. *
  28229. * http://www.apache.org/licenses/LICENSE-2.0
  28230. *
  28231. * Unless required by applicable law or agreed to in writing,
  28232. * software distributed under the License is distributed on an
  28233. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28234. * KIND, either express or implied. See the License for the
  28235. * specific language governing permissions and limitations
  28236. * under the License.
  28237. */
  28238. // import createGraphFromNodeEdge from './chart/helper/createGraphFromNodeEdge';
  28239. /**
  28240. * Create a muti dimension List structure from seriesModel.
  28241. * @param {module:echarts/model/Model} seriesModel
  28242. * @return {module:echarts/data/List} list
  28243. */
  28244. function createList(seriesModel) {
  28245. return createListFromArray(seriesModel.getSource(), seriesModel);
  28246. }
  28247. var dataStack$1 = {
  28248. isDimensionStacked: isDimensionStacked,
  28249. enableDataStack: enableDataStack
  28250. };
  28251. /**
  28252. * Create scale
  28253. * @param {Array.<number>} dataExtent
  28254. * @param {Object|module:echarts/Model} option
  28255. */
  28256. function createScale(dataExtent, option) {
  28257. var axisModel = option;
  28258. if (!Model.isInstance(option)) {
  28259. axisModel = new Model(option);
  28260. mixin(axisModel, axisModelCommonMixin);
  28261. }
  28262. var scale = createScaleByModel(axisModel);
  28263. scale.setExtent(dataExtent[0], dataExtent[1]);
  28264. niceScaleExtent(scale, axisModel);
  28265. return scale;
  28266. }
  28267. /**
  28268. * Mixin common methods to axis model,
  28269. *
  28270. * Inlcude methods
  28271. * `getFormattedLabels() => Array.<string>`
  28272. * `getCategories() => Array.<string>`
  28273. * `getMin(origin: boolean) => number`
  28274. * `getMax(origin: boolean) => number`
  28275. * `getNeedCrossZero() => boolean`
  28276. * `setRange(start: number, end: number)`
  28277. * `resetRange()`
  28278. */
  28279. function mixinAxisModelCommonMethods(Model$$1) {
  28280. mixin(Model$$1, axisModelCommonMixin);
  28281. }
  28282. var helper = (Object.freeze || Object)({
  28283. createList: createList,
  28284. getLayoutRect: getLayoutRect,
  28285. dataStack: dataStack$1,
  28286. createScale: createScale,
  28287. mixinAxisModelCommonMethods: mixinAxisModelCommonMethods,
  28288. completeDimensions: completeDimensions,
  28289. createDimensions: createDimensions,
  28290. createSymbol: createSymbol
  28291. });
  28292. var EPSILON$3 = 1e-8;
  28293. function isAroundEqual$1(a, b) {
  28294. return Math.abs(a - b) < EPSILON$3;
  28295. }
  28296. function contain$1(points, x, y) {
  28297. var w = 0;
  28298. var p = points[0];
  28299. if (!p) {
  28300. return false;
  28301. }
  28302. for (var i = 1; i < points.length; i++) {
  28303. var p2 = points[i];
  28304. w += windingLine(p[0], p[1], p2[0], p2[1], x, y);
  28305. p = p2;
  28306. }
  28307. // Close polygon
  28308. var p0 = points[0];
  28309. if (!isAroundEqual$1(p[0], p0[0]) || !isAroundEqual$1(p[1], p0[1])) {
  28310. w += windingLine(p[0], p[1], p0[0], p0[1], x, y);
  28311. }
  28312. return w !== 0;
  28313. }
  28314. /*
  28315. * Licensed to the Apache Software Foundation (ASF) under one
  28316. * or more contributor license agreements. See the NOTICE file
  28317. * distributed with this work for additional information
  28318. * regarding copyright ownership. The ASF licenses this file
  28319. * to you under the Apache License, Version 2.0 (the
  28320. * "License"); you may not use this file except in compliance
  28321. * with the License. You may obtain a copy of the License at
  28322. *
  28323. * http://www.apache.org/licenses/LICENSE-2.0
  28324. *
  28325. * Unless required by applicable law or agreed to in writing,
  28326. * software distributed under the License is distributed on an
  28327. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28328. * KIND, either express or implied. See the License for the
  28329. * specific language governing permissions and limitations
  28330. * under the License.
  28331. */
  28332. /**
  28333. * @module echarts/coord/geo/Region
  28334. */
  28335. /**
  28336. * @param {string} name
  28337. * @param {Array} geometries
  28338. * @param {Array.<number>} cp
  28339. */
  28340. function Region(name, geometries, cp) {
  28341. /**
  28342. * @type {string}
  28343. * @readOnly
  28344. */
  28345. this.name = name;
  28346. /**
  28347. * @type {Array.<Array>}
  28348. * @readOnly
  28349. */
  28350. this.geometries = geometries;
  28351. if (!cp) {
  28352. var rect = this.getBoundingRect();
  28353. cp = [
  28354. rect.x + rect.width / 2,
  28355. rect.y + rect.height / 2
  28356. ];
  28357. }
  28358. else {
  28359. cp = [cp[0], cp[1]];
  28360. }
  28361. /**
  28362. * @type {Array.<number>}
  28363. */
  28364. this.center = cp;
  28365. }
  28366. Region.prototype = {
  28367. constructor: Region,
  28368. properties: null,
  28369. /**
  28370. * @return {module:zrender/core/BoundingRect}
  28371. */
  28372. getBoundingRect: function () {
  28373. var rect = this._rect;
  28374. if (rect) {
  28375. return rect;
  28376. }
  28377. var MAX_NUMBER = Number.MAX_VALUE;
  28378. var min$$1 = [MAX_NUMBER, MAX_NUMBER];
  28379. var max$$1 = [-MAX_NUMBER, -MAX_NUMBER];
  28380. var min2 = [];
  28381. var max2 = [];
  28382. var geometries = this.geometries;
  28383. for (var i = 0; i < geometries.length; i++) {
  28384. // Only support polygon
  28385. if (geometries[i].type !== 'polygon') {
  28386. continue;
  28387. }
  28388. // Doesn't consider hole
  28389. var exterior = geometries[i].exterior;
  28390. fromPoints(exterior, min2, max2);
  28391. min(min$$1, min$$1, min2);
  28392. max(max$$1, max$$1, max2);
  28393. }
  28394. // No data
  28395. if (i === 0) {
  28396. min$$1[0] = min$$1[1] = max$$1[0] = max$$1[1] = 0;
  28397. }
  28398. return (this._rect = new BoundingRect(
  28399. min$$1[0], min$$1[1], max$$1[0] - min$$1[0], max$$1[1] - min$$1[1]
  28400. ));
  28401. },
  28402. /**
  28403. * @param {<Array.<number>} coord
  28404. * @return {boolean}
  28405. */
  28406. contain: function (coord) {
  28407. var rect = this.getBoundingRect();
  28408. var geometries = this.geometries;
  28409. if (!rect.contain(coord[0], coord[1])) {
  28410. return false;
  28411. }
  28412. loopGeo: for (var i = 0, len$$1 = geometries.length; i < len$$1; i++) {
  28413. // Only support polygon.
  28414. if (geometries[i].type !== 'polygon') {
  28415. continue;
  28416. }
  28417. var exterior = geometries[i].exterior;
  28418. var interiors = geometries[i].interiors;
  28419. if (contain$1(exterior, coord[0], coord[1])) {
  28420. // Not in the region if point is in the hole.
  28421. for (var k = 0; k < (interiors ? interiors.length : 0); k++) {
  28422. if (contain$1(interiors[k])) {
  28423. continue loopGeo;
  28424. }
  28425. }
  28426. return true;
  28427. }
  28428. }
  28429. return false;
  28430. },
  28431. transformTo: function (x, y, width, height) {
  28432. var rect = this.getBoundingRect();
  28433. var aspect = rect.width / rect.height;
  28434. if (!width) {
  28435. width = aspect * height;
  28436. }
  28437. else if (!height) {
  28438. height = width / aspect ;
  28439. }
  28440. var target = new BoundingRect(x, y, width, height);
  28441. var transform = rect.calculateTransform(target);
  28442. var geometries = this.geometries;
  28443. for (var i = 0; i < geometries.length; i++) {
  28444. // Only support polygon.
  28445. if (geometries[i].type !== 'polygon') {
  28446. continue;
  28447. }
  28448. var exterior = geometries[i].exterior;
  28449. var interiors = geometries[i].interiors;
  28450. for (var p = 0; p < exterior.length; p++) {
  28451. applyTransform(exterior[p], exterior[p], transform);
  28452. }
  28453. for (var h = 0; h < (interiors ? interiors.length : 0); h++) {
  28454. for (var p = 0; p < interiors[h].length; p++) {
  28455. applyTransform(interiors[h][p], interiors[h][p], transform);
  28456. }
  28457. }
  28458. }
  28459. rect = this._rect;
  28460. rect.copy(target);
  28461. // Update center
  28462. this.center = [
  28463. rect.x + rect.width / 2,
  28464. rect.y + rect.height / 2
  28465. ];
  28466. }
  28467. };
  28468. /*
  28469. * Licensed to the Apache Software Foundation (ASF) under one
  28470. * or more contributor license agreements. See the NOTICE file
  28471. * distributed with this work for additional information
  28472. * regarding copyright ownership. The ASF licenses this file
  28473. * to you under the Apache License, Version 2.0 (the
  28474. * "License"); you may not use this file except in compliance
  28475. * with the License. You may obtain a copy of the License at
  28476. *
  28477. * http://www.apache.org/licenses/LICENSE-2.0
  28478. *
  28479. * Unless required by applicable law or agreed to in writing,
  28480. * software distributed under the License is distributed on an
  28481. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28482. * KIND, either express or implied. See the License for the
  28483. * specific language governing permissions and limitations
  28484. * under the License.
  28485. */
  28486. /**
  28487. * Parse and decode geo json
  28488. * @module echarts/coord/geo/parseGeoJson
  28489. */
  28490. function decode(json) {
  28491. if (!json.UTF8Encoding) {
  28492. return json;
  28493. }
  28494. var encodeScale = json.UTF8Scale;
  28495. if (encodeScale == null) {
  28496. encodeScale = 1024;
  28497. }
  28498. var features = json.features;
  28499. for (var f = 0; f < features.length; f++) {
  28500. var feature = features[f];
  28501. var geometry = feature.geometry;
  28502. var coordinates = geometry.coordinates;
  28503. var encodeOffsets = geometry.encodeOffsets;
  28504. for (var c = 0; c < coordinates.length; c++) {
  28505. var coordinate = coordinates[c];
  28506. if (geometry.type === 'Polygon') {
  28507. coordinates[c] = decodePolygon(
  28508. coordinate,
  28509. encodeOffsets[c],
  28510. encodeScale
  28511. );
  28512. }
  28513. else if (geometry.type === 'MultiPolygon') {
  28514. for (var c2 = 0; c2 < coordinate.length; c2++) {
  28515. var polygon = coordinate[c2];
  28516. coordinate[c2] = decodePolygon(
  28517. polygon,
  28518. encodeOffsets[c][c2],
  28519. encodeScale
  28520. );
  28521. }
  28522. }
  28523. }
  28524. }
  28525. // Has been decoded
  28526. json.UTF8Encoding = false;
  28527. return json;
  28528. }
  28529. function decodePolygon(coordinate, encodeOffsets, encodeScale) {
  28530. var result = [];
  28531. var prevX = encodeOffsets[0];
  28532. var prevY = encodeOffsets[1];
  28533. for (var i = 0; i < coordinate.length; i += 2) {
  28534. var x = coordinate.charCodeAt(i) - 64;
  28535. var y = coordinate.charCodeAt(i + 1) - 64;
  28536. // ZigZag decoding
  28537. x = (x >> 1) ^ (-(x & 1));
  28538. y = (y >> 1) ^ (-(y & 1));
  28539. // Delta deocding
  28540. x += prevX;
  28541. y += prevY;
  28542. prevX = x;
  28543. prevY = y;
  28544. // Dequantize
  28545. result.push([x / encodeScale, y / encodeScale]);
  28546. }
  28547. return result;
  28548. }
  28549. /**
  28550. * @alias module:echarts/coord/geo/parseGeoJson
  28551. * @param {Object} geoJson
  28552. * @return {module:zrender/container/Group}
  28553. */
  28554. var parseGeoJson$1 = function (geoJson) {
  28555. decode(geoJson);
  28556. return map(filter(geoJson.features, function (featureObj) {
  28557. // Output of mapshaper may have geometry null
  28558. return featureObj.geometry
  28559. && featureObj.properties
  28560. && featureObj.geometry.coordinates.length > 0;
  28561. }), function (featureObj) {
  28562. var properties = featureObj.properties;
  28563. var geo = featureObj.geometry;
  28564. var coordinates = geo.coordinates;
  28565. var geometries = [];
  28566. if (geo.type === 'Polygon') {
  28567. geometries.push({
  28568. type: 'polygon',
  28569. // According to the GeoJSON specification.
  28570. // First must be exterior, and the rest are all interior(holes).
  28571. exterior: coordinates[0],
  28572. interiors: coordinates.slice(1)
  28573. });
  28574. }
  28575. if (geo.type === 'MultiPolygon') {
  28576. each$1(coordinates, function (item) {
  28577. if (item[0]) {
  28578. geometries.push({
  28579. type: 'polygon',
  28580. exterior: item[0],
  28581. interiors: item.slice(1)
  28582. });
  28583. }
  28584. });
  28585. }
  28586. var region = new Region(
  28587. properties.name,
  28588. geometries,
  28589. properties.cp
  28590. );
  28591. region.properties = properties;
  28592. return region;
  28593. });
  28594. };
  28595. /*
  28596. * Licensed to the Apache Software Foundation (ASF) under one
  28597. * or more contributor license agreements. See the NOTICE file
  28598. * distributed with this work for additional information
  28599. * regarding copyright ownership. The ASF licenses this file
  28600. * to you under the Apache License, Version 2.0 (the
  28601. * "License"); you may not use this file except in compliance
  28602. * with the License. You may obtain a copy of the License at
  28603. *
  28604. * http://www.apache.org/licenses/LICENSE-2.0
  28605. *
  28606. * Unless required by applicable law or agreed to in writing,
  28607. * software distributed under the License is distributed on an
  28608. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28609. * KIND, either express or implied. See the License for the
  28610. * specific language governing permissions and limitations
  28611. * under the License.
  28612. */
  28613. var inner$6 = makeInner();
  28614. /**
  28615. * @param {module:echats/coord/Axis} axis
  28616. * @return {Object} {
  28617. * labels: [{
  28618. * formattedLabel: string,
  28619. * rawLabel: string,
  28620. * tickValue: number
  28621. * }, ...],
  28622. * labelCategoryInterval: number
  28623. * }
  28624. */
  28625. function createAxisLabels(axis) {
  28626. // Only ordinal scale support tick interval
  28627. return axis.type === 'category'
  28628. ? makeCategoryLabels(axis)
  28629. : makeRealNumberLabels(axis);
  28630. }
  28631. /**
  28632. * @param {module:echats/coord/Axis} axis
  28633. * @param {module:echarts/model/Model} tickModel For example, can be axisTick, splitLine, splitArea.
  28634. * @return {Object} {
  28635. * ticks: Array.<number>
  28636. * tickCategoryInterval: number
  28637. * }
  28638. */
  28639. function createAxisTicks(axis, tickModel) {
  28640. // Only ordinal scale support tick interval
  28641. return axis.type === 'category'
  28642. ? makeCategoryTicks(axis, tickModel)
  28643. : {ticks: axis.scale.getTicks()};
  28644. }
  28645. function makeCategoryLabels(axis) {
  28646. var labelModel = axis.getLabelModel();
  28647. var labelsCache = getListCache(axis, 'labels');
  28648. var optionLabelInterval = getOptionCategoryInterval(labelModel);
  28649. var result = listCacheGet(labelsCache, optionLabelInterval);
  28650. if (result) {
  28651. return result;
  28652. }
  28653. var labels;
  28654. var numericLabelInterval;
  28655. if (!labelModel.get('show') || axis.scale.isBlank()) {
  28656. labels = [];
  28657. }
  28658. else if (isFunction$1(optionLabelInterval)) {
  28659. labels = makeLabelsByCustomizedCategoryInterval(axis, optionLabelInterval);
  28660. }
  28661. else {
  28662. numericLabelInterval = optionLabelInterval === 'auto'
  28663. ? makeAutoCategoryInterval(axis) : optionLabelInterval;
  28664. labels = makeLabelsByNumericCategoryInterval(axis, numericLabelInterval);
  28665. }
  28666. // Cache to avoid calling interval function repeatly.
  28667. return listCacheSet(labelsCache, optionLabelInterval, {
  28668. labels: labels, labelCategoryInterval: numericLabelInterval
  28669. });
  28670. }
  28671. function makeCategoryTicks(axis, tickModel) {
  28672. var ticksCache = getListCache(axis, 'ticks');
  28673. var optionTickInterval = getOptionCategoryInterval(tickModel);
  28674. var result = listCacheGet(ticksCache, optionTickInterval);
  28675. if (result) {
  28676. return result;
  28677. }
  28678. var ticks;
  28679. var numericTickInterval = optionTickInterval;
  28680. // Optimize for the case that large category data and no label displayed,
  28681. // we should not return all ticks.
  28682. if (!tickModel.get('show') || axis.scale.isBlank()) {
  28683. ticks = [];
  28684. }
  28685. if (isFunction$1(numericTickInterval)) {
  28686. ticks = makeLabelsByCustomizedCategoryInterval(axis, numericTickInterval, true);
  28687. }
  28688. // Always use label interval by default.
  28689. else {
  28690. if (numericTickInterval === 'auto') {
  28691. var labelsResult = makeCategoryLabels(axis);
  28692. numericTickInterval = labelsResult.labelCategoryInterval;
  28693. if (numericTickInterval != null) {
  28694. ticks = map(labelsResult.labels, function (labelItem) {
  28695. return labelItem.tickValue;
  28696. });
  28697. }
  28698. else {
  28699. numericTickInterval = makeAutoCategoryInterval(axis, true);
  28700. }
  28701. }
  28702. if (ticks == null) {
  28703. ticks = makeLabelsByNumericCategoryInterval(axis, numericTickInterval, true);
  28704. }
  28705. }
  28706. // Cache to avoid calling interval function repeatly.
  28707. return listCacheSet(ticksCache, optionTickInterval, {
  28708. ticks: ticks, tickCategoryInterval: numericTickInterval
  28709. });
  28710. }
  28711. function makeRealNumberLabels(axis) {
  28712. var ticks = axis.scale.getTicks();
  28713. var labelFormatter = makeLabelFormatter(axis);
  28714. return {
  28715. labels: map(ticks, function (tickValue, idx) {
  28716. return {
  28717. formattedLabel: labelFormatter(tickValue, idx),
  28718. rawLabel: axis.scale.getLabel(tickValue),
  28719. tickValue: tickValue
  28720. };
  28721. })
  28722. };
  28723. }
  28724. // Large category data calculation is performence sensitive, and ticks and label
  28725. // probably be fetched by multiple times. So we cache the result.
  28726. // axis is created each time during a ec process, so we do not need to clear cache.
  28727. function getListCache(axis, prop) {
  28728. // Because key can be funciton, and cache size always be small, we use array cache.
  28729. return inner$6(axis)[prop] || (inner$6(axis)[prop] = []);
  28730. }
  28731. function listCacheGet(cache, key) {
  28732. for (var i = 0; i < cache.length; i++) {
  28733. if (cache[i].key === key) {
  28734. return cache[i].value;
  28735. }
  28736. }
  28737. }
  28738. function listCacheSet(cache, key, value) {
  28739. cache.push({key: key, value: value});
  28740. return value;
  28741. }
  28742. function makeAutoCategoryInterval(axis, hideLabel) {
  28743. var cacheKey = hideLabel ? 'tickAutoInterval' : 'autoInterval';
  28744. var result = inner$6(axis)[cacheKey];
  28745. if (result != null) {
  28746. return result;
  28747. }
  28748. return (
  28749. inner$6(axis)[cacheKey] = axis.calculateCategoryInterval(hideLabel)
  28750. );
  28751. }
  28752. /**
  28753. * Calculate interval for category axis ticks and labels.
  28754. * To get precise result, at least one of `getRotate` and `isHorizontal`
  28755. * should be implemented in axis.
  28756. */
  28757. function calculateCategoryInterval(axis, hideLabel) {
  28758. var params = fetchAutoCategoryIntervalCalculationParams(axis);
  28759. var labelFormatter = makeLabelFormatter(axis);
  28760. var rotation = (params.axisRotate - params.labelRotate) / 180 * Math.PI;
  28761. var ordinalScale = axis.scale;
  28762. var ordinalExtent = ordinalScale.getExtent();
  28763. // Providing this method is for optimization:
  28764. // avoid generating a long array by `getTicks`
  28765. // in large category data case.
  28766. var tickCount = ordinalScale.count();
  28767. if (ordinalExtent[1] - ordinalExtent[0] < 1) {
  28768. return 0;
  28769. }
  28770. var step = 1;
  28771. // Simple optimization. Empirical value: tick count should less than 40.
  28772. if (tickCount > 40) {
  28773. step = Math.max(1, Math.floor(tickCount / 40));
  28774. }
  28775. var tickValue = ordinalExtent[0];
  28776. var unitSpan = axis.dataToCoord(tickValue + 1) - axis.dataToCoord(tickValue);
  28777. var unitW = Math.abs(unitSpan * Math.cos(rotation));
  28778. var unitH = Math.abs(unitSpan * Math.sin(rotation));
  28779. var maxW = 0;
  28780. var maxH = 0;
  28781. // Caution: Performance sensitive for large category data.
  28782. // Consider dataZoom, we should make appropriate step to avoid O(n) loop.
  28783. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  28784. var width = 0;
  28785. var height = 0;
  28786. if (!hideLabel) {
  28787. // Polar is also calculated in assumptive linear layout here.
  28788. // Not precise, do not consider align and vertical align
  28789. // and each distance from axis line yet.
  28790. var rect = getBoundingRect(
  28791. labelFormatter(tickValue), params.font, 'center', 'top'
  28792. );
  28793. // Magic number
  28794. width = rect.width * 1.3;
  28795. height = rect.height * 1.3;
  28796. }
  28797. // Min size, void long loop.
  28798. maxW = Math.max(maxW, width, 7);
  28799. maxH = Math.max(maxH, height, 7);
  28800. }
  28801. var dw = maxW / unitW;
  28802. var dh = maxH / unitH;
  28803. // 0/0 is NaN, 1/0 is Infinity.
  28804. isNaN(dw) && (dw = Infinity);
  28805. isNaN(dh) && (dh = Infinity);
  28806. var interval = Math.max(0, Math.floor(Math.min(dw, dh)));
  28807. var cache = inner$6(axis.model);
  28808. var lastAutoInterval = cache.lastAutoInterval;
  28809. var lastTickCount = cache.lastTickCount;
  28810. // Use cache to keep interval stable while moving zoom window,
  28811. // otherwise the calculated interval might jitter when the zoom
  28812. // window size is close to the interval-changing size.
  28813. if (lastAutoInterval != null
  28814. && lastTickCount != null
  28815. && Math.abs(lastAutoInterval - interval) <= 1
  28816. && Math.abs(lastTickCount - tickCount) <= 1
  28817. // Always choose the bigger one, otherwise the critical
  28818. // point is not the same when zooming in or zooming out.
  28819. && lastAutoInterval > interval
  28820. ) {
  28821. interval = lastAutoInterval;
  28822. }
  28823. // Only update cache if cache not used, otherwise the
  28824. // changing of interval is too insensitive.
  28825. else {
  28826. cache.lastTickCount = tickCount;
  28827. cache.lastAutoInterval = interval;
  28828. }
  28829. return interval;
  28830. }
  28831. function fetchAutoCategoryIntervalCalculationParams(axis) {
  28832. var labelModel = axis.getLabelModel();
  28833. return {
  28834. axisRotate: axis.getRotate
  28835. ? axis.getRotate()
  28836. : (axis.isHorizontal && !axis.isHorizontal())
  28837. ? 90
  28838. : 0,
  28839. labelRotate: labelModel.get('rotate') || 0,
  28840. font: labelModel.getFont()
  28841. };
  28842. }
  28843. function makeLabelsByNumericCategoryInterval(axis, categoryInterval, onlyTick) {
  28844. var labelFormatter = makeLabelFormatter(axis);
  28845. var ordinalScale = axis.scale;
  28846. var ordinalExtent = ordinalScale.getExtent();
  28847. var labelModel = axis.getLabelModel();
  28848. var result = [];
  28849. // TODO: axisType: ordinalTime, pick the tick from each month/day/year/...
  28850. var step = Math.max((categoryInterval || 0) + 1, 1);
  28851. var startTick = ordinalExtent[0];
  28852. var tickCount = ordinalScale.count();
  28853. // Calculate start tick based on zero if possible to keep label consistent
  28854. // while zooming and moving while interval > 0. Otherwise the selection
  28855. // of displayable ticks and symbols probably keep changing.
  28856. // 3 is empirical value.
  28857. if (startTick !== 0 && step > 1 && tickCount / step > 2) {
  28858. startTick = Math.round(Math.ceil(startTick / step) * step);
  28859. }
  28860. // (1) Only add min max label here but leave overlap checking
  28861. // to render stage, which also ensure the returned list
  28862. // suitable for splitLine and splitArea rendering.
  28863. // (2) Scales except category always contain min max label so
  28864. // do not need to perform this process.
  28865. var showMinMax = {
  28866. min: labelModel.get('showMinLabel'),
  28867. max: labelModel.get('showMaxLabel')
  28868. };
  28869. if (showMinMax.min && startTick !== ordinalExtent[0]) {
  28870. addItem(ordinalExtent[0]);
  28871. }
  28872. // Optimize: avoid generating large array by `ordinalScale.getTicks()`.
  28873. var tickValue = startTick;
  28874. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  28875. addItem(tickValue);
  28876. }
  28877. if (showMinMax.max && tickValue !== ordinalExtent[1]) {
  28878. addItem(ordinalExtent[1]);
  28879. }
  28880. function addItem(tVal) {
  28881. result.push(onlyTick
  28882. ? tVal
  28883. : {
  28884. formattedLabel: labelFormatter(tVal),
  28885. rawLabel: ordinalScale.getLabel(tVal),
  28886. tickValue: tVal
  28887. }
  28888. );
  28889. }
  28890. return result;
  28891. }
  28892. // When interval is function, the result `false` means ignore the tick.
  28893. // It is time consuming for large category data.
  28894. function makeLabelsByCustomizedCategoryInterval(axis, categoryInterval, onlyTick) {
  28895. var ordinalScale = axis.scale;
  28896. var labelFormatter = makeLabelFormatter(axis);
  28897. var result = [];
  28898. each$1(ordinalScale.getTicks(), function (tickValue) {
  28899. var rawLabel = ordinalScale.getLabel(tickValue);
  28900. if (categoryInterval(tickValue, rawLabel)) {
  28901. result.push(onlyTick
  28902. ? tickValue
  28903. : {
  28904. formattedLabel: labelFormatter(tickValue),
  28905. rawLabel: rawLabel,
  28906. tickValue: tickValue
  28907. }
  28908. );
  28909. }
  28910. });
  28911. return result;
  28912. }
  28913. // Can be null|'auto'|number|function
  28914. function getOptionCategoryInterval(model) {
  28915. var interval = model.get('interval');
  28916. return interval == null ? 'auto' : interval;
  28917. }
  28918. /*
  28919. * Licensed to the Apache Software Foundation (ASF) under one
  28920. * or more contributor license agreements. See the NOTICE file
  28921. * distributed with this work for additional information
  28922. * regarding copyright ownership. The ASF licenses this file
  28923. * to you under the Apache License, Version 2.0 (the
  28924. * "License"); you may not use this file except in compliance
  28925. * with the License. You may obtain a copy of the License at
  28926. *
  28927. * http://www.apache.org/licenses/LICENSE-2.0
  28928. *
  28929. * Unless required by applicable law or agreed to in writing,
  28930. * software distributed under the License is distributed on an
  28931. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28932. * KIND, either express or implied. See the License for the
  28933. * specific language governing permissions and limitations
  28934. * under the License.
  28935. */
  28936. var NORMALIZED_EXTENT = [0, 1];
  28937. /**
  28938. * Base class of Axis.
  28939. * @constructor
  28940. */
  28941. var Axis = function (dim, scale, extent) {
  28942. /**
  28943. * Axis dimension. Such as 'x', 'y', 'z', 'angle', 'radius'.
  28944. * @type {string}
  28945. */
  28946. this.dim = dim;
  28947. /**
  28948. * Axis scale
  28949. * @type {module:echarts/coord/scale/*}
  28950. */
  28951. this.scale = scale;
  28952. /**
  28953. * @type {Array.<number>}
  28954. * @private
  28955. */
  28956. this._extent = extent || [0, 0];
  28957. /**
  28958. * @type {boolean}
  28959. */
  28960. this.inverse = false;
  28961. /**
  28962. * Usually true when axis has a ordinal scale
  28963. * @type {boolean}
  28964. */
  28965. this.onBand = false;
  28966. };
  28967. Axis.prototype = {
  28968. constructor: Axis,
  28969. /**
  28970. * If axis extent contain given coord
  28971. * @param {number} coord
  28972. * @return {boolean}
  28973. */
  28974. contain: function (coord) {
  28975. var extent = this._extent;
  28976. var min = Math.min(extent[0], extent[1]);
  28977. var max = Math.max(extent[0], extent[1]);
  28978. return coord >= min && coord <= max;
  28979. },
  28980. /**
  28981. * If axis extent contain given data
  28982. * @param {number} data
  28983. * @return {boolean}
  28984. */
  28985. containData: function (data) {
  28986. return this.contain(this.dataToCoord(data));
  28987. },
  28988. /**
  28989. * Get coord extent.
  28990. * @return {Array.<number>}
  28991. */
  28992. getExtent: function () {
  28993. return this._extent.slice();
  28994. },
  28995. /**
  28996. * Get precision used for formatting
  28997. * @param {Array.<number>} [dataExtent]
  28998. * @return {number}
  28999. */
  29000. getPixelPrecision: function (dataExtent) {
  29001. return getPixelPrecision(
  29002. dataExtent || this.scale.getExtent(),
  29003. this._extent
  29004. );
  29005. },
  29006. /**
  29007. * Set coord extent
  29008. * @param {number} start
  29009. * @param {number} end
  29010. */
  29011. setExtent: function (start, end) {
  29012. var extent = this._extent;
  29013. extent[0] = start;
  29014. extent[1] = end;
  29015. },
  29016. /**
  29017. * Convert data to coord. Data is the rank if it has an ordinal scale
  29018. * @param {number} data
  29019. * @param {boolean} clamp
  29020. * @return {number}
  29021. */
  29022. dataToCoord: function (data, clamp) {
  29023. var extent = this._extent;
  29024. var scale = this.scale;
  29025. data = scale.normalize(data);
  29026. if (this.onBand && scale.type === 'ordinal') {
  29027. extent = extent.slice();
  29028. fixExtentWithBands(extent, scale.count());
  29029. }
  29030. return linearMap(data, NORMALIZED_EXTENT, extent, clamp);
  29031. },
  29032. /**
  29033. * Convert coord to data. Data is the rank if it has an ordinal scale
  29034. * @param {number} coord
  29035. * @param {boolean} clamp
  29036. * @return {number}
  29037. */
  29038. coordToData: function (coord, clamp) {
  29039. var extent = this._extent;
  29040. var scale = this.scale;
  29041. if (this.onBand && scale.type === 'ordinal') {
  29042. extent = extent.slice();
  29043. fixExtentWithBands(extent, scale.count());
  29044. }
  29045. var t = linearMap(coord, extent, NORMALIZED_EXTENT, clamp);
  29046. return this.scale.scale(t);
  29047. },
  29048. /**
  29049. * Convert pixel point to data in axis
  29050. * @param {Array.<number>} point
  29051. * @param {boolean} clamp
  29052. * @return {number} data
  29053. */
  29054. pointToData: function (point, clamp) {
  29055. // Should be implemented in derived class if necessary.
  29056. },
  29057. /**
  29058. * Different from `zrUtil.map(axis.getTicks(), axis.dataToCoord, axis)`,
  29059. * `axis.getTicksCoords` considers `onBand`, which is used by
  29060. * `boundaryGap:true` of category axis and splitLine and splitArea.
  29061. * @param {Object} [opt]
  29062. * @param {number} [opt.tickModel=axis.model.getModel('axisTick')]
  29063. * @param {boolean} [opt.clamp] If `true`, the first and the last
  29064. * tick must be at the axis end points. Otherwise, clip ticks
  29065. * that outside the axis extent.
  29066. * @return {Array.<Object>} [{
  29067. * coord: ...,
  29068. * tickValue: ...
  29069. * }, ...]
  29070. */
  29071. getTicksCoords: function (opt) {
  29072. opt = opt || {};
  29073. var tickModel = opt.tickModel || this.getTickModel();
  29074. var result = createAxisTicks(this, tickModel);
  29075. var ticks = result.ticks;
  29076. var ticksCoords = map(ticks, function (tickValue) {
  29077. return {
  29078. coord: this.dataToCoord(tickValue),
  29079. tickValue: tickValue
  29080. };
  29081. }, this);
  29082. var alignWithLabel = tickModel.get('alignWithLabel');
  29083. fixOnBandTicksCoords(
  29084. this, ticksCoords, result.tickCategoryInterval, alignWithLabel, opt.clamp
  29085. );
  29086. return ticksCoords;
  29087. },
  29088. /**
  29089. * @return {Array.<Object>} [{
  29090. * formattedLabel: string,
  29091. * rawLabel: axis.scale.getLabel(tickValue)
  29092. * tickValue: number
  29093. * }, ...]
  29094. */
  29095. getViewLabels: function () {
  29096. return createAxisLabels(this).labels;
  29097. },
  29098. /**
  29099. * @return {module:echarts/coord/model/Model}
  29100. */
  29101. getLabelModel: function () {
  29102. return this.model.getModel('axisLabel');
  29103. },
  29104. /**
  29105. * Notice here we only get the default tick model. For splitLine
  29106. * or splitArea, we should pass the splitLineModel or splitAreaModel
  29107. * manually when calling `getTicksCoords`.
  29108. * In GL, this method may be overrided to:
  29109. * `axisModel.getModel('axisTick', grid3DModel.getModel('axisTick'));`
  29110. * @return {module:echarts/coord/model/Model}
  29111. */
  29112. getTickModel: function () {
  29113. return this.model.getModel('axisTick');
  29114. },
  29115. /**
  29116. * Get width of band
  29117. * @return {number}
  29118. */
  29119. getBandWidth: function () {
  29120. var axisExtent = this._extent;
  29121. var dataExtent = this.scale.getExtent();
  29122. var len = dataExtent[1] - dataExtent[0] + (this.onBand ? 1 : 0);
  29123. // Fix #2728, avoid NaN when only one data.
  29124. len === 0 && (len = 1);
  29125. var size = Math.abs(axisExtent[1] - axisExtent[0]);
  29126. return Math.abs(size) / len;
  29127. },
  29128. /**
  29129. * @abstract
  29130. * @return {boolean} Is horizontal
  29131. */
  29132. isHorizontal: null,
  29133. /**
  29134. * @abstract
  29135. * @return {number} Get axis rotate, by degree.
  29136. */
  29137. getRotate: null,
  29138. /**
  29139. * Only be called in category axis.
  29140. * Can be overrided, consider other axes like in 3D.
  29141. * @param {boolean} hideLabel
  29142. * @return {number} Auto interval for cateogry axis tick and label
  29143. */
  29144. calculateCategoryInterval: function (hideLabel) {
  29145. return calculateCategoryInterval(this, hideLabel);
  29146. }
  29147. };
  29148. function fixExtentWithBands(extent, nTick) {
  29149. var size = extent[1] - extent[0];
  29150. var len = nTick;
  29151. var margin = size / len / 2;
  29152. extent[0] += margin;
  29153. extent[1] -= margin;
  29154. }
  29155. // If axis has labels [1, 2, 3, 4]. Bands on the axis are
  29156. // |---1---|---2---|---3---|---4---|.
  29157. // So the displayed ticks and splitLine/splitArea should between
  29158. // each data item, otherwise cause misleading (e.g., split tow bars
  29159. // of a single data item when there are two bar series).
  29160. // Also consider if tickCategoryInterval > 0 and onBand, ticks and
  29161. // splitLine/spliteArea should layout appropriately corresponding
  29162. // to displayed labels. (So we should not use `getBandWidth` in this
  29163. // case).
  29164. function fixOnBandTicksCoords(axis, ticksCoords, tickCategoryInterval, alignWithLabel, clamp) {
  29165. var ticksLen = ticksCoords.length;
  29166. if (!axis.onBand || alignWithLabel || !ticksLen) {
  29167. return;
  29168. }
  29169. var axisExtent = axis.getExtent();
  29170. var last;
  29171. if (ticksLen === 1) {
  29172. ticksCoords[0].coord = axisExtent[0];
  29173. last = ticksCoords[1] = {coord: axisExtent[0]};
  29174. }
  29175. else {
  29176. var shift = (ticksCoords[1].coord - ticksCoords[0].coord);
  29177. each$1(ticksCoords, function (ticksItem) {
  29178. ticksItem.coord -= shift / 2;
  29179. var tickCategoryInterval = tickCategoryInterval || 0;
  29180. // Avoid split a single data item when odd interval.
  29181. if (tickCategoryInterval % 2 > 0) {
  29182. ticksItem.coord -= shift / ((tickCategoryInterval + 1) * 2);
  29183. }
  29184. });
  29185. last = {coord: ticksCoords[ticksLen - 1].coord + shift};
  29186. ticksCoords.push(last);
  29187. }
  29188. var inverse = axisExtent[0] > axisExtent[1];
  29189. if (littleThan(ticksCoords[0].coord, axisExtent[0])) {
  29190. clamp ? (ticksCoords[0].coord = axisExtent[0]) : ticksCoords.shift();
  29191. }
  29192. if (clamp && littleThan(axisExtent[0], ticksCoords[0].coord)) {
  29193. ticksCoords.unshift({coord: axisExtent[0]});
  29194. }
  29195. if (littleThan(axisExtent[1], last.coord)) {
  29196. clamp ? (last.coord = axisExtent[1]) : ticksCoords.pop();
  29197. }
  29198. if (clamp && littleThan(last.coord, axisExtent[1])) {
  29199. ticksCoords.push({coord: axisExtent[1]});
  29200. }
  29201. function littleThan(a, b) {
  29202. return inverse ? a > b : a < b;
  29203. }
  29204. }
  29205. /*
  29206. * Licensed to the Apache Software Foundation (ASF) under one
  29207. * or more contributor license agreements. See the NOTICE file
  29208. * distributed with this work for additional information
  29209. * regarding copyright ownership. The ASF licenses this file
  29210. * to you under the Apache License, Version 2.0 (the
  29211. * "License"); you may not use this file except in compliance
  29212. * with the License. You may obtain a copy of the License at
  29213. *
  29214. * http://www.apache.org/licenses/LICENSE-2.0
  29215. *
  29216. * Unless required by applicable law or agreed to in writing,
  29217. * software distributed under the License is distributed on an
  29218. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29219. * KIND, either express or implied. See the License for the
  29220. * specific language governing permissions and limitations
  29221. * under the License.
  29222. */
  29223. /**
  29224. * Do not mount those modules on 'src/echarts' for better tree shaking.
  29225. */
  29226. var parseGeoJson = parseGeoJson$1;
  29227. var ecUtil = {};
  29228. each$1([
  29229. 'map', 'each', 'filter', 'indexOf', 'inherits', 'reduce', 'filter',
  29230. 'bind', 'curry', 'isArray', 'isString', 'isObject', 'isFunction',
  29231. 'extend', 'defaults', 'clone', 'merge'
  29232. ],
  29233. function (name) {
  29234. ecUtil[name] = zrUtil[name];
  29235. }
  29236. );
  29237. /*
  29238. * Licensed to the Apache Software Foundation (ASF) under one
  29239. * or more contributor license agreements. See the NOTICE file
  29240. * distributed with this work for additional information
  29241. * regarding copyright ownership. The ASF licenses this file
  29242. * to you under the Apache License, Version 2.0 (the
  29243. * "License"); you may not use this file except in compliance
  29244. * with the License. You may obtain a copy of the License at
  29245. *
  29246. * http://www.apache.org/licenses/LICENSE-2.0
  29247. *
  29248. * Unless required by applicable law or agreed to in writing,
  29249. * software distributed under the License is distributed on an
  29250. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29251. * KIND, either express or implied. See the License for the
  29252. * specific language governing permissions and limitations
  29253. * under the License.
  29254. */
  29255. SeriesModel.extend({
  29256. type: 'series.line',
  29257. dependencies: ['grid', 'polar'],
  29258. getInitialData: function (option, ecModel) {
  29259. if (__DEV__) {
  29260. var coordSys = option.coordinateSystem;
  29261. if (coordSys !== 'polar' && coordSys !== 'cartesian2d') {
  29262. throw new Error('Line not support coordinateSystem besides cartesian and polar');
  29263. }
  29264. }
  29265. return createListFromArray(this.getSource(), this);
  29266. },
  29267. defaultOption: {
  29268. zlevel: 0,
  29269. z: 2,
  29270. coordinateSystem: 'cartesian2d',
  29271. legendHoverLink: true,
  29272. hoverAnimation: true,
  29273. // stack: null
  29274. // xAxisIndex: 0,
  29275. // yAxisIndex: 0,
  29276. // polarIndex: 0,
  29277. // If clip the overflow value
  29278. clipOverflow: true,
  29279. // cursor: null,
  29280. label: {
  29281. position: 'top'
  29282. },
  29283. // itemStyle: {
  29284. // },
  29285. lineStyle: {
  29286. width: 2,
  29287. type: 'solid'
  29288. },
  29289. // areaStyle: {
  29290. // origin of areaStyle. Valid values:
  29291. // `'auto'/null/undefined`: from axisLine to data
  29292. // `'start'`: from min to data
  29293. // `'end'`: from data to max
  29294. // origin: 'auto'
  29295. // },
  29296. // false, 'start', 'end', 'middle'
  29297. step: false,
  29298. // Disabled if step is true
  29299. smooth: false,
  29300. smoothMonotone: null,
  29301. symbol: 'emptyCircle',
  29302. symbolSize: 4,
  29303. symbolRotate: null,
  29304. showSymbol: true,
  29305. // `false`: follow the label interval strategy.
  29306. // `true`: show all symbols.
  29307. // `'auto'`: If possible, show all symbols, otherwise
  29308. // follow the label interval strategy.
  29309. showAllSymbol: 'auto',
  29310. // Whether to connect break point.
  29311. connectNulls: false,
  29312. // Sampling for large data. Can be: 'average', 'max', 'min', 'sum'.
  29313. sampling: 'none',
  29314. animationEasing: 'linear',
  29315. // Disable progressive
  29316. progressive: 0,
  29317. hoverLayerThreshold: Infinity
  29318. }
  29319. });
  29320. /*
  29321. * Licensed to the Apache Software Foundation (ASF) under one
  29322. * or more contributor license agreements. See the NOTICE file
  29323. * distributed with this work for additional information
  29324. * regarding copyright ownership. The ASF licenses this file
  29325. * to you under the Apache License, Version 2.0 (the
  29326. * "License"); you may not use this file except in compliance
  29327. * with the License. You may obtain a copy of the License at
  29328. *
  29329. * http://www.apache.org/licenses/LICENSE-2.0
  29330. *
  29331. * Unless required by applicable law or agreed to in writing,
  29332. * software distributed under the License is distributed on an
  29333. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29334. * KIND, either express or implied. See the License for the
  29335. * specific language governing permissions and limitations
  29336. * under the License.
  29337. */
  29338. /**
  29339. * @param {module:echarts/data/List} data
  29340. * @param {number} dataIndex
  29341. * @return {string} label string. Not null/undefined
  29342. */
  29343. function getDefaultLabel(data, dataIndex) {
  29344. var labelDims = data.mapDimension('defaultedLabel', true);
  29345. var len = labelDims.length;
  29346. // Simple optimization (in lots of cases, label dims length is 1)
  29347. if (len === 1) {
  29348. return retrieveRawValue(data, dataIndex, labelDims[0]);
  29349. }
  29350. else if (len) {
  29351. var vals = [];
  29352. for (var i = 0; i < labelDims.length; i++) {
  29353. var val = retrieveRawValue(data, dataIndex, labelDims[i]);
  29354. vals.push(val);
  29355. }
  29356. return vals.join(' ');
  29357. }
  29358. }
  29359. /*
  29360. * Licensed to the Apache Software Foundation (ASF) under one
  29361. * or more contributor license agreements. See the NOTICE file
  29362. * distributed with this work for additional information
  29363. * regarding copyright ownership. The ASF licenses this file
  29364. * to you under the Apache License, Version 2.0 (the
  29365. * "License"); you may not use this file except in compliance
  29366. * with the License. You may obtain a copy of the License at
  29367. *
  29368. * http://www.apache.org/licenses/LICENSE-2.0
  29369. *
  29370. * Unless required by applicable law or agreed to in writing,
  29371. * software distributed under the License is distributed on an
  29372. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29373. * KIND, either express or implied. See the License for the
  29374. * specific language governing permissions and limitations
  29375. * under the License.
  29376. */
  29377. /**
  29378. * @module echarts/chart/helper/Symbol
  29379. */
  29380. /**
  29381. * @constructor
  29382. * @alias {module:echarts/chart/helper/Symbol}
  29383. * @param {module:echarts/data/List} data
  29384. * @param {number} idx
  29385. * @extends {module:zrender/graphic/Group}
  29386. */
  29387. function SymbolClz$1(data, idx, seriesScope) {
  29388. Group.call(this);
  29389. this.updateData(data, idx, seriesScope);
  29390. }
  29391. var symbolProto = SymbolClz$1.prototype;
  29392. /**
  29393. * @public
  29394. * @static
  29395. * @param {module:echarts/data/List} data
  29396. * @param {number} dataIndex
  29397. * @return {Array.<number>} [width, height]
  29398. */
  29399. var getSymbolSize = SymbolClz$1.getSymbolSize = function (data, idx) {
  29400. var symbolSize = data.getItemVisual(idx, 'symbolSize');
  29401. return symbolSize instanceof Array
  29402. ? symbolSize.slice()
  29403. : [+symbolSize, +symbolSize];
  29404. };
  29405. function getScale(symbolSize) {
  29406. return [symbolSize[0] / 2, symbolSize[1] / 2];
  29407. }
  29408. function driftSymbol(dx, dy) {
  29409. this.parent.drift(dx, dy);
  29410. }
  29411. symbolProto._createSymbol = function (
  29412. symbolType,
  29413. data,
  29414. idx,
  29415. symbolSize,
  29416. keepAspect
  29417. ) {
  29418. // Remove paths created before
  29419. this.removeAll();
  29420. var color = data.getItemVisual(idx, 'color');
  29421. // var symbolPath = createSymbol(
  29422. // symbolType, -0.5, -0.5, 1, 1, color
  29423. // );
  29424. // If width/height are set too small (e.g., set to 1) on ios10
  29425. // and macOS Sierra, a circle stroke become a rect, no matter what
  29426. // the scale is set. So we set width/height as 2. See #4150.
  29427. var symbolPath = createSymbol(
  29428. symbolType, -1, -1, 2, 2, color, keepAspect
  29429. );
  29430. symbolPath.attr({
  29431. z2: 100,
  29432. culling: true,
  29433. scale: getScale(symbolSize)
  29434. });
  29435. // Rewrite drift method
  29436. symbolPath.drift = driftSymbol;
  29437. this._symbolType = symbolType;
  29438. this.add(symbolPath);
  29439. };
  29440. /**
  29441. * Stop animation
  29442. * @param {boolean} toLastFrame
  29443. */
  29444. symbolProto.stopSymbolAnimation = function (toLastFrame) {
  29445. this.childAt(0).stopAnimation(toLastFrame);
  29446. };
  29447. /**
  29448. * FIXME:
  29449. * Caution: This method breaks the encapsulation of this module,
  29450. * but it indeed brings convenience. So do not use the method
  29451. * unless you detailedly know all the implements of `Symbol`,
  29452. * especially animation.
  29453. *
  29454. * Get symbol path element.
  29455. */
  29456. symbolProto.getSymbolPath = function () {
  29457. return this.childAt(0);
  29458. };
  29459. /**
  29460. * Get scale(aka, current symbol size).
  29461. * Including the change caused by animation
  29462. */
  29463. symbolProto.getScale = function () {
  29464. return this.childAt(0).scale;
  29465. };
  29466. /**
  29467. * Highlight symbol
  29468. */
  29469. symbolProto.highlight = function () {
  29470. this.childAt(0).trigger('emphasis');
  29471. };
  29472. /**
  29473. * Downplay symbol
  29474. */
  29475. symbolProto.downplay = function () {
  29476. this.childAt(0).trigger('normal');
  29477. };
  29478. /**
  29479. * @param {number} zlevel
  29480. * @param {number} z
  29481. */
  29482. symbolProto.setZ = function (zlevel, z) {
  29483. var symbolPath = this.childAt(0);
  29484. symbolPath.zlevel = zlevel;
  29485. symbolPath.z = z;
  29486. };
  29487. symbolProto.setDraggable = function (draggable) {
  29488. var symbolPath = this.childAt(0);
  29489. symbolPath.draggable = draggable;
  29490. symbolPath.cursor = draggable ? 'move' : 'pointer';
  29491. };
  29492. /**
  29493. * Update symbol properties
  29494. * @param {module:echarts/data/List} data
  29495. * @param {number} idx
  29496. * @param {Object} [seriesScope]
  29497. * @param {Object} [seriesScope.itemStyle]
  29498. * @param {Object} [seriesScope.hoverItemStyle]
  29499. * @param {Object} [seriesScope.symbolRotate]
  29500. * @param {Object} [seriesScope.symbolOffset]
  29501. * @param {module:echarts/model/Model} [seriesScope.labelModel]
  29502. * @param {module:echarts/model/Model} [seriesScope.hoverLabelModel]
  29503. * @param {boolean} [seriesScope.hoverAnimation]
  29504. * @param {Object} [seriesScope.cursorStyle]
  29505. * @param {module:echarts/model/Model} [seriesScope.itemModel]
  29506. * @param {string} [seriesScope.symbolInnerColor]
  29507. * @param {Object} [seriesScope.fadeIn=false]
  29508. */
  29509. symbolProto.updateData = function (data, idx, seriesScope) {
  29510. this.silent = false;
  29511. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  29512. var seriesModel = data.hostModel;
  29513. var symbolSize = getSymbolSize(data, idx);
  29514. var isInit = symbolType !== this._symbolType;
  29515. if (isInit) {
  29516. var keepAspect = data.getItemVisual(idx, 'symbolKeepAspect');
  29517. this._createSymbol(symbolType, data, idx, symbolSize, keepAspect);
  29518. }
  29519. else {
  29520. var symbolPath = this.childAt(0);
  29521. symbolPath.silent = false;
  29522. updateProps(symbolPath, {
  29523. scale: getScale(symbolSize)
  29524. }, seriesModel, idx);
  29525. }
  29526. this._updateCommon(data, idx, symbolSize, seriesScope);
  29527. if (isInit) {
  29528. var symbolPath = this.childAt(0);
  29529. var fadeIn = seriesScope && seriesScope.fadeIn;
  29530. var target = {scale: symbolPath.scale.slice()};
  29531. fadeIn && (target.style = {opacity: symbolPath.style.opacity});
  29532. symbolPath.scale = [0, 0];
  29533. fadeIn && (symbolPath.style.opacity = 0);
  29534. initProps(symbolPath, target, seriesModel, idx);
  29535. }
  29536. this._seriesModel = seriesModel;
  29537. };
  29538. // Update common properties
  29539. var normalStyleAccessPath = ['itemStyle'];
  29540. var emphasisStyleAccessPath = ['emphasis', 'itemStyle'];
  29541. var normalLabelAccessPath = ['label'];
  29542. var emphasisLabelAccessPath = ['emphasis', 'label'];
  29543. /**
  29544. * @param {module:echarts/data/List} data
  29545. * @param {number} idx
  29546. * @param {Array.<number>} symbolSize
  29547. * @param {Object} [seriesScope]
  29548. */
  29549. symbolProto._updateCommon = function (data, idx, symbolSize, seriesScope) {
  29550. var symbolPath = this.childAt(0);
  29551. var seriesModel = data.hostModel;
  29552. var color = data.getItemVisual(idx, 'color');
  29553. // Reset style
  29554. if (symbolPath.type !== 'image') {
  29555. symbolPath.useStyle({
  29556. strokeNoScale: true
  29557. });
  29558. }
  29559. var itemStyle = seriesScope && seriesScope.itemStyle;
  29560. var hoverItemStyle = seriesScope && seriesScope.hoverItemStyle;
  29561. var symbolRotate = seriesScope && seriesScope.symbolRotate;
  29562. var symbolOffset = seriesScope && seriesScope.symbolOffset;
  29563. var labelModel = seriesScope && seriesScope.labelModel;
  29564. var hoverLabelModel = seriesScope && seriesScope.hoverLabelModel;
  29565. var hoverAnimation = seriesScope && seriesScope.hoverAnimation;
  29566. var cursorStyle = seriesScope && seriesScope.cursorStyle;
  29567. if (!seriesScope || data.hasItemOption) {
  29568. var itemModel = (seriesScope && seriesScope.itemModel)
  29569. ? seriesScope.itemModel : data.getItemModel(idx);
  29570. // Color must be excluded.
  29571. // Because symbol provide setColor individually to set fill and stroke
  29572. itemStyle = itemModel.getModel(normalStyleAccessPath).getItemStyle(['color']);
  29573. hoverItemStyle = itemModel.getModel(emphasisStyleAccessPath).getItemStyle();
  29574. symbolRotate = itemModel.getShallow('symbolRotate');
  29575. symbolOffset = itemModel.getShallow('symbolOffset');
  29576. labelModel = itemModel.getModel(normalLabelAccessPath);
  29577. hoverLabelModel = itemModel.getModel(emphasisLabelAccessPath);
  29578. hoverAnimation = itemModel.getShallow('hoverAnimation');
  29579. cursorStyle = itemModel.getShallow('cursor');
  29580. }
  29581. else {
  29582. hoverItemStyle = extend({}, hoverItemStyle);
  29583. }
  29584. var elStyle = symbolPath.style;
  29585. symbolPath.attr('rotation', (symbolRotate || 0) * Math.PI / 180 || 0);
  29586. if (symbolOffset) {
  29587. symbolPath.attr('position', [
  29588. parsePercent$1(symbolOffset[0], symbolSize[0]),
  29589. parsePercent$1(symbolOffset[1], symbolSize[1])
  29590. ]);
  29591. }
  29592. cursorStyle && symbolPath.attr('cursor', cursorStyle);
  29593. // PENDING setColor before setStyle!!!
  29594. symbolPath.setColor(color, seriesScope && seriesScope.symbolInnerColor);
  29595. symbolPath.setStyle(itemStyle);
  29596. var opacity = data.getItemVisual(idx, 'opacity');
  29597. if (opacity != null) {
  29598. elStyle.opacity = opacity;
  29599. }
  29600. var liftZ = data.getItemVisual(idx, 'liftZ');
  29601. var z2Origin = symbolPath.__z2Origin;
  29602. if (liftZ != null) {
  29603. if (z2Origin == null) {
  29604. symbolPath.__z2Origin = symbolPath.z2;
  29605. symbolPath.z2 += liftZ;
  29606. }
  29607. }
  29608. else if (z2Origin != null) {
  29609. symbolPath.z2 = z2Origin;
  29610. symbolPath.__z2Origin = null;
  29611. }
  29612. var useNameLabel = seriesScope && seriesScope.useNameLabel;
  29613. setLabelStyle(
  29614. elStyle, hoverItemStyle, labelModel, hoverLabelModel,
  29615. {
  29616. labelFetcher: seriesModel,
  29617. labelDataIndex: idx,
  29618. defaultText: getLabelDefaultText,
  29619. isRectText: true,
  29620. autoColor: color
  29621. }
  29622. );
  29623. // Do not execute util needed.
  29624. function getLabelDefaultText(idx, opt) {
  29625. return useNameLabel ? data.getName(idx) : getDefaultLabel(data, idx);
  29626. }
  29627. symbolPath.off('mouseover')
  29628. .off('mouseout')
  29629. .off('emphasis')
  29630. .off('normal');
  29631. symbolPath.hoverStyle = hoverItemStyle;
  29632. // FIXME
  29633. // Do not use symbol.trigger('emphasis'), but use symbol.highlight() instead.
  29634. setHoverStyle(symbolPath);
  29635. var scale = getScale(symbolSize);
  29636. if (hoverAnimation && seriesModel.isAnimationEnabled()) {
  29637. var onEmphasis = function() {
  29638. // Do not support this hover animation util some scenario required.
  29639. // Animation can only be supported in hover layer when using `el.incremetal`.
  29640. if (this.incremental) {
  29641. return;
  29642. }
  29643. var ratio = scale[1] / scale[0];
  29644. this.animateTo({
  29645. scale: [
  29646. Math.max(scale[0] * 1.1, scale[0] + 3),
  29647. Math.max(scale[1] * 1.1, scale[1] + 3 * ratio)
  29648. ]
  29649. }, 400, 'elasticOut');
  29650. };
  29651. var onNormal = function() {
  29652. if (this.incremental) {
  29653. return;
  29654. }
  29655. this.animateTo({
  29656. scale: scale
  29657. }, 400, 'elasticOut');
  29658. };
  29659. symbolPath.on('mouseover', onEmphasis)
  29660. .on('mouseout', onNormal)
  29661. .on('emphasis', onEmphasis)
  29662. .on('normal', onNormal);
  29663. }
  29664. };
  29665. /**
  29666. * @param {Function} cb
  29667. * @param {Object} [opt]
  29668. * @param {Object} [opt.keepLabel=true]
  29669. */
  29670. symbolProto.fadeOut = function (cb, opt) {
  29671. var symbolPath = this.childAt(0);
  29672. // Avoid mistaken hover when fading out
  29673. this.silent = symbolPath.silent = true;
  29674. // Not show text when animating
  29675. !(opt && opt.keepLabel) && (symbolPath.style.text = null);
  29676. updateProps(
  29677. symbolPath,
  29678. {
  29679. style: {opacity: 0},
  29680. scale: [0, 0]
  29681. },
  29682. this._seriesModel,
  29683. this.dataIndex,
  29684. cb
  29685. );
  29686. };
  29687. inherits(SymbolClz$1, Group);
  29688. /*
  29689. * Licensed to the Apache Software Foundation (ASF) under one
  29690. * or more contributor license agreements. See the NOTICE file
  29691. * distributed with this work for additional information
  29692. * regarding copyright ownership. The ASF licenses this file
  29693. * to you under the Apache License, Version 2.0 (the
  29694. * "License"); you may not use this file except in compliance
  29695. * with the License. You may obtain a copy of the License at
  29696. *
  29697. * http://www.apache.org/licenses/LICENSE-2.0
  29698. *
  29699. * Unless required by applicable law or agreed to in writing,
  29700. * software distributed under the License is distributed on an
  29701. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29702. * KIND, either express or implied. See the License for the
  29703. * specific language governing permissions and limitations
  29704. * under the License.
  29705. */
  29706. /**
  29707. * @module echarts/chart/helper/SymbolDraw
  29708. */
  29709. /**
  29710. * @constructor
  29711. * @alias module:echarts/chart/helper/SymbolDraw
  29712. * @param {module:zrender/graphic/Group} [symbolCtor]
  29713. */
  29714. function SymbolDraw(symbolCtor) {
  29715. this.group = new Group();
  29716. this._symbolCtor = symbolCtor || SymbolClz$1;
  29717. }
  29718. var symbolDrawProto = SymbolDraw.prototype;
  29719. function symbolNeedsDraw(data, point, idx, opt) {
  29720. return point && !isNaN(point[0]) && !isNaN(point[1])
  29721. && !(opt.isIgnore && opt.isIgnore(idx))
  29722. // We do not set clipShape on group, because it will cut part of
  29723. // the symbol element shape. We use the same clip shape here as
  29724. // the line clip.
  29725. && !(opt.clipShape && !opt.clipShape.contain(point[0], point[1]))
  29726. && data.getItemVisual(idx, 'symbol') !== 'none';
  29727. }
  29728. /**
  29729. * Update symbols draw by new data
  29730. * @param {module:echarts/data/List} data
  29731. * @param {Object} [opt] Or isIgnore
  29732. * @param {Function} [opt.isIgnore]
  29733. * @param {Object} [opt.clipShape]
  29734. */
  29735. symbolDrawProto.updateData = function (data, opt) {
  29736. opt = normalizeUpdateOpt(opt);
  29737. var group = this.group;
  29738. var seriesModel = data.hostModel;
  29739. var oldData = this._data;
  29740. var SymbolCtor = this._symbolCtor;
  29741. var seriesScope = makeSeriesScope(data);
  29742. // There is no oldLineData only when first rendering or switching from
  29743. // stream mode to normal mode, where previous elements should be removed.
  29744. if (!oldData) {
  29745. group.removeAll();
  29746. }
  29747. data.diff(oldData)
  29748. .add(function (newIdx) {
  29749. var point = data.getItemLayout(newIdx);
  29750. if (symbolNeedsDraw(data, point, newIdx, opt)) {
  29751. var symbolEl = new SymbolCtor(data, newIdx, seriesScope);
  29752. symbolEl.attr('position', point);
  29753. data.setItemGraphicEl(newIdx, symbolEl);
  29754. group.add(symbolEl);
  29755. }
  29756. })
  29757. .update(function (newIdx, oldIdx) {
  29758. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  29759. var point = data.getItemLayout(newIdx);
  29760. if (!symbolNeedsDraw(data, point, newIdx, opt)) {
  29761. group.remove(symbolEl);
  29762. return;
  29763. }
  29764. if (!symbolEl) {
  29765. symbolEl = new SymbolCtor(data, newIdx);
  29766. symbolEl.attr('position', point);
  29767. }
  29768. else {
  29769. symbolEl.updateData(data, newIdx, seriesScope);
  29770. updateProps(symbolEl, {
  29771. position: point
  29772. }, seriesModel);
  29773. }
  29774. // Add back
  29775. group.add(symbolEl);
  29776. data.setItemGraphicEl(newIdx, symbolEl);
  29777. })
  29778. .remove(function (oldIdx) {
  29779. var el = oldData.getItemGraphicEl(oldIdx);
  29780. el && el.fadeOut(function () {
  29781. group.remove(el);
  29782. });
  29783. })
  29784. .execute();
  29785. this._data = data;
  29786. };
  29787. symbolDrawProto.isPersistent = function () {
  29788. return true;
  29789. };
  29790. symbolDrawProto.updateLayout = function () {
  29791. var data = this._data;
  29792. if (data) {
  29793. // Not use animation
  29794. data.eachItemGraphicEl(function (el, idx) {
  29795. var point = data.getItemLayout(idx);
  29796. el.attr('position', point);
  29797. });
  29798. }
  29799. };
  29800. symbolDrawProto.incrementalPrepareUpdate = function (data) {
  29801. this._seriesScope = makeSeriesScope(data);
  29802. this._data = null;
  29803. this.group.removeAll();
  29804. };
  29805. /**
  29806. * Update symbols draw by new data
  29807. * @param {module:echarts/data/List} data
  29808. * @param {Object} [opt] Or isIgnore
  29809. * @param {Function} [opt.isIgnore]
  29810. * @param {Object} [opt.clipShape]
  29811. */
  29812. symbolDrawProto.incrementalUpdate = function (taskParams, data, opt) {
  29813. opt = normalizeUpdateOpt(opt);
  29814. function updateIncrementalAndHover(el) {
  29815. if (!el.isGroup) {
  29816. el.incremental = el.useHoverLayer = true;
  29817. }
  29818. }
  29819. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  29820. var point = data.getItemLayout(idx);
  29821. if (symbolNeedsDraw(data, point, idx, opt)) {
  29822. var el = new this._symbolCtor(data, idx, this._seriesScope);
  29823. el.traverse(updateIncrementalAndHover);
  29824. el.attr('position', point);
  29825. this.group.add(el);
  29826. data.setItemGraphicEl(idx, el);
  29827. }
  29828. }
  29829. };
  29830. function normalizeUpdateOpt(opt) {
  29831. if (opt != null && !isObject$1(opt)) {
  29832. opt = {isIgnore: opt};
  29833. }
  29834. return opt || {};
  29835. }
  29836. symbolDrawProto.remove = function (enableAnimation) {
  29837. var group = this.group;
  29838. var data = this._data;
  29839. // Incremental model do not have this._data.
  29840. if (data && enableAnimation) {
  29841. data.eachItemGraphicEl(function (el) {
  29842. el.fadeOut(function () {
  29843. group.remove(el);
  29844. });
  29845. });
  29846. }
  29847. else {
  29848. group.removeAll();
  29849. }
  29850. };
  29851. function makeSeriesScope(data) {
  29852. var seriesModel = data.hostModel;
  29853. return {
  29854. itemStyle: seriesModel.getModel('itemStyle').getItemStyle(['color']),
  29855. hoverItemStyle: seriesModel.getModel('emphasis.itemStyle').getItemStyle(),
  29856. symbolRotate: seriesModel.get('symbolRotate'),
  29857. symbolOffset: seriesModel.get('symbolOffset'),
  29858. hoverAnimation: seriesModel.get('hoverAnimation'),
  29859. labelModel: seriesModel.getModel('label'),
  29860. hoverLabelModel: seriesModel.getModel('emphasis.label'),
  29861. cursorStyle: seriesModel.get('cursor')
  29862. };
  29863. }
  29864. /*
  29865. * Licensed to the Apache Software Foundation (ASF) under one
  29866. * or more contributor license agreements. See the NOTICE file
  29867. * distributed with this work for additional information
  29868. * regarding copyright ownership. The ASF licenses this file
  29869. * to you under the Apache License, Version 2.0 (the
  29870. * "License"); you may not use this file except in compliance
  29871. * with the License. You may obtain a copy of the License at
  29872. *
  29873. * http://www.apache.org/licenses/LICENSE-2.0
  29874. *
  29875. * Unless required by applicable law or agreed to in writing,
  29876. * software distributed under the License is distributed on an
  29877. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29878. * KIND, either express or implied. See the License for the
  29879. * specific language governing permissions and limitations
  29880. * under the License.
  29881. */
  29882. /**
  29883. * @param {Object} coordSys
  29884. * @param {module:echarts/data/List} data
  29885. * @param {string} valueOrigin lineSeries.option.areaStyle.origin
  29886. */
  29887. function prepareDataCoordInfo(coordSys, data, valueOrigin) {
  29888. var baseAxis = coordSys.getBaseAxis();
  29889. var valueAxis = coordSys.getOtherAxis(baseAxis);
  29890. var valueStart = getValueStart(valueAxis, valueOrigin);
  29891. var baseAxisDim = baseAxis.dim;
  29892. var valueAxisDim = valueAxis.dim;
  29893. var valueDim = data.mapDimension(valueAxisDim);
  29894. var baseDim = data.mapDimension(baseAxisDim);
  29895. var baseDataOffset = valueAxisDim === 'x' || valueAxisDim === 'radius' ? 1 : 0;
  29896. var dims = map(coordSys.dimensions, function (coordDim) {
  29897. return data.mapDimension(coordDim);
  29898. });
  29899. var stacked;
  29900. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  29901. if (stacked |= isDimensionStacked(data, dims[0], dims[1])) { // jshint ignore:line
  29902. dims[0] = stackResultDim;
  29903. }
  29904. if (stacked |= isDimensionStacked(data, dims[1], dims[0])) { // jshint ignore:line
  29905. dims[1] = stackResultDim;
  29906. }
  29907. return {
  29908. dataDimsForPoint: dims,
  29909. valueStart: valueStart,
  29910. valueAxisDim: valueAxisDim,
  29911. baseAxisDim: baseAxisDim,
  29912. stacked: !!stacked,
  29913. valueDim: valueDim,
  29914. baseDim: baseDim,
  29915. baseDataOffset: baseDataOffset,
  29916. stackedOverDimension: data.getCalculationInfo('stackedOverDimension')
  29917. };
  29918. }
  29919. function getValueStart(valueAxis, valueOrigin) {
  29920. var valueStart = 0;
  29921. var extent = valueAxis.scale.getExtent();
  29922. if (valueOrigin === 'start') {
  29923. valueStart = extent[0];
  29924. }
  29925. else if (valueOrigin === 'end') {
  29926. valueStart = extent[1];
  29927. }
  29928. // auto
  29929. else {
  29930. // Both positive
  29931. if (extent[0] > 0) {
  29932. valueStart = extent[0];
  29933. }
  29934. // Both negative
  29935. else if (extent[1] < 0) {
  29936. valueStart = extent[1];
  29937. }
  29938. // If is one positive, and one negative, onZero shall be true
  29939. }
  29940. return valueStart;
  29941. }
  29942. function getStackedOnPoint(dataCoordInfo, coordSys, data, idx) {
  29943. var value = NaN;
  29944. if (dataCoordInfo.stacked) {
  29945. value = data.get(data.getCalculationInfo('stackedOverDimension'), idx);
  29946. }
  29947. if (isNaN(value)) {
  29948. value = dataCoordInfo.valueStart;
  29949. }
  29950. var baseDataOffset = dataCoordInfo.baseDataOffset;
  29951. var stackedData = [];
  29952. stackedData[baseDataOffset] = data.get(dataCoordInfo.baseDim, idx);
  29953. stackedData[1 - baseDataOffset] = value;
  29954. return coordSys.dataToPoint(stackedData);
  29955. }
  29956. /*
  29957. * Licensed to the Apache Software Foundation (ASF) under one
  29958. * or more contributor license agreements. See the NOTICE file
  29959. * distributed with this work for additional information
  29960. * regarding copyright ownership. The ASF licenses this file
  29961. * to you under the Apache License, Version 2.0 (the
  29962. * "License"); you may not use this file except in compliance
  29963. * with the License. You may obtain a copy of the License at
  29964. *
  29965. * http://www.apache.org/licenses/LICENSE-2.0
  29966. *
  29967. * Unless required by applicable law or agreed to in writing,
  29968. * software distributed under the License is distributed on an
  29969. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29970. * KIND, either express or implied. See the License for the
  29971. * specific language governing permissions and limitations
  29972. * under the License.
  29973. */
  29974. // var arrayDiff = require('zrender/src/core/arrayDiff');
  29975. // 'zrender/src/core/arrayDiff' has been used before, but it did
  29976. // not do well in performance when roam with fixed dataZoom window.
  29977. // function convertToIntId(newIdList, oldIdList) {
  29978. // // Generate int id instead of string id.
  29979. // // Compare string maybe slow in score function of arrDiff
  29980. // // Assume id in idList are all unique
  29981. // var idIndicesMap = {};
  29982. // var idx = 0;
  29983. // for (var i = 0; i < newIdList.length; i++) {
  29984. // idIndicesMap[newIdList[i]] = idx;
  29985. // newIdList[i] = idx++;
  29986. // }
  29987. // for (var i = 0; i < oldIdList.length; i++) {
  29988. // var oldId = oldIdList[i];
  29989. // // Same with newIdList
  29990. // if (idIndicesMap[oldId]) {
  29991. // oldIdList[i] = idIndicesMap[oldId];
  29992. // }
  29993. // else {
  29994. // oldIdList[i] = idx++;
  29995. // }
  29996. // }
  29997. // }
  29998. function diffData(oldData, newData) {
  29999. var diffResult = [];
  30000. newData.diff(oldData)
  30001. .add(function (idx) {
  30002. diffResult.push({cmd: '+', idx: idx});
  30003. })
  30004. .update(function (newIdx, oldIdx) {
  30005. diffResult.push({cmd: '=', idx: oldIdx, idx1: newIdx});
  30006. })
  30007. .remove(function (idx) {
  30008. diffResult.push({cmd: '-', idx: idx});
  30009. })
  30010. .execute();
  30011. return diffResult;
  30012. }
  30013. var lineAnimationDiff = function (
  30014. oldData, newData,
  30015. oldStackedOnPoints, newStackedOnPoints,
  30016. oldCoordSys, newCoordSys,
  30017. oldValueOrigin, newValueOrigin
  30018. ) {
  30019. var diff = diffData(oldData, newData);
  30020. // var newIdList = newData.mapArray(newData.getId);
  30021. // var oldIdList = oldData.mapArray(oldData.getId);
  30022. // convertToIntId(newIdList, oldIdList);
  30023. // // FIXME One data ?
  30024. // diff = arrayDiff(oldIdList, newIdList);
  30025. var currPoints = [];
  30026. var nextPoints = [];
  30027. // Points for stacking base line
  30028. var currStackedPoints = [];
  30029. var nextStackedPoints = [];
  30030. var status = [];
  30031. var sortedIndices = [];
  30032. var rawIndices = [];
  30033. var newDataOldCoordInfo = prepareDataCoordInfo(oldCoordSys, newData, oldValueOrigin);
  30034. var oldDataNewCoordInfo = prepareDataCoordInfo(newCoordSys, oldData, newValueOrigin);
  30035. for (var i = 0; i < diff.length; i++) {
  30036. var diffItem = diff[i];
  30037. var pointAdded = true;
  30038. // FIXME, animation is not so perfect when dataZoom window moves fast
  30039. // Which is in case remvoing or add more than one data in the tail or head
  30040. switch (diffItem.cmd) {
  30041. case '=':
  30042. var currentPt = oldData.getItemLayout(diffItem.idx);
  30043. var nextPt = newData.getItemLayout(diffItem.idx1);
  30044. // If previous data is NaN, use next point directly
  30045. if (isNaN(currentPt[0]) || isNaN(currentPt[1])) {
  30046. currentPt = nextPt.slice();
  30047. }
  30048. currPoints.push(currentPt);
  30049. nextPoints.push(nextPt);
  30050. currStackedPoints.push(oldStackedOnPoints[diffItem.idx]);
  30051. nextStackedPoints.push(newStackedOnPoints[diffItem.idx1]);
  30052. rawIndices.push(newData.getRawIndex(diffItem.idx1));
  30053. break;
  30054. case '+':
  30055. var idx = diffItem.idx;
  30056. currPoints.push(
  30057. oldCoordSys.dataToPoint([
  30058. newData.get(newDataOldCoordInfo.dataDimsForPoint[0], idx),
  30059. newData.get(newDataOldCoordInfo.dataDimsForPoint[1], idx)
  30060. ])
  30061. );
  30062. nextPoints.push(newData.getItemLayout(idx).slice());
  30063. currStackedPoints.push(
  30064. getStackedOnPoint(newDataOldCoordInfo, oldCoordSys, newData, idx)
  30065. );
  30066. nextStackedPoints.push(newStackedOnPoints[idx]);
  30067. rawIndices.push(newData.getRawIndex(idx));
  30068. break;
  30069. case '-':
  30070. var idx = diffItem.idx;
  30071. var rawIndex = oldData.getRawIndex(idx);
  30072. // Data is replaced. In the case of dynamic data queue
  30073. // FIXME FIXME FIXME
  30074. if (rawIndex !== idx) {
  30075. currPoints.push(oldData.getItemLayout(idx));
  30076. nextPoints.push(newCoordSys.dataToPoint([
  30077. oldData.get(oldDataNewCoordInfo.dataDimsForPoint[0], idx),
  30078. oldData.get(oldDataNewCoordInfo.dataDimsForPoint[1], idx)
  30079. ]));
  30080. currStackedPoints.push(oldStackedOnPoints[idx]);
  30081. nextStackedPoints.push(
  30082. getStackedOnPoint(oldDataNewCoordInfo, newCoordSys, oldData, idx)
  30083. );
  30084. rawIndices.push(rawIndex);
  30085. }
  30086. else {
  30087. pointAdded = false;
  30088. }
  30089. }
  30090. // Original indices
  30091. if (pointAdded) {
  30092. status.push(diffItem);
  30093. sortedIndices.push(sortedIndices.length);
  30094. }
  30095. }
  30096. // Diff result may be crossed if all items are changed
  30097. // Sort by data index
  30098. sortedIndices.sort(function (a, b) {
  30099. return rawIndices[a] - rawIndices[b];
  30100. });
  30101. var sortedCurrPoints = [];
  30102. var sortedNextPoints = [];
  30103. var sortedCurrStackedPoints = [];
  30104. var sortedNextStackedPoints = [];
  30105. var sortedStatus = [];
  30106. for (var i = 0; i < sortedIndices.length; i++) {
  30107. var idx = sortedIndices[i];
  30108. sortedCurrPoints[i] = currPoints[idx];
  30109. sortedNextPoints[i] = nextPoints[idx];
  30110. sortedCurrStackedPoints[i] = currStackedPoints[idx];
  30111. sortedNextStackedPoints[i] = nextStackedPoints[idx];
  30112. sortedStatus[i] = status[idx];
  30113. }
  30114. return {
  30115. current: sortedCurrPoints,
  30116. next: sortedNextPoints,
  30117. stackedOnCurrent: sortedCurrStackedPoints,
  30118. stackedOnNext: sortedNextStackedPoints,
  30119. status: sortedStatus
  30120. };
  30121. };
  30122. /*
  30123. * Licensed to the Apache Software Foundation (ASF) under one
  30124. * or more contributor license agreements. See the NOTICE file
  30125. * distributed with this work for additional information
  30126. * regarding copyright ownership. The ASF licenses this file
  30127. * to you under the Apache License, Version 2.0 (the
  30128. * "License"); you may not use this file except in compliance
  30129. * with the License. You may obtain a copy of the License at
  30130. *
  30131. * http://www.apache.org/licenses/LICENSE-2.0
  30132. *
  30133. * Unless required by applicable law or agreed to in writing,
  30134. * software distributed under the License is distributed on an
  30135. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30136. * KIND, either express or implied. See the License for the
  30137. * specific language governing permissions and limitations
  30138. * under the License.
  30139. */
  30140. // Poly path support NaN point
  30141. var vec2Min = min;
  30142. var vec2Max = max;
  30143. var scaleAndAdd$1 = scaleAndAdd;
  30144. var v2Copy = copy;
  30145. // Temporary variable
  30146. var v = [];
  30147. var cp0 = [];
  30148. var cp1 = [];
  30149. function isPointNull(p) {
  30150. return isNaN(p[0]) || isNaN(p[1]);
  30151. }
  30152. function drawSegment(
  30153. ctx, points, start, segLen, allLen,
  30154. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  30155. ) {
  30156. if (smoothMonotone == null) {
  30157. if (isMono(points, 'x')) {
  30158. return drawMono(ctx, points, start, segLen, allLen,
  30159. dir, smoothMin, smoothMax, smooth, 'x', connectNulls);
  30160. }
  30161. else if (isMono(points, 'y')) {
  30162. return drawMono(ctx, points, start, segLen, allLen,
  30163. dir, smoothMin, smoothMax, smooth, 'y', connectNulls);
  30164. }
  30165. else {
  30166. return drawNonMono.apply(this, arguments);
  30167. }
  30168. }
  30169. else if (smoothMonotone !== 'none' && isMono(points, smoothMonotone)) {
  30170. return drawMono.apply(this, arguments);
  30171. }
  30172. else {
  30173. return drawNonMono.apply(this, arguments);
  30174. }
  30175. }
  30176. /**
  30177. * Check if points is in monotone.
  30178. *
  30179. * @param {number[][]} points Array of points which is in [x, y] form
  30180. * @param {string} smoothMonotone 'x', 'y', or 'none', stating for which
  30181. * dimension that is checking.
  30182. * If is 'none', `drawNonMono` should be
  30183. * called.
  30184. * If is undefined, either being monotone
  30185. * in 'x' or 'y' will call `drawMono`.
  30186. */
  30187. function isMono(points, smoothMonotone) {
  30188. if (points.length <= 1) {
  30189. return true;
  30190. }
  30191. var dim = smoothMonotone === 'x' ? 0 : 1;
  30192. var last = points[0][dim];
  30193. var lastDiff = 0;
  30194. for (var i = 1; i < points.length; ++i) {
  30195. var diff = points[i][dim] - last;
  30196. if (!isNaN(diff) && !isNaN(lastDiff)
  30197. && diff !== 0 && lastDiff !== 0
  30198. && ((diff >= 0) !== (lastDiff >= 0))
  30199. ) {
  30200. return false;
  30201. }
  30202. if (!isNaN(diff) && diff !== 0) {
  30203. lastDiff = diff;
  30204. last = points[i][dim];
  30205. }
  30206. }
  30207. return true;
  30208. }
  30209. /**
  30210. * Draw smoothed line in monotone, in which only vertical or horizontal bezier
  30211. * control points will be used. This should be used when points are monotone
  30212. * either in x or y dimension.
  30213. */
  30214. function drawMono(
  30215. ctx, points, start, segLen, allLen,
  30216. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  30217. ) {
  30218. var prevIdx = 0;
  30219. var idx = start;
  30220. for (var k = 0; k < segLen; k++) {
  30221. var p = points[idx];
  30222. if (idx >= allLen || idx < 0) {
  30223. break;
  30224. }
  30225. if (isPointNull(p)) {
  30226. if (connectNulls) {
  30227. idx += dir;
  30228. continue;
  30229. }
  30230. break;
  30231. }
  30232. if (idx === start) {
  30233. ctx[dir > 0 ? 'moveTo' : 'lineTo'](p[0], p[1]);
  30234. }
  30235. else {
  30236. if (smooth > 0) {
  30237. var prevP = points[prevIdx];
  30238. var dim = smoothMonotone === 'y' ? 1 : 0;
  30239. // Length of control point to p, either in x or y, but not both
  30240. var ctrlLen = (p[dim] - prevP[dim]) * smooth;
  30241. v2Copy(cp0, prevP);
  30242. cp0[dim] = prevP[dim] + ctrlLen;
  30243. v2Copy(cp1, p);
  30244. cp1[dim] = p[dim] - ctrlLen;
  30245. ctx.bezierCurveTo(
  30246. cp0[0], cp0[1],
  30247. cp1[0], cp1[1],
  30248. p[0], p[1]
  30249. );
  30250. }
  30251. else {
  30252. ctx.lineTo(p[0], p[1]);
  30253. }
  30254. }
  30255. prevIdx = idx;
  30256. idx += dir;
  30257. }
  30258. return k;
  30259. }
  30260. /**
  30261. * Draw smoothed line in non-monotone, in may cause undesired curve in extreme
  30262. * situations. This should be used when points are non-monotone neither in x or
  30263. * y dimension.
  30264. */
  30265. function drawNonMono(
  30266. ctx, points, start, segLen, allLen,
  30267. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  30268. ) {
  30269. var prevIdx = 0;
  30270. var idx = start;
  30271. for (var k = 0; k < segLen; k++) {
  30272. var p = points[idx];
  30273. if (idx >= allLen || idx < 0) {
  30274. break;
  30275. }
  30276. if (isPointNull(p)) {
  30277. if (connectNulls) {
  30278. idx += dir;
  30279. continue;
  30280. }
  30281. break;
  30282. }
  30283. if (idx === start) {
  30284. ctx[dir > 0 ? 'moveTo' : 'lineTo'](p[0], p[1]);
  30285. v2Copy(cp0, p);
  30286. }
  30287. else {
  30288. if (smooth > 0) {
  30289. var nextIdx = idx + dir;
  30290. var nextP = points[nextIdx];
  30291. if (connectNulls) {
  30292. // Find next point not null
  30293. while (nextP && isPointNull(points[nextIdx])) {
  30294. nextIdx += dir;
  30295. nextP = points[nextIdx];
  30296. }
  30297. }
  30298. var ratioNextSeg = 0.5;
  30299. var prevP = points[prevIdx];
  30300. var nextP = points[nextIdx];
  30301. // Last point
  30302. if (!nextP || isPointNull(nextP)) {
  30303. v2Copy(cp1, p);
  30304. }
  30305. else {
  30306. // If next data is null in not connect case
  30307. if (isPointNull(nextP) && !connectNulls) {
  30308. nextP = p;
  30309. }
  30310. sub(v, nextP, prevP);
  30311. var lenPrevSeg;
  30312. var lenNextSeg;
  30313. if (smoothMonotone === 'x' || smoothMonotone === 'y') {
  30314. var dim = smoothMonotone === 'x' ? 0 : 1;
  30315. lenPrevSeg = Math.abs(p[dim] - prevP[dim]);
  30316. lenNextSeg = Math.abs(p[dim] - nextP[dim]);
  30317. }
  30318. else {
  30319. lenPrevSeg = dist(p, prevP);
  30320. lenNextSeg = dist(p, nextP);
  30321. }
  30322. // Use ratio of seg length
  30323. ratioNextSeg = lenNextSeg / (lenNextSeg + lenPrevSeg);
  30324. scaleAndAdd$1(cp1, p, v, -smooth * (1 - ratioNextSeg));
  30325. }
  30326. // Smooth constraint
  30327. vec2Min(cp0, cp0, smoothMax);
  30328. vec2Max(cp0, cp0, smoothMin);
  30329. vec2Min(cp1, cp1, smoothMax);
  30330. vec2Max(cp1, cp1, smoothMin);
  30331. ctx.bezierCurveTo(
  30332. cp0[0], cp0[1],
  30333. cp1[0], cp1[1],
  30334. p[0], p[1]
  30335. );
  30336. // cp0 of next segment
  30337. scaleAndAdd$1(cp0, p, v, smooth * ratioNextSeg);
  30338. }
  30339. else {
  30340. ctx.lineTo(p[0], p[1]);
  30341. }
  30342. }
  30343. prevIdx = idx;
  30344. idx += dir;
  30345. }
  30346. return k;
  30347. }
  30348. function getBoundingBox(points, smoothConstraint) {
  30349. var ptMin = [Infinity, Infinity];
  30350. var ptMax = [-Infinity, -Infinity];
  30351. if (smoothConstraint) {
  30352. for (var i = 0; i < points.length; i++) {
  30353. var pt = points[i];
  30354. if (pt[0] < ptMin[0]) { ptMin[0] = pt[0]; }
  30355. if (pt[1] < ptMin[1]) { ptMin[1] = pt[1]; }
  30356. if (pt[0] > ptMax[0]) { ptMax[0] = pt[0]; }
  30357. if (pt[1] > ptMax[1]) { ptMax[1] = pt[1]; }
  30358. }
  30359. }
  30360. return {
  30361. min: smoothConstraint ? ptMin : ptMax,
  30362. max: smoothConstraint ? ptMax : ptMin
  30363. };
  30364. }
  30365. var Polyline$1 = Path.extend({
  30366. type: 'ec-polyline',
  30367. shape: {
  30368. points: [],
  30369. smooth: 0,
  30370. smoothConstraint: true,
  30371. smoothMonotone: null,
  30372. connectNulls: false
  30373. },
  30374. style: {
  30375. fill: null,
  30376. stroke: '#000'
  30377. },
  30378. brush: fixClipWithShadow(Path.prototype.brush),
  30379. buildPath: function (ctx, shape) {
  30380. var points = shape.points;
  30381. var i = 0;
  30382. var len$$1 = points.length;
  30383. var result = getBoundingBox(points, shape.smoothConstraint);
  30384. if (shape.connectNulls) {
  30385. // Must remove first and last null values avoid draw error in polygon
  30386. for (; len$$1 > 0; len$$1--) {
  30387. if (!isPointNull(points[len$$1 - 1])) {
  30388. break;
  30389. }
  30390. }
  30391. for (; i < len$$1; i++) {
  30392. if (!isPointNull(points[i])) {
  30393. break;
  30394. }
  30395. }
  30396. }
  30397. while (i < len$$1) {
  30398. i += drawSegment(
  30399. ctx, points, i, len$$1, len$$1,
  30400. 1, result.min, result.max, shape.smooth,
  30401. shape.smoothMonotone, shape.connectNulls
  30402. ) + 1;
  30403. }
  30404. }
  30405. });
  30406. var Polygon$1 = Path.extend({
  30407. type: 'ec-polygon',
  30408. shape: {
  30409. points: [],
  30410. // Offset between stacked base points and points
  30411. stackedOnPoints: [],
  30412. smooth: 0,
  30413. stackedOnSmooth: 0,
  30414. smoothConstraint: true,
  30415. smoothMonotone: null,
  30416. connectNulls: false
  30417. },
  30418. brush: fixClipWithShadow(Path.prototype.brush),
  30419. buildPath: function (ctx, shape) {
  30420. var points = shape.points;
  30421. var stackedOnPoints = shape.stackedOnPoints;
  30422. var i = 0;
  30423. var len$$1 = points.length;
  30424. var smoothMonotone = shape.smoothMonotone;
  30425. var bbox = getBoundingBox(points, shape.smoothConstraint);
  30426. var stackedOnBBox = getBoundingBox(stackedOnPoints, shape.smoothConstraint);
  30427. if (shape.connectNulls) {
  30428. // Must remove first and last null values avoid draw error in polygon
  30429. for (; len$$1 > 0; len$$1--) {
  30430. if (!isPointNull(points[len$$1 - 1])) {
  30431. break;
  30432. }
  30433. }
  30434. for (; i < len$$1; i++) {
  30435. if (!isPointNull(points[i])) {
  30436. break;
  30437. }
  30438. }
  30439. }
  30440. while (i < len$$1) {
  30441. var k = drawSegment(
  30442. ctx, points, i, len$$1, len$$1,
  30443. 1, bbox.min, bbox.max, shape.smooth,
  30444. smoothMonotone, shape.connectNulls
  30445. );
  30446. drawSegment(
  30447. ctx, stackedOnPoints, i + k - 1, k, len$$1,
  30448. -1, stackedOnBBox.min, stackedOnBBox.max, shape.stackedOnSmooth,
  30449. smoothMonotone, shape.connectNulls
  30450. );
  30451. i += k + 1;
  30452. ctx.closePath();
  30453. }
  30454. }
  30455. });
  30456. /*
  30457. * Licensed to the Apache Software Foundation (ASF) under one
  30458. * or more contributor license agreements. See the NOTICE file
  30459. * distributed with this work for additional information
  30460. * regarding copyright ownership. The ASF licenses this file
  30461. * to you under the Apache License, Version 2.0 (the
  30462. * "License"); you may not use this file except in compliance
  30463. * with the License. You may obtain a copy of the License at
  30464. *
  30465. * http://www.apache.org/licenses/LICENSE-2.0
  30466. *
  30467. * Unless required by applicable law or agreed to in writing,
  30468. * software distributed under the License is distributed on an
  30469. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30470. * KIND, either express or implied. See the License for the
  30471. * specific language governing permissions and limitations
  30472. * under the License.
  30473. */
  30474. // FIXME step not support polar
  30475. function isPointsSame(points1, points2) {
  30476. if (points1.length !== points2.length) {
  30477. return;
  30478. }
  30479. for (var i = 0; i < points1.length; i++) {
  30480. var p1 = points1[i];
  30481. var p2 = points2[i];
  30482. if (p1[0] !== p2[0] || p1[1] !== p2[1]) {
  30483. return;
  30484. }
  30485. }
  30486. return true;
  30487. }
  30488. function getSmooth(smooth) {
  30489. return typeof (smooth) === 'number' ? smooth : (smooth ? 0.5 : 0);
  30490. }
  30491. function getAxisExtentWithGap(axis) {
  30492. var extent = axis.getGlobalExtent();
  30493. if (axis.onBand) {
  30494. // Remove extra 1px to avoid line miter in clipped edge
  30495. var halfBandWidth = axis.getBandWidth() / 2 - 1;
  30496. var dir = extent[1] > extent[0] ? 1 : -1;
  30497. extent[0] += dir * halfBandWidth;
  30498. extent[1] -= dir * halfBandWidth;
  30499. }
  30500. return extent;
  30501. }
  30502. /**
  30503. * @param {module:echarts/coord/cartesian/Cartesian2D|module:echarts/coord/polar/Polar} coordSys
  30504. * @param {module:echarts/data/List} data
  30505. * @param {Object} dataCoordInfo
  30506. * @param {Array.<Array.<number>>} points
  30507. */
  30508. function getStackedOnPoints(coordSys, data, dataCoordInfo) {
  30509. if (!dataCoordInfo.valueDim) {
  30510. return [];
  30511. }
  30512. var points = [];
  30513. for (var idx = 0, len = data.count(); idx < len; idx++) {
  30514. points.push(getStackedOnPoint(dataCoordInfo, coordSys, data, idx));
  30515. }
  30516. return points;
  30517. }
  30518. function createGridClipShape(cartesian, hasAnimation, forSymbol, seriesModel) {
  30519. var xExtent = getAxisExtentWithGap(cartesian.getAxis('x'));
  30520. var yExtent = getAxisExtentWithGap(cartesian.getAxis('y'));
  30521. var isHorizontal = cartesian.getBaseAxis().isHorizontal();
  30522. var x = Math.min(xExtent[0], xExtent[1]);
  30523. var y = Math.min(yExtent[0], yExtent[1]);
  30524. var width = Math.max(xExtent[0], xExtent[1]) - x;
  30525. var height = Math.max(yExtent[0], yExtent[1]) - y;
  30526. // Avoid float number rounding error for symbol on the edge of axis extent.
  30527. // See #7913 and `test/dataZoom-clip.html`.
  30528. if (forSymbol) {
  30529. x -= 0.5;
  30530. width += 0.5;
  30531. y -= 0.5;
  30532. height += 0.5;
  30533. }
  30534. else {
  30535. var lineWidth = seriesModel.get('lineStyle.width') || 2;
  30536. // Expand clip shape to avoid clipping when line value exceeds axis
  30537. var expandSize = seriesModel.get('clipOverflow') ? lineWidth / 2 : Math.max(width, height);
  30538. if (isHorizontal) {
  30539. y -= expandSize;
  30540. height += expandSize * 2;
  30541. }
  30542. else {
  30543. x -= expandSize;
  30544. width += expandSize * 2;
  30545. }
  30546. }
  30547. var clipPath = new Rect({
  30548. shape: {
  30549. x: x,
  30550. y: y,
  30551. width: width,
  30552. height: height
  30553. }
  30554. });
  30555. if (hasAnimation) {
  30556. clipPath.shape[isHorizontal ? 'width' : 'height'] = 0;
  30557. initProps(clipPath, {
  30558. shape: {
  30559. width: width,
  30560. height: height
  30561. }
  30562. }, seriesModel);
  30563. }
  30564. return clipPath;
  30565. }
  30566. function createPolarClipShape(polar, hasAnimation, forSymbol, seriesModel) {
  30567. var angleAxis = polar.getAngleAxis();
  30568. var radiusAxis = polar.getRadiusAxis();
  30569. var radiusExtent = radiusAxis.getExtent().slice();
  30570. radiusExtent[0] > radiusExtent[1] && radiusExtent.reverse();
  30571. var angleExtent = angleAxis.getExtent();
  30572. var RADIAN = Math.PI / 180;
  30573. // Avoid float number rounding error for symbol on the edge of axis extent.
  30574. if (forSymbol) {
  30575. radiusExtent[0] -= 0.5;
  30576. radiusExtent[1] += 0.5;
  30577. }
  30578. var clipPath = new Sector({
  30579. shape: {
  30580. cx: round$1(polar.cx, 1),
  30581. cy: round$1(polar.cy, 1),
  30582. r0: round$1(radiusExtent[0], 1),
  30583. r: round$1(radiusExtent[1], 1),
  30584. startAngle: -angleExtent[0] * RADIAN,
  30585. endAngle: -angleExtent[1] * RADIAN,
  30586. clockwise: angleAxis.inverse
  30587. }
  30588. });
  30589. if (hasAnimation) {
  30590. clipPath.shape.endAngle = -angleExtent[0] * RADIAN;
  30591. initProps(clipPath, {
  30592. shape: {
  30593. endAngle: -angleExtent[1] * RADIAN
  30594. }
  30595. }, seriesModel);
  30596. }
  30597. return clipPath;
  30598. }
  30599. function createClipShape(coordSys, hasAnimation, forSymbol, seriesModel) {
  30600. return coordSys.type === 'polar'
  30601. ? createPolarClipShape(coordSys, hasAnimation, forSymbol, seriesModel)
  30602. : createGridClipShape(coordSys, hasAnimation, forSymbol, seriesModel);
  30603. }
  30604. function turnPointsIntoStep(points, coordSys, stepTurnAt) {
  30605. var baseAxis = coordSys.getBaseAxis();
  30606. var baseIndex = baseAxis.dim === 'x' || baseAxis.dim === 'radius' ? 0 : 1;
  30607. var stepPoints = [];
  30608. for (var i = 0; i < points.length - 1; i++) {
  30609. var nextPt = points[i + 1];
  30610. var pt = points[i];
  30611. stepPoints.push(pt);
  30612. var stepPt = [];
  30613. switch (stepTurnAt) {
  30614. case 'end':
  30615. stepPt[baseIndex] = nextPt[baseIndex];
  30616. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  30617. // default is start
  30618. stepPoints.push(stepPt);
  30619. break;
  30620. case 'middle':
  30621. // default is start
  30622. var middle = (pt[baseIndex] + nextPt[baseIndex]) / 2;
  30623. var stepPt2 = [];
  30624. stepPt[baseIndex] = stepPt2[baseIndex] = middle;
  30625. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  30626. stepPt2[1 - baseIndex] = nextPt[1 - baseIndex];
  30627. stepPoints.push(stepPt);
  30628. stepPoints.push(stepPt2);
  30629. break;
  30630. default:
  30631. stepPt[baseIndex] = pt[baseIndex];
  30632. stepPt[1 - baseIndex] = nextPt[1 - baseIndex];
  30633. // default is start
  30634. stepPoints.push(stepPt);
  30635. }
  30636. }
  30637. // Last points
  30638. points[i] && stepPoints.push(points[i]);
  30639. return stepPoints;
  30640. }
  30641. function getVisualGradient(data, coordSys) {
  30642. var visualMetaList = data.getVisual('visualMeta');
  30643. if (!visualMetaList || !visualMetaList.length || !data.count()) {
  30644. // When data.count() is 0, gradient range can not be calculated.
  30645. return;
  30646. }
  30647. if (coordSys.type !== 'cartesian2d') {
  30648. if (__DEV__) {
  30649. console.warn('Visual map on line style is only supported on cartesian2d.');
  30650. }
  30651. return;
  30652. }
  30653. var coordDim;
  30654. var visualMeta;
  30655. for (var i = visualMetaList.length - 1; i >= 0; i--) {
  30656. var dimIndex = visualMetaList[i].dimension;
  30657. var dimName = data.dimensions[dimIndex];
  30658. var dimInfo = data.getDimensionInfo(dimName);
  30659. coordDim = dimInfo && dimInfo.coordDim;
  30660. // Can only be x or y
  30661. if (coordDim === 'x' || coordDim === 'y') {
  30662. visualMeta = visualMetaList[i];
  30663. break;
  30664. }
  30665. }
  30666. if (!visualMeta) {
  30667. if (__DEV__) {
  30668. console.warn('Visual map on line style only support x or y dimension.');
  30669. }
  30670. return;
  30671. }
  30672. // If the area to be rendered is bigger than area defined by LinearGradient,
  30673. // the canvas spec prescribes that the color of the first stop and the last
  30674. // stop should be used. But if two stops are added at offset 0, in effect
  30675. // browsers use the color of the second stop to render area outside
  30676. // LinearGradient. So we can only infinitesimally extend area defined in
  30677. // LinearGradient to render `outerColors`.
  30678. var axis = coordSys.getAxis(coordDim);
  30679. // dataToCoor mapping may not be linear, but must be monotonic.
  30680. var colorStops = map(visualMeta.stops, function (stop) {
  30681. return {
  30682. coord: axis.toGlobalCoord(axis.dataToCoord(stop.value)),
  30683. color: stop.color
  30684. };
  30685. });
  30686. var stopLen = colorStops.length;
  30687. var outerColors = visualMeta.outerColors.slice();
  30688. if (stopLen && colorStops[0].coord > colorStops[stopLen - 1].coord) {
  30689. colorStops.reverse();
  30690. outerColors.reverse();
  30691. }
  30692. var tinyExtent = 10; // Arbitrary value: 10px
  30693. var minCoord = colorStops[0].coord - tinyExtent;
  30694. var maxCoord = colorStops[stopLen - 1].coord + tinyExtent;
  30695. var coordSpan = maxCoord - minCoord;
  30696. if (coordSpan < 1e-3) {
  30697. return 'transparent';
  30698. }
  30699. each$1(colorStops, function (stop) {
  30700. stop.offset = (stop.coord - minCoord) / coordSpan;
  30701. });
  30702. colorStops.push({
  30703. offset: stopLen ? colorStops[stopLen - 1].offset : 0.5,
  30704. color: outerColors[1] || 'transparent'
  30705. });
  30706. colorStops.unshift({ // notice colorStops.length have been changed.
  30707. offset: stopLen ? colorStops[0].offset : 0.5,
  30708. color: outerColors[0] || 'transparent'
  30709. });
  30710. // zrUtil.each(colorStops, function (colorStop) {
  30711. // // Make sure each offset has rounded px to avoid not sharp edge
  30712. // colorStop.offset = (Math.round(colorStop.offset * (end - start) + start) - start) / (end - start);
  30713. // });
  30714. var gradient = new LinearGradient(0, 0, 0, 0, colorStops, true);
  30715. gradient[coordDim] = minCoord;
  30716. gradient[coordDim + '2'] = maxCoord;
  30717. return gradient;
  30718. }
  30719. function getIsIgnoreFunc(seriesModel, data, coordSys) {
  30720. var showAllSymbol = seriesModel.get('showAllSymbol');
  30721. var isAuto = showAllSymbol === 'auto';
  30722. if (showAllSymbol && !isAuto) {
  30723. return;
  30724. }
  30725. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  30726. if (!categoryAxis) {
  30727. return;
  30728. }
  30729. // Note that category label interval strategy might bring some weird effect
  30730. // in some scenario: users may wonder why some of the symbols are not
  30731. // displayed. So we show all symbols as possible as we can.
  30732. if (isAuto
  30733. // Simplify the logic, do not determine label overlap here.
  30734. && canShowAllSymbolForCategory(categoryAxis, data)
  30735. ) {
  30736. return;
  30737. }
  30738. // Otherwise follow the label interval strategy on category axis.
  30739. var categoryDataDim = data.mapDimension(categoryAxis.dim);
  30740. var labelMap = {};
  30741. each$1(categoryAxis.getViewLabels(), function (labelItem) {
  30742. labelMap[labelItem.tickValue] = 1;
  30743. });
  30744. return function (dataIndex) {
  30745. return !labelMap.hasOwnProperty(data.get(categoryDataDim, dataIndex));
  30746. };
  30747. }
  30748. function canShowAllSymbolForCategory(categoryAxis, data) {
  30749. // In mose cases, line is monotonous on category axis, and the label size
  30750. // is close with each other. So we check the symbol size and some of the
  30751. // label size alone with the category axis to estimate whether all symbol
  30752. // can be shown without overlap.
  30753. var axisExtent = categoryAxis.getExtent();
  30754. var availSize = Math.abs(axisExtent[1] - axisExtent[0]) / categoryAxis.scale.count();
  30755. isNaN(availSize) && (availSize = 0); // 0/0 is NaN.
  30756. // Sampling some points, max 5.
  30757. var dataLen = data.count();
  30758. var step = Math.max(1, Math.round(dataLen / 5));
  30759. for (var dataIndex = 0; dataIndex < dataLen; dataIndex += step) {
  30760. if (SymbolClz$1.getSymbolSize(
  30761. data, dataIndex
  30762. // Only for cartesian, where `isHorizontal` exists.
  30763. )[categoryAxis.isHorizontal() ? 1 : 0]
  30764. // Empirical number
  30765. * 1.5 > availSize
  30766. ) {
  30767. return false;
  30768. }
  30769. }
  30770. return true;
  30771. }
  30772. Chart.extend({
  30773. type: 'line',
  30774. init: function () {
  30775. var lineGroup = new Group();
  30776. var symbolDraw = new SymbolDraw();
  30777. this.group.add(symbolDraw.group);
  30778. this._symbolDraw = symbolDraw;
  30779. this._lineGroup = lineGroup;
  30780. },
  30781. render: function (seriesModel, ecModel, api) {
  30782. var coordSys = seriesModel.coordinateSystem;
  30783. var group = this.group;
  30784. var data = seriesModel.getData();
  30785. var lineStyleModel = seriesModel.getModel('lineStyle');
  30786. var areaStyleModel = seriesModel.getModel('areaStyle');
  30787. var points = data.mapArray(data.getItemLayout);
  30788. var isCoordSysPolar = coordSys.type === 'polar';
  30789. var prevCoordSys = this._coordSys;
  30790. var symbolDraw = this._symbolDraw;
  30791. var polyline = this._polyline;
  30792. var polygon = this._polygon;
  30793. var lineGroup = this._lineGroup;
  30794. var hasAnimation = seriesModel.get('animation');
  30795. var isAreaChart = !areaStyleModel.isEmpty();
  30796. var valueOrigin = areaStyleModel.get('origin');
  30797. var dataCoordInfo = prepareDataCoordInfo(coordSys, data, valueOrigin);
  30798. var stackedOnPoints = getStackedOnPoints(coordSys, data, dataCoordInfo);
  30799. var showSymbol = seriesModel.get('showSymbol');
  30800. var isIgnoreFunc = showSymbol && !isCoordSysPolar
  30801. && getIsIgnoreFunc(seriesModel, data, coordSys);
  30802. // Remove temporary symbols
  30803. var oldData = this._data;
  30804. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  30805. if (el.__temp) {
  30806. group.remove(el);
  30807. oldData.setItemGraphicEl(idx, null);
  30808. }
  30809. });
  30810. // Remove previous created symbols if showSymbol changed to false
  30811. if (!showSymbol) {
  30812. symbolDraw.remove();
  30813. }
  30814. group.add(lineGroup);
  30815. // FIXME step not support polar
  30816. var step = !isCoordSysPolar && seriesModel.get('step');
  30817. // Initialization animation or coordinate system changed
  30818. if (
  30819. !(polyline && prevCoordSys.type === coordSys.type && step === this._step)
  30820. ) {
  30821. showSymbol && symbolDraw.updateData(data, {
  30822. isIgnore: isIgnoreFunc,
  30823. clipShape: createClipShape(coordSys, false, true, seriesModel)
  30824. });
  30825. if (step) {
  30826. // TODO If stacked series is not step
  30827. points = turnPointsIntoStep(points, coordSys, step);
  30828. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  30829. }
  30830. polyline = this._newPolyline(points, coordSys, hasAnimation);
  30831. if (isAreaChart) {
  30832. polygon = this._newPolygon(
  30833. points, stackedOnPoints,
  30834. coordSys, hasAnimation
  30835. );
  30836. }
  30837. lineGroup.setClipPath(createClipShape(coordSys, true, false, seriesModel));
  30838. }
  30839. else {
  30840. if (isAreaChart && !polygon) {
  30841. // If areaStyle is added
  30842. polygon = this._newPolygon(
  30843. points, stackedOnPoints,
  30844. coordSys, hasAnimation
  30845. );
  30846. }
  30847. else if (polygon && !isAreaChart) {
  30848. // If areaStyle is removed
  30849. lineGroup.remove(polygon);
  30850. polygon = this._polygon = null;
  30851. }
  30852. // Update clipPath
  30853. lineGroup.setClipPath(createClipShape(coordSys, false, false, seriesModel));
  30854. // Always update, or it is wrong in the case turning on legend
  30855. // because points are not changed
  30856. showSymbol && symbolDraw.updateData(data, {
  30857. isIgnore: isIgnoreFunc,
  30858. clipShape: createClipShape(coordSys, false, true, seriesModel)
  30859. });
  30860. // Stop symbol animation and sync with line points
  30861. // FIXME performance?
  30862. data.eachItemGraphicEl(function (el) {
  30863. el.stopAnimation(true);
  30864. });
  30865. // In the case data zoom triggerred refreshing frequently
  30866. // Data may not change if line has a category axis. So it should animate nothing
  30867. if (!isPointsSame(this._stackedOnPoints, stackedOnPoints)
  30868. || !isPointsSame(this._points, points)
  30869. ) {
  30870. if (hasAnimation) {
  30871. this._updateAnimation(
  30872. data, stackedOnPoints, coordSys, api, step, valueOrigin
  30873. );
  30874. }
  30875. else {
  30876. // Not do it in update with animation
  30877. if (step) {
  30878. // TODO If stacked series is not step
  30879. points = turnPointsIntoStep(points, coordSys, step);
  30880. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  30881. }
  30882. polyline.setShape({
  30883. points: points
  30884. });
  30885. polygon && polygon.setShape({
  30886. points: points,
  30887. stackedOnPoints: stackedOnPoints
  30888. });
  30889. }
  30890. }
  30891. }
  30892. var visualColor = getVisualGradient(data, coordSys) || data.getVisual('color');
  30893. polyline.useStyle(defaults(
  30894. // Use color in lineStyle first
  30895. lineStyleModel.getLineStyle(),
  30896. {
  30897. fill: 'none',
  30898. stroke: visualColor,
  30899. lineJoin: 'bevel'
  30900. }
  30901. ));
  30902. var smooth = seriesModel.get('smooth');
  30903. smooth = getSmooth(seriesModel.get('smooth'));
  30904. polyline.setShape({
  30905. smooth: smooth,
  30906. smoothMonotone: seriesModel.get('smoothMonotone'),
  30907. connectNulls: seriesModel.get('connectNulls')
  30908. });
  30909. if (polygon) {
  30910. var stackedOnSeries = data.getCalculationInfo('stackedOnSeries');
  30911. var stackedOnSmooth = 0;
  30912. polygon.useStyle(defaults(
  30913. areaStyleModel.getAreaStyle(),
  30914. {
  30915. fill: visualColor,
  30916. opacity: 0.7,
  30917. lineJoin: 'bevel'
  30918. }
  30919. ));
  30920. if (stackedOnSeries) {
  30921. stackedOnSmooth = getSmooth(stackedOnSeries.get('smooth'));
  30922. }
  30923. polygon.setShape({
  30924. smooth: smooth,
  30925. stackedOnSmooth: stackedOnSmooth,
  30926. smoothMonotone: seriesModel.get('smoothMonotone'),
  30927. connectNulls: seriesModel.get('connectNulls')
  30928. });
  30929. }
  30930. this._data = data;
  30931. // Save the coordinate system for transition animation when data changed
  30932. this._coordSys = coordSys;
  30933. this._stackedOnPoints = stackedOnPoints;
  30934. this._points = points;
  30935. this._step = step;
  30936. this._valueOrigin = valueOrigin;
  30937. },
  30938. dispose: function () {},
  30939. highlight: function (seriesModel, ecModel, api, payload) {
  30940. var data = seriesModel.getData();
  30941. var dataIndex = queryDataIndex(data, payload);
  30942. if (!(dataIndex instanceof Array) && dataIndex != null && dataIndex >= 0) {
  30943. var symbol = data.getItemGraphicEl(dataIndex);
  30944. if (!symbol) {
  30945. // Create a temporary symbol if it is not exists
  30946. var pt = data.getItemLayout(dataIndex);
  30947. if (!pt) {
  30948. // Null data
  30949. return;
  30950. }
  30951. symbol = new SymbolClz$1(data, dataIndex);
  30952. symbol.position = pt;
  30953. symbol.setZ(
  30954. seriesModel.get('zlevel'),
  30955. seriesModel.get('z')
  30956. );
  30957. symbol.ignore = isNaN(pt[0]) || isNaN(pt[1]);
  30958. symbol.__temp = true;
  30959. data.setItemGraphicEl(dataIndex, symbol);
  30960. // Stop scale animation
  30961. symbol.stopSymbolAnimation(true);
  30962. this.group.add(symbol);
  30963. }
  30964. symbol.highlight();
  30965. }
  30966. else {
  30967. // Highlight whole series
  30968. Chart.prototype.highlight.call(
  30969. this, seriesModel, ecModel, api, payload
  30970. );
  30971. }
  30972. },
  30973. downplay: function (seriesModel, ecModel, api, payload) {
  30974. var data = seriesModel.getData();
  30975. var dataIndex = queryDataIndex(data, payload);
  30976. if (dataIndex != null && dataIndex >= 0) {
  30977. var symbol = data.getItemGraphicEl(dataIndex);
  30978. if (symbol) {
  30979. if (symbol.__temp) {
  30980. data.setItemGraphicEl(dataIndex, null);
  30981. this.group.remove(symbol);
  30982. }
  30983. else {
  30984. symbol.downplay();
  30985. }
  30986. }
  30987. }
  30988. else {
  30989. // FIXME
  30990. // can not downplay completely.
  30991. // Downplay whole series
  30992. Chart.prototype.downplay.call(
  30993. this, seriesModel, ecModel, api, payload
  30994. );
  30995. }
  30996. },
  30997. /**
  30998. * @param {module:zrender/container/Group} group
  30999. * @param {Array.<Array.<number>>} points
  31000. * @private
  31001. */
  31002. _newPolyline: function (points) {
  31003. var polyline = this._polyline;
  31004. // Remove previous created polyline
  31005. if (polyline) {
  31006. this._lineGroup.remove(polyline);
  31007. }
  31008. polyline = new Polyline$1({
  31009. shape: {
  31010. points: points
  31011. },
  31012. silent: true,
  31013. z2: 10
  31014. });
  31015. this._lineGroup.add(polyline);
  31016. this._polyline = polyline;
  31017. return polyline;
  31018. },
  31019. /**
  31020. * @param {module:zrender/container/Group} group
  31021. * @param {Array.<Array.<number>>} stackedOnPoints
  31022. * @param {Array.<Array.<number>>} points
  31023. * @private
  31024. */
  31025. _newPolygon: function (points, stackedOnPoints) {
  31026. var polygon = this._polygon;
  31027. // Remove previous created polygon
  31028. if (polygon) {
  31029. this._lineGroup.remove(polygon);
  31030. }
  31031. polygon = new Polygon$1({
  31032. shape: {
  31033. points: points,
  31034. stackedOnPoints: stackedOnPoints
  31035. },
  31036. silent: true
  31037. });
  31038. this._lineGroup.add(polygon);
  31039. this._polygon = polygon;
  31040. return polygon;
  31041. },
  31042. /**
  31043. * @private
  31044. */
  31045. // FIXME Two value axis
  31046. _updateAnimation: function (data, stackedOnPoints, coordSys, api, step, valueOrigin) {
  31047. var polyline = this._polyline;
  31048. var polygon = this._polygon;
  31049. var seriesModel = data.hostModel;
  31050. var diff = lineAnimationDiff(
  31051. this._data, data,
  31052. this._stackedOnPoints, stackedOnPoints,
  31053. this._coordSys, coordSys,
  31054. this._valueOrigin, valueOrigin
  31055. );
  31056. var current = diff.current;
  31057. var stackedOnCurrent = diff.stackedOnCurrent;
  31058. var next = diff.next;
  31059. var stackedOnNext = diff.stackedOnNext;
  31060. if (step) {
  31061. // TODO If stacked series is not step
  31062. current = turnPointsIntoStep(diff.current, coordSys, step);
  31063. stackedOnCurrent = turnPointsIntoStep(diff.stackedOnCurrent, coordSys, step);
  31064. next = turnPointsIntoStep(diff.next, coordSys, step);
  31065. stackedOnNext = turnPointsIntoStep(diff.stackedOnNext, coordSys, step);
  31066. }
  31067. // `diff.current` is subset of `current` (which should be ensured by
  31068. // turnPointsIntoStep), so points in `__points` can be updated when
  31069. // points in `current` are update during animation.
  31070. polyline.shape.__points = diff.current;
  31071. polyline.shape.points = current;
  31072. updateProps(polyline, {
  31073. shape: {
  31074. points: next
  31075. }
  31076. }, seriesModel);
  31077. if (polygon) {
  31078. polygon.setShape({
  31079. points: current,
  31080. stackedOnPoints: stackedOnCurrent
  31081. });
  31082. updateProps(polygon, {
  31083. shape: {
  31084. points: next,
  31085. stackedOnPoints: stackedOnNext
  31086. }
  31087. }, seriesModel);
  31088. }
  31089. var updatedDataInfo = [];
  31090. var diffStatus = diff.status;
  31091. for (var i = 0; i < diffStatus.length; i++) {
  31092. var cmd = diffStatus[i].cmd;
  31093. if (cmd === '=') {
  31094. var el = data.getItemGraphicEl(diffStatus[i].idx1);
  31095. if (el) {
  31096. updatedDataInfo.push({
  31097. el: el,
  31098. ptIdx: i // Index of points
  31099. });
  31100. }
  31101. }
  31102. }
  31103. if (polyline.animators && polyline.animators.length) {
  31104. polyline.animators[0].during(function () {
  31105. for (var i = 0; i < updatedDataInfo.length; i++) {
  31106. var el = updatedDataInfo[i].el;
  31107. el.attr('position', polyline.shape.__points[updatedDataInfo[i].ptIdx]);
  31108. }
  31109. });
  31110. }
  31111. },
  31112. remove: function (ecModel) {
  31113. var group = this.group;
  31114. var oldData = this._data;
  31115. this._lineGroup.removeAll();
  31116. this._symbolDraw.remove(true);
  31117. // Remove temporary created elements when highlighting
  31118. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  31119. if (el.__temp) {
  31120. group.remove(el);
  31121. oldData.setItemGraphicEl(idx, null);
  31122. }
  31123. });
  31124. this._polyline =
  31125. this._polygon =
  31126. this._coordSys =
  31127. this._points =
  31128. this._stackedOnPoints =
  31129. this._data = null;
  31130. }
  31131. });
  31132. /*
  31133. * Licensed to the Apache Software Foundation (ASF) under one
  31134. * or more contributor license agreements. See the NOTICE file
  31135. * distributed with this work for additional information
  31136. * regarding copyright ownership. The ASF licenses this file
  31137. * to you under the Apache License, Version 2.0 (the
  31138. * "License"); you may not use this file except in compliance
  31139. * with the License. You may obtain a copy of the License at
  31140. *
  31141. * http://www.apache.org/licenses/LICENSE-2.0
  31142. *
  31143. * Unless required by applicable law or agreed to in writing,
  31144. * software distributed under the License is distributed on an
  31145. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31146. * KIND, either express or implied. See the License for the
  31147. * specific language governing permissions and limitations
  31148. * under the License.
  31149. */
  31150. var visualSymbol = function (seriesType, defaultSymbolType, legendSymbol) {
  31151. // Encoding visual for all series include which is filtered for legend drawing
  31152. return {
  31153. seriesType: seriesType,
  31154. // For legend.
  31155. performRawSeries: true,
  31156. reset: function (seriesModel, ecModel, api) {
  31157. var data = seriesModel.getData();
  31158. var symbolType = seriesModel.get('symbol') || defaultSymbolType;
  31159. var symbolSize = seriesModel.get('symbolSize');
  31160. var keepAspect = seriesModel.get('symbolKeepAspect');
  31161. data.setVisual({
  31162. legendSymbol: legendSymbol || symbolType,
  31163. symbol: symbolType,
  31164. symbolSize: symbolSize,
  31165. symbolKeepAspect: keepAspect
  31166. });
  31167. // Only visible series has each data be visual encoded
  31168. if (ecModel.isSeriesFiltered(seriesModel)) {
  31169. return;
  31170. }
  31171. var hasCallback = typeof symbolSize === 'function';
  31172. function dataEach(data, idx) {
  31173. if (typeof symbolSize === 'function') {
  31174. var rawValue = seriesModel.getRawValue(idx);
  31175. // FIXME
  31176. var params = seriesModel.getDataParams(idx);
  31177. data.setItemVisual(idx, 'symbolSize', symbolSize(rawValue, params));
  31178. }
  31179. if (data.hasItemOption) {
  31180. var itemModel = data.getItemModel(idx);
  31181. var itemSymbolType = itemModel.getShallow('symbol', true);
  31182. var itemSymbolSize = itemModel.getShallow('symbolSize',
  31183. true);
  31184. var itemSymbolKeepAspect =
  31185. itemModel.getShallow('symbolKeepAspect',true);
  31186. // If has item symbol
  31187. if (itemSymbolType != null) {
  31188. data.setItemVisual(idx, 'symbol', itemSymbolType);
  31189. }
  31190. if (itemSymbolSize != null) {
  31191. // PENDING Transform symbolSize ?
  31192. data.setItemVisual(idx, 'symbolSize', itemSymbolSize);
  31193. }
  31194. if (itemSymbolKeepAspect != null) {
  31195. data.setItemVisual(idx, 'symbolKeepAspect',
  31196. itemSymbolKeepAspect);
  31197. }
  31198. }
  31199. }
  31200. return { dataEach: (data.hasItemOption || hasCallback) ? dataEach : null };
  31201. }
  31202. };
  31203. };
  31204. /*
  31205. * Licensed to the Apache Software Foundation (ASF) under one
  31206. * or more contributor license agreements. See the NOTICE file
  31207. * distributed with this work for additional information
  31208. * regarding copyright ownership. The ASF licenses this file
  31209. * to you under the Apache License, Version 2.0 (the
  31210. * "License"); you may not use this file except in compliance
  31211. * with the License. You may obtain a copy of the License at
  31212. *
  31213. * http://www.apache.org/licenses/LICENSE-2.0
  31214. *
  31215. * Unless required by applicable law or agreed to in writing,
  31216. * software distributed under the License is distributed on an
  31217. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31218. * KIND, either express or implied. See the License for the
  31219. * specific language governing permissions and limitations
  31220. * under the License.
  31221. */
  31222. var pointsLayout = function (seriesType) {
  31223. return {
  31224. seriesType: seriesType,
  31225. plan: createRenderPlanner(),
  31226. reset: function (seriesModel) {
  31227. var data = seriesModel.getData();
  31228. var coordSys = seriesModel.coordinateSystem;
  31229. var pipelineContext = seriesModel.pipelineContext;
  31230. var isLargeRender = pipelineContext.large;
  31231. if (!coordSys) {
  31232. return;
  31233. }
  31234. var dims = map(coordSys.dimensions, function (dim) {
  31235. return data.mapDimension(dim);
  31236. }).slice(0, 2);
  31237. var dimLen = dims.length;
  31238. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  31239. if (isDimensionStacked(data, dims[0], dims[1])) {
  31240. dims[0] = stackResultDim;
  31241. }
  31242. if (isDimensionStacked(data, dims[1], dims[0])) {
  31243. dims[1] = stackResultDim;
  31244. }
  31245. function progress(params, data) {
  31246. var segCount = params.end - params.start;
  31247. var points = isLargeRender && new Float32Array(segCount * dimLen);
  31248. for (var i = params.start, offset = 0, tmpIn = [], tmpOut = []; i < params.end; i++) {
  31249. var point;
  31250. if (dimLen === 1) {
  31251. var x = data.get(dims[0], i);
  31252. point = !isNaN(x) && coordSys.dataToPoint(x, null, tmpOut);
  31253. }
  31254. else {
  31255. var x = tmpIn[0] = data.get(dims[0], i);
  31256. var y = tmpIn[1] = data.get(dims[1], i);
  31257. // Also {Array.<number>}, not undefined to avoid if...else... statement
  31258. point = !isNaN(x) && !isNaN(y) && coordSys.dataToPoint(tmpIn, null, tmpOut);
  31259. }
  31260. if (isLargeRender) {
  31261. points[offset++] = point ? point[0] : NaN;
  31262. points[offset++] = point ? point[1] : NaN;
  31263. }
  31264. else {
  31265. data.setItemLayout(i, (point && point.slice()) || [NaN, NaN]);
  31266. }
  31267. }
  31268. isLargeRender && data.setLayout('symbolPoints', points);
  31269. }
  31270. return dimLen && {progress: progress};
  31271. }
  31272. };
  31273. };
  31274. /*
  31275. * Licensed to the Apache Software Foundation (ASF) under one
  31276. * or more contributor license agreements. See the NOTICE file
  31277. * distributed with this work for additional information
  31278. * regarding copyright ownership. The ASF licenses this file
  31279. * to you under the Apache License, Version 2.0 (the
  31280. * "License"); you may not use this file except in compliance
  31281. * with the License. You may obtain a copy of the License at
  31282. *
  31283. * http://www.apache.org/licenses/LICENSE-2.0
  31284. *
  31285. * Unless required by applicable law or agreed to in writing,
  31286. * software distributed under the License is distributed on an
  31287. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31288. * KIND, either express or implied. See the License for the
  31289. * specific language governing permissions and limitations
  31290. * under the License.
  31291. */
  31292. var samplers = {
  31293. average: function (frame) {
  31294. var sum = 0;
  31295. var count = 0;
  31296. for (var i = 0; i < frame.length; i++) {
  31297. if (!isNaN(frame[i])) {
  31298. sum += frame[i];
  31299. count++;
  31300. }
  31301. }
  31302. // Return NaN if count is 0
  31303. return count === 0 ? NaN : sum / count;
  31304. },
  31305. sum: function (frame) {
  31306. var sum = 0;
  31307. for (var i = 0; i < frame.length; i++) {
  31308. // Ignore NaN
  31309. sum += frame[i] || 0;
  31310. }
  31311. return sum;
  31312. },
  31313. max: function (frame) {
  31314. var max = -Infinity;
  31315. for (var i = 0; i < frame.length; i++) {
  31316. frame[i] > max && (max = frame[i]);
  31317. }
  31318. // NaN will cause illegal axis extent.
  31319. return isFinite(max) ? max : NaN;
  31320. },
  31321. min: function (frame) {
  31322. var min = Infinity;
  31323. for (var i = 0; i < frame.length; i++) {
  31324. frame[i] < min && (min = frame[i]);
  31325. }
  31326. // NaN will cause illegal axis extent.
  31327. return isFinite(min) ? min : NaN;
  31328. },
  31329. // TODO
  31330. // Median
  31331. nearest: function (frame) {
  31332. return frame[0];
  31333. }
  31334. };
  31335. var indexSampler = function (frame, value) {
  31336. return Math.round(frame.length / 2);
  31337. };
  31338. var dataSample = function (seriesType) {
  31339. return {
  31340. seriesType: seriesType,
  31341. modifyOutputEnd: true,
  31342. reset: function (seriesModel, ecModel, api) {
  31343. var data = seriesModel.getData();
  31344. var sampling = seriesModel.get('sampling');
  31345. var coordSys = seriesModel.coordinateSystem;
  31346. // Only cartesian2d support down sampling
  31347. if (coordSys.type === 'cartesian2d' && sampling) {
  31348. var baseAxis = coordSys.getBaseAxis();
  31349. var valueAxis = coordSys.getOtherAxis(baseAxis);
  31350. var extent = baseAxis.getExtent();
  31351. // Coordinste system has been resized
  31352. var size = extent[1] - extent[0];
  31353. var rate = Math.round(data.count() / size);
  31354. if (rate > 1) {
  31355. var sampler;
  31356. if (typeof sampling === 'string') {
  31357. sampler = samplers[sampling];
  31358. }
  31359. else if (typeof sampling === 'function') {
  31360. sampler = sampling;
  31361. }
  31362. if (sampler) {
  31363. // Only support sample the first dim mapped from value axis.
  31364. seriesModel.setData(data.downSample(
  31365. data.mapDimension(valueAxis.dim), 1 / rate, sampler, indexSampler
  31366. ));
  31367. }
  31368. }
  31369. }
  31370. }
  31371. };
  31372. };
  31373. /*
  31374. * Licensed to the Apache Software Foundation (ASF) under one
  31375. * or more contributor license agreements. See the NOTICE file
  31376. * distributed with this work for additional information
  31377. * regarding copyright ownership. The ASF licenses this file
  31378. * to you under the Apache License, Version 2.0 (the
  31379. * "License"); you may not use this file except in compliance
  31380. * with the License. You may obtain a copy of the License at
  31381. *
  31382. * http://www.apache.org/licenses/LICENSE-2.0
  31383. *
  31384. * Unless required by applicable law or agreed to in writing,
  31385. * software distributed under the License is distributed on an
  31386. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31387. * KIND, either express or implied. See the License for the
  31388. * specific language governing permissions and limitations
  31389. * under the License.
  31390. */
  31391. /**
  31392. * Cartesian coordinate system
  31393. * @module echarts/coord/Cartesian
  31394. *
  31395. */
  31396. function dimAxisMapper(dim) {
  31397. return this._axes[dim];
  31398. }
  31399. /**
  31400. * @alias module:echarts/coord/Cartesian
  31401. * @constructor
  31402. */
  31403. var Cartesian = function (name) {
  31404. this._axes = {};
  31405. this._dimList = [];
  31406. /**
  31407. * @type {string}
  31408. */
  31409. this.name = name || '';
  31410. };
  31411. Cartesian.prototype = {
  31412. constructor: Cartesian,
  31413. type: 'cartesian',
  31414. /**
  31415. * Get axis
  31416. * @param {number|string} dim
  31417. * @return {module:echarts/coord/Cartesian~Axis}
  31418. */
  31419. getAxis: function (dim) {
  31420. return this._axes[dim];
  31421. },
  31422. /**
  31423. * Get axes list
  31424. * @return {Array.<module:echarts/coord/Cartesian~Axis>}
  31425. */
  31426. getAxes: function () {
  31427. return map(this._dimList, dimAxisMapper, this);
  31428. },
  31429. /**
  31430. * Get axes list by given scale type
  31431. */
  31432. getAxesByScale: function (scaleType) {
  31433. scaleType = scaleType.toLowerCase();
  31434. return filter(
  31435. this.getAxes(),
  31436. function (axis) {
  31437. return axis.scale.type === scaleType;
  31438. }
  31439. );
  31440. },
  31441. /**
  31442. * Add axis
  31443. * @param {module:echarts/coord/Cartesian.Axis}
  31444. */
  31445. addAxis: function (axis) {
  31446. var dim = axis.dim;
  31447. this._axes[dim] = axis;
  31448. this._dimList.push(dim);
  31449. },
  31450. /**
  31451. * Convert data to coord in nd space
  31452. * @param {Array.<number>|Object.<string, number>} val
  31453. * @return {Array.<number>|Object.<string, number>}
  31454. */
  31455. dataToCoord: function (val) {
  31456. return this._dataCoordConvert(val, 'dataToCoord');
  31457. },
  31458. /**
  31459. * Convert coord in nd space to data
  31460. * @param {Array.<number>|Object.<string, number>} val
  31461. * @return {Array.<number>|Object.<string, number>}
  31462. */
  31463. coordToData: function (val) {
  31464. return this._dataCoordConvert(val, 'coordToData');
  31465. },
  31466. _dataCoordConvert: function (input, method) {
  31467. var dimList = this._dimList;
  31468. var output = input instanceof Array ? [] : {};
  31469. for (var i = 0; i < dimList.length; i++) {
  31470. var dim = dimList[i];
  31471. var axis = this._axes[dim];
  31472. output[dim] = axis[method](input[dim]);
  31473. }
  31474. return output;
  31475. }
  31476. };
  31477. /*
  31478. * Licensed to the Apache Software Foundation (ASF) under one
  31479. * or more contributor license agreements. See the NOTICE file
  31480. * distributed with this work for additional information
  31481. * regarding copyright ownership. The ASF licenses this file
  31482. * to you under the Apache License, Version 2.0 (the
  31483. * "License"); you may not use this file except in compliance
  31484. * with the License. You may obtain a copy of the License at
  31485. *
  31486. * http://www.apache.org/licenses/LICENSE-2.0
  31487. *
  31488. * Unless required by applicable law or agreed to in writing,
  31489. * software distributed under the License is distributed on an
  31490. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31491. * KIND, either express or implied. See the License for the
  31492. * specific language governing permissions and limitations
  31493. * under the License.
  31494. */
  31495. function Cartesian2D(name) {
  31496. Cartesian.call(this, name);
  31497. }
  31498. Cartesian2D.prototype = {
  31499. constructor: Cartesian2D,
  31500. type: 'cartesian2d',
  31501. /**
  31502. * @type {Array.<string>}
  31503. * @readOnly
  31504. */
  31505. dimensions: ['x', 'y'],
  31506. /**
  31507. * Base axis will be used on stacking.
  31508. *
  31509. * @return {module:echarts/coord/cartesian/Axis2D}
  31510. */
  31511. getBaseAxis: function () {
  31512. return this.getAxesByScale('ordinal')[0]
  31513. || this.getAxesByScale('time')[0]
  31514. || this.getAxis('x');
  31515. },
  31516. /**
  31517. * If contain point
  31518. * @param {Array.<number>} point
  31519. * @return {boolean}
  31520. */
  31521. containPoint: function (point) {
  31522. var axisX = this.getAxis('x');
  31523. var axisY = this.getAxis('y');
  31524. return axisX.contain(axisX.toLocalCoord(point[0]))
  31525. && axisY.contain(axisY.toLocalCoord(point[1]));
  31526. },
  31527. /**
  31528. * If contain data
  31529. * @param {Array.<number>} data
  31530. * @return {boolean}
  31531. */
  31532. containData: function (data) {
  31533. return this.getAxis('x').containData(data[0])
  31534. && this.getAxis('y').containData(data[1]);
  31535. },
  31536. /**
  31537. * @param {Array.<number>} data
  31538. * @param {Array.<number>} out
  31539. * @return {Array.<number>}
  31540. */
  31541. dataToPoint: function (data, reserved, out) {
  31542. var xAxis = this.getAxis('x');
  31543. var yAxis = this.getAxis('y');
  31544. out = out || [];
  31545. out[0] = xAxis.toGlobalCoord(xAxis.dataToCoord(data[0]));
  31546. out[1] = yAxis.toGlobalCoord(yAxis.dataToCoord(data[1]));
  31547. return out;
  31548. },
  31549. /**
  31550. * @param {Array.<number>} data
  31551. * @param {Array.<number>} out
  31552. * @return {Array.<number>}
  31553. */
  31554. clampData: function (data, out) {
  31555. var xScale = this.getAxis('x').scale;
  31556. var yScale = this.getAxis('y').scale;
  31557. var xAxisExtent = xScale.getExtent();
  31558. var yAxisExtent = yScale.getExtent();
  31559. var x = xScale.parse(data[0]);
  31560. var y = yScale.parse(data[1]);
  31561. out = out || [];
  31562. out[0] = Math.min(
  31563. Math.max(Math.min(xAxisExtent[0], xAxisExtent[1]), x),
  31564. Math.max(xAxisExtent[0], xAxisExtent[1])
  31565. );
  31566. out[1] = Math.min(
  31567. Math.max(Math.min(yAxisExtent[0], yAxisExtent[1]), y),
  31568. Math.max(yAxisExtent[0], yAxisExtent[1])
  31569. );
  31570. return out;
  31571. },
  31572. /**
  31573. * @param {Array.<number>} point
  31574. * @param {Array.<number>} out
  31575. * @return {Array.<number>}
  31576. */
  31577. pointToData: function (point, out) {
  31578. var xAxis = this.getAxis('x');
  31579. var yAxis = this.getAxis('y');
  31580. out = out || [];
  31581. out[0] = xAxis.coordToData(xAxis.toLocalCoord(point[0]));
  31582. out[1] = yAxis.coordToData(yAxis.toLocalCoord(point[1]));
  31583. return out;
  31584. },
  31585. /**
  31586. * Get other axis
  31587. * @param {module:echarts/coord/cartesian/Axis2D} axis
  31588. */
  31589. getOtherAxis: function (axis) {
  31590. return this.getAxis(axis.dim === 'x' ? 'y' : 'x');
  31591. }
  31592. };
  31593. inherits(Cartesian2D, Cartesian);
  31594. /*
  31595. * Licensed to the Apache Software Foundation (ASF) under one
  31596. * or more contributor license agreements. See the NOTICE file
  31597. * distributed with this work for additional information
  31598. * regarding copyright ownership. The ASF licenses this file
  31599. * to you under the Apache License, Version 2.0 (the
  31600. * "License"); you may not use this file except in compliance
  31601. * with the License. You may obtain a copy of the License at
  31602. *
  31603. * http://www.apache.org/licenses/LICENSE-2.0
  31604. *
  31605. * Unless required by applicable law or agreed to in writing,
  31606. * software distributed under the License is distributed on an
  31607. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31608. * KIND, either express or implied. See the License for the
  31609. * specific language governing permissions and limitations
  31610. * under the License.
  31611. */
  31612. /**
  31613. * Extend axis 2d
  31614. * @constructor module:echarts/coord/cartesian/Axis2D
  31615. * @extends {module:echarts/coord/cartesian/Axis}
  31616. * @param {string} dim
  31617. * @param {*} scale
  31618. * @param {Array.<number>} coordExtent
  31619. * @param {string} axisType
  31620. * @param {string} position
  31621. */
  31622. var Axis2D = function (dim, scale, coordExtent, axisType, position) {
  31623. Axis.call(this, dim, scale, coordExtent);
  31624. /**
  31625. * Axis type
  31626. * - 'category'
  31627. * - 'value'
  31628. * - 'time'
  31629. * - 'log'
  31630. * @type {string}
  31631. */
  31632. this.type = axisType || 'value';
  31633. /**
  31634. * Axis position
  31635. * - 'top'
  31636. * - 'bottom'
  31637. * - 'left'
  31638. * - 'right'
  31639. */
  31640. this.position = position || 'bottom';
  31641. };
  31642. Axis2D.prototype = {
  31643. constructor: Axis2D,
  31644. /**
  31645. * Index of axis, can be used as key
  31646. */
  31647. index: 0,
  31648. /**
  31649. * Implemented in <module:echarts/coord/cartesian/Grid>.
  31650. * @return {Array.<module:echarts/coord/cartesian/Axis2D>}
  31651. * If not on zero of other axis, return null/undefined.
  31652. * If no axes, return an empty array.
  31653. */
  31654. getAxesOnZeroOf: null,
  31655. /**
  31656. * Axis model
  31657. * @param {module:echarts/coord/cartesian/AxisModel}
  31658. */
  31659. model: null,
  31660. isHorizontal: function () {
  31661. var position = this.position;
  31662. return position === 'top' || position === 'bottom';
  31663. },
  31664. /**
  31665. * Each item cooresponds to this.getExtent(), which
  31666. * means globalExtent[0] may greater than globalExtent[1],
  31667. * unless `asc` is input.
  31668. *
  31669. * @param {boolean} [asc]
  31670. * @return {Array.<number>}
  31671. */
  31672. getGlobalExtent: function (asc) {
  31673. var ret = this.getExtent();
  31674. ret[0] = this.toGlobalCoord(ret[0]);
  31675. ret[1] = this.toGlobalCoord(ret[1]);
  31676. asc && ret[0] > ret[1] && ret.reverse();
  31677. return ret;
  31678. },
  31679. getOtherAxis: function () {
  31680. this.grid.getOtherAxis();
  31681. },
  31682. /**
  31683. * @override
  31684. */
  31685. pointToData: function (point, clamp) {
  31686. return this.coordToData(this.toLocalCoord(point[this.dim === 'x' ? 0 : 1]), clamp);
  31687. },
  31688. /**
  31689. * Transform global coord to local coord,
  31690. * i.e. var localCoord = axis.toLocalCoord(80);
  31691. * designate by module:echarts/coord/cartesian/Grid.
  31692. * @type {Function}
  31693. */
  31694. toLocalCoord: null,
  31695. /**
  31696. * Transform global coord to local coord,
  31697. * i.e. var globalCoord = axis.toLocalCoord(40);
  31698. * designate by module:echarts/coord/cartesian/Grid.
  31699. * @type {Function}
  31700. */
  31701. toGlobalCoord: null
  31702. };
  31703. inherits(Axis2D, Axis);
  31704. /*
  31705. * Licensed to the Apache Software Foundation (ASF) under one
  31706. * or more contributor license agreements. See the NOTICE file
  31707. * distributed with this work for additional information
  31708. * regarding copyright ownership. The ASF licenses this file
  31709. * to you under the Apache License, Version 2.0 (the
  31710. * "License"); you may not use this file except in compliance
  31711. * with the License. You may obtain a copy of the License at
  31712. *
  31713. * http://www.apache.org/licenses/LICENSE-2.0
  31714. *
  31715. * Unless required by applicable law or agreed to in writing,
  31716. * software distributed under the License is distributed on an
  31717. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31718. * KIND, either express or implied. See the License for the
  31719. * specific language governing permissions and limitations
  31720. * under the License.
  31721. */
  31722. var defaultOption = {
  31723. show: true,
  31724. zlevel: 0,
  31725. z: 0,
  31726. // Inverse the axis.
  31727. inverse: false,
  31728. // Axis name displayed.
  31729. name: '',
  31730. // 'start' | 'middle' | 'end'
  31731. nameLocation: 'end',
  31732. // By degree. By defualt auto rotate by nameLocation.
  31733. nameRotate: null,
  31734. nameTruncate: {
  31735. maxWidth: null,
  31736. ellipsis: '...',
  31737. placeholder: '.'
  31738. },
  31739. // Use global text style by default.
  31740. nameTextStyle: {},
  31741. // The gap between axisName and axisLine.
  31742. nameGap: 15,
  31743. // Default `false` to support tooltip.
  31744. silent: false,
  31745. // Default `false` to avoid legacy user event listener fail.
  31746. triggerEvent: false,
  31747. tooltip: {
  31748. show: false
  31749. },
  31750. axisPointer: {},
  31751. axisLine: {
  31752. show: true,
  31753. onZero: true,
  31754. onZeroAxisIndex: null,
  31755. lineStyle: {
  31756. color: '#333',
  31757. width: 1,
  31758. type: 'solid'
  31759. },
  31760. // The arrow at both ends the the axis.
  31761. symbol: ['none', 'none'],
  31762. symbolSize: [10, 15]
  31763. },
  31764. axisTick: {
  31765. show: true,
  31766. // Whether axisTick is inside the grid or outside the grid.
  31767. inside: false,
  31768. // The length of axisTick.
  31769. length: 5,
  31770. lineStyle: {
  31771. width: 1
  31772. }
  31773. },
  31774. axisLabel: {
  31775. show: true,
  31776. // Whether axisLabel is inside the grid or outside the grid.
  31777. inside: false,
  31778. rotate: 0,
  31779. // true | false | null/undefined (auto)
  31780. showMinLabel: null,
  31781. // true | false | null/undefined (auto)
  31782. showMaxLabel: null,
  31783. margin: 8,
  31784. // formatter: null,
  31785. fontSize: 12
  31786. },
  31787. splitLine: {
  31788. show: true,
  31789. lineStyle: {
  31790. color: ['#ccc'],
  31791. width: 1,
  31792. type: 'solid'
  31793. }
  31794. },
  31795. splitArea: {
  31796. show: false,
  31797. areaStyle: {
  31798. color: ['rgba(250,250,250,0.3)','rgba(200,200,200,0.3)']
  31799. }
  31800. }
  31801. };
  31802. var axisDefault = {};
  31803. axisDefault.categoryAxis = merge({
  31804. // The gap at both ends of the axis. For categoryAxis, boolean.
  31805. boundaryGap: true,
  31806. // Set false to faster category collection.
  31807. // Only usefull in the case like: category is
  31808. // ['2012-01-01', '2012-01-02', ...], where the input
  31809. // data has been ensured not duplicate and is large data.
  31810. // null means "auto":
  31811. // if axis.data provided, do not deduplication,
  31812. // else do deduplication.
  31813. deduplication: null,
  31814. // splitArea: {
  31815. // show: false
  31816. // },
  31817. splitLine: {
  31818. show: false
  31819. },
  31820. axisTick: {
  31821. // If tick is align with label when boundaryGap is true
  31822. alignWithLabel: false,
  31823. interval: 'auto'
  31824. },
  31825. axisLabel: {
  31826. interval: 'auto'
  31827. }
  31828. }, defaultOption);
  31829. axisDefault.valueAxis = merge({
  31830. // The gap at both ends of the axis. For value axis, [GAP, GAP], where
  31831. // `GAP` can be an absolute pixel number (like `35`), or percent (like `'30%'`)
  31832. boundaryGap: [0, 0],
  31833. // TODO
  31834. // min/max: [30, datamin, 60] or [20, datamin] or [datamin, 60]
  31835. // Min value of the axis. can be:
  31836. // + a number
  31837. // + 'dataMin': use the min value in data.
  31838. // + null/undefined: auto decide min value (consider pretty look and boundaryGap).
  31839. // min: null,
  31840. // Max value of the axis. can be:
  31841. // + a number
  31842. // + 'dataMax': use the max value in data.
  31843. // + null/undefined: auto decide max value (consider pretty look and boundaryGap).
  31844. // max: null,
  31845. // Readonly prop, specifies start value of the range when using data zoom.
  31846. // rangeStart: null
  31847. // Readonly prop, specifies end value of the range when using data zoom.
  31848. // rangeEnd: null
  31849. // Optional value can be:
  31850. // + `false`: always include value 0.
  31851. // + `true`: the extent do not consider value 0.
  31852. // scale: false,
  31853. // AxisTick and axisLabel and splitLine are caculated based on splitNumber.
  31854. splitNumber: 5
  31855. // Interval specifies the span of the ticks is mandatorily.
  31856. // interval: null
  31857. // Specify min interval when auto calculate tick interval.
  31858. // minInterval: null
  31859. // Specify max interval when auto calculate tick interval.
  31860. // maxInterval: null
  31861. }, defaultOption);
  31862. axisDefault.timeAxis = defaults({
  31863. scale: true,
  31864. min: 'dataMin',
  31865. max: 'dataMax'
  31866. }, axisDefault.valueAxis);
  31867. axisDefault.logAxis = defaults({
  31868. scale: true,
  31869. logBase: 10
  31870. }, axisDefault.valueAxis);
  31871. /*
  31872. * Licensed to the Apache Software Foundation (ASF) under one
  31873. * or more contributor license agreements. See the NOTICE file
  31874. * distributed with this work for additional information
  31875. * regarding copyright ownership. The ASF licenses this file
  31876. * to you under the Apache License, Version 2.0 (the
  31877. * "License"); you may not use this file except in compliance
  31878. * with the License. You may obtain a copy of the License at
  31879. *
  31880. * http://www.apache.org/licenses/LICENSE-2.0
  31881. *
  31882. * Unless required by applicable law or agreed to in writing,
  31883. * software distributed under the License is distributed on an
  31884. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31885. * KIND, either express or implied. See the License for the
  31886. * specific language governing permissions and limitations
  31887. * under the License.
  31888. */
  31889. // FIXME axisType is fixed ?
  31890. var AXIS_TYPES = ['value', 'category', 'time', 'log'];
  31891. /**
  31892. * Generate sub axis model class
  31893. * @param {string} axisName 'x' 'y' 'radius' 'angle' 'parallel'
  31894. * @param {module:echarts/model/Component} BaseAxisModelClass
  31895. * @param {Function} axisTypeDefaulter
  31896. * @param {Object} [extraDefaultOption]
  31897. */
  31898. var axisModelCreator = function (axisName, BaseAxisModelClass, axisTypeDefaulter, extraDefaultOption) {
  31899. each$1(AXIS_TYPES, function (axisType) {
  31900. BaseAxisModelClass.extend({
  31901. /**
  31902. * @readOnly
  31903. */
  31904. type: axisName + 'Axis.' + axisType,
  31905. mergeDefaultAndTheme: function (option, ecModel) {
  31906. var layoutMode = this.layoutMode;
  31907. var inputPositionParams = layoutMode
  31908. ? getLayoutParams(option) : {};
  31909. var themeModel = ecModel.getTheme();
  31910. merge(option, themeModel.get(axisType + 'Axis'));
  31911. merge(option, this.getDefaultOption());
  31912. option.type = axisTypeDefaulter(axisName, option);
  31913. if (layoutMode) {
  31914. mergeLayoutParam(option, inputPositionParams, layoutMode);
  31915. }
  31916. },
  31917. /**
  31918. * @override
  31919. */
  31920. optionUpdated: function () {
  31921. var thisOption = this.option;
  31922. if (thisOption.type === 'category') {
  31923. this.__ordinalMeta = OrdinalMeta.createByAxisModel(this);
  31924. }
  31925. },
  31926. /**
  31927. * Should not be called before all of 'getInitailData' finished.
  31928. * Because categories are collected during initializing data.
  31929. */
  31930. getCategories: function (rawData) {
  31931. var option = this.option;
  31932. // FIXME
  31933. // warning if called before all of 'getInitailData' finished.
  31934. if (option.type === 'category') {
  31935. if (rawData) {
  31936. return option.data;
  31937. }
  31938. return this.__ordinalMeta.categories;
  31939. }
  31940. },
  31941. getOrdinalMeta: function () {
  31942. return this.__ordinalMeta;
  31943. },
  31944. defaultOption: mergeAll(
  31945. [
  31946. {},
  31947. axisDefault[axisType + 'Axis'],
  31948. extraDefaultOption
  31949. ],
  31950. true
  31951. )
  31952. });
  31953. });
  31954. ComponentModel.registerSubTypeDefaulter(
  31955. axisName + 'Axis',
  31956. curry(axisTypeDefaulter, axisName)
  31957. );
  31958. };
  31959. /*
  31960. * Licensed to the Apache Software Foundation (ASF) under one
  31961. * or more contributor license agreements. See the NOTICE file
  31962. * distributed with this work for additional information
  31963. * regarding copyright ownership. The ASF licenses this file
  31964. * to you under the Apache License, Version 2.0 (the
  31965. * "License"); you may not use this file except in compliance
  31966. * with the License. You may obtain a copy of the License at
  31967. *
  31968. * http://www.apache.org/licenses/LICENSE-2.0
  31969. *
  31970. * Unless required by applicable law or agreed to in writing,
  31971. * software distributed under the License is distributed on an
  31972. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31973. * KIND, either express or implied. See the License for the
  31974. * specific language governing permissions and limitations
  31975. * under the License.
  31976. */
  31977. var AxisModel = ComponentModel.extend({
  31978. type: 'cartesian2dAxis',
  31979. /**
  31980. * @type {module:echarts/coord/cartesian/Axis2D}
  31981. */
  31982. axis: null,
  31983. /**
  31984. * @override
  31985. */
  31986. init: function () {
  31987. AxisModel.superApply(this, 'init', arguments);
  31988. this.resetRange();
  31989. },
  31990. /**
  31991. * @override
  31992. */
  31993. mergeOption: function () {
  31994. AxisModel.superApply(this, 'mergeOption', arguments);
  31995. this.resetRange();
  31996. },
  31997. /**
  31998. * @override
  31999. */
  32000. restoreData: function () {
  32001. AxisModel.superApply(this, 'restoreData', arguments);
  32002. this.resetRange();
  32003. },
  32004. /**
  32005. * @override
  32006. * @return {module:echarts/model/Component}
  32007. */
  32008. getCoordSysModel: function () {
  32009. return this.ecModel.queryComponents({
  32010. mainType: 'grid',
  32011. index: this.option.gridIndex,
  32012. id: this.option.gridId
  32013. })[0];
  32014. }
  32015. });
  32016. function getAxisType(axisDim, option) {
  32017. // Default axis with data is category axis
  32018. return option.type || (option.data ? 'category' : 'value');
  32019. }
  32020. merge(AxisModel.prototype, axisModelCommonMixin);
  32021. var extraOption = {
  32022. // gridIndex: 0,
  32023. // gridId: '',
  32024. // Offset is for multiple axis on the same position
  32025. offset: 0
  32026. };
  32027. axisModelCreator('x', AxisModel, getAxisType, extraOption);
  32028. axisModelCreator('y', AxisModel, getAxisType, extraOption);
  32029. /*
  32030. * Licensed to the Apache Software Foundation (ASF) under one
  32031. * or more contributor license agreements. See the NOTICE file
  32032. * distributed with this work for additional information
  32033. * regarding copyright ownership. The ASF licenses this file
  32034. * to you under the Apache License, Version 2.0 (the
  32035. * "License"); you may not use this file except in compliance
  32036. * with the License. You may obtain a copy of the License at
  32037. *
  32038. * http://www.apache.org/licenses/LICENSE-2.0
  32039. *
  32040. * Unless required by applicable law or agreed to in writing,
  32041. * software distributed under the License is distributed on an
  32042. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32043. * KIND, either express or implied. See the License for the
  32044. * specific language governing permissions and limitations
  32045. * under the License.
  32046. */
  32047. // Grid 是在有直角坐标系的时候必须要存在的
  32048. // 所以这里也要被 Cartesian2D 依赖
  32049. ComponentModel.extend({
  32050. type: 'grid',
  32051. dependencies: ['xAxis', 'yAxis'],
  32052. layoutMode: 'box',
  32053. /**
  32054. * @type {module:echarts/coord/cartesian/Grid}
  32055. */
  32056. coordinateSystem: null,
  32057. defaultOption: {
  32058. show: false,
  32059. zlevel: 0,
  32060. z: 0,
  32061. left: '10%',
  32062. top: 60,
  32063. right: '10%',
  32064. bottom: 60,
  32065. // If grid size contain label
  32066. containLabel: false,
  32067. // width: {totalWidth} - left - right,
  32068. // height: {totalHeight} - top - bottom,
  32069. backgroundColor: 'rgba(0,0,0,0)',
  32070. borderWidth: 1,
  32071. borderColor: '#ccc'
  32072. }
  32073. });
  32074. /*
  32075. * Licensed to the Apache Software Foundation (ASF) under one
  32076. * or more contributor license agreements. See the NOTICE file
  32077. * distributed with this work for additional information
  32078. * regarding copyright ownership. The ASF licenses this file
  32079. * to you under the Apache License, Version 2.0 (the
  32080. * "License"); you may not use this file except in compliance
  32081. * with the License. You may obtain a copy of the License at
  32082. *
  32083. * http://www.apache.org/licenses/LICENSE-2.0
  32084. *
  32085. * Unless required by applicable law or agreed to in writing,
  32086. * software distributed under the License is distributed on an
  32087. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32088. * KIND, either express or implied. See the License for the
  32089. * specific language governing permissions and limitations
  32090. * under the License.
  32091. */
  32092. /**
  32093. * Grid is a region which contains at most 4 cartesian systems
  32094. *
  32095. * TODO Default cartesian
  32096. */
  32097. // Depends on GridModel, AxisModel, which performs preprocess.
  32098. /**
  32099. * Check if the axis is used in the specified grid
  32100. * @inner
  32101. */
  32102. function isAxisUsedInTheGrid(axisModel, gridModel, ecModel) {
  32103. return axisModel.getCoordSysModel() === gridModel;
  32104. }
  32105. function Grid(gridModel, ecModel, api) {
  32106. /**
  32107. * @type {Object.<string, module:echarts/coord/cartesian/Cartesian2D>}
  32108. * @private
  32109. */
  32110. this._coordsMap = {};
  32111. /**
  32112. * @type {Array.<module:echarts/coord/cartesian/Cartesian>}
  32113. * @private
  32114. */
  32115. this._coordsList = [];
  32116. /**
  32117. * @type {Object.<string, module:echarts/coord/cartesian/Axis2D>}
  32118. * @private
  32119. */
  32120. this._axesMap = {};
  32121. /**
  32122. * @type {Array.<module:echarts/coord/cartesian/Axis2D>}
  32123. * @private
  32124. */
  32125. this._axesList = [];
  32126. this._initCartesian(gridModel, ecModel, api);
  32127. this.model = gridModel;
  32128. }
  32129. var gridProto = Grid.prototype;
  32130. gridProto.type = 'grid';
  32131. gridProto.axisPointerEnabled = true;
  32132. gridProto.getRect = function () {
  32133. return this._rect;
  32134. };
  32135. gridProto.update = function (ecModel, api) {
  32136. var axesMap = this._axesMap;
  32137. this._updateScale(ecModel, this.model);
  32138. each$1(axesMap.x, function (xAxis) {
  32139. niceScaleExtent(xAxis.scale, xAxis.model);
  32140. });
  32141. each$1(axesMap.y, function (yAxis) {
  32142. niceScaleExtent(yAxis.scale, yAxis.model);
  32143. });
  32144. each$1(axesMap.x, function (xAxis) {
  32145. fixAxisOnZero(axesMap, 'y', xAxis);
  32146. });
  32147. each$1(axesMap.y, function (yAxis) {
  32148. fixAxisOnZero(axesMap, 'x', yAxis);
  32149. });
  32150. // Resize again if containLabel is enabled
  32151. // FIXME It may cause getting wrong grid size in data processing stage
  32152. this.resize(this.model, api);
  32153. };
  32154. function fixAxisOnZero(axesMap, otherAxisDim, axis) {
  32155. axis.getAxesOnZeroOf = function () {
  32156. // TODO: onZero of multiple axes.
  32157. return otherAxis ? [otherAxis] : [];
  32158. };
  32159. // onZero can not be enabled in these two situations:
  32160. // 1. When any other axis is a category axis.
  32161. // 2. When no axis is cross 0 point.
  32162. var otherAxes = axesMap[otherAxisDim];
  32163. var otherAxis;
  32164. var axisModel = axis.model;
  32165. var onZero = axisModel.get('axisLine.onZero');
  32166. var onZeroAxisIndex = axisModel.get('axisLine.onZeroAxisIndex');
  32167. if (!onZero) {
  32168. return;
  32169. }
  32170. // If target axis is specified.
  32171. if (onZeroAxisIndex != null) {
  32172. if (canOnZeroToAxis(otherAxes[onZeroAxisIndex])) {
  32173. otherAxis = otherAxes[onZeroAxisIndex];
  32174. }
  32175. return;
  32176. }
  32177. // Find the first available other axis.
  32178. for (var idx in otherAxes) {
  32179. if (otherAxes.hasOwnProperty(idx) && canOnZeroToAxis(otherAxes[idx])) {
  32180. otherAxis = otherAxes[idx];
  32181. break;
  32182. }
  32183. }
  32184. }
  32185. function canOnZeroToAxis(axis) {
  32186. return axis && axis.type !== 'category' && axis.type !== 'time' && ifAxisCrossZero(axis);
  32187. }
  32188. /**
  32189. * Resize the grid
  32190. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  32191. * @param {module:echarts/ExtensionAPI} api
  32192. */
  32193. gridProto.resize = function (gridModel, api, ignoreContainLabel) {
  32194. var gridRect = getLayoutRect(
  32195. gridModel.getBoxLayoutParams(), {
  32196. width: api.getWidth(),
  32197. height: api.getHeight()
  32198. });
  32199. this._rect = gridRect;
  32200. var axesList = this._axesList;
  32201. adjustAxes();
  32202. // Minus label size
  32203. if (!ignoreContainLabel && gridModel.get('containLabel')) {
  32204. each$1(axesList, function (axis) {
  32205. if (!axis.model.get('axisLabel.inside')) {
  32206. var labelUnionRect = estimateLabelUnionRect(axis);
  32207. if (labelUnionRect) {
  32208. var dim = axis.isHorizontal() ? 'height' : 'width';
  32209. var margin = axis.model.get('axisLabel.margin');
  32210. gridRect[dim] -= labelUnionRect[dim] + margin;
  32211. if (axis.position === 'top') {
  32212. gridRect.y += labelUnionRect.height + margin;
  32213. }
  32214. else if (axis.position === 'left') {
  32215. gridRect.x += labelUnionRect.width + margin;
  32216. }
  32217. }
  32218. }
  32219. });
  32220. adjustAxes();
  32221. }
  32222. function adjustAxes() {
  32223. each$1(axesList, function (axis) {
  32224. var isHorizontal = axis.isHorizontal();
  32225. var extent = isHorizontal ? [0, gridRect.width] : [0, gridRect.height];
  32226. var idx = axis.inverse ? 1 : 0;
  32227. axis.setExtent(extent[idx], extent[1 - idx]);
  32228. updateAxisTransform(axis, isHorizontal ? gridRect.x : gridRect.y);
  32229. });
  32230. }
  32231. };
  32232. /**
  32233. * @param {string} axisType
  32234. * @param {number} [axisIndex]
  32235. */
  32236. gridProto.getAxis = function (axisType, axisIndex) {
  32237. var axesMapOnDim = this._axesMap[axisType];
  32238. if (axesMapOnDim != null) {
  32239. if (axisIndex == null) {
  32240. // Find first axis
  32241. for (var name in axesMapOnDim) {
  32242. if (axesMapOnDim.hasOwnProperty(name)) {
  32243. return axesMapOnDim[name];
  32244. }
  32245. }
  32246. }
  32247. return axesMapOnDim[axisIndex];
  32248. }
  32249. };
  32250. /**
  32251. * @return {Array.<module:echarts/coord/Axis>}
  32252. */
  32253. gridProto.getAxes = function () {
  32254. return this._axesList.slice();
  32255. };
  32256. /**
  32257. * Usage:
  32258. * grid.getCartesian(xAxisIndex, yAxisIndex);
  32259. * grid.getCartesian(xAxisIndex);
  32260. * grid.getCartesian(null, yAxisIndex);
  32261. * grid.getCartesian({xAxisIndex: ..., yAxisIndex: ...});
  32262. *
  32263. * @param {number|Object} [xAxisIndex]
  32264. * @param {number} [yAxisIndex]
  32265. */
  32266. gridProto.getCartesian = function (xAxisIndex, yAxisIndex) {
  32267. if (xAxisIndex != null && yAxisIndex != null) {
  32268. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  32269. return this._coordsMap[key];
  32270. }
  32271. if (isObject$1(xAxisIndex)) {
  32272. yAxisIndex = xAxisIndex.yAxisIndex;
  32273. xAxisIndex = xAxisIndex.xAxisIndex;
  32274. }
  32275. // When only xAxisIndex or yAxisIndex given, find its first cartesian.
  32276. for (var i = 0, coordList = this._coordsList; i < coordList.length; i++) {
  32277. if (coordList[i].getAxis('x').index === xAxisIndex
  32278. || coordList[i].getAxis('y').index === yAxisIndex
  32279. ) {
  32280. return coordList[i];
  32281. }
  32282. }
  32283. };
  32284. gridProto.getCartesians = function () {
  32285. return this._coordsList.slice();
  32286. };
  32287. /**
  32288. * @implements
  32289. * see {module:echarts/CoodinateSystem}
  32290. */
  32291. gridProto.convertToPixel = function (ecModel, finder, value) {
  32292. var target = this._findConvertTarget(ecModel, finder);
  32293. return target.cartesian
  32294. ? target.cartesian.dataToPoint(value)
  32295. : target.axis
  32296. ? target.axis.toGlobalCoord(target.axis.dataToCoord(value))
  32297. : null;
  32298. };
  32299. /**
  32300. * @implements
  32301. * see {module:echarts/CoodinateSystem}
  32302. */
  32303. gridProto.convertFromPixel = function (ecModel, finder, value) {
  32304. var target = this._findConvertTarget(ecModel, finder);
  32305. return target.cartesian
  32306. ? target.cartesian.pointToData(value)
  32307. : target.axis
  32308. ? target.axis.coordToData(target.axis.toLocalCoord(value))
  32309. : null;
  32310. };
  32311. /**
  32312. * @inner
  32313. */
  32314. gridProto._findConvertTarget = function (ecModel, finder) {
  32315. var seriesModel = finder.seriesModel;
  32316. var xAxisModel = finder.xAxisModel
  32317. || (seriesModel && seriesModel.getReferringComponents('xAxis')[0]);
  32318. var yAxisModel = finder.yAxisModel
  32319. || (seriesModel && seriesModel.getReferringComponents('yAxis')[0]);
  32320. var gridModel = finder.gridModel;
  32321. var coordsList = this._coordsList;
  32322. var cartesian;
  32323. var axis;
  32324. if (seriesModel) {
  32325. cartesian = seriesModel.coordinateSystem;
  32326. indexOf(coordsList, cartesian) < 0 && (cartesian = null);
  32327. }
  32328. else if (xAxisModel && yAxisModel) {
  32329. cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  32330. }
  32331. else if (xAxisModel) {
  32332. axis = this.getAxis('x', xAxisModel.componentIndex);
  32333. }
  32334. else if (yAxisModel) {
  32335. axis = this.getAxis('y', yAxisModel.componentIndex);
  32336. }
  32337. // Lowest priority.
  32338. else if (gridModel) {
  32339. var grid = gridModel.coordinateSystem;
  32340. if (grid === this) {
  32341. cartesian = this._coordsList[0];
  32342. }
  32343. }
  32344. return {cartesian: cartesian, axis: axis};
  32345. };
  32346. /**
  32347. * @implements
  32348. * see {module:echarts/CoodinateSystem}
  32349. */
  32350. gridProto.containPoint = function (point) {
  32351. var coord = this._coordsList[0];
  32352. if (coord) {
  32353. return coord.containPoint(point);
  32354. }
  32355. };
  32356. /**
  32357. * Initialize cartesian coordinate systems
  32358. * @private
  32359. */
  32360. gridProto._initCartesian = function (gridModel, ecModel, api) {
  32361. var axisPositionUsed = {
  32362. left: false,
  32363. right: false,
  32364. top: false,
  32365. bottom: false
  32366. };
  32367. var axesMap = {
  32368. x: {},
  32369. y: {}
  32370. };
  32371. var axesCount = {
  32372. x: 0,
  32373. y: 0
  32374. };
  32375. /// Create axis
  32376. ecModel.eachComponent('xAxis', createAxisCreator('x'), this);
  32377. ecModel.eachComponent('yAxis', createAxisCreator('y'), this);
  32378. if (!axesCount.x || !axesCount.y) {
  32379. // Roll back when there no either x or y axis
  32380. this._axesMap = {};
  32381. this._axesList = [];
  32382. return;
  32383. }
  32384. this._axesMap = axesMap;
  32385. /// Create cartesian2d
  32386. each$1(axesMap.x, function (xAxis, xAxisIndex) {
  32387. each$1(axesMap.y, function (yAxis, yAxisIndex) {
  32388. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  32389. var cartesian = new Cartesian2D(key);
  32390. cartesian.grid = this;
  32391. cartesian.model = gridModel;
  32392. this._coordsMap[key] = cartesian;
  32393. this._coordsList.push(cartesian);
  32394. cartesian.addAxis(xAxis);
  32395. cartesian.addAxis(yAxis);
  32396. }, this);
  32397. }, this);
  32398. function createAxisCreator(axisType) {
  32399. return function (axisModel, idx) {
  32400. if (!isAxisUsedInTheGrid(axisModel, gridModel, ecModel)) {
  32401. return;
  32402. }
  32403. var axisPosition = axisModel.get('position');
  32404. if (axisType === 'x') {
  32405. // Fix position
  32406. if (axisPosition !== 'top' && axisPosition !== 'bottom') {
  32407. // Default bottom of X
  32408. axisPosition = 'bottom';
  32409. if (axisPositionUsed[axisPosition]) {
  32410. axisPosition = axisPosition === 'top' ? 'bottom' : 'top';
  32411. }
  32412. }
  32413. }
  32414. else {
  32415. // Fix position
  32416. if (axisPosition !== 'left' && axisPosition !== 'right') {
  32417. // Default left of Y
  32418. axisPosition = 'left';
  32419. if (axisPositionUsed[axisPosition]) {
  32420. axisPosition = axisPosition === 'left' ? 'right' : 'left';
  32421. }
  32422. }
  32423. }
  32424. axisPositionUsed[axisPosition] = true;
  32425. var axis = new Axis2D(
  32426. axisType, createScaleByModel(axisModel),
  32427. [0, 0],
  32428. axisModel.get('type'),
  32429. axisPosition
  32430. );
  32431. var isCategory = axis.type === 'category';
  32432. axis.onBand = isCategory && axisModel.get('boundaryGap');
  32433. axis.inverse = axisModel.get('inverse');
  32434. // Inject axis into axisModel
  32435. axisModel.axis = axis;
  32436. // Inject axisModel into axis
  32437. axis.model = axisModel;
  32438. // Inject grid info axis
  32439. axis.grid = this;
  32440. // Index of axis, can be used as key
  32441. axis.index = idx;
  32442. this._axesList.push(axis);
  32443. axesMap[axisType][idx] = axis;
  32444. axesCount[axisType]++;
  32445. };
  32446. }
  32447. };
  32448. /**
  32449. * Update cartesian properties from series
  32450. * @param {module:echarts/model/Option} option
  32451. * @private
  32452. */
  32453. gridProto._updateScale = function (ecModel, gridModel) {
  32454. // Reset scale
  32455. each$1(this._axesList, function (axis) {
  32456. axis.scale.setExtent(Infinity, -Infinity);
  32457. });
  32458. ecModel.eachSeries(function (seriesModel) {
  32459. if (isCartesian2D(seriesModel)) {
  32460. var axesModels = findAxesModels(seriesModel, ecModel);
  32461. var xAxisModel = axesModels[0];
  32462. var yAxisModel = axesModels[1];
  32463. if (!isAxisUsedInTheGrid(xAxisModel, gridModel, ecModel)
  32464. || !isAxisUsedInTheGrid(yAxisModel, gridModel, ecModel)
  32465. ) {
  32466. return;
  32467. }
  32468. var cartesian = this.getCartesian(
  32469. xAxisModel.componentIndex, yAxisModel.componentIndex
  32470. );
  32471. var data = seriesModel.getData();
  32472. var xAxis = cartesian.getAxis('x');
  32473. var yAxis = cartesian.getAxis('y');
  32474. if (data.type === 'list') {
  32475. unionExtent(data, xAxis, seriesModel);
  32476. unionExtent(data, yAxis, seriesModel);
  32477. }
  32478. }
  32479. }, this);
  32480. function unionExtent(data, axis, seriesModel) {
  32481. each$1(data.mapDimension(axis.dim, true), function (dim) {
  32482. axis.scale.unionExtentFromData(data, dim);
  32483. });
  32484. }
  32485. };
  32486. /**
  32487. * @param {string} [dim] 'x' or 'y' or 'auto' or null/undefined
  32488. * @return {Object} {baseAxes: [], otherAxes: []}
  32489. */
  32490. gridProto.getTooltipAxes = function (dim) {
  32491. var baseAxes = [];
  32492. var otherAxes = [];
  32493. each$1(this.getCartesians(), function (cartesian) {
  32494. var baseAxis = (dim != null && dim !== 'auto')
  32495. ? cartesian.getAxis(dim) : cartesian.getBaseAxis();
  32496. var otherAxis = cartesian.getOtherAxis(baseAxis);
  32497. indexOf(baseAxes, baseAxis) < 0 && baseAxes.push(baseAxis);
  32498. indexOf(otherAxes, otherAxis) < 0 && otherAxes.push(otherAxis);
  32499. });
  32500. return {baseAxes: baseAxes, otherAxes: otherAxes};
  32501. };
  32502. /**
  32503. * @inner
  32504. */
  32505. function updateAxisTransform(axis, coordBase) {
  32506. var axisExtent = axis.getExtent();
  32507. var axisExtentSum = axisExtent[0] + axisExtent[1];
  32508. // Fast transform
  32509. axis.toGlobalCoord = axis.dim === 'x'
  32510. ? function (coord) {
  32511. return coord + coordBase;
  32512. }
  32513. : function (coord) {
  32514. return axisExtentSum - coord + coordBase;
  32515. };
  32516. axis.toLocalCoord = axis.dim === 'x'
  32517. ? function (coord) {
  32518. return coord - coordBase;
  32519. }
  32520. : function (coord) {
  32521. return axisExtentSum - coord + coordBase;
  32522. };
  32523. }
  32524. var axesTypes = ['xAxis', 'yAxis'];
  32525. /**
  32526. * @inner
  32527. */
  32528. function findAxesModels(seriesModel, ecModel) {
  32529. return map(axesTypes, function (axisType) {
  32530. var axisModel = seriesModel.getReferringComponents(axisType)[0];
  32531. if (__DEV__) {
  32532. if (!axisModel) {
  32533. throw new Error(axisType + ' "' + retrieve(
  32534. seriesModel.get(axisType + 'Index'),
  32535. seriesModel.get(axisType + 'Id'),
  32536. 0
  32537. ) + '" not found');
  32538. }
  32539. }
  32540. return axisModel;
  32541. });
  32542. }
  32543. /**
  32544. * @inner
  32545. */
  32546. function isCartesian2D(seriesModel) {
  32547. return seriesModel.get('coordinateSystem') === 'cartesian2d';
  32548. }
  32549. Grid.create = function (ecModel, api) {
  32550. var grids = [];
  32551. ecModel.eachComponent('grid', function (gridModel, idx) {
  32552. var grid = new Grid(gridModel, ecModel, api);
  32553. grid.name = 'grid_' + idx;
  32554. // dataSampling requires axis extent, so resize
  32555. // should be performed in create stage.
  32556. grid.resize(gridModel, api, true);
  32557. gridModel.coordinateSystem = grid;
  32558. grids.push(grid);
  32559. });
  32560. // Inject the coordinateSystems into seriesModel
  32561. ecModel.eachSeries(function (seriesModel) {
  32562. if (!isCartesian2D(seriesModel)) {
  32563. return;
  32564. }
  32565. var axesModels = findAxesModels(seriesModel, ecModel);
  32566. var xAxisModel = axesModels[0];
  32567. var yAxisModel = axesModels[1];
  32568. var gridModel = xAxisModel.getCoordSysModel();
  32569. if (__DEV__) {
  32570. if (!gridModel) {
  32571. throw new Error(
  32572. 'Grid "' + retrieve(
  32573. xAxisModel.get('gridIndex'),
  32574. xAxisModel.get('gridId'),
  32575. 0
  32576. ) + '" not found'
  32577. );
  32578. }
  32579. if (xAxisModel.getCoordSysModel() !== yAxisModel.getCoordSysModel()) {
  32580. throw new Error('xAxis and yAxis must use the same grid');
  32581. }
  32582. }
  32583. var grid = gridModel.coordinateSystem;
  32584. seriesModel.coordinateSystem = grid.getCartesian(
  32585. xAxisModel.componentIndex, yAxisModel.componentIndex
  32586. );
  32587. });
  32588. return grids;
  32589. };
  32590. // For deciding which dimensions to use when creating list data
  32591. Grid.dimensions = Grid.prototype.dimensions = Cartesian2D.prototype.dimensions;
  32592. CoordinateSystemManager.register('cartesian2d', Grid);
  32593. /*
  32594. * Licensed to the Apache Software Foundation (ASF) under one
  32595. * or more contributor license agreements. See the NOTICE file
  32596. * distributed with this work for additional information
  32597. * regarding copyright ownership. The ASF licenses this file
  32598. * to you under the Apache License, Version 2.0 (the
  32599. * "License"); you may not use this file except in compliance
  32600. * with the License. You may obtain a copy of the License at
  32601. *
  32602. * http://www.apache.org/licenses/LICENSE-2.0
  32603. *
  32604. * Unless required by applicable law or agreed to in writing,
  32605. * software distributed under the License is distributed on an
  32606. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32607. * KIND, either express or implied. See the License for the
  32608. * specific language governing permissions and limitations
  32609. * under the License.
  32610. */
  32611. var PI$2 = Math.PI;
  32612. function makeAxisEventDataBase(axisModel) {
  32613. var eventData = {
  32614. componentType: axisModel.mainType
  32615. };
  32616. eventData[axisModel.mainType + 'Index'] = axisModel.componentIndex;
  32617. return eventData;
  32618. }
  32619. /**
  32620. * A final axis is translated and rotated from a "standard axis".
  32621. * So opt.position and opt.rotation is required.
  32622. *
  32623. * A standard axis is and axis from [0, 0] to [0, axisExtent[1]],
  32624. * for example: (0, 0) ------------> (0, 50)
  32625. *
  32626. * nameDirection or tickDirection or labelDirection is 1 means tick
  32627. * or label is below the standard axis, whereas is -1 means above
  32628. * the standard axis. labelOffset means offset between label and axis,
  32629. * which is useful when 'onZero', where axisLabel is in the grid and
  32630. * label in outside grid.
  32631. *
  32632. * Tips: like always,
  32633. * positive rotation represents anticlockwise, and negative rotation
  32634. * represents clockwise.
  32635. * The direction of position coordinate is the same as the direction
  32636. * of screen coordinate.
  32637. *
  32638. * Do not need to consider axis 'inverse', which is auto processed by
  32639. * axis extent.
  32640. *
  32641. * @param {module:zrender/container/Group} group
  32642. * @param {Object} axisModel
  32643. * @param {Object} opt Standard axis parameters.
  32644. * @param {Array.<number>} opt.position [x, y]
  32645. * @param {number} opt.rotation by radian
  32646. * @param {number} [opt.nameDirection=1] 1 or -1 Used when nameLocation is 'middle' or 'center'.
  32647. * @param {number} [opt.tickDirection=1] 1 or -1
  32648. * @param {number} [opt.labelDirection=1] 1 or -1
  32649. * @param {number} [opt.labelOffset=0] Usefull when onZero.
  32650. * @param {string} [opt.axisLabelShow] default get from axisModel.
  32651. * @param {string} [opt.axisName] default get from axisModel.
  32652. * @param {number} [opt.axisNameAvailableWidth]
  32653. * @param {number} [opt.labelRotate] by degree, default get from axisModel.
  32654. * @param {number} [opt.strokeContainThreshold] Default label interval when label
  32655. * @param {number} [opt.nameTruncateMaxWidth]
  32656. */
  32657. var AxisBuilder = function (axisModel, opt) {
  32658. /**
  32659. * @readOnly
  32660. */
  32661. this.opt = opt;
  32662. /**
  32663. * @readOnly
  32664. */
  32665. this.axisModel = axisModel;
  32666. // Default value
  32667. defaults(
  32668. opt,
  32669. {
  32670. labelOffset: 0,
  32671. nameDirection: 1,
  32672. tickDirection: 1,
  32673. labelDirection: 1,
  32674. silent: true
  32675. }
  32676. );
  32677. /**
  32678. * @readOnly
  32679. */
  32680. this.group = new Group();
  32681. // FIXME Not use a seperate text group?
  32682. var dumbGroup = new Group({
  32683. position: opt.position.slice(),
  32684. rotation: opt.rotation
  32685. });
  32686. // this.group.add(dumbGroup);
  32687. // this._dumbGroup = dumbGroup;
  32688. dumbGroup.updateTransform();
  32689. this._transform = dumbGroup.transform;
  32690. this._dumbGroup = dumbGroup;
  32691. };
  32692. AxisBuilder.prototype = {
  32693. constructor: AxisBuilder,
  32694. hasBuilder: function (name) {
  32695. return !!builders[name];
  32696. },
  32697. add: function (name) {
  32698. builders[name].call(this);
  32699. },
  32700. getGroup: function () {
  32701. return this.group;
  32702. }
  32703. };
  32704. var builders = {
  32705. /**
  32706. * @private
  32707. */
  32708. axisLine: function () {
  32709. var opt = this.opt;
  32710. var axisModel = this.axisModel;
  32711. if (!axisModel.get('axisLine.show')) {
  32712. return;
  32713. }
  32714. var extent = this.axisModel.axis.getExtent();
  32715. var matrix = this._transform;
  32716. var pt1 = [extent[0], 0];
  32717. var pt2 = [extent[1], 0];
  32718. if (matrix) {
  32719. applyTransform(pt1, pt1, matrix);
  32720. applyTransform(pt2, pt2, matrix);
  32721. }
  32722. var lineStyle = extend(
  32723. {
  32724. lineCap: 'round'
  32725. },
  32726. axisModel.getModel('axisLine.lineStyle').getLineStyle()
  32727. );
  32728. this.group.add(new Line(subPixelOptimizeLine({
  32729. // Id for animation
  32730. anid: 'line',
  32731. shape: {
  32732. x1: pt1[0],
  32733. y1: pt1[1],
  32734. x2: pt2[0],
  32735. y2: pt2[1]
  32736. },
  32737. style: lineStyle,
  32738. strokeContainThreshold: opt.strokeContainThreshold || 5,
  32739. silent: true,
  32740. z2: 1
  32741. })));
  32742. var arrows = axisModel.get('axisLine.symbol');
  32743. var arrowSize = axisModel.get('axisLine.symbolSize');
  32744. var arrowOffset = axisModel.get('axisLine.symbolOffset') || 0;
  32745. if (typeof arrowOffset === 'number') {
  32746. arrowOffset = [arrowOffset, arrowOffset];
  32747. }
  32748. if (arrows != null) {
  32749. if (typeof arrows === 'string') {
  32750. // Use the same arrow for start and end point
  32751. arrows = [arrows, arrows];
  32752. }
  32753. if (typeof arrowSize === 'string'
  32754. || typeof arrowSize === 'number'
  32755. ) {
  32756. // Use the same size for width and height
  32757. arrowSize = [arrowSize, arrowSize];
  32758. }
  32759. var symbolWidth = arrowSize[0];
  32760. var symbolHeight = arrowSize[1];
  32761. each$1([{
  32762. rotate: opt.rotation + Math.PI / 2,
  32763. offset: arrowOffset[0],
  32764. r: 0
  32765. }, {
  32766. rotate: opt.rotation - Math.PI / 2,
  32767. offset: arrowOffset[1],
  32768. r: Math.sqrt((pt1[0] - pt2[0]) * (pt1[0] - pt2[0])
  32769. + (pt1[1] - pt2[1]) * (pt1[1] - pt2[1]))
  32770. }], function (point, index) {
  32771. if (arrows[index] !== 'none' && arrows[index] != null) {
  32772. var symbol = createSymbol(
  32773. arrows[index],
  32774. -symbolWidth / 2,
  32775. -symbolHeight / 2,
  32776. symbolWidth,
  32777. symbolHeight,
  32778. lineStyle.stroke,
  32779. true
  32780. );
  32781. // Calculate arrow position with offset
  32782. var r = point.r + point.offset;
  32783. var pos = [
  32784. pt1[0] + r * Math.cos(opt.rotation),
  32785. pt1[1] - r * Math.sin(opt.rotation)
  32786. ];
  32787. symbol.attr({
  32788. rotation: point.rotate,
  32789. position: pos,
  32790. silent: true
  32791. });
  32792. this.group.add(symbol);
  32793. }
  32794. }, this);
  32795. }
  32796. },
  32797. /**
  32798. * @private
  32799. */
  32800. axisTickLabel: function () {
  32801. var axisModel = this.axisModel;
  32802. var opt = this.opt;
  32803. var tickEls = buildAxisTick(this, axisModel, opt);
  32804. var labelEls = buildAxisLabel(this, axisModel, opt);
  32805. fixMinMaxLabelShow(axisModel, labelEls, tickEls);
  32806. },
  32807. /**
  32808. * @private
  32809. */
  32810. axisName: function () {
  32811. var opt = this.opt;
  32812. var axisModel = this.axisModel;
  32813. var name = retrieve(opt.axisName, axisModel.get('name'));
  32814. if (!name) {
  32815. return;
  32816. }
  32817. var nameLocation = axisModel.get('nameLocation');
  32818. var nameDirection = opt.nameDirection;
  32819. var textStyleModel = axisModel.getModel('nameTextStyle');
  32820. var gap = axisModel.get('nameGap') || 0;
  32821. var extent = this.axisModel.axis.getExtent();
  32822. var gapSignal = extent[0] > extent[1] ? -1 : 1;
  32823. var pos = [
  32824. nameLocation === 'start'
  32825. ? extent[0] - gapSignal * gap
  32826. : nameLocation === 'end'
  32827. ? extent[1] + gapSignal * gap
  32828. : (extent[0] + extent[1]) / 2, // 'middle'
  32829. // Reuse labelOffset.
  32830. isNameLocationCenter(nameLocation) ? opt.labelOffset + nameDirection * gap : 0
  32831. ];
  32832. var labelLayout;
  32833. var nameRotation = axisModel.get('nameRotate');
  32834. if (nameRotation != null) {
  32835. nameRotation = nameRotation * PI$2 / 180; // To radian.
  32836. }
  32837. var axisNameAvailableWidth;
  32838. if (isNameLocationCenter(nameLocation)) {
  32839. labelLayout = innerTextLayout(
  32840. opt.rotation,
  32841. nameRotation != null ? nameRotation : opt.rotation, // Adapt to axis.
  32842. nameDirection
  32843. );
  32844. }
  32845. else {
  32846. labelLayout = endTextLayout(
  32847. opt, nameLocation, nameRotation || 0, extent
  32848. );
  32849. axisNameAvailableWidth = opt.axisNameAvailableWidth;
  32850. if (axisNameAvailableWidth != null) {
  32851. axisNameAvailableWidth = Math.abs(
  32852. axisNameAvailableWidth / Math.sin(labelLayout.rotation)
  32853. );
  32854. !isFinite(axisNameAvailableWidth) && (axisNameAvailableWidth = null);
  32855. }
  32856. }
  32857. var textFont = textStyleModel.getFont();
  32858. var truncateOpt = axisModel.get('nameTruncate', true) || {};
  32859. var ellipsis = truncateOpt.ellipsis;
  32860. var maxWidth = retrieve(
  32861. opt.nameTruncateMaxWidth, truncateOpt.maxWidth, axisNameAvailableWidth
  32862. );
  32863. // FIXME
  32864. // truncate rich text? (consider performance)
  32865. var truncatedText = (ellipsis != null && maxWidth != null)
  32866. ? truncateText$1(
  32867. name, maxWidth, textFont, ellipsis,
  32868. {minChar: 2, placeholder: truncateOpt.placeholder}
  32869. )
  32870. : name;
  32871. var tooltipOpt = axisModel.get('tooltip', true);
  32872. var mainType = axisModel.mainType;
  32873. var formatterParams = {
  32874. componentType: mainType,
  32875. name: name,
  32876. $vars: ['name']
  32877. };
  32878. formatterParams[mainType + 'Index'] = axisModel.componentIndex;
  32879. var textEl = new Text({
  32880. // Id for animation
  32881. anid: 'name',
  32882. __fullText: name,
  32883. __truncatedText: truncatedText,
  32884. position: pos,
  32885. rotation: labelLayout.rotation,
  32886. silent: isSilent(axisModel),
  32887. z2: 1,
  32888. tooltip: (tooltipOpt && tooltipOpt.show)
  32889. ? extend({
  32890. content: name,
  32891. formatter: function () {
  32892. return name;
  32893. },
  32894. formatterParams: formatterParams
  32895. }, tooltipOpt)
  32896. : null
  32897. });
  32898. setTextStyle(textEl.style, textStyleModel, {
  32899. text: truncatedText,
  32900. textFont: textFont,
  32901. textFill: textStyleModel.getTextColor()
  32902. || axisModel.get('axisLine.lineStyle.color'),
  32903. textAlign: labelLayout.textAlign,
  32904. textVerticalAlign: labelLayout.textVerticalAlign
  32905. });
  32906. if (axisModel.get('triggerEvent')) {
  32907. textEl.eventData = makeAxisEventDataBase(axisModel);
  32908. textEl.eventData.targetType = 'axisName';
  32909. textEl.eventData.name = name;
  32910. }
  32911. // FIXME
  32912. this._dumbGroup.add(textEl);
  32913. textEl.updateTransform();
  32914. this.group.add(textEl);
  32915. textEl.decomposeTransform();
  32916. }
  32917. };
  32918. /**
  32919. * @public
  32920. * @static
  32921. * @param {Object} opt
  32922. * @param {number} axisRotation in radian
  32923. * @param {number} textRotation in radian
  32924. * @param {number} direction
  32925. * @return {Object} {
  32926. * rotation, // according to axis
  32927. * textAlign,
  32928. * textVerticalAlign
  32929. * }
  32930. */
  32931. var innerTextLayout = AxisBuilder.innerTextLayout = function (axisRotation, textRotation, direction) {
  32932. var rotationDiff = remRadian(textRotation - axisRotation);
  32933. var textAlign;
  32934. var textVerticalAlign;
  32935. if (isRadianAroundZero(rotationDiff)) { // Label is parallel with axis line.
  32936. textVerticalAlign = direction > 0 ? 'top' : 'bottom';
  32937. textAlign = 'center';
  32938. }
  32939. else if (isRadianAroundZero(rotationDiff - PI$2)) { // Label is inverse parallel with axis line.
  32940. textVerticalAlign = direction > 0 ? 'bottom' : 'top';
  32941. textAlign = 'center';
  32942. }
  32943. else {
  32944. textVerticalAlign = 'middle';
  32945. if (rotationDiff > 0 && rotationDiff < PI$2) {
  32946. textAlign = direction > 0 ? 'right' : 'left';
  32947. }
  32948. else {
  32949. textAlign = direction > 0 ? 'left' : 'right';
  32950. }
  32951. }
  32952. return {
  32953. rotation: rotationDiff,
  32954. textAlign: textAlign,
  32955. textVerticalAlign: textVerticalAlign
  32956. };
  32957. };
  32958. function endTextLayout(opt, textPosition, textRotate, extent) {
  32959. var rotationDiff = remRadian(textRotate - opt.rotation);
  32960. var textAlign;
  32961. var textVerticalAlign;
  32962. var inverse = extent[0] > extent[1];
  32963. var onLeft = (textPosition === 'start' && !inverse)
  32964. || (textPosition !== 'start' && inverse);
  32965. if (isRadianAroundZero(rotationDiff - PI$2 / 2)) {
  32966. textVerticalAlign = onLeft ? 'bottom' : 'top';
  32967. textAlign = 'center';
  32968. }
  32969. else if (isRadianAroundZero(rotationDiff - PI$2 * 1.5)) {
  32970. textVerticalAlign = onLeft ? 'top' : 'bottom';
  32971. textAlign = 'center';
  32972. }
  32973. else {
  32974. textVerticalAlign = 'middle';
  32975. if (rotationDiff < PI$2 * 1.5 && rotationDiff > PI$2 / 2) {
  32976. textAlign = onLeft ? 'left' : 'right';
  32977. }
  32978. else {
  32979. textAlign = onLeft ? 'right' : 'left';
  32980. }
  32981. }
  32982. return {
  32983. rotation: rotationDiff,
  32984. textAlign: textAlign,
  32985. textVerticalAlign: textVerticalAlign
  32986. };
  32987. }
  32988. function isSilent(axisModel) {
  32989. var tooltipOpt = axisModel.get('tooltip');
  32990. return axisModel.get('silent')
  32991. // Consider mouse cursor, add these restrictions.
  32992. || !(
  32993. axisModel.get('triggerEvent') || (tooltipOpt && tooltipOpt.show)
  32994. );
  32995. }
  32996. function fixMinMaxLabelShow(axisModel, labelEls, tickEls) {
  32997. // If min or max are user set, we need to check
  32998. // If the tick on min(max) are overlap on their neighbour tick
  32999. // If they are overlapped, we need to hide the min(max) tick label
  33000. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  33001. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  33002. // FIXME
  33003. // Have not consider onBand yet, where tick els is more than label els.
  33004. labelEls = labelEls || [];
  33005. tickEls = tickEls || [];
  33006. var firstLabel = labelEls[0];
  33007. var nextLabel = labelEls[1];
  33008. var lastLabel = labelEls[labelEls.length - 1];
  33009. var prevLabel = labelEls[labelEls.length - 2];
  33010. var firstTick = tickEls[0];
  33011. var nextTick = tickEls[1];
  33012. var lastTick = tickEls[tickEls.length - 1];
  33013. var prevTick = tickEls[tickEls.length - 2];
  33014. if (showMinLabel === false) {
  33015. ignoreEl(firstLabel);
  33016. ignoreEl(firstTick);
  33017. }
  33018. else if (isTwoLabelOverlapped(firstLabel, nextLabel)) {
  33019. if (showMinLabel) {
  33020. ignoreEl(nextLabel);
  33021. ignoreEl(nextTick);
  33022. }
  33023. else {
  33024. ignoreEl(firstLabel);
  33025. ignoreEl(firstTick);
  33026. }
  33027. }
  33028. if (showMaxLabel === false) {
  33029. ignoreEl(lastLabel);
  33030. ignoreEl(lastTick);
  33031. }
  33032. else if (isTwoLabelOverlapped(prevLabel, lastLabel)) {
  33033. if (showMaxLabel) {
  33034. ignoreEl(prevLabel);
  33035. ignoreEl(prevTick);
  33036. }
  33037. else {
  33038. ignoreEl(lastLabel);
  33039. ignoreEl(lastTick);
  33040. }
  33041. }
  33042. }
  33043. function ignoreEl(el) {
  33044. el && (el.ignore = true);
  33045. }
  33046. function isTwoLabelOverlapped(current, next, labelLayout) {
  33047. // current and next has the same rotation.
  33048. var firstRect = current && current.getBoundingRect().clone();
  33049. var nextRect = next && next.getBoundingRect().clone();
  33050. if (!firstRect || !nextRect) {
  33051. return;
  33052. }
  33053. // When checking intersect of two rotated labels, we use mRotationBack
  33054. // to avoid that boundingRect is enlarge when using `boundingRect.applyTransform`.
  33055. var mRotationBack = identity([]);
  33056. rotate(mRotationBack, mRotationBack, -current.rotation);
  33057. firstRect.applyTransform(mul$1([], mRotationBack, current.getLocalTransform()));
  33058. nextRect.applyTransform(mul$1([], mRotationBack, next.getLocalTransform()));
  33059. return firstRect.intersect(nextRect);
  33060. }
  33061. function isNameLocationCenter(nameLocation) {
  33062. return nameLocation === 'middle' || nameLocation === 'center';
  33063. }
  33064. function buildAxisTick(axisBuilder, axisModel, opt) {
  33065. var axis = axisModel.axis;
  33066. if (!axisModel.get('axisTick.show') || axis.scale.isBlank()) {
  33067. return;
  33068. }
  33069. var tickModel = axisModel.getModel('axisTick');
  33070. var lineStyleModel = tickModel.getModel('lineStyle');
  33071. var tickLen = tickModel.get('length');
  33072. var ticksCoords = axis.getTicksCoords();
  33073. var pt1 = [];
  33074. var pt2 = [];
  33075. var matrix = axisBuilder._transform;
  33076. var tickEls = [];
  33077. for (var i = 0; i < ticksCoords.length; i++) {
  33078. var tickCoord = ticksCoords[i].coord;
  33079. pt1[0] = tickCoord;
  33080. pt1[1] = 0;
  33081. pt2[0] = tickCoord;
  33082. pt2[1] = opt.tickDirection * tickLen;
  33083. if (matrix) {
  33084. applyTransform(pt1, pt1, matrix);
  33085. applyTransform(pt2, pt2, matrix);
  33086. }
  33087. // Tick line, Not use group transform to have better line draw
  33088. var tickEl = new Line(subPixelOptimizeLine({
  33089. // Id for animation
  33090. anid: 'tick_' + ticksCoords[i].tickValue,
  33091. shape: {
  33092. x1: pt1[0],
  33093. y1: pt1[1],
  33094. x2: pt2[0],
  33095. y2: pt2[1]
  33096. },
  33097. style: defaults(
  33098. lineStyleModel.getLineStyle(),
  33099. {
  33100. stroke: axisModel.get('axisLine.lineStyle.color')
  33101. }
  33102. ),
  33103. z2: 2,
  33104. silent: true
  33105. }));
  33106. axisBuilder.group.add(tickEl);
  33107. tickEls.push(tickEl);
  33108. }
  33109. return tickEls;
  33110. }
  33111. function buildAxisLabel(axisBuilder, axisModel, opt) {
  33112. var axis = axisModel.axis;
  33113. var show = retrieve(opt.axisLabelShow, axisModel.get('axisLabel.show'));
  33114. if (!show || axis.scale.isBlank()) {
  33115. return;
  33116. }
  33117. var labelModel = axisModel.getModel('axisLabel');
  33118. var labelMargin = labelModel.get('margin');
  33119. var labels = axis.getViewLabels();
  33120. // Special label rotate.
  33121. var labelRotation = (
  33122. retrieve(opt.labelRotate, labelModel.get('rotate')) || 0
  33123. ) * PI$2 / 180;
  33124. var labelLayout = innerTextLayout(opt.rotation, labelRotation, opt.labelDirection);
  33125. var rawCategoryData = axisModel.getCategories(true);
  33126. var labelEls = [];
  33127. var silent = isSilent(axisModel);
  33128. var triggerEvent = axisModel.get('triggerEvent');
  33129. each$1(labels, function (labelItem, index) {
  33130. var tickValue = labelItem.tickValue;
  33131. var formattedLabel = labelItem.formattedLabel;
  33132. var rawLabel = labelItem.rawLabel;
  33133. var itemLabelModel = labelModel;
  33134. if (rawCategoryData && rawCategoryData[tickValue] && rawCategoryData[tickValue].textStyle) {
  33135. itemLabelModel = new Model(
  33136. rawCategoryData[tickValue].textStyle, labelModel, axisModel.ecModel
  33137. );
  33138. }
  33139. var textColor = itemLabelModel.getTextColor()
  33140. || axisModel.get('axisLine.lineStyle.color');
  33141. var tickCoord = axis.dataToCoord(tickValue);
  33142. var pos = [
  33143. tickCoord,
  33144. opt.labelOffset + opt.labelDirection * labelMargin
  33145. ];
  33146. var textEl = new Text({
  33147. // Id for animation
  33148. anid: 'label_' + tickValue,
  33149. position: pos,
  33150. rotation: labelLayout.rotation,
  33151. silent: silent,
  33152. z2: 10
  33153. });
  33154. setTextStyle(textEl.style, itemLabelModel, {
  33155. text: formattedLabel,
  33156. textAlign: itemLabelModel.getShallow('align', true)
  33157. || labelLayout.textAlign,
  33158. textVerticalAlign: itemLabelModel.getShallow('verticalAlign', true)
  33159. || itemLabelModel.getShallow('baseline', true)
  33160. || labelLayout.textVerticalAlign,
  33161. textFill: typeof textColor === 'function'
  33162. ? textColor(
  33163. // (1) In category axis with data zoom, tick is not the original
  33164. // index of axis.data. So tick should not be exposed to user
  33165. // in category axis.
  33166. // (2) Compatible with previous version, which always use formatted label as
  33167. // input. But in interval scale the formatted label is like '223,445', which
  33168. // maked user repalce ','. So we modify it to return original val but remain
  33169. // it as 'string' to avoid error in replacing.
  33170. axis.type === 'category'
  33171. ? rawLabel
  33172. : axis.type === 'value'
  33173. ? tickValue + ''
  33174. : tickValue,
  33175. index
  33176. )
  33177. : textColor
  33178. });
  33179. // Pack data for mouse event
  33180. if (triggerEvent) {
  33181. textEl.eventData = makeAxisEventDataBase(axisModel);
  33182. textEl.eventData.targetType = 'axisLabel';
  33183. textEl.eventData.value = rawLabel;
  33184. }
  33185. // FIXME
  33186. axisBuilder._dumbGroup.add(textEl);
  33187. textEl.updateTransform();
  33188. labelEls.push(textEl);
  33189. axisBuilder.group.add(textEl);
  33190. textEl.decomposeTransform();
  33191. });
  33192. return labelEls;
  33193. }
  33194. /*
  33195. * Licensed to the Apache Software Foundation (ASF) under one
  33196. * or more contributor license agreements. See the NOTICE file
  33197. * distributed with this work for additional information
  33198. * regarding copyright ownership. The ASF licenses this file
  33199. * to you under the Apache License, Version 2.0 (the
  33200. * "License"); you may not use this file except in compliance
  33201. * with the License. You may obtain a copy of the License at
  33202. *
  33203. * http://www.apache.org/licenses/LICENSE-2.0
  33204. *
  33205. * Unless required by applicable law or agreed to in writing,
  33206. * software distributed under the License is distributed on an
  33207. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33208. * KIND, either express or implied. See the License for the
  33209. * specific language governing permissions and limitations
  33210. * under the License.
  33211. */
  33212. var each$6 = each$1;
  33213. var curry$1 = curry;
  33214. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  33215. // allAxesInfo should be updated when setOption performed.
  33216. function collect(ecModel, api) {
  33217. var result = {
  33218. /**
  33219. * key: makeKey(axis.model)
  33220. * value: {
  33221. * axis,
  33222. * coordSys,
  33223. * axisPointerModel,
  33224. * triggerTooltip,
  33225. * involveSeries,
  33226. * snap,
  33227. * seriesModels,
  33228. * seriesDataCount
  33229. * }
  33230. */
  33231. axesInfo: {},
  33232. seriesInvolved: false,
  33233. /**
  33234. * key: makeKey(coordSys.model)
  33235. * value: Object: key makeKey(axis.model), value: axisInfo
  33236. */
  33237. coordSysAxesInfo: {},
  33238. coordSysMap: {}
  33239. };
  33240. collectAxesInfo(result, ecModel, api);
  33241. // Check seriesInvolved for performance, in case too many series in some chart.
  33242. result.seriesInvolved && collectSeriesInfo(result, ecModel);
  33243. return result;
  33244. }
  33245. function collectAxesInfo(result, ecModel, api) {
  33246. var globalTooltipModel = ecModel.getComponent('tooltip');
  33247. var globalAxisPointerModel = ecModel.getComponent('axisPointer');
  33248. // links can only be set on global.
  33249. var linksOption = globalAxisPointerModel.get('link', true) || [];
  33250. var linkGroups = [];
  33251. // Collect axes info.
  33252. each$6(api.getCoordinateSystems(), function (coordSys) {
  33253. // Some coordinate system do not support axes, like geo.
  33254. if (!coordSys.axisPointerEnabled) {
  33255. return;
  33256. }
  33257. var coordSysKey = makeKey(coordSys.model);
  33258. var axesInfoInCoordSys = result.coordSysAxesInfo[coordSysKey] = {};
  33259. result.coordSysMap[coordSysKey] = coordSys;
  33260. // Set tooltip (like 'cross') is a convienent way to show axisPointer
  33261. // for user. So we enable seting tooltip on coordSys model.
  33262. var coordSysModel = coordSys.model;
  33263. var baseTooltipModel = coordSysModel.getModel('tooltip', globalTooltipModel);
  33264. each$6(coordSys.getAxes(), curry$1(saveTooltipAxisInfo, false, null));
  33265. // If axis tooltip used, choose tooltip axis for each coordSys.
  33266. // Notice this case: coordSys is `grid` but not `cartesian2D` here.
  33267. if (coordSys.getTooltipAxes
  33268. && globalTooltipModel
  33269. // If tooltip.showContent is set as false, tooltip will not
  33270. // show but axisPointer will show as normal.
  33271. && baseTooltipModel.get('show')
  33272. ) {
  33273. // Compatible with previous logic. But series.tooltip.trigger: 'axis'
  33274. // or series.data[n].tooltip.trigger: 'axis' are not support any more.
  33275. var triggerAxis = baseTooltipModel.get('trigger') === 'axis';
  33276. var cross = baseTooltipModel.get('axisPointer.type') === 'cross';
  33277. var tooltipAxes = coordSys.getTooltipAxes(baseTooltipModel.get('axisPointer.axis'));
  33278. if (triggerAxis || cross) {
  33279. each$6(tooltipAxes.baseAxes, curry$1(
  33280. saveTooltipAxisInfo, cross ? 'cross' : true, triggerAxis
  33281. ));
  33282. }
  33283. if (cross) {
  33284. each$6(tooltipAxes.otherAxes, curry$1(saveTooltipAxisInfo, 'cross', false));
  33285. }
  33286. }
  33287. // fromTooltip: true | false | 'cross'
  33288. // triggerTooltip: true | false | null
  33289. function saveTooltipAxisInfo(fromTooltip, triggerTooltip, axis) {
  33290. var axisPointerModel = axis.model.getModel('axisPointer', globalAxisPointerModel);
  33291. var axisPointerShow = axisPointerModel.get('show');
  33292. if (!axisPointerShow || (
  33293. axisPointerShow === 'auto'
  33294. && !fromTooltip
  33295. && !isHandleTrigger(axisPointerModel)
  33296. )) {
  33297. return;
  33298. }
  33299. if (triggerTooltip == null) {
  33300. triggerTooltip = axisPointerModel.get('triggerTooltip');
  33301. }
  33302. axisPointerModel = fromTooltip
  33303. ? makeAxisPointerModel(
  33304. axis, baseTooltipModel, globalAxisPointerModel, ecModel,
  33305. fromTooltip, triggerTooltip
  33306. )
  33307. : axisPointerModel;
  33308. var snap = axisPointerModel.get('snap');
  33309. var key = makeKey(axis.model);
  33310. var involveSeries = triggerTooltip || snap || axis.type === 'category';
  33311. // If result.axesInfo[key] exist, override it (tooltip has higher priority).
  33312. var axisInfo = result.axesInfo[key] = {
  33313. key: key,
  33314. axis: axis,
  33315. coordSys: coordSys,
  33316. axisPointerModel: axisPointerModel,
  33317. triggerTooltip: triggerTooltip,
  33318. involveSeries: involveSeries,
  33319. snap: snap,
  33320. useHandle: isHandleTrigger(axisPointerModel),
  33321. seriesModels: []
  33322. };
  33323. axesInfoInCoordSys[key] = axisInfo;
  33324. result.seriesInvolved |= involveSeries;
  33325. var groupIndex = getLinkGroupIndex(linksOption, axis);
  33326. if (groupIndex != null) {
  33327. var linkGroup = linkGroups[groupIndex] || (linkGroups[groupIndex] = {axesInfo: {}});
  33328. linkGroup.axesInfo[key] = axisInfo;
  33329. linkGroup.mapper = linksOption[groupIndex].mapper;
  33330. axisInfo.linkGroup = linkGroup;
  33331. }
  33332. }
  33333. });
  33334. }
  33335. function makeAxisPointerModel(
  33336. axis, baseTooltipModel, globalAxisPointerModel, ecModel, fromTooltip, triggerTooltip
  33337. ) {
  33338. var tooltipAxisPointerModel = baseTooltipModel.getModel('axisPointer');
  33339. var volatileOption = {};
  33340. each$6(
  33341. [
  33342. 'type', 'snap', 'lineStyle', 'shadowStyle', 'label',
  33343. 'animation', 'animationDurationUpdate', 'animationEasingUpdate', 'z'
  33344. ],
  33345. function (field) {
  33346. volatileOption[field] = clone(tooltipAxisPointerModel.get(field));
  33347. }
  33348. );
  33349. // category axis do not auto snap, otherwise some tick that do not
  33350. // has value can not be hovered. value/time/log axis default snap if
  33351. // triggered from tooltip and trigger tooltip.
  33352. volatileOption.snap = axis.type !== 'category' && !!triggerTooltip;
  33353. // Compatibel with previous behavior, tooltip axis do not show label by default.
  33354. // Only these properties can be overrided from tooltip to axisPointer.
  33355. if (tooltipAxisPointerModel.get('type') === 'cross') {
  33356. volatileOption.type = 'line';
  33357. }
  33358. var labelOption = volatileOption.label || (volatileOption.label = {});
  33359. // Follow the convention, do not show label when triggered by tooltip by default.
  33360. labelOption.show == null && (labelOption.show = false);
  33361. if (fromTooltip === 'cross') {
  33362. // When 'cross', both axes show labels.
  33363. var tooltipAxisPointerLabelShow = tooltipAxisPointerModel.get('label.show');
  33364. labelOption.show = tooltipAxisPointerLabelShow != null ? tooltipAxisPointerLabelShow : true;
  33365. // If triggerTooltip, this is a base axis, which should better not use cross style
  33366. // (cross style is dashed by default)
  33367. if (!triggerTooltip) {
  33368. var crossStyle = volatileOption.lineStyle = tooltipAxisPointerModel.get('crossStyle');
  33369. crossStyle && defaults(labelOption, crossStyle.textStyle);
  33370. }
  33371. }
  33372. return axis.model.getModel(
  33373. 'axisPointer',
  33374. new Model(volatileOption, globalAxisPointerModel, ecModel)
  33375. );
  33376. }
  33377. function collectSeriesInfo(result, ecModel) {
  33378. // Prepare data for axis trigger
  33379. ecModel.eachSeries(function (seriesModel) {
  33380. // Notice this case: this coordSys is `cartesian2D` but not `grid`.
  33381. var coordSys = seriesModel.coordinateSystem;
  33382. var seriesTooltipTrigger = seriesModel.get('tooltip.trigger', true);
  33383. var seriesTooltipShow = seriesModel.get('tooltip.show', true);
  33384. if (!coordSys
  33385. || seriesTooltipTrigger === 'none'
  33386. || seriesTooltipTrigger === false
  33387. || seriesTooltipTrigger === 'item'
  33388. || seriesTooltipShow === false
  33389. || seriesModel.get('axisPointer.show', true) === false
  33390. ) {
  33391. return;
  33392. }
  33393. each$6(result.coordSysAxesInfo[makeKey(coordSys.model)], function (axisInfo) {
  33394. var axis = axisInfo.axis;
  33395. if (coordSys.getAxis(axis.dim) === axis) {
  33396. axisInfo.seriesModels.push(seriesModel);
  33397. axisInfo.seriesDataCount == null && (axisInfo.seriesDataCount = 0);
  33398. axisInfo.seriesDataCount += seriesModel.getData().count();
  33399. }
  33400. });
  33401. }, this);
  33402. }
  33403. /**
  33404. * For example:
  33405. * {
  33406. * axisPointer: {
  33407. * links: [{
  33408. * xAxisIndex: [2, 4],
  33409. * yAxisIndex: 'all'
  33410. * }, {
  33411. * xAxisId: ['a5', 'a7'],
  33412. * xAxisName: 'xxx'
  33413. * }]
  33414. * }
  33415. * }
  33416. */
  33417. function getLinkGroupIndex(linksOption, axis) {
  33418. var axisModel = axis.model;
  33419. var dim = axis.dim;
  33420. for (var i = 0; i < linksOption.length; i++) {
  33421. var linkOption = linksOption[i] || {};
  33422. if (checkPropInLink(linkOption[dim + 'AxisId'], axisModel.id)
  33423. || checkPropInLink(linkOption[dim + 'AxisIndex'], axisModel.componentIndex)
  33424. || checkPropInLink(linkOption[dim + 'AxisName'], axisModel.name)
  33425. ) {
  33426. return i;
  33427. }
  33428. }
  33429. }
  33430. function checkPropInLink(linkPropValue, axisPropValue) {
  33431. return linkPropValue === 'all'
  33432. || (isArray(linkPropValue) && indexOf(linkPropValue, axisPropValue) >= 0)
  33433. || linkPropValue === axisPropValue;
  33434. }
  33435. function fixValue(axisModel) {
  33436. var axisInfo = getAxisInfo(axisModel);
  33437. if (!axisInfo) {
  33438. return;
  33439. }
  33440. var axisPointerModel = axisInfo.axisPointerModel;
  33441. var scale = axisInfo.axis.scale;
  33442. var option = axisPointerModel.option;
  33443. var status = axisPointerModel.get('status');
  33444. var value = axisPointerModel.get('value');
  33445. // Parse init value for category and time axis.
  33446. if (value != null) {
  33447. value = scale.parse(value);
  33448. }
  33449. var useHandle = isHandleTrigger(axisPointerModel);
  33450. // If `handle` used, `axisPointer` will always be displayed, so value
  33451. // and status should be initialized.
  33452. if (status == null) {
  33453. option.status = useHandle ? 'show' : 'hide';
  33454. }
  33455. var extent = scale.getExtent().slice();
  33456. extent[0] > extent[1] && extent.reverse();
  33457. if (// Pick a value on axis when initializing.
  33458. value == null
  33459. // If both `handle` and `dataZoom` are used, value may be out of axis extent,
  33460. // where we should re-pick a value to keep `handle` displaying normally.
  33461. || value > extent[1]
  33462. ) {
  33463. // Make handle displayed on the end of the axis when init, which looks better.
  33464. value = extent[1];
  33465. }
  33466. if (value < extent[0]) {
  33467. value = extent[0];
  33468. }
  33469. option.value = value;
  33470. if (useHandle) {
  33471. option.status = axisInfo.axis.scale.isBlank() ? 'hide' : 'show';
  33472. }
  33473. }
  33474. function getAxisInfo(axisModel) {
  33475. var coordSysAxesInfo = (axisModel.ecModel.getComponent('axisPointer') || {}).coordSysAxesInfo;
  33476. return coordSysAxesInfo && coordSysAxesInfo.axesInfo[makeKey(axisModel)];
  33477. }
  33478. function getAxisPointerModel(axisModel) {
  33479. var axisInfo = getAxisInfo(axisModel);
  33480. return axisInfo && axisInfo.axisPointerModel;
  33481. }
  33482. function isHandleTrigger(axisPointerModel) {
  33483. return !!axisPointerModel.get('handle.show');
  33484. }
  33485. /**
  33486. * @param {module:echarts/model/Model} model
  33487. * @return {string} unique key
  33488. */
  33489. function makeKey(model) {
  33490. return model.type + '||' + model.id;
  33491. }
  33492. /*
  33493. * Licensed to the Apache Software Foundation (ASF) under one
  33494. * or more contributor license agreements. See the NOTICE file
  33495. * distributed with this work for additional information
  33496. * regarding copyright ownership. The ASF licenses this file
  33497. * to you under the Apache License, Version 2.0 (the
  33498. * "License"); you may not use this file except in compliance
  33499. * with the License. You may obtain a copy of the License at
  33500. *
  33501. * http://www.apache.org/licenses/LICENSE-2.0
  33502. *
  33503. * Unless required by applicable law or agreed to in writing,
  33504. * software distributed under the License is distributed on an
  33505. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33506. * KIND, either express or implied. See the License for the
  33507. * specific language governing permissions and limitations
  33508. * under the License.
  33509. */
  33510. /**
  33511. * Base class of AxisView.
  33512. */
  33513. var AxisView = extendComponentView({
  33514. type: 'axis',
  33515. /**
  33516. * @private
  33517. */
  33518. _axisPointer: null,
  33519. /**
  33520. * @protected
  33521. * @type {string}
  33522. */
  33523. axisPointerClass: null,
  33524. /**
  33525. * @override
  33526. */
  33527. render: function (axisModel, ecModel, api, payload) {
  33528. // FIXME
  33529. // This process should proformed after coordinate systems updated
  33530. // (axis scale updated), and should be performed each time update.
  33531. // So put it here temporarily, although it is not appropriate to
  33532. // put a model-writing procedure in `view`.
  33533. this.axisPointerClass && fixValue(axisModel);
  33534. AxisView.superApply(this, 'render', arguments);
  33535. updateAxisPointer(this, axisModel, ecModel, api, payload, true);
  33536. },
  33537. /**
  33538. * Action handler.
  33539. * @public
  33540. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  33541. * @param {module:echarts/model/Global} ecModel
  33542. * @param {module:echarts/ExtensionAPI} api
  33543. * @param {Object} payload
  33544. */
  33545. updateAxisPointer: function (axisModel, ecModel, api, payload, force) {
  33546. updateAxisPointer(this, axisModel, ecModel, api, payload, false);
  33547. },
  33548. /**
  33549. * @override
  33550. */
  33551. remove: function (ecModel, api) {
  33552. var axisPointer = this._axisPointer;
  33553. axisPointer && axisPointer.remove(api);
  33554. AxisView.superApply(this, 'remove', arguments);
  33555. },
  33556. /**
  33557. * @override
  33558. */
  33559. dispose: function (ecModel, api) {
  33560. disposeAxisPointer(this, api);
  33561. AxisView.superApply(this, 'dispose', arguments);
  33562. }
  33563. });
  33564. function updateAxisPointer(axisView, axisModel, ecModel, api, payload, forceRender) {
  33565. var Clazz = AxisView.getAxisPointerClass(axisView.axisPointerClass);
  33566. if (!Clazz) {
  33567. return;
  33568. }
  33569. var axisPointerModel = getAxisPointerModel(axisModel);
  33570. axisPointerModel
  33571. ? (axisView._axisPointer || (axisView._axisPointer = new Clazz()))
  33572. .render(axisModel, axisPointerModel, api, forceRender)
  33573. : disposeAxisPointer(axisView, api);
  33574. }
  33575. function disposeAxisPointer(axisView, ecModel, api) {
  33576. var axisPointer = axisView._axisPointer;
  33577. axisPointer && axisPointer.dispose(ecModel, api);
  33578. axisView._axisPointer = null;
  33579. }
  33580. var axisPointerClazz = [];
  33581. AxisView.registerAxisPointerClass = function (type, clazz) {
  33582. if (__DEV__) {
  33583. if (axisPointerClazz[type]) {
  33584. throw new Error('axisPointer ' + type + ' exists');
  33585. }
  33586. }
  33587. axisPointerClazz[type] = clazz;
  33588. };
  33589. AxisView.getAxisPointerClass = function (type) {
  33590. return type && axisPointerClazz[type];
  33591. };
  33592. /*
  33593. * Licensed to the Apache Software Foundation (ASF) under one
  33594. * or more contributor license agreements. See the NOTICE file
  33595. * distributed with this work for additional information
  33596. * regarding copyright ownership. The ASF licenses this file
  33597. * to you under the Apache License, Version 2.0 (the
  33598. * "License"); you may not use this file except in compliance
  33599. * with the License. You may obtain a copy of the License at
  33600. *
  33601. * http://www.apache.org/licenses/LICENSE-2.0
  33602. *
  33603. * Unless required by applicable law or agreed to in writing,
  33604. * software distributed under the License is distributed on an
  33605. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33606. * KIND, either express or implied. See the License for the
  33607. * specific language governing permissions and limitations
  33608. * under the License.
  33609. */
  33610. /**
  33611. * Can only be called after coordinate system creation stage.
  33612. * (Can be called before coordinate system update stage).
  33613. *
  33614. * @param {Object} opt {labelInside}
  33615. * @return {Object} {
  33616. * position, rotation, labelDirection, labelOffset,
  33617. * tickDirection, labelRotate, z2
  33618. * }
  33619. */
  33620. function layout$1(gridModel, axisModel, opt) {
  33621. opt = opt || {};
  33622. var grid = gridModel.coordinateSystem;
  33623. var axis = axisModel.axis;
  33624. var layout = {};
  33625. var otherAxisOnZeroOf = axis.getAxesOnZeroOf()[0];
  33626. var rawAxisPosition = axis.position;
  33627. var axisPosition = otherAxisOnZeroOf ? 'onZero' : rawAxisPosition;
  33628. var axisDim = axis.dim;
  33629. var rect = grid.getRect();
  33630. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  33631. var idx = {left: 0, right: 1, top: 0, bottom: 1, onZero: 2};
  33632. var axisOffset = axisModel.get('offset') || 0;
  33633. var posBound = axisDim === 'x'
  33634. ? [rectBound[2] - axisOffset, rectBound[3] + axisOffset]
  33635. : [rectBound[0] - axisOffset, rectBound[1] + axisOffset];
  33636. if (otherAxisOnZeroOf) {
  33637. var onZeroCoord = otherAxisOnZeroOf.toGlobalCoord(otherAxisOnZeroOf.dataToCoord(0));
  33638. posBound[idx['onZero']] = Math.max(Math.min(onZeroCoord, posBound[1]), posBound[0]);
  33639. }
  33640. // Axis position
  33641. layout.position = [
  33642. axisDim === 'y' ? posBound[idx[axisPosition]] : rectBound[0],
  33643. axisDim === 'x' ? posBound[idx[axisPosition]] : rectBound[3]
  33644. ];
  33645. // Axis rotation
  33646. layout.rotation = Math.PI / 2 * (axisDim === 'x' ? 0 : 1);
  33647. // Tick and label direction, x y is axisDim
  33648. var dirMap = {top: -1, bottom: 1, left: -1, right: 1};
  33649. layout.labelDirection = layout.tickDirection = layout.nameDirection = dirMap[rawAxisPosition];
  33650. layout.labelOffset = otherAxisOnZeroOf ? posBound[idx[rawAxisPosition]] - posBound[idx['onZero']] : 0;
  33651. if (axisModel.get('axisTick.inside')) {
  33652. layout.tickDirection = -layout.tickDirection;
  33653. }
  33654. if (retrieve(opt.labelInside, axisModel.get('axisLabel.inside'))) {
  33655. layout.labelDirection = -layout.labelDirection;
  33656. }
  33657. // Special label rotation
  33658. var labelRotate = axisModel.get('axisLabel.rotate');
  33659. layout.labelRotate = axisPosition === 'top' ? -labelRotate : labelRotate;
  33660. // Over splitLine and splitArea
  33661. layout.z2 = 1;
  33662. return layout;
  33663. }
  33664. /*
  33665. * Licensed to the Apache Software Foundation (ASF) under one
  33666. * or more contributor license agreements. See the NOTICE file
  33667. * distributed with this work for additional information
  33668. * regarding copyright ownership. The ASF licenses this file
  33669. * to you under the Apache License, Version 2.0 (the
  33670. * "License"); you may not use this file except in compliance
  33671. * with the License. You may obtain a copy of the License at
  33672. *
  33673. * http://www.apache.org/licenses/LICENSE-2.0
  33674. *
  33675. * Unless required by applicable law or agreed to in writing,
  33676. * software distributed under the License is distributed on an
  33677. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33678. * KIND, either express or implied. See the License for the
  33679. * specific language governing permissions and limitations
  33680. * under the License.
  33681. */
  33682. var axisBuilderAttrs = [
  33683. 'axisLine', 'axisTickLabel', 'axisName'
  33684. ];
  33685. var selfBuilderAttrs = [
  33686. 'splitArea', 'splitLine'
  33687. ];
  33688. // function getAlignWithLabel(model, axisModel) {
  33689. // var alignWithLabel = model.get('alignWithLabel');
  33690. // if (alignWithLabel === 'auto') {
  33691. // alignWithLabel = axisModel.get('axisTick.alignWithLabel');
  33692. // }
  33693. // return alignWithLabel;
  33694. // }
  33695. var CartesianAxisView = AxisView.extend({
  33696. type: 'cartesianAxis',
  33697. axisPointerClass: 'CartesianAxisPointer',
  33698. /**
  33699. * @override
  33700. */
  33701. render: function (axisModel, ecModel, api, payload) {
  33702. this.group.removeAll();
  33703. var oldAxisGroup = this._axisGroup;
  33704. this._axisGroup = new Group();
  33705. this.group.add(this._axisGroup);
  33706. if (!axisModel.get('show')) {
  33707. return;
  33708. }
  33709. var gridModel = axisModel.getCoordSysModel();
  33710. var layout = layout$1(gridModel, axisModel);
  33711. var axisBuilder = new AxisBuilder(axisModel, layout);
  33712. each$1(axisBuilderAttrs, axisBuilder.add, axisBuilder);
  33713. this._axisGroup.add(axisBuilder.getGroup());
  33714. each$1(selfBuilderAttrs, function (name) {
  33715. if (axisModel.get(name + '.show')) {
  33716. this['_' + name](axisModel, gridModel);
  33717. }
  33718. }, this);
  33719. groupTransition(oldAxisGroup, this._axisGroup, axisModel);
  33720. CartesianAxisView.superCall(this, 'render', axisModel, ecModel, api, payload);
  33721. },
  33722. remove: function () {
  33723. this._splitAreaColors = null;
  33724. },
  33725. /**
  33726. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  33727. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  33728. * @private
  33729. */
  33730. _splitLine: function (axisModel, gridModel) {
  33731. var axis = axisModel.axis;
  33732. if (axis.scale.isBlank()) {
  33733. return;
  33734. }
  33735. var splitLineModel = axisModel.getModel('splitLine');
  33736. var lineStyleModel = splitLineModel.getModel('lineStyle');
  33737. var lineColors = lineStyleModel.get('color');
  33738. lineColors = isArray(lineColors) ? lineColors : [lineColors];
  33739. var gridRect = gridModel.coordinateSystem.getRect();
  33740. var isHorizontal = axis.isHorizontal();
  33741. var lineCount = 0;
  33742. var ticksCoords = axis.getTicksCoords({
  33743. tickModel: splitLineModel
  33744. });
  33745. var p1 = [];
  33746. var p2 = [];
  33747. // Simple optimization
  33748. // Batching the lines if color are the same
  33749. var lineStyle = lineStyleModel.getLineStyle();
  33750. for (var i = 0; i < ticksCoords.length; i++) {
  33751. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  33752. if (isHorizontal) {
  33753. p1[0] = tickCoord;
  33754. p1[1] = gridRect.y;
  33755. p2[0] = tickCoord;
  33756. p2[1] = gridRect.y + gridRect.height;
  33757. }
  33758. else {
  33759. p1[0] = gridRect.x;
  33760. p1[1] = tickCoord;
  33761. p2[0] = gridRect.x + gridRect.width;
  33762. p2[1] = tickCoord;
  33763. }
  33764. var colorIndex = (lineCount++) % lineColors.length;
  33765. this._axisGroup.add(new Line(subPixelOptimizeLine({
  33766. anid: 'line_' + ticksCoords[i].tickValue,
  33767. shape: {
  33768. x1: p1[0],
  33769. y1: p1[1],
  33770. x2: p2[0],
  33771. y2: p2[1]
  33772. },
  33773. style: defaults({
  33774. stroke: lineColors[colorIndex]
  33775. }, lineStyle),
  33776. silent: true
  33777. })));
  33778. }
  33779. },
  33780. /**
  33781. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  33782. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  33783. * @private
  33784. */
  33785. _splitArea: function (axisModel, gridModel) {
  33786. var axis = axisModel.axis;
  33787. if (axis.scale.isBlank()) {
  33788. return;
  33789. }
  33790. var splitAreaModel = axisModel.getModel('splitArea');
  33791. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  33792. var areaColors = areaStyleModel.get('color');
  33793. var gridRect = gridModel.coordinateSystem.getRect();
  33794. var ticksCoords = axis.getTicksCoords({
  33795. tickModel: splitAreaModel,
  33796. clamp: true
  33797. });
  33798. if (!ticksCoords.length) {
  33799. return;
  33800. }
  33801. // For Making appropriate splitArea animation, the color and anid
  33802. // should be corresponding to previous one if possible.
  33803. var areaColorsLen = areaColors.length;
  33804. var lastSplitAreaColors = this._splitAreaColors;
  33805. var newSplitAreaColors = createHashMap();
  33806. var colorIndex = 0;
  33807. if (lastSplitAreaColors) {
  33808. for (var i = 0; i < ticksCoords.length; i++) {
  33809. var cIndex = lastSplitAreaColors.get(ticksCoords[i].tickValue);
  33810. if (cIndex != null) {
  33811. colorIndex = (cIndex + (areaColorsLen - 1) * i) % areaColorsLen;
  33812. break;
  33813. }
  33814. }
  33815. }
  33816. var prev = axis.toGlobalCoord(ticksCoords[0].coord);
  33817. var areaStyle = areaStyleModel.getAreaStyle();
  33818. areaColors = isArray(areaColors) ? areaColors : [areaColors];
  33819. for (var i = 1; i < ticksCoords.length; i++) {
  33820. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  33821. var x;
  33822. var y;
  33823. var width;
  33824. var height;
  33825. if (axis.isHorizontal()) {
  33826. x = prev;
  33827. y = gridRect.y;
  33828. width = tickCoord - x;
  33829. height = gridRect.height;
  33830. prev = x + width;
  33831. }
  33832. else {
  33833. x = gridRect.x;
  33834. y = prev;
  33835. width = gridRect.width;
  33836. height = tickCoord - y;
  33837. prev = y + height;
  33838. }
  33839. var tickValue = ticksCoords[i - 1].tickValue;
  33840. tickValue != null && newSplitAreaColors.set(tickValue, colorIndex);
  33841. this._axisGroup.add(new Rect({
  33842. anid: 'area_' + tickValue,
  33843. shape: {
  33844. x: x,
  33845. y: y,
  33846. width: width,
  33847. height: height
  33848. },
  33849. style: defaults({
  33850. fill: areaColors[colorIndex]
  33851. }, areaStyle),
  33852. silent: true
  33853. }));
  33854. colorIndex = (colorIndex + 1) % areaColorsLen;
  33855. }
  33856. this._splitAreaColors = newSplitAreaColors;
  33857. }
  33858. });
  33859. CartesianAxisView.extend({
  33860. type: 'xAxis'
  33861. });
  33862. CartesianAxisView.extend({
  33863. type: 'yAxis'
  33864. });
  33865. /*
  33866. * Licensed to the Apache Software Foundation (ASF) under one
  33867. * or more contributor license agreements. See the NOTICE file
  33868. * distributed with this work for additional information
  33869. * regarding copyright ownership. The ASF licenses this file
  33870. * to you under the Apache License, Version 2.0 (the
  33871. * "License"); you may not use this file except in compliance
  33872. * with the License. You may obtain a copy of the License at
  33873. *
  33874. * http://www.apache.org/licenses/LICENSE-2.0
  33875. *
  33876. * Unless required by applicable law or agreed to in writing,
  33877. * software distributed under the License is distributed on an
  33878. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33879. * KIND, either express or implied. See the License for the
  33880. * specific language governing permissions and limitations
  33881. * under the License.
  33882. */
  33883. /*
  33884. * Licensed to the Apache Software Foundation (ASF) under one
  33885. * or more contributor license agreements. See the NOTICE file
  33886. * distributed with this work for additional information
  33887. * regarding copyright ownership. The ASF licenses this file
  33888. * to you under the Apache License, Version 2.0 (the
  33889. * "License"); you may not use this file except in compliance
  33890. * with the License. You may obtain a copy of the License at
  33891. *
  33892. * http://www.apache.org/licenses/LICENSE-2.0
  33893. *
  33894. * Unless required by applicable law or agreed to in writing,
  33895. * software distributed under the License is distributed on an
  33896. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33897. * KIND, either express or implied. See the License for the
  33898. * specific language governing permissions and limitations
  33899. * under the License.
  33900. */
  33901. // Grid view
  33902. extendComponentView({
  33903. type: 'grid',
  33904. render: function (gridModel, ecModel) {
  33905. this.group.removeAll();
  33906. if (gridModel.get('show')) {
  33907. this.group.add(new Rect({
  33908. shape: gridModel.coordinateSystem.getRect(),
  33909. style: defaults({
  33910. fill: gridModel.get('backgroundColor')
  33911. }, gridModel.getItemStyle()),
  33912. silent: true,
  33913. z2: -1
  33914. }));
  33915. }
  33916. }
  33917. });
  33918. registerPreprocessor(function (option) {
  33919. // Only create grid when need
  33920. if (option.xAxis && option.yAxis && !option.grid) {
  33921. option.grid = {};
  33922. }
  33923. });
  33924. /*
  33925. * Licensed to the Apache Software Foundation (ASF) under one
  33926. * or more contributor license agreements. See the NOTICE file
  33927. * distributed with this work for additional information
  33928. * regarding copyright ownership. The ASF licenses this file
  33929. * to you under the Apache License, Version 2.0 (the
  33930. * "License"); you may not use this file except in compliance
  33931. * with the License. You may obtain a copy of the License at
  33932. *
  33933. * http://www.apache.org/licenses/LICENSE-2.0
  33934. *
  33935. * Unless required by applicable law or agreed to in writing,
  33936. * software distributed under the License is distributed on an
  33937. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33938. * KIND, either express or implied. See the License for the
  33939. * specific language governing permissions and limitations
  33940. * under the License.
  33941. */
  33942. // In case developer forget to include grid component
  33943. registerVisual(visualSymbol('line', 'circle', 'line'));
  33944. registerLayout(pointsLayout('line'));
  33945. // Down sample after filter
  33946. registerProcessor(
  33947. PRIORITY.PROCESSOR.STATISTIC,
  33948. dataSample('line')
  33949. );
  33950. /*
  33951. * Licensed to the Apache Software Foundation (ASF) under one
  33952. * or more contributor license agreements. See the NOTICE file
  33953. * distributed with this work for additional information
  33954. * regarding copyright ownership. The ASF licenses this file
  33955. * to you under the Apache License, Version 2.0 (the
  33956. * "License"); you may not use this file except in compliance
  33957. * with the License. You may obtain a copy of the License at
  33958. *
  33959. * http://www.apache.org/licenses/LICENSE-2.0
  33960. *
  33961. * Unless required by applicable law or agreed to in writing,
  33962. * software distributed under the License is distributed on an
  33963. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33964. * KIND, either express or implied. See the License for the
  33965. * specific language governing permissions and limitations
  33966. * under the License.
  33967. */
  33968. var BaseBarSeries = SeriesModel.extend({
  33969. type: 'series.__base_bar__',
  33970. getInitialData: function (option, ecModel) {
  33971. return createListFromArray(this.getSource(), this);
  33972. },
  33973. getMarkerPosition: function (value) {
  33974. var coordSys = this.coordinateSystem;
  33975. if (coordSys) {
  33976. // PENDING if clamp ?
  33977. var pt = coordSys.dataToPoint(coordSys.clampData(value));
  33978. var data = this.getData();
  33979. var offset = data.getLayout('offset');
  33980. var size = data.getLayout('size');
  33981. var offsetIndex = coordSys.getBaseAxis().isHorizontal() ? 0 : 1;
  33982. pt[offsetIndex] += offset + size / 2;
  33983. return pt;
  33984. }
  33985. return [NaN, NaN];
  33986. },
  33987. defaultOption: {
  33988. zlevel: 0, // 一级层叠
  33989. z: 2, // 二级层叠
  33990. coordinateSystem: 'cartesian2d',
  33991. legendHoverLink: true,
  33992. // stack: null
  33993. // Cartesian coordinate system
  33994. // xAxisIndex: 0,
  33995. // yAxisIndex: 0,
  33996. // 最小高度改为0
  33997. barMinHeight: 0,
  33998. // 最小角度为0,仅对极坐标系下的柱状图有效
  33999. barMinAngle: 0,
  34000. // cursor: null,
  34001. large: false,
  34002. largeThreshold: 400,
  34003. progressive: 5e3,
  34004. progressiveChunkMode: 'mod',
  34005. // barMaxWidth: null,
  34006. // 默认自适应
  34007. // barWidth: null,
  34008. // 柱间距离,默认为柱形宽度的30%,可设固定值
  34009. // barGap: '30%',
  34010. // 类目间柱形距离,默认为类目间距的20%,可设固定值
  34011. // barCategoryGap: '20%',
  34012. // label: {
  34013. // show: false
  34014. // },
  34015. itemStyle: {},
  34016. emphasis: {}
  34017. }
  34018. });
  34019. /*
  34020. * Licensed to the Apache Software Foundation (ASF) under one
  34021. * or more contributor license agreements. See the NOTICE file
  34022. * distributed with this work for additional information
  34023. * regarding copyright ownership. The ASF licenses this file
  34024. * to you under the Apache License, Version 2.0 (the
  34025. * "License"); you may not use this file except in compliance
  34026. * with the License. You may obtain a copy of the License at
  34027. *
  34028. * http://www.apache.org/licenses/LICENSE-2.0
  34029. *
  34030. * Unless required by applicable law or agreed to in writing,
  34031. * software distributed under the License is distributed on an
  34032. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34033. * KIND, either express or implied. See the License for the
  34034. * specific language governing permissions and limitations
  34035. * under the License.
  34036. */
  34037. BaseBarSeries.extend({
  34038. type: 'series.bar',
  34039. dependencies: ['grid', 'polar'],
  34040. brushSelector: 'rect',
  34041. /**
  34042. * @override
  34043. */
  34044. getProgressive: function () {
  34045. // Do not support progressive in normal mode.
  34046. return this.get('large')
  34047. ? this.get('progressive')
  34048. : false;
  34049. },
  34050. /**
  34051. * @override
  34052. */
  34053. getProgressiveThreshold: function () {
  34054. // Do not support progressive in normal mode.
  34055. var progressiveThreshold = this.get('progressiveThreshold');
  34056. var largeThreshold = this.get('largeThreshold');
  34057. if (largeThreshold > progressiveThreshold) {
  34058. progressiveThreshold = largeThreshold;
  34059. }
  34060. return progressiveThreshold;
  34061. }
  34062. });
  34063. /*
  34064. * Licensed to the Apache Software Foundation (ASF) under one
  34065. * or more contributor license agreements. See the NOTICE file
  34066. * distributed with this work for additional information
  34067. * regarding copyright ownership. The ASF licenses this file
  34068. * to you under the Apache License, Version 2.0 (the
  34069. * "License"); you may not use this file except in compliance
  34070. * with the License. You may obtain a copy of the License at
  34071. *
  34072. * http://www.apache.org/licenses/LICENSE-2.0
  34073. *
  34074. * Unless required by applicable law or agreed to in writing,
  34075. * software distributed under the License is distributed on an
  34076. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34077. * KIND, either express or implied. See the License for the
  34078. * specific language governing permissions and limitations
  34079. * under the License.
  34080. */
  34081. function setLabel(
  34082. normalStyle, hoverStyle, itemModel, color, seriesModel, dataIndex, labelPositionOutside
  34083. ) {
  34084. var labelModel = itemModel.getModel('label');
  34085. var hoverLabelModel = itemModel.getModel('emphasis.label');
  34086. setLabelStyle(
  34087. normalStyle, hoverStyle, labelModel, hoverLabelModel,
  34088. {
  34089. labelFetcher: seriesModel,
  34090. labelDataIndex: dataIndex,
  34091. defaultText: getDefaultLabel(seriesModel.getData(), dataIndex),
  34092. isRectText: true,
  34093. autoColor: color
  34094. }
  34095. );
  34096. fixPosition(normalStyle);
  34097. fixPosition(hoverStyle);
  34098. }
  34099. function fixPosition(style, labelPositionOutside) {
  34100. if (style.textPosition === 'outside') {
  34101. style.textPosition = labelPositionOutside;
  34102. }
  34103. }
  34104. /*
  34105. * Licensed to the Apache Software Foundation (ASF) under one
  34106. * or more contributor license agreements. See the NOTICE file
  34107. * distributed with this work for additional information
  34108. * regarding copyright ownership. The ASF licenses this file
  34109. * to you under the Apache License, Version 2.0 (the
  34110. * "License"); you may not use this file except in compliance
  34111. * with the License. You may obtain a copy of the License at
  34112. *
  34113. * http://www.apache.org/licenses/LICENSE-2.0
  34114. *
  34115. * Unless required by applicable law or agreed to in writing,
  34116. * software distributed under the License is distributed on an
  34117. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34118. * KIND, either express or implied. See the License for the
  34119. * specific language governing permissions and limitations
  34120. * under the License.
  34121. */
  34122. var getBarItemStyle = makeStyleMapper(
  34123. [
  34124. ['fill', 'color'],
  34125. ['stroke', 'borderColor'],
  34126. ['lineWidth', 'borderWidth'],
  34127. // Compatitable with 2
  34128. ['stroke', 'barBorderColor'],
  34129. ['lineWidth', 'barBorderWidth'],
  34130. ['opacity'],
  34131. ['shadowBlur'],
  34132. ['shadowOffsetX'],
  34133. ['shadowOffsetY'],
  34134. ['shadowColor']
  34135. ]
  34136. );
  34137. var barItemStyle = {
  34138. getBarItemStyle: function (excludes) {
  34139. var style = getBarItemStyle(this, excludes);
  34140. if (this.getBorderLineDash) {
  34141. var lineDash = this.getBorderLineDash();
  34142. lineDash && (style.lineDash = lineDash);
  34143. }
  34144. return style;
  34145. }
  34146. };
  34147. /*
  34148. * Licensed to the Apache Software Foundation (ASF) under one
  34149. * or more contributor license agreements. See the NOTICE file
  34150. * distributed with this work for additional information
  34151. * regarding copyright ownership. The ASF licenses this file
  34152. * to you under the Apache License, Version 2.0 (the
  34153. * "License"); you may not use this file except in compliance
  34154. * with the License. You may obtain a copy of the License at
  34155. *
  34156. * http://www.apache.org/licenses/LICENSE-2.0
  34157. *
  34158. * Unless required by applicable law or agreed to in writing,
  34159. * software distributed under the License is distributed on an
  34160. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34161. * KIND, either express or implied. See the License for the
  34162. * specific language governing permissions and limitations
  34163. * under the License.
  34164. */
  34165. var BAR_BORDER_WIDTH_QUERY = ['itemStyle', 'barBorderWidth'];
  34166. // FIXME
  34167. // Just for compatible with ec2.
  34168. extend(Model.prototype, barItemStyle);
  34169. extendChartView({
  34170. type: 'bar',
  34171. render: function (seriesModel, ecModel, api) {
  34172. this._updateDrawMode(seriesModel);
  34173. var coordinateSystemType = seriesModel.get('coordinateSystem');
  34174. if (coordinateSystemType === 'cartesian2d'
  34175. || coordinateSystemType === 'polar'
  34176. ) {
  34177. this._isLargeDraw
  34178. ? this._renderLarge(seriesModel, ecModel, api)
  34179. : this._renderNormal(seriesModel, ecModel, api);
  34180. }
  34181. else if (__DEV__) {
  34182. console.warn('Only cartesian2d and polar supported for bar.');
  34183. }
  34184. return this.group;
  34185. },
  34186. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  34187. this._clear();
  34188. this._updateDrawMode(seriesModel);
  34189. },
  34190. incrementalRender: function (params, seriesModel, ecModel, api) {
  34191. // Do not support progressive in normal mode.
  34192. this._incrementalRenderLarge(params, seriesModel);
  34193. },
  34194. _updateDrawMode: function (seriesModel) {
  34195. var isLargeDraw = seriesModel.pipelineContext.large;
  34196. if (this._isLargeDraw == null || isLargeDraw ^ this._isLargeDraw) {
  34197. this._isLargeDraw = isLargeDraw;
  34198. this._clear();
  34199. }
  34200. },
  34201. _renderNormal: function (seriesModel, ecModel, api) {
  34202. var group = this.group;
  34203. var data = seriesModel.getData();
  34204. var oldData = this._data;
  34205. var coord = seriesModel.coordinateSystem;
  34206. var baseAxis = coord.getBaseAxis();
  34207. var isHorizontalOrRadial;
  34208. if (coord.type === 'cartesian2d') {
  34209. isHorizontalOrRadial = baseAxis.isHorizontal();
  34210. }
  34211. else if (coord.type === 'polar') {
  34212. isHorizontalOrRadial = baseAxis.dim === 'angle';
  34213. }
  34214. var animationModel = seriesModel.isAnimationEnabled() ? seriesModel : null;
  34215. data.diff(oldData)
  34216. .add(function (dataIndex) {
  34217. if (!data.hasValue(dataIndex)) {
  34218. return;
  34219. }
  34220. var itemModel = data.getItemModel(dataIndex);
  34221. var layout = getLayout[coord.type](data, dataIndex, itemModel);
  34222. var el = elementCreator[coord.type](
  34223. data, dataIndex, itemModel, layout, isHorizontalOrRadial, animationModel
  34224. );
  34225. data.setItemGraphicEl(dataIndex, el);
  34226. group.add(el);
  34227. updateStyle(
  34228. el, data, dataIndex, itemModel, layout,
  34229. seriesModel, isHorizontalOrRadial, coord.type === 'polar'
  34230. );
  34231. })
  34232. .update(function (newIndex, oldIndex) {
  34233. var el = oldData.getItemGraphicEl(oldIndex);
  34234. if (!data.hasValue(newIndex)) {
  34235. group.remove(el);
  34236. return;
  34237. }
  34238. var itemModel = data.getItemModel(newIndex);
  34239. var layout = getLayout[coord.type](data, newIndex, itemModel);
  34240. if (el) {
  34241. updateProps(el, {shape: layout}, animationModel, newIndex);
  34242. }
  34243. else {
  34244. el = elementCreator[coord.type](
  34245. data, newIndex, itemModel, layout, isHorizontalOrRadial, animationModel, true
  34246. );
  34247. }
  34248. data.setItemGraphicEl(newIndex, el);
  34249. // Add back
  34250. group.add(el);
  34251. updateStyle(
  34252. el, data, newIndex, itemModel, layout,
  34253. seriesModel, isHorizontalOrRadial, coord.type === 'polar'
  34254. );
  34255. })
  34256. .remove(function (dataIndex) {
  34257. var el = oldData.getItemGraphicEl(dataIndex);
  34258. if (coord.type === 'cartesian2d') {
  34259. el && removeRect(dataIndex, animationModel, el);
  34260. }
  34261. else {
  34262. el && removeSector(dataIndex, animationModel, el);
  34263. }
  34264. })
  34265. .execute();
  34266. this._data = data;
  34267. },
  34268. _renderLarge: function (seriesModel, ecModel, api) {
  34269. this._clear();
  34270. createLarge(seriesModel, this.group);
  34271. },
  34272. _incrementalRenderLarge: function (params, seriesModel) {
  34273. createLarge(seriesModel, this.group, true);
  34274. },
  34275. dispose: noop,
  34276. remove: function (ecModel) {
  34277. this._clear(ecModel);
  34278. },
  34279. _clear: function (ecModel) {
  34280. var group = this.group;
  34281. var data = this._data;
  34282. if (ecModel && ecModel.get('animation') && data && !this._isLargeDraw) {
  34283. data.eachItemGraphicEl(function (el) {
  34284. if (el.type === 'sector') {
  34285. removeSector(el.dataIndex, ecModel, el);
  34286. }
  34287. else {
  34288. removeRect(el.dataIndex, ecModel, el);
  34289. }
  34290. });
  34291. }
  34292. else {
  34293. group.removeAll();
  34294. }
  34295. this._data = null;
  34296. }
  34297. });
  34298. var elementCreator = {
  34299. cartesian2d: function (
  34300. data, dataIndex, itemModel, layout, isHorizontal,
  34301. animationModel, isUpdate
  34302. ) {
  34303. var rect = new Rect({shape: extend({}, layout)});
  34304. // Animation
  34305. if (animationModel) {
  34306. var rectShape = rect.shape;
  34307. var animateProperty = isHorizontal ? 'height' : 'width';
  34308. var animateTarget = {};
  34309. rectShape[animateProperty] = 0;
  34310. animateTarget[animateProperty] = layout[animateProperty];
  34311. graphic[isUpdate ? 'updateProps' : 'initProps'](rect, {
  34312. shape: animateTarget
  34313. }, animationModel, dataIndex);
  34314. }
  34315. return rect;
  34316. },
  34317. polar: function (
  34318. data, dataIndex, itemModel, layout, isRadial,
  34319. animationModel, isUpdate
  34320. ) {
  34321. // Keep the same logic with bar in catesion: use end value to control
  34322. // direction. Notice that if clockwise is true (by default), the sector
  34323. // will always draw clockwisely, no matter whether endAngle is greater
  34324. // or less than startAngle.
  34325. var clockwise = layout.startAngle < layout.endAngle;
  34326. var sector = new Sector({
  34327. shape: defaults({clockwise: clockwise}, layout)
  34328. });
  34329. // Animation
  34330. if (animationModel) {
  34331. var sectorShape = sector.shape;
  34332. var animateProperty = isRadial ? 'r' : 'endAngle';
  34333. var animateTarget = {};
  34334. sectorShape[animateProperty] = isRadial ? 0 : layout.startAngle;
  34335. animateTarget[animateProperty] = layout[animateProperty];
  34336. graphic[isUpdate ? 'updateProps' : 'initProps'](sector, {
  34337. shape: animateTarget
  34338. }, animationModel, dataIndex);
  34339. }
  34340. return sector;
  34341. }
  34342. };
  34343. function removeRect(dataIndex, animationModel, el) {
  34344. // Not show text when animating
  34345. el.style.text = null;
  34346. updateProps(el, {
  34347. shape: {
  34348. width: 0
  34349. }
  34350. }, animationModel, dataIndex, function () {
  34351. el.parent && el.parent.remove(el);
  34352. });
  34353. }
  34354. function removeSector(dataIndex, animationModel, el) {
  34355. // Not show text when animating
  34356. el.style.text = null;
  34357. updateProps(el, {
  34358. shape: {
  34359. r: el.shape.r0
  34360. }
  34361. }, animationModel, dataIndex, function () {
  34362. el.parent && el.parent.remove(el);
  34363. });
  34364. }
  34365. var getLayout = {
  34366. cartesian2d: function (data, dataIndex, itemModel) {
  34367. var layout = data.getItemLayout(dataIndex);
  34368. var fixedLineWidth = getLineWidth(itemModel, layout);
  34369. // fix layout with lineWidth
  34370. var signX = layout.width > 0 ? 1 : -1;
  34371. var signY = layout.height > 0 ? 1 : -1;
  34372. return {
  34373. x: layout.x + signX * fixedLineWidth / 2,
  34374. y: layout.y + signY * fixedLineWidth / 2,
  34375. width: layout.width - signX * fixedLineWidth,
  34376. height: layout.height - signY * fixedLineWidth
  34377. };
  34378. },
  34379. polar: function (data, dataIndex, itemModel) {
  34380. var layout = data.getItemLayout(dataIndex);
  34381. return {
  34382. cx: layout.cx,
  34383. cy: layout.cy,
  34384. r0: layout.r0,
  34385. r: layout.r,
  34386. startAngle: layout.startAngle,
  34387. endAngle: layout.endAngle
  34388. };
  34389. }
  34390. };
  34391. function updateStyle(
  34392. el, data, dataIndex, itemModel, layout, seriesModel, isHorizontal, isPolar
  34393. ) {
  34394. var color = data.getItemVisual(dataIndex, 'color');
  34395. var opacity = data.getItemVisual(dataIndex, 'opacity');
  34396. var itemStyleModel = itemModel.getModel('itemStyle');
  34397. var hoverStyle = itemModel.getModel('emphasis.itemStyle').getBarItemStyle();
  34398. if (!isPolar) {
  34399. el.setShape('r', itemStyleModel.get('barBorderRadius') || 0);
  34400. }
  34401. el.useStyle(defaults(
  34402. {
  34403. fill: color,
  34404. opacity: opacity
  34405. },
  34406. itemStyleModel.getBarItemStyle()
  34407. ));
  34408. var cursorStyle = itemModel.getShallow('cursor');
  34409. cursorStyle && el.attr('cursor', cursorStyle);
  34410. var labelPositionOutside = isHorizontal
  34411. ? (layout.height > 0 ? 'bottom' : 'top')
  34412. : (layout.width > 0 ? 'left' : 'right');
  34413. if (!isPolar) {
  34414. setLabel(
  34415. el.style, hoverStyle, itemModel, color,
  34416. seriesModel, dataIndex, labelPositionOutside
  34417. );
  34418. }
  34419. setHoverStyle(el, hoverStyle);
  34420. }
  34421. // In case width or height are too small.
  34422. function getLineWidth(itemModel, rawLayout) {
  34423. var lineWidth = itemModel.get(BAR_BORDER_WIDTH_QUERY) || 0;
  34424. return Math.min(lineWidth, Math.abs(rawLayout.width), Math.abs(rawLayout.height));
  34425. }
  34426. var LargePath = Path.extend({
  34427. type: 'largeBar',
  34428. shape: {points: []},
  34429. buildPath: function (ctx, shape) {
  34430. // Drawing lines is more efficient than drawing
  34431. // a whole line or drawing rects.
  34432. var points = shape.points;
  34433. var startPoint = this.__startPoint;
  34434. var valueIdx = this.__valueIdx;
  34435. for (var i = 0; i < points.length; i += 2) {
  34436. startPoint[this.__valueIdx] = points[i + valueIdx];
  34437. ctx.moveTo(startPoint[0], startPoint[1]);
  34438. ctx.lineTo(points[i], points[i + 1]);
  34439. }
  34440. }
  34441. });
  34442. function createLarge(seriesModel, group, incremental) {
  34443. // TODO support polar
  34444. var data = seriesModel.getData();
  34445. var startPoint = [];
  34446. var valueIdx = data.getLayout('valueAxisHorizontal') ? 1 : 0;
  34447. startPoint[1 - valueIdx] = data.getLayout('valueAxisStart');
  34448. var el = new LargePath({
  34449. shape: {points: data.getLayout('largePoints')},
  34450. incremental: !!incremental,
  34451. __startPoint: startPoint,
  34452. __valueIdx: valueIdx
  34453. });
  34454. group.add(el);
  34455. setLargeStyle(el, seriesModel, data);
  34456. }
  34457. function setLargeStyle(el, seriesModel, data) {
  34458. var borderColor = data.getVisual('borderColor') || data.getVisual('color');
  34459. var itemStyle = seriesModel.getModel('itemStyle').getItemStyle(['color', 'borderColor']);
  34460. el.useStyle(itemStyle);
  34461. el.style.fill = null;
  34462. el.style.stroke = borderColor;
  34463. el.style.lineWidth = data.getLayout('barWidth');
  34464. }
  34465. /*
  34466. * Licensed to the Apache Software Foundation (ASF) under one
  34467. * or more contributor license agreements. See the NOTICE file
  34468. * distributed with this work for additional information
  34469. * regarding copyright ownership. The ASF licenses this file
  34470. * to you under the Apache License, Version 2.0 (the
  34471. * "License"); you may not use this file except in compliance
  34472. * with the License. You may obtain a copy of the License at
  34473. *
  34474. * http://www.apache.org/licenses/LICENSE-2.0
  34475. *
  34476. * Unless required by applicable law or agreed to in writing,
  34477. * software distributed under the License is distributed on an
  34478. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34479. * KIND, either express or implied. See the License for the
  34480. * specific language governing permissions and limitations
  34481. * under the License.
  34482. */
  34483. // In case developer forget to include grid component
  34484. registerLayout(curry(layout, 'bar'));
  34485. // Should after normal bar layout, otherwise it is blocked by normal bar layout.
  34486. registerLayout(largeLayout);
  34487. registerVisual({
  34488. seriesType: 'bar',
  34489. reset: function (seriesModel) {
  34490. // Visual coding for legend
  34491. seriesModel.getData().setVisual('legendSymbol', 'roundRect');
  34492. }
  34493. });
  34494. /*
  34495. * Licensed to the Apache Software Foundation (ASF) under one
  34496. * or more contributor license agreements. See the NOTICE file
  34497. * distributed with this work for additional information
  34498. * regarding copyright ownership. The ASF licenses this file
  34499. * to you under the Apache License, Version 2.0 (the
  34500. * "License"); you may not use this file except in compliance
  34501. * with the License. You may obtain a copy of the License at
  34502. *
  34503. * http://www.apache.org/licenses/LICENSE-2.0
  34504. *
  34505. * Unless required by applicable law or agreed to in writing,
  34506. * software distributed under the License is distributed on an
  34507. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34508. * KIND, either express or implied. See the License for the
  34509. * specific language governing permissions and limitations
  34510. * under the License.
  34511. */
  34512. /**
  34513. * [Usage]:
  34514. * (1)
  34515. * createListSimply(seriesModel, ['value']);
  34516. * (2)
  34517. * createListSimply(seriesModel, {
  34518. * coordDimensions: ['value'],
  34519. * dimensionsCount: 5
  34520. * });
  34521. *
  34522. * @param {module:echarts/model/Series} seriesModel
  34523. * @param {Object|Array.<string|Object>} opt opt or coordDimensions
  34524. * The options in opt, see `echarts/data/helper/createDimensions`
  34525. * @param {Array.<string>} [nameList]
  34526. * @return {module:echarts/data/List}
  34527. */
  34528. var createListSimply = function (seriesModel, opt, nameList) {
  34529. opt = isArray(opt) && {coordDimensions: opt} || extend({}, opt);
  34530. var source = seriesModel.getSource();
  34531. var dimensionsInfo = createDimensions(source, opt);
  34532. var list = new List(dimensionsInfo, seriesModel);
  34533. list.initData(source, nameList);
  34534. return list;
  34535. };
  34536. /*
  34537. * Licensed to the Apache Software Foundation (ASF) under one
  34538. * or more contributor license agreements. See the NOTICE file
  34539. * distributed with this work for additional information
  34540. * regarding copyright ownership. The ASF licenses this file
  34541. * to you under the Apache License, Version 2.0 (the
  34542. * "License"); you may not use this file except in compliance
  34543. * with the License. You may obtain a copy of the License at
  34544. *
  34545. * http://www.apache.org/licenses/LICENSE-2.0
  34546. *
  34547. * Unless required by applicable law or agreed to in writing,
  34548. * software distributed under the License is distributed on an
  34549. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34550. * KIND, either express or implied. See the License for the
  34551. * specific language governing permissions and limitations
  34552. * under the License.
  34553. */
  34554. /**
  34555. * Data selectable mixin for chart series.
  34556. * To eanble data select, option of series must have `selectedMode`.
  34557. * And each data item will use `selected` to toggle itself selected status
  34558. */
  34559. var selectableMixin = {
  34560. /**
  34561. * @param {Array.<Object>} targetList [{name, value, selected}, ...]
  34562. * If targetList is an array, it should like [{name: ..., value: ...}, ...].
  34563. * If targetList is a "List", it must have coordDim: 'value' dimension and name.
  34564. */
  34565. updateSelectedMap: function (targetList) {
  34566. this._targetList = isArray(targetList) ? targetList.slice() : [];
  34567. this._selectTargetMap = reduce(targetList || [], function (targetMap, target) {
  34568. targetMap.set(target.name, target);
  34569. return targetMap;
  34570. }, createHashMap());
  34571. },
  34572. /**
  34573. * Either name or id should be passed as input here.
  34574. * If both of them are defined, id is used.
  34575. *
  34576. * @param {string|undefined} name name of data
  34577. * @param {number|undefined} id dataIndex of data
  34578. */
  34579. // PENGING If selectedMode is null ?
  34580. select: function (name, id) {
  34581. var target = id != null
  34582. ? this._targetList[id]
  34583. : this._selectTargetMap.get(name);
  34584. var selectedMode = this.get('selectedMode');
  34585. if (selectedMode === 'single') {
  34586. this._selectTargetMap.each(function (target) {
  34587. target.selected = false;
  34588. });
  34589. }
  34590. target && (target.selected = true);
  34591. },
  34592. /**
  34593. * Either name or id should be passed as input here.
  34594. * If both of them are defined, id is used.
  34595. *
  34596. * @param {string|undefined} name name of data
  34597. * @param {number|undefined} id dataIndex of data
  34598. */
  34599. unSelect: function (name, id) {
  34600. var target = id != null
  34601. ? this._targetList[id]
  34602. : this._selectTargetMap.get(name);
  34603. // var selectedMode = this.get('selectedMode');
  34604. // selectedMode !== 'single' && target && (target.selected = false);
  34605. target && (target.selected = false);
  34606. },
  34607. /**
  34608. * Either name or id should be passed as input here.
  34609. * If both of them are defined, id is used.
  34610. *
  34611. * @param {string|undefined} name name of data
  34612. * @param {number|undefined} id dataIndex of data
  34613. */
  34614. toggleSelected: function (name, id) {
  34615. var target = id != null
  34616. ? this._targetList[id]
  34617. : this._selectTargetMap.get(name);
  34618. if (target != null) {
  34619. this[target.selected ? 'unSelect' : 'select'](name, id);
  34620. return target.selected;
  34621. }
  34622. },
  34623. /**
  34624. * Either name or id should be passed as input here.
  34625. * If both of them are defined, id is used.
  34626. *
  34627. * @param {string|undefined} name name of data
  34628. * @param {number|undefined} id dataIndex of data
  34629. */
  34630. isSelected: function (name, id) {
  34631. var target = id != null
  34632. ? this._targetList[id]
  34633. : this._selectTargetMap.get(name);
  34634. return target && target.selected;
  34635. }
  34636. };
  34637. /*
  34638. * Licensed to the Apache Software Foundation (ASF) under one
  34639. * or more contributor license agreements. See the NOTICE file
  34640. * distributed with this work for additional information
  34641. * regarding copyright ownership. The ASF licenses this file
  34642. * to you under the Apache License, Version 2.0 (the
  34643. * "License"); you may not use this file except in compliance
  34644. * with the License. You may obtain a copy of the License at
  34645. *
  34646. * http://www.apache.org/licenses/LICENSE-2.0
  34647. *
  34648. * Unless required by applicable law or agreed to in writing,
  34649. * software distributed under the License is distributed on an
  34650. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34651. * KIND, either express or implied. See the License for the
  34652. * specific language governing permissions and limitations
  34653. * under the License.
  34654. */
  34655. var PieSeries = extendSeriesModel({
  34656. type: 'series.pie',
  34657. // Overwrite
  34658. init: function (option) {
  34659. PieSeries.superApply(this, 'init', arguments);
  34660. // Enable legend selection for each data item
  34661. // Use a function instead of direct access because data reference may changed
  34662. this.legendDataProvider = function () {
  34663. return this.getRawData();
  34664. };
  34665. this.updateSelectedMap(this._createSelectableList());
  34666. this._defaultLabelLine(option);
  34667. },
  34668. // Overwrite
  34669. mergeOption: function (newOption) {
  34670. PieSeries.superCall(this, 'mergeOption', newOption);
  34671. this.updateSelectedMap(this._createSelectableList());
  34672. },
  34673. getInitialData: function (option, ecModel) {
  34674. return createListSimply(this, ['value']);
  34675. },
  34676. _createSelectableList: function () {
  34677. var data = this.getRawData();
  34678. var valueDim = data.mapDimension('value');
  34679. var targetList = [];
  34680. for (var i = 0, len = data.count(); i < len; i++) {
  34681. targetList.push({
  34682. name: data.getName(i),
  34683. value: data.get(valueDim, i),
  34684. selected: retrieveRawAttr(data, i, 'selected')
  34685. });
  34686. }
  34687. return targetList;
  34688. },
  34689. // Overwrite
  34690. getDataParams: function (dataIndex) {
  34691. var data = this.getData();
  34692. var params = PieSeries.superCall(this, 'getDataParams', dataIndex);
  34693. // FIXME toFixed?
  34694. var valueList = [];
  34695. data.each(data.mapDimension('value'), function (value) {
  34696. valueList.push(value);
  34697. });
  34698. params.percent = getPercentWithPrecision(
  34699. valueList,
  34700. dataIndex,
  34701. data.hostModel.get('percentPrecision')
  34702. );
  34703. params.$vars.push('percent');
  34704. return params;
  34705. },
  34706. _defaultLabelLine: function (option) {
  34707. // Extend labelLine emphasis
  34708. defaultEmphasis(option, 'labelLine', ['show']);
  34709. var labelLineNormalOpt = option.labelLine;
  34710. var labelLineEmphasisOpt = option.emphasis.labelLine;
  34711. // Not show label line if `label.normal.show = false`
  34712. labelLineNormalOpt.show = labelLineNormalOpt.show
  34713. && option.label.show;
  34714. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show
  34715. && option.emphasis.label.show;
  34716. },
  34717. defaultOption: {
  34718. zlevel: 0,
  34719. z: 2,
  34720. legendHoverLink: true,
  34721. hoverAnimation: true,
  34722. // 默认全局居中
  34723. center: ['50%', '50%'],
  34724. radius: [0, '75%'],
  34725. // 默认顺时针
  34726. clockwise: true,
  34727. startAngle: 90,
  34728. // 最小角度改为0
  34729. minAngle: 0,
  34730. // 选中时扇区偏移量
  34731. selectedOffset: 10,
  34732. // 高亮扇区偏移量
  34733. hoverOffset: 10,
  34734. // If use strategy to avoid label overlapping
  34735. avoidLabelOverlap: true,
  34736. // 选择模式,默认关闭,可选single,multiple
  34737. // selectedMode: false,
  34738. // 南丁格尔玫瑰图模式,'radius'(半径) | 'area'(面积)
  34739. // roseType: null,
  34740. percentPrecision: 2,
  34741. // If still show when all data zero.
  34742. stillShowZeroSum: true,
  34743. // cursor: null,
  34744. label: {
  34745. // If rotate around circle
  34746. rotate: false,
  34747. show: true,
  34748. // 'outer', 'inside', 'center'
  34749. position: 'outer'
  34750. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  34751. // 默认使用全局文本样式,详见TEXTSTYLE
  34752. // distance: 当position为inner时有效,为label位置到圆心的距离与圆半径(环状图为内外半径和)的比例系数
  34753. },
  34754. // Enabled when label.normal.position is 'outer'
  34755. labelLine: {
  34756. show: true,
  34757. // 引导线两段中的第一段长度
  34758. length: 15,
  34759. // 引导线两段中的第二段长度
  34760. length2: 15,
  34761. smooth: false,
  34762. lineStyle: {
  34763. // color: 各异,
  34764. width: 1,
  34765. type: 'solid'
  34766. }
  34767. },
  34768. itemStyle: {
  34769. borderWidth: 1
  34770. },
  34771. // Animation type canbe expansion, scale
  34772. animationType: 'expansion',
  34773. animationEasing: 'cubicOut'
  34774. }
  34775. });
  34776. mixin(PieSeries, selectableMixin);
  34777. /*
  34778. * Licensed to the Apache Software Foundation (ASF) under one
  34779. * or more contributor license agreements. See the NOTICE file
  34780. * distributed with this work for additional information
  34781. * regarding copyright ownership. The ASF licenses this file
  34782. * to you under the Apache License, Version 2.0 (the
  34783. * "License"); you may not use this file except in compliance
  34784. * with the License. You may obtain a copy of the License at
  34785. *
  34786. * http://www.apache.org/licenses/LICENSE-2.0
  34787. *
  34788. * Unless required by applicable law or agreed to in writing,
  34789. * software distributed under the License is distributed on an
  34790. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34791. * KIND, either express or implied. See the License for the
  34792. * specific language governing permissions and limitations
  34793. * under the License.
  34794. */
  34795. /**
  34796. * @param {module:echarts/model/Series} seriesModel
  34797. * @param {boolean} hasAnimation
  34798. * @inner
  34799. */
  34800. function updateDataSelected(uid, seriesModel, hasAnimation, api) {
  34801. var data = seriesModel.getData();
  34802. var dataIndex = this.dataIndex;
  34803. var name = data.getName(dataIndex);
  34804. var selectedOffset = seriesModel.get('selectedOffset');
  34805. api.dispatchAction({
  34806. type: 'pieToggleSelect',
  34807. from: uid,
  34808. name: name,
  34809. seriesId: seriesModel.id
  34810. });
  34811. data.each(function (idx) {
  34812. toggleItemSelected(
  34813. data.getItemGraphicEl(idx),
  34814. data.getItemLayout(idx),
  34815. seriesModel.isSelected(data.getName(idx)),
  34816. selectedOffset,
  34817. hasAnimation
  34818. );
  34819. });
  34820. }
  34821. /**
  34822. * @param {module:zrender/graphic/Sector} el
  34823. * @param {Object} layout
  34824. * @param {boolean} isSelected
  34825. * @param {number} selectedOffset
  34826. * @param {boolean} hasAnimation
  34827. * @inner
  34828. */
  34829. function toggleItemSelected(el, layout, isSelected, selectedOffset, hasAnimation) {
  34830. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  34831. var dx = Math.cos(midAngle);
  34832. var dy = Math.sin(midAngle);
  34833. var offset = isSelected ? selectedOffset : 0;
  34834. var position = [dx * offset, dy * offset];
  34835. hasAnimation
  34836. // animateTo will stop revious animation like update transition
  34837. ? el.animate()
  34838. .when(200, {
  34839. position: position
  34840. })
  34841. .start('bounceOut')
  34842. : el.attr('position', position);
  34843. }
  34844. /**
  34845. * Piece of pie including Sector, Label, LabelLine
  34846. * @constructor
  34847. * @extends {module:zrender/graphic/Group}
  34848. */
  34849. function PiePiece(data, idx) {
  34850. Group.call(this);
  34851. var sector = new Sector({
  34852. z2: 2
  34853. });
  34854. var polyline = new Polyline();
  34855. var text = new Text();
  34856. this.add(sector);
  34857. this.add(polyline);
  34858. this.add(text);
  34859. this.updateData(data, idx, true);
  34860. // Hover to change label and labelLine
  34861. function onEmphasis() {
  34862. polyline.ignore = polyline.hoverIgnore;
  34863. text.ignore = text.hoverIgnore;
  34864. }
  34865. function onNormal() {
  34866. polyline.ignore = polyline.normalIgnore;
  34867. text.ignore = text.normalIgnore;
  34868. }
  34869. this.on('emphasis', onEmphasis)
  34870. .on('normal', onNormal)
  34871. .on('mouseover', onEmphasis)
  34872. .on('mouseout', onNormal);
  34873. }
  34874. var piePieceProto = PiePiece.prototype;
  34875. piePieceProto.updateData = function (data, idx, firstCreate) {
  34876. var sector = this.childAt(0);
  34877. var seriesModel = data.hostModel;
  34878. var itemModel = data.getItemModel(idx);
  34879. var layout = data.getItemLayout(idx);
  34880. var sectorShape = extend({}, layout);
  34881. sectorShape.label = null;
  34882. if (firstCreate) {
  34883. sector.setShape(sectorShape);
  34884. var animationType = seriesModel.getShallow('animationType');
  34885. if (animationType === 'scale') {
  34886. sector.shape.r = layout.r0;
  34887. initProps(sector, {
  34888. shape: {
  34889. r: layout.r
  34890. }
  34891. }, seriesModel, idx);
  34892. }
  34893. // Expansion
  34894. else {
  34895. sector.shape.endAngle = layout.startAngle;
  34896. updateProps(sector, {
  34897. shape: {
  34898. endAngle: layout.endAngle
  34899. }
  34900. }, seriesModel, idx);
  34901. }
  34902. }
  34903. else {
  34904. updateProps(sector, {
  34905. shape: sectorShape
  34906. }, seriesModel, idx);
  34907. }
  34908. // Update common style
  34909. var visualColor = data.getItemVisual(idx, 'color');
  34910. sector.useStyle(
  34911. defaults(
  34912. {
  34913. lineJoin: 'bevel',
  34914. fill: visualColor
  34915. },
  34916. itemModel.getModel('itemStyle').getItemStyle()
  34917. )
  34918. );
  34919. sector.hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  34920. var cursorStyle = itemModel.getShallow('cursor');
  34921. cursorStyle && sector.attr('cursor', cursorStyle);
  34922. // Toggle selected
  34923. toggleItemSelected(
  34924. this,
  34925. data.getItemLayout(idx),
  34926. seriesModel.isSelected(null, idx),
  34927. seriesModel.get('selectedOffset'),
  34928. seriesModel.get('animation')
  34929. );
  34930. function onEmphasis() {
  34931. // Sector may has animation of updating data. Force to move to the last frame
  34932. // Or it may stopped on the wrong shape
  34933. sector.stopAnimation(true);
  34934. sector.animateTo({
  34935. shape: {
  34936. r: layout.r + seriesModel.get('hoverOffset')
  34937. }
  34938. }, 300, 'elasticOut');
  34939. }
  34940. function onNormal() {
  34941. sector.stopAnimation(true);
  34942. sector.animateTo({
  34943. shape: {
  34944. r: layout.r
  34945. }
  34946. }, 300, 'elasticOut');
  34947. }
  34948. sector.off('mouseover').off('mouseout').off('emphasis').off('normal');
  34949. if (itemModel.get('hoverAnimation') && seriesModel.isAnimationEnabled()) {
  34950. sector
  34951. .on('mouseover', onEmphasis)
  34952. .on('mouseout', onNormal)
  34953. .on('emphasis', onEmphasis)
  34954. .on('normal', onNormal);
  34955. }
  34956. this._updateLabel(data, idx);
  34957. setHoverStyle(this);
  34958. };
  34959. piePieceProto._updateLabel = function (data, idx) {
  34960. var labelLine = this.childAt(1);
  34961. var labelText = this.childAt(2);
  34962. var seriesModel = data.hostModel;
  34963. var itemModel = data.getItemModel(idx);
  34964. var layout = data.getItemLayout(idx);
  34965. var labelLayout = layout.label;
  34966. var visualColor = data.getItemVisual(idx, 'color');
  34967. updateProps(labelLine, {
  34968. shape: {
  34969. points: labelLayout.linePoints || [
  34970. [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y]
  34971. ]
  34972. }
  34973. }, seriesModel, idx);
  34974. updateProps(labelText, {
  34975. style: {
  34976. x: labelLayout.x,
  34977. y: labelLayout.y
  34978. }
  34979. }, seriesModel, idx);
  34980. labelText.attr({
  34981. rotation: labelLayout.rotation,
  34982. origin: [labelLayout.x, labelLayout.y],
  34983. z2: 10
  34984. });
  34985. var labelModel = itemModel.getModel('label');
  34986. var labelHoverModel = itemModel.getModel('emphasis.label');
  34987. var labelLineModel = itemModel.getModel('labelLine');
  34988. var labelLineHoverModel = itemModel.getModel('emphasis.labelLine');
  34989. var visualColor = data.getItemVisual(idx, 'color');
  34990. setLabelStyle(
  34991. labelText.style, labelText.hoverStyle = {}, labelModel, labelHoverModel,
  34992. {
  34993. labelFetcher: data.hostModel,
  34994. labelDataIndex: idx,
  34995. defaultText: data.getName(idx),
  34996. autoColor: visualColor,
  34997. useInsideStyle: !!labelLayout.inside
  34998. },
  34999. {
  35000. textAlign: labelLayout.textAlign,
  35001. textVerticalAlign: labelLayout.verticalAlign,
  35002. opacity: data.getItemVisual(idx, 'opacity')
  35003. }
  35004. );
  35005. labelText.ignore = labelText.normalIgnore = !labelModel.get('show');
  35006. labelText.hoverIgnore = !labelHoverModel.get('show');
  35007. labelLine.ignore = labelLine.normalIgnore = !labelLineModel.get('show');
  35008. labelLine.hoverIgnore = !labelLineHoverModel.get('show');
  35009. // Default use item visual color
  35010. labelLine.setStyle({
  35011. stroke: visualColor,
  35012. opacity: data.getItemVisual(idx, 'opacity')
  35013. });
  35014. labelLine.setStyle(labelLineModel.getModel('lineStyle').getLineStyle());
  35015. labelLine.hoverStyle = labelLineHoverModel.getModel('lineStyle').getLineStyle();
  35016. var smooth = labelLineModel.get('smooth');
  35017. if (smooth && smooth === true) {
  35018. smooth = 0.4;
  35019. }
  35020. labelLine.setShape({
  35021. smooth: smooth
  35022. });
  35023. };
  35024. inherits(PiePiece, Group);
  35025. // Pie view
  35026. var PieView = Chart.extend({
  35027. type: 'pie',
  35028. init: function () {
  35029. var sectorGroup = new Group();
  35030. this._sectorGroup = sectorGroup;
  35031. },
  35032. render: function (seriesModel, ecModel, api, payload) {
  35033. if (payload && (payload.from === this.uid)) {
  35034. return;
  35035. }
  35036. var data = seriesModel.getData();
  35037. var oldData = this._data;
  35038. var group = this.group;
  35039. var hasAnimation = ecModel.get('animation');
  35040. var isFirstRender = !oldData;
  35041. var animationType = seriesModel.get('animationType');
  35042. var onSectorClick = curry(
  35043. updateDataSelected, this.uid, seriesModel, hasAnimation, api
  35044. );
  35045. var selectedMode = seriesModel.get('selectedMode');
  35046. data.diff(oldData)
  35047. .add(function (idx) {
  35048. var piePiece = new PiePiece(data, idx);
  35049. // Default expansion animation
  35050. if (isFirstRender && animationType !== 'scale') {
  35051. piePiece.eachChild(function (child) {
  35052. child.stopAnimation(true);
  35053. });
  35054. }
  35055. selectedMode && piePiece.on('click', onSectorClick);
  35056. data.setItemGraphicEl(idx, piePiece);
  35057. group.add(piePiece);
  35058. })
  35059. .update(function (newIdx, oldIdx) {
  35060. var piePiece = oldData.getItemGraphicEl(oldIdx);
  35061. piePiece.updateData(data, newIdx);
  35062. piePiece.off('click');
  35063. selectedMode && piePiece.on('click', onSectorClick);
  35064. group.add(piePiece);
  35065. data.setItemGraphicEl(newIdx, piePiece);
  35066. })
  35067. .remove(function (idx) {
  35068. var piePiece = oldData.getItemGraphicEl(idx);
  35069. group.remove(piePiece);
  35070. })
  35071. .execute();
  35072. if (
  35073. hasAnimation && isFirstRender && data.count() > 0
  35074. // Default expansion animation
  35075. && animationType !== 'scale'
  35076. ) {
  35077. var shape = data.getItemLayout(0);
  35078. var r = Math.max(api.getWidth(), api.getHeight()) / 2;
  35079. var removeClipPath = bind(group.removeClipPath, group);
  35080. group.setClipPath(this._createClipPath(
  35081. shape.cx, shape.cy, r, shape.startAngle, shape.clockwise, removeClipPath, seriesModel
  35082. ));
  35083. }
  35084. this._data = data;
  35085. },
  35086. dispose: function () {},
  35087. _createClipPath: function (
  35088. cx, cy, r, startAngle, clockwise, cb, seriesModel
  35089. ) {
  35090. var clipPath = new Sector({
  35091. shape: {
  35092. cx: cx,
  35093. cy: cy,
  35094. r0: 0,
  35095. r: r,
  35096. startAngle: startAngle,
  35097. endAngle: startAngle,
  35098. clockwise: clockwise
  35099. }
  35100. });
  35101. initProps(clipPath, {
  35102. shape: {
  35103. endAngle: startAngle + (clockwise ? 1 : -1) * Math.PI * 2
  35104. }
  35105. }, seriesModel, cb);
  35106. return clipPath;
  35107. },
  35108. /**
  35109. * @implement
  35110. */
  35111. containPoint: function (point, seriesModel) {
  35112. var data = seriesModel.getData();
  35113. var itemLayout = data.getItemLayout(0);
  35114. if (itemLayout) {
  35115. var dx = point[0] - itemLayout.cx;
  35116. var dy = point[1] - itemLayout.cy;
  35117. var radius = Math.sqrt(dx * dx + dy * dy);
  35118. return radius <= itemLayout.r && radius >= itemLayout.r0;
  35119. }
  35120. }
  35121. });
  35122. /*
  35123. * Licensed to the Apache Software Foundation (ASF) under one
  35124. * or more contributor license agreements. See the NOTICE file
  35125. * distributed with this work for additional information
  35126. * regarding copyright ownership. The ASF licenses this file
  35127. * to you under the Apache License, Version 2.0 (the
  35128. * "License"); you may not use this file except in compliance
  35129. * with the License. You may obtain a copy of the License at
  35130. *
  35131. * http://www.apache.org/licenses/LICENSE-2.0
  35132. *
  35133. * Unless required by applicable law or agreed to in writing,
  35134. * software distributed under the License is distributed on an
  35135. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35136. * KIND, either express or implied. See the License for the
  35137. * specific language governing permissions and limitations
  35138. * under the License.
  35139. */
  35140. var createDataSelectAction = function (seriesType, actionInfos) {
  35141. each$1(actionInfos, function (actionInfo) {
  35142. actionInfo.update = 'updateView';
  35143. /**
  35144. * @payload
  35145. * @property {string} seriesName
  35146. * @property {string} name
  35147. */
  35148. registerAction(actionInfo, function (payload, ecModel) {
  35149. var selected = {};
  35150. ecModel.eachComponent(
  35151. {mainType: 'series', subType: seriesType, query: payload},
  35152. function (seriesModel) {
  35153. if (seriesModel[actionInfo.method]) {
  35154. seriesModel[actionInfo.method](
  35155. payload.name,
  35156. payload.dataIndex
  35157. );
  35158. }
  35159. var data = seriesModel.getData();
  35160. // Create selected map
  35161. data.each(function (idx) {
  35162. var name = data.getName(idx);
  35163. selected[name] = seriesModel.isSelected(name)
  35164. || false;
  35165. });
  35166. }
  35167. );
  35168. return {
  35169. name: payload.name,
  35170. selected: selected
  35171. };
  35172. });
  35173. });
  35174. };
  35175. /*
  35176. * Licensed to the Apache Software Foundation (ASF) under one
  35177. * or more contributor license agreements. See the NOTICE file
  35178. * distributed with this work for additional information
  35179. * regarding copyright ownership. The ASF licenses this file
  35180. * to you under the Apache License, Version 2.0 (the
  35181. * "License"); you may not use this file except in compliance
  35182. * with the License. You may obtain a copy of the License at
  35183. *
  35184. * http://www.apache.org/licenses/LICENSE-2.0
  35185. *
  35186. * Unless required by applicable law or agreed to in writing,
  35187. * software distributed under the License is distributed on an
  35188. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35189. * KIND, either express or implied. See the License for the
  35190. * specific language governing permissions and limitations
  35191. * under the License.
  35192. */
  35193. // Pick color from palette for each data item.
  35194. // Applicable for charts that require applying color palette
  35195. // in data level (like pie, funnel, chord).
  35196. var dataColor = function (seriesType) {
  35197. return {
  35198. getTargetSeries: function (ecModel) {
  35199. // Pie and funnel may use diferrent scope
  35200. var paletteScope = {};
  35201. var seiresModelMap = createHashMap();
  35202. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  35203. seriesModel.__paletteScope = paletteScope;
  35204. seiresModelMap.set(seriesModel.uid, seriesModel);
  35205. });
  35206. return seiresModelMap;
  35207. },
  35208. reset: function (seriesModel, ecModel) {
  35209. var dataAll = seriesModel.getRawData();
  35210. var idxMap = {};
  35211. var data = seriesModel.getData();
  35212. data.each(function (idx) {
  35213. var rawIdx = data.getRawIndex(idx);
  35214. idxMap[rawIdx] = idx;
  35215. });
  35216. dataAll.each(function (rawIdx) {
  35217. var filteredIdx = idxMap[rawIdx];
  35218. // If series.itemStyle.normal.color is a function. itemVisual may be encoded
  35219. var singleDataColor = filteredIdx != null
  35220. && data.getItemVisual(filteredIdx, 'color', true);
  35221. if (!singleDataColor) {
  35222. // FIXME Performance
  35223. var itemModel = dataAll.getItemModel(rawIdx);
  35224. var color = itemModel.get('itemStyle.color')
  35225. || seriesModel.getColorFromPalette(
  35226. dataAll.getName(rawIdx) || (rawIdx + ''), seriesModel.__paletteScope,
  35227. dataAll.count()
  35228. );
  35229. // Legend may use the visual info in data before processed
  35230. dataAll.setItemVisual(rawIdx, 'color', color);
  35231. // Data is not filtered
  35232. if (filteredIdx != null) {
  35233. data.setItemVisual(filteredIdx, 'color', color);
  35234. }
  35235. }
  35236. else {
  35237. // Set data all color for legend
  35238. dataAll.setItemVisual(rawIdx, 'color', singleDataColor);
  35239. }
  35240. });
  35241. }
  35242. };
  35243. };
  35244. /*
  35245. * Licensed to the Apache Software Foundation (ASF) under one
  35246. * or more contributor license agreements. See the NOTICE file
  35247. * distributed with this work for additional information
  35248. * regarding copyright ownership. The ASF licenses this file
  35249. * to you under the Apache License, Version 2.0 (the
  35250. * "License"); you may not use this file except in compliance
  35251. * with the License. You may obtain a copy of the License at
  35252. *
  35253. * http://www.apache.org/licenses/LICENSE-2.0
  35254. *
  35255. * Unless required by applicable law or agreed to in writing,
  35256. * software distributed under the License is distributed on an
  35257. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35258. * KIND, either express or implied. See the License for the
  35259. * specific language governing permissions and limitations
  35260. * under the License.
  35261. */
  35262. // FIXME emphasis label position is not same with normal label position
  35263. function adjustSingleSide(list, cx, cy, r, dir, viewWidth, viewHeight) {
  35264. list.sort(function (a, b) {
  35265. return a.y - b.y;
  35266. });
  35267. // 压
  35268. function shiftDown(start, end, delta, dir) {
  35269. for (var j = start; j < end; j++) {
  35270. list[j].y += delta;
  35271. if (j > start
  35272. && j + 1 < end
  35273. && list[j + 1].y > list[j].y + list[j].height
  35274. ) {
  35275. shiftUp(j, delta / 2);
  35276. return;
  35277. }
  35278. }
  35279. shiftUp(end - 1, delta / 2);
  35280. }
  35281. // 弹
  35282. function shiftUp(end, delta) {
  35283. for (var j = end; j >= 0; j--) {
  35284. list[j].y -= delta;
  35285. if (j > 0
  35286. && list[j].y > list[j - 1].y + list[j - 1].height
  35287. ) {
  35288. break;
  35289. }
  35290. }
  35291. }
  35292. function changeX(list, isDownList, cx, cy, r, dir) {
  35293. var lastDeltaX = dir > 0
  35294. ? isDownList // 右侧
  35295. ? Number.MAX_VALUE // 下
  35296. : 0 // 上
  35297. : isDownList // 左侧
  35298. ? Number.MAX_VALUE // 下
  35299. : 0; // 上
  35300. for (var i = 0, l = list.length; i < l; i++) {
  35301. // Not change x for center label
  35302. if (list[i].position === 'center') {
  35303. continue;
  35304. }
  35305. var deltaY = Math.abs(list[i].y - cy);
  35306. var length = list[i].len;
  35307. var length2 = list[i].len2;
  35308. var deltaX = (deltaY < r + length)
  35309. ? Math.sqrt(
  35310. (r + length + length2) * (r + length + length2)
  35311. - deltaY * deltaY
  35312. )
  35313. : Math.abs(list[i].x - cx);
  35314. if (isDownList && deltaX >= lastDeltaX) {
  35315. // 右下,左下
  35316. deltaX = lastDeltaX - 10;
  35317. }
  35318. if (!isDownList && deltaX <= lastDeltaX) {
  35319. // 右上,左上
  35320. deltaX = lastDeltaX + 10;
  35321. }
  35322. list[i].x = cx + deltaX * dir;
  35323. lastDeltaX = deltaX;
  35324. }
  35325. }
  35326. var lastY = 0;
  35327. var delta;
  35328. var len = list.length;
  35329. var upList = [];
  35330. var downList = [];
  35331. for (var i = 0; i < len; i++) {
  35332. delta = list[i].y - lastY;
  35333. if (delta < 0) {
  35334. shiftDown(i, len, -delta, dir);
  35335. }
  35336. lastY = list[i].y + list[i].height;
  35337. }
  35338. if (viewHeight - lastY < 0) {
  35339. shiftUp(len - 1, lastY - viewHeight);
  35340. }
  35341. for (var i = 0; i < len; i++) {
  35342. if (list[i].y >= cy) {
  35343. downList.push(list[i]);
  35344. }
  35345. else {
  35346. upList.push(list[i]);
  35347. }
  35348. }
  35349. changeX(upList, false, cx, cy, r, dir);
  35350. changeX(downList, true, cx, cy, r, dir);
  35351. }
  35352. function avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight) {
  35353. var leftList = [];
  35354. var rightList = [];
  35355. for (var i = 0; i < labelLayoutList.length; i++) {
  35356. if (labelLayoutList[i].x < cx) {
  35357. leftList.push(labelLayoutList[i]);
  35358. }
  35359. else {
  35360. rightList.push(labelLayoutList[i]);
  35361. }
  35362. }
  35363. adjustSingleSide(rightList, cx, cy, r, 1, viewWidth, viewHeight);
  35364. adjustSingleSide(leftList, cx, cy, r, -1, viewWidth, viewHeight);
  35365. for (var i = 0; i < labelLayoutList.length; i++) {
  35366. var linePoints = labelLayoutList[i].linePoints;
  35367. if (linePoints) {
  35368. var dist = linePoints[1][0] - linePoints[2][0];
  35369. if (labelLayoutList[i].x < cx) {
  35370. linePoints[2][0] = labelLayoutList[i].x + 3;
  35371. }
  35372. else {
  35373. linePoints[2][0] = labelLayoutList[i].x - 3;
  35374. }
  35375. linePoints[1][1] = linePoints[2][1] = labelLayoutList[i].y;
  35376. linePoints[1][0] = linePoints[2][0] + dist;
  35377. }
  35378. }
  35379. }
  35380. var labelLayout = function (seriesModel, r, viewWidth, viewHeight) {
  35381. var data = seriesModel.getData();
  35382. var labelLayoutList = [];
  35383. var cx;
  35384. var cy;
  35385. var hasLabelRotate = false;
  35386. data.each(function (idx) {
  35387. var layout = data.getItemLayout(idx);
  35388. var itemModel = data.getItemModel(idx);
  35389. var labelModel = itemModel.getModel('label');
  35390. // Use position in normal or emphasis
  35391. var labelPosition = labelModel.get('position') || itemModel.get('emphasis.label.position');
  35392. var labelLineModel = itemModel.getModel('labelLine');
  35393. var labelLineLen = labelLineModel.get('length');
  35394. var labelLineLen2 = labelLineModel.get('length2');
  35395. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  35396. var dx = Math.cos(midAngle);
  35397. var dy = Math.sin(midAngle);
  35398. var textX;
  35399. var textY;
  35400. var linePoints;
  35401. var textAlign;
  35402. cx = layout.cx;
  35403. cy = layout.cy;
  35404. var isLabelInside = labelPosition === 'inside' || labelPosition === 'inner';
  35405. if (labelPosition === 'center') {
  35406. textX = layout.cx;
  35407. textY = layout.cy;
  35408. textAlign = 'center';
  35409. }
  35410. else {
  35411. var x1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dx : layout.r * dx) + cx;
  35412. var y1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dy : layout.r * dy) + cy;
  35413. textX = x1 + dx * 3;
  35414. textY = y1 + dy * 3;
  35415. if (!isLabelInside) {
  35416. // For roseType
  35417. var x2 = x1 + dx * (labelLineLen + r - layout.r);
  35418. var y2 = y1 + dy * (labelLineLen + r - layout.r);
  35419. var x3 = x2 + ((dx < 0 ? -1 : 1) * labelLineLen2);
  35420. var y3 = y2;
  35421. textX = x3 + (dx < 0 ? -5 : 5);
  35422. textY = y3;
  35423. linePoints = [[x1, y1], [x2, y2], [x3, y3]];
  35424. }
  35425. textAlign = isLabelInside ? 'center' : (dx > 0 ? 'left' : 'right');
  35426. }
  35427. var font = labelModel.getFont();
  35428. var labelRotate = labelModel.get('rotate')
  35429. ? (dx < 0 ? -midAngle + Math.PI : -midAngle) : 0;
  35430. var text = seriesModel.getFormattedLabel(idx, 'normal')
  35431. || data.getName(idx);
  35432. var textRect = getBoundingRect(
  35433. text, font, textAlign, 'top'
  35434. );
  35435. hasLabelRotate = !!labelRotate;
  35436. layout.label = {
  35437. x: textX,
  35438. y: textY,
  35439. position: labelPosition,
  35440. height: textRect.height,
  35441. len: labelLineLen,
  35442. len2: labelLineLen2,
  35443. linePoints: linePoints,
  35444. textAlign: textAlign,
  35445. verticalAlign: 'middle',
  35446. rotation: labelRotate,
  35447. inside: isLabelInside
  35448. };
  35449. // Not layout the inside label
  35450. if (!isLabelInside) {
  35451. labelLayoutList.push(layout.label);
  35452. }
  35453. });
  35454. if (!hasLabelRotate && seriesModel.get('avoidLabelOverlap')) {
  35455. avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight);
  35456. }
  35457. };
  35458. /*
  35459. * Licensed to the Apache Software Foundation (ASF) under one
  35460. * or more contributor license agreements. See the NOTICE file
  35461. * distributed with this work for additional information
  35462. * regarding copyright ownership. The ASF licenses this file
  35463. * to you under the Apache License, Version 2.0 (the
  35464. * "License"); you may not use this file except in compliance
  35465. * with the License. You may obtain a copy of the License at
  35466. *
  35467. * http://www.apache.org/licenses/LICENSE-2.0
  35468. *
  35469. * Unless required by applicable law or agreed to in writing,
  35470. * software distributed under the License is distributed on an
  35471. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35472. * KIND, either express or implied. See the License for the
  35473. * specific language governing permissions and limitations
  35474. * under the License.
  35475. */
  35476. var PI2$4 = Math.PI * 2;
  35477. var RADIAN = Math.PI / 180;
  35478. var pieLayout = function (seriesType, ecModel, api, payload) {
  35479. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  35480. var data = seriesModel.getData();
  35481. var valueDim = data.mapDimension('value');
  35482. var center = seriesModel.get('center');
  35483. var radius = seriesModel.get('radius');
  35484. if (!isArray(radius)) {
  35485. radius = [0, radius];
  35486. }
  35487. if (!isArray(center)) {
  35488. center = [center, center];
  35489. }
  35490. var width = api.getWidth();
  35491. var height = api.getHeight();
  35492. var size = Math.min(width, height);
  35493. var cx = parsePercent$1(center[0], width);
  35494. var cy = parsePercent$1(center[1], height);
  35495. var r0 = parsePercent$1(radius[0], size / 2);
  35496. var r = parsePercent$1(radius[1], size / 2);
  35497. var startAngle = -seriesModel.get('startAngle') * RADIAN;
  35498. var minAngle = seriesModel.get('minAngle') * RADIAN;
  35499. var validDataCount = 0;
  35500. data.each(valueDim, function (value) {
  35501. !isNaN(value) && validDataCount++;
  35502. });
  35503. var sum = data.getSum(valueDim);
  35504. // Sum may be 0
  35505. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  35506. var clockwise = seriesModel.get('clockwise');
  35507. var roseType = seriesModel.get('roseType');
  35508. var stillShowZeroSum = seriesModel.get('stillShowZeroSum');
  35509. // [0...max]
  35510. var extent = data.getDataExtent(valueDim);
  35511. extent[0] = 0;
  35512. // In the case some sector angle is smaller than minAngle
  35513. var restAngle = PI2$4;
  35514. var valueSumLargerThanMinAngle = 0;
  35515. var currentAngle = startAngle;
  35516. var dir = clockwise ? 1 : -1;
  35517. data.each(valueDim, function (value, idx) {
  35518. var angle;
  35519. if (isNaN(value)) {
  35520. data.setItemLayout(idx, {
  35521. angle: NaN,
  35522. startAngle: NaN,
  35523. endAngle: NaN,
  35524. clockwise: clockwise,
  35525. cx: cx,
  35526. cy: cy,
  35527. r0: r0,
  35528. r: roseType
  35529. ? NaN
  35530. : r
  35531. });
  35532. return;
  35533. }
  35534. // FIXME 兼容 2.0 但是 roseType 是 area 的时候才是这样?
  35535. if (roseType !== 'area') {
  35536. angle = (sum === 0 && stillShowZeroSum)
  35537. ? unitRadian : (value * unitRadian);
  35538. }
  35539. else {
  35540. angle = PI2$4 / validDataCount;
  35541. }
  35542. if (angle < minAngle) {
  35543. angle = minAngle;
  35544. restAngle -= minAngle;
  35545. }
  35546. else {
  35547. valueSumLargerThanMinAngle += value;
  35548. }
  35549. var endAngle = currentAngle + dir * angle;
  35550. data.setItemLayout(idx, {
  35551. angle: angle,
  35552. startAngle: currentAngle,
  35553. endAngle: endAngle,
  35554. clockwise: clockwise,
  35555. cx: cx,
  35556. cy: cy,
  35557. r0: r0,
  35558. r: roseType
  35559. ? linearMap(value, extent, [r0, r])
  35560. : r
  35561. });
  35562. currentAngle = endAngle;
  35563. });
  35564. // Some sector is constrained by minAngle
  35565. // Rest sectors needs recalculate angle
  35566. if (restAngle < PI2$4 && validDataCount) {
  35567. // Average the angle if rest angle is not enough after all angles is
  35568. // Constrained by minAngle
  35569. if (restAngle <= 1e-3) {
  35570. var angle = PI2$4 / validDataCount;
  35571. data.each(valueDim, function (value, idx) {
  35572. if (!isNaN(value)) {
  35573. var layout = data.getItemLayout(idx);
  35574. layout.angle = angle;
  35575. layout.startAngle = startAngle + dir * idx * angle;
  35576. layout.endAngle = startAngle + dir * (idx + 1) * angle;
  35577. }
  35578. });
  35579. }
  35580. else {
  35581. unitRadian = restAngle / valueSumLargerThanMinAngle;
  35582. currentAngle = startAngle;
  35583. data.each(valueDim, function (value, idx) {
  35584. if (!isNaN(value)) {
  35585. var layout = data.getItemLayout(idx);
  35586. var angle = layout.angle === minAngle
  35587. ? minAngle : value * unitRadian;
  35588. layout.startAngle = currentAngle;
  35589. layout.endAngle = currentAngle + dir * angle;
  35590. currentAngle += dir * angle;
  35591. }
  35592. });
  35593. }
  35594. }
  35595. labelLayout(seriesModel, r, width, height);
  35596. });
  35597. };
  35598. /*
  35599. * Licensed to the Apache Software Foundation (ASF) under one
  35600. * or more contributor license agreements. See the NOTICE file
  35601. * distributed with this work for additional information
  35602. * regarding copyright ownership. The ASF licenses this file
  35603. * to you under the Apache License, Version 2.0 (the
  35604. * "License"); you may not use this file except in compliance
  35605. * with the License. You may obtain a copy of the License at
  35606. *
  35607. * http://www.apache.org/licenses/LICENSE-2.0
  35608. *
  35609. * Unless required by applicable law or agreed to in writing,
  35610. * software distributed under the License is distributed on an
  35611. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35612. * KIND, either express or implied. See the License for the
  35613. * specific language governing permissions and limitations
  35614. * under the License.
  35615. */
  35616. var dataFilter = function (seriesType) {
  35617. return {
  35618. seriesType: seriesType,
  35619. reset: function (seriesModel, ecModel) {
  35620. var legendModels = ecModel.findComponents({
  35621. mainType: 'legend'
  35622. });
  35623. if (!legendModels || !legendModels.length) {
  35624. return;
  35625. }
  35626. var data = seriesModel.getData();
  35627. data.filterSelf(function (idx) {
  35628. var name = data.getName(idx);
  35629. // If in any legend component the status is not selected.
  35630. for (var i = 0; i < legendModels.length; i++) {
  35631. if (!legendModels[i].isSelected(name)) {
  35632. return false;
  35633. }
  35634. }
  35635. return true;
  35636. });
  35637. }
  35638. };
  35639. };
  35640. /*
  35641. * Licensed to the Apache Software Foundation (ASF) under one
  35642. * or more contributor license agreements. See the NOTICE file
  35643. * distributed with this work for additional information
  35644. * regarding copyright ownership. The ASF licenses this file
  35645. * to you under the Apache License, Version 2.0 (the
  35646. * "License"); you may not use this file except in compliance
  35647. * with the License. You may obtain a copy of the License at
  35648. *
  35649. * http://www.apache.org/licenses/LICENSE-2.0
  35650. *
  35651. * Unless required by applicable law or agreed to in writing,
  35652. * software distributed under the License is distributed on an
  35653. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35654. * KIND, either express or implied. See the License for the
  35655. * specific language governing permissions and limitations
  35656. * under the License.
  35657. */
  35658. createDataSelectAction('pie', [{
  35659. type: 'pieToggleSelect',
  35660. event: 'pieselectchanged',
  35661. method: 'toggleSelected'
  35662. }, {
  35663. type: 'pieSelect',
  35664. event: 'pieselected',
  35665. method: 'select'
  35666. }, {
  35667. type: 'pieUnSelect',
  35668. event: 'pieunselected',
  35669. method: 'unSelect'
  35670. }]);
  35671. registerVisual(dataColor('pie'));
  35672. registerLayout(curry(pieLayout, 'pie'));
  35673. registerProcessor(dataFilter('pie'));
  35674. /*
  35675. * Licensed to the Apache Software Foundation (ASF) under one
  35676. * or more contributor license agreements. See the NOTICE file
  35677. * distributed with this work for additional information
  35678. * regarding copyright ownership. The ASF licenses this file
  35679. * to you under the Apache License, Version 2.0 (the
  35680. * "License"); you may not use this file except in compliance
  35681. * with the License. You may obtain a copy of the License at
  35682. *
  35683. * http://www.apache.org/licenses/LICENSE-2.0
  35684. *
  35685. * Unless required by applicable law or agreed to in writing,
  35686. * software distributed under the License is distributed on an
  35687. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35688. * KIND, either express or implied. See the License for the
  35689. * specific language governing permissions and limitations
  35690. * under the License.
  35691. */
  35692. SeriesModel.extend({
  35693. type: 'series.scatter',
  35694. dependencies: ['grid', 'polar', 'geo', 'singleAxis', 'calendar'],
  35695. getInitialData: function (option, ecModel) {
  35696. return createListFromArray(this.getSource(), this);
  35697. },
  35698. brushSelector: 'point',
  35699. getProgressive: function () {
  35700. var progressive = this.option.progressive;
  35701. if (progressive == null) {
  35702. // PENDING
  35703. return this.option.large ? 5e3 : this.get('progressive');
  35704. }
  35705. return progressive;
  35706. },
  35707. getProgressiveThreshold: function () {
  35708. var progressiveThreshold = this.option.progressiveThreshold;
  35709. if (progressiveThreshold == null) {
  35710. // PENDING
  35711. return this.option.large ? 1e4 : this.get('progressiveThreshold');
  35712. }
  35713. return progressiveThreshold;
  35714. },
  35715. defaultOption: {
  35716. coordinateSystem: 'cartesian2d',
  35717. zlevel: 0,
  35718. z: 2,
  35719. legendHoverLink: true,
  35720. hoverAnimation: true,
  35721. // Cartesian coordinate system
  35722. // xAxisIndex: 0,
  35723. // yAxisIndex: 0,
  35724. // Polar coordinate system
  35725. // polarIndex: 0,
  35726. // Geo coordinate system
  35727. // geoIndex: 0,
  35728. // symbol: null, // 图形类型
  35729. symbolSize: 10, // 图形大小,半宽(半径)参数,当图形为方向或菱形则总宽度为symbolSize * 2
  35730. // symbolRotate: null, // 图形旋转控制
  35731. large: false,
  35732. // Available when large is true
  35733. largeThreshold: 2000,
  35734. // cursor: null,
  35735. // label: {
  35736. // show: false
  35737. // distance: 5,
  35738. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  35739. // position: 默认自适应,水平布局为'top',垂直布局为'right',可选为
  35740. // 'inside'|'left'|'right'|'top'|'bottom'
  35741. // 默认使用全局文本样式,详见TEXTSTYLE
  35742. // },
  35743. itemStyle: {
  35744. opacity: 0.8
  35745. // color: 各异
  35746. }
  35747. // progressive: null
  35748. }
  35749. });
  35750. /*
  35751. * Licensed to the Apache Software Foundation (ASF) under one
  35752. * or more contributor license agreements. See the NOTICE file
  35753. * distributed with this work for additional information
  35754. * regarding copyright ownership. The ASF licenses this file
  35755. * to you under the Apache License, Version 2.0 (the
  35756. * "License"); you may not use this file except in compliance
  35757. * with the License. You may obtain a copy of the License at
  35758. *
  35759. * http://www.apache.org/licenses/LICENSE-2.0
  35760. *
  35761. * Unless required by applicable law or agreed to in writing,
  35762. * software distributed under the License is distributed on an
  35763. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35764. * KIND, either express or implied. See the License for the
  35765. * specific language governing permissions and limitations
  35766. * under the License.
  35767. */
  35768. // TODO Batch by color
  35769. var BOOST_SIZE_THRESHOLD = 4;
  35770. var LargeSymbolPath = extendShape({
  35771. shape: {
  35772. points: null
  35773. },
  35774. symbolProxy: null,
  35775. buildPath: function (path, shape) {
  35776. var points = shape.points;
  35777. var size = shape.size;
  35778. var symbolProxy = this.symbolProxy;
  35779. var symbolProxyShape = symbolProxy.shape;
  35780. var ctx = path.getContext ? path.getContext() : path;
  35781. var canBoost = ctx && size[0] < BOOST_SIZE_THRESHOLD;
  35782. // Do draw in afterBrush.
  35783. if (canBoost) {
  35784. return;
  35785. }
  35786. for (var i = 0; i < points.length;) {
  35787. var x = points[i++];
  35788. var y = points[i++];
  35789. if (isNaN(x) || isNaN(y)) {
  35790. continue;
  35791. }
  35792. symbolProxyShape.x = x - size[0] / 2;
  35793. symbolProxyShape.y = y - size[1] / 2;
  35794. symbolProxyShape.width = size[0];
  35795. symbolProxyShape.height = size[1];
  35796. symbolProxy.buildPath(path, symbolProxyShape, true);
  35797. }
  35798. },
  35799. afterBrush: function (ctx) {
  35800. var shape = this.shape;
  35801. var points = shape.points;
  35802. var size = shape.size;
  35803. var canBoost = size[0] < BOOST_SIZE_THRESHOLD;
  35804. if (!canBoost) {
  35805. return;
  35806. }
  35807. this.setTransform(ctx);
  35808. // PENDING If style or other canvas status changed?
  35809. for (var i = 0; i < points.length;) {
  35810. var x = points[i++];
  35811. var y = points[i++];
  35812. if (isNaN(x) || isNaN(y)) {
  35813. continue;
  35814. }
  35815. // fillRect is faster than building a rect path and draw.
  35816. // And it support light globalCompositeOperation.
  35817. ctx.fillRect(
  35818. x - size[0] / 2, y - size[1] / 2,
  35819. size[0], size[1]
  35820. );
  35821. }
  35822. this.restoreTransform(ctx);
  35823. },
  35824. findDataIndex: function (x, y) {
  35825. // TODO ???
  35826. // Consider transform
  35827. var shape = this.shape;
  35828. var points = shape.points;
  35829. var size = shape.size;
  35830. var w = Math.max(size[0], 4);
  35831. var h = Math.max(size[1], 4);
  35832. // Not consider transform
  35833. // Treat each element as a rect
  35834. // top down traverse
  35835. for (var idx = points.length / 2 - 1; idx >= 0; idx--) {
  35836. var i = idx * 2;
  35837. var x0 = points[i] - w / 2;
  35838. var y0 = points[i + 1] - h / 2;
  35839. if (x >= x0 && y >= y0 && x <= x0 + w && y <= y0 + h) {
  35840. return idx;
  35841. }
  35842. }
  35843. return -1;
  35844. }
  35845. });
  35846. function LargeSymbolDraw() {
  35847. this.group = new Group();
  35848. }
  35849. var largeSymbolProto = LargeSymbolDraw.prototype;
  35850. largeSymbolProto.isPersistent = function () {
  35851. return !this._incremental;
  35852. };
  35853. /**
  35854. * Update symbols draw by new data
  35855. * @param {module:echarts/data/List} data
  35856. */
  35857. largeSymbolProto.updateData = function (data) {
  35858. this.group.removeAll();
  35859. var symbolEl = new LargeSymbolPath({
  35860. rectHover: true,
  35861. cursor: 'default'
  35862. });
  35863. symbolEl.setShape({
  35864. points: data.getLayout('symbolPoints')
  35865. });
  35866. this._setCommon(symbolEl, data);
  35867. this.group.add(symbolEl);
  35868. this._incremental = null;
  35869. };
  35870. largeSymbolProto.updateLayout = function (data) {
  35871. if (this._incremental) {
  35872. return;
  35873. }
  35874. var points = data.getLayout('symbolPoints');
  35875. this.group.eachChild(function (child) {
  35876. if (child.startIndex != null) {
  35877. var len = (child.endIndex - child.startIndex) * 2;
  35878. var byteOffset = child.startIndex * 4 * 2;
  35879. points = new Float32Array(points.buffer, byteOffset, len);
  35880. }
  35881. child.setShape('points', points);
  35882. });
  35883. };
  35884. largeSymbolProto.incrementalPrepareUpdate = function (data) {
  35885. this.group.removeAll();
  35886. this._clearIncremental();
  35887. // Only use incremental displayables when data amount is larger than 2 million.
  35888. // PENDING Incremental data?
  35889. if (data.count() > 2e6) {
  35890. if (!this._incremental) {
  35891. this._incremental = new IncrementalDisplayble({
  35892. silent: true
  35893. });
  35894. }
  35895. this.group.add(this._incremental);
  35896. }
  35897. else {
  35898. this._incremental = null;
  35899. }
  35900. };
  35901. largeSymbolProto.incrementalUpdate = function (taskParams, data) {
  35902. var symbolEl;
  35903. if (this._incremental) {
  35904. symbolEl = new LargeSymbolPath();
  35905. this._incremental.addDisplayable(symbolEl, true);
  35906. }
  35907. else {
  35908. symbolEl = new LargeSymbolPath({
  35909. rectHover: true,
  35910. cursor: 'default',
  35911. startIndex: taskParams.start,
  35912. endIndex: taskParams.end
  35913. });
  35914. symbolEl.incremental = true;
  35915. this.group.add(symbolEl);
  35916. }
  35917. symbolEl.setShape({
  35918. points: data.getLayout('symbolPoints')
  35919. });
  35920. this._setCommon(symbolEl, data, !!this._incremental);
  35921. };
  35922. largeSymbolProto._setCommon = function (symbolEl, data, isIncremental) {
  35923. var hostModel = data.hostModel;
  35924. // TODO
  35925. // if (data.hasItemVisual.symbolSize) {
  35926. // // TODO typed array?
  35927. // symbolEl.setShape('sizes', data.mapArray(
  35928. // function (idx) {
  35929. // var size = data.getItemVisual(idx, 'symbolSize');
  35930. // return (size instanceof Array) ? size : [size, size];
  35931. // }
  35932. // ));
  35933. // }
  35934. // else {
  35935. var size = data.getVisual('symbolSize');
  35936. symbolEl.setShape('size', (size instanceof Array) ? size : [size, size]);
  35937. // }
  35938. // Create symbolProxy to build path for each data
  35939. symbolEl.symbolProxy = createSymbol(
  35940. data.getVisual('symbol'), 0, 0, 0, 0
  35941. );
  35942. // Use symbolProxy setColor method
  35943. symbolEl.setColor = symbolEl.symbolProxy.setColor;
  35944. var extrudeShadow = symbolEl.shape.size[0] < BOOST_SIZE_THRESHOLD;
  35945. symbolEl.useStyle(
  35946. // Draw shadow when doing fillRect is extremely slow.
  35947. hostModel.getModel('itemStyle').getItemStyle(extrudeShadow ? ['color', 'shadowBlur', 'shadowColor'] : ['color'])
  35948. );
  35949. var visualColor = data.getVisual('color');
  35950. if (visualColor) {
  35951. symbolEl.setColor(visualColor);
  35952. }
  35953. if (!isIncremental) {
  35954. // Enable tooltip
  35955. // PENDING May have performance issue when path is extremely large
  35956. symbolEl.seriesIndex = hostModel.seriesIndex;
  35957. symbolEl.on('mousemove', function (e) {
  35958. symbolEl.dataIndex = null;
  35959. var dataIndex = symbolEl.findDataIndex(e.offsetX, e.offsetY);
  35960. if (dataIndex >= 0) {
  35961. // Provide dataIndex for tooltip
  35962. symbolEl.dataIndex = dataIndex + (symbolEl.startIndex || 0);
  35963. }
  35964. });
  35965. }
  35966. };
  35967. largeSymbolProto.remove = function () {
  35968. this._clearIncremental();
  35969. this._incremental = null;
  35970. this.group.removeAll();
  35971. };
  35972. largeSymbolProto._clearIncremental = function () {
  35973. var incremental = this._incremental;
  35974. if (incremental) {
  35975. incremental.clearDisplaybles();
  35976. }
  35977. };
  35978. /*
  35979. * Licensed to the Apache Software Foundation (ASF) under one
  35980. * or more contributor license agreements. See the NOTICE file
  35981. * distributed with this work for additional information
  35982. * regarding copyright ownership. The ASF licenses this file
  35983. * to you under the Apache License, Version 2.0 (the
  35984. * "License"); you may not use this file except in compliance
  35985. * with the License. You may obtain a copy of the License at
  35986. *
  35987. * http://www.apache.org/licenses/LICENSE-2.0
  35988. *
  35989. * Unless required by applicable law or agreed to in writing,
  35990. * software distributed under the License is distributed on an
  35991. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35992. * KIND, either express or implied. See the License for the
  35993. * specific language governing permissions and limitations
  35994. * under the License.
  35995. */
  35996. extendChartView({
  35997. type: 'scatter',
  35998. render: function (seriesModel, ecModel, api) {
  35999. var data = seriesModel.getData();
  36000. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  36001. symbolDraw.updateData(data);
  36002. this._finished = true;
  36003. },
  36004. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  36005. var data = seriesModel.getData();
  36006. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  36007. symbolDraw.incrementalPrepareUpdate(data);
  36008. this._finished = false;
  36009. },
  36010. incrementalRender: function (taskParams, seriesModel, ecModel) {
  36011. this._symbolDraw.incrementalUpdate(taskParams, seriesModel.getData());
  36012. this._finished = taskParams.end === seriesModel.getData().count();
  36013. },
  36014. updateTransform: function (seriesModel, ecModel, api) {
  36015. var data = seriesModel.getData();
  36016. // Must mark group dirty and make sure the incremental layer will be cleared
  36017. // PENDING
  36018. this.group.dirty();
  36019. if (!this._finished || data.count() > 1e4 || !this._symbolDraw.isPersistent()) {
  36020. return {
  36021. update: true
  36022. };
  36023. }
  36024. else {
  36025. var res = pointsLayout().reset(seriesModel);
  36026. if (res.progress) {
  36027. res.progress({ start: 0, end: data.count() }, data);
  36028. }
  36029. this._symbolDraw.updateLayout(data);
  36030. }
  36031. },
  36032. _updateSymbolDraw: function (data, seriesModel) {
  36033. var symbolDraw = this._symbolDraw;
  36034. var pipelineContext = seriesModel.pipelineContext;
  36035. var isLargeDraw = pipelineContext.large;
  36036. if (!symbolDraw || isLargeDraw !== this._isLargeDraw) {
  36037. symbolDraw && symbolDraw.remove();
  36038. symbolDraw = this._symbolDraw = isLargeDraw
  36039. ? new LargeSymbolDraw()
  36040. : new SymbolDraw();
  36041. this._isLargeDraw = isLargeDraw;
  36042. this.group.removeAll();
  36043. }
  36044. this.group.add(symbolDraw.group);
  36045. return symbolDraw;
  36046. },
  36047. remove: function (ecModel, api) {
  36048. this._symbolDraw && this._symbolDraw.remove(true);
  36049. this._symbolDraw = null;
  36050. },
  36051. dispose: function () {}
  36052. });
  36053. /*
  36054. * Licensed to the Apache Software Foundation (ASF) under one
  36055. * or more contributor license agreements. See the NOTICE file
  36056. * distributed with this work for additional information
  36057. * regarding copyright ownership. The ASF licenses this file
  36058. * to you under the Apache License, Version 2.0 (the
  36059. * "License"); you may not use this file except in compliance
  36060. * with the License. You may obtain a copy of the License at
  36061. *
  36062. * http://www.apache.org/licenses/LICENSE-2.0
  36063. *
  36064. * Unless required by applicable law or agreed to in writing,
  36065. * software distributed under the License is distributed on an
  36066. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36067. * KIND, either express or implied. See the License for the
  36068. * specific language governing permissions and limitations
  36069. * under the License.
  36070. */
  36071. // import * as zrUtil from 'zrender/src/core/util';
  36072. // In case developer forget to include grid component
  36073. registerVisual(visualSymbol('scatter', 'circle'));
  36074. registerLayout(pointsLayout('scatter'));
  36075. // echarts.registerProcessor(function (ecModel, api) {
  36076. // ecModel.eachSeriesByType('scatter', function (seriesModel) {
  36077. // var data = seriesModel.getData();
  36078. // var coordSys = seriesModel.coordinateSystem;
  36079. // if (coordSys.type !== 'geo') {
  36080. // return;
  36081. // }
  36082. // var startPt = coordSys.pointToData([0, 0]);
  36083. // var endPt = coordSys.pointToData([api.getWidth(), api.getHeight()]);
  36084. // var dims = zrUtil.map(coordSys.dimensions, function (dim) {
  36085. // return data.mapDimension(dim);
  36086. // });
  36087. // var range = {};
  36088. // range[dims[0]] = [Math.min(startPt[0], endPt[0]), Math.max(startPt[0], endPt[0])];
  36089. // range[dims[1]] = [Math.min(startPt[1], endPt[1]), Math.max(startPt[1], endPt[1])];
  36090. // data.selectRange(range);
  36091. // });
  36092. // });
  36093. /*
  36094. * Licensed to the Apache Software Foundation (ASF) under one
  36095. * or more contributor license agreements. See the NOTICE file
  36096. * distributed with this work for additional information
  36097. * regarding copyright ownership. The ASF licenses this file
  36098. * to you under the Apache License, Version 2.0 (the
  36099. * "License"); you may not use this file except in compliance
  36100. * with the License. You may obtain a copy of the License at
  36101. *
  36102. * http://www.apache.org/licenses/LICENSE-2.0
  36103. *
  36104. * Unless required by applicable law or agreed to in writing,
  36105. * software distributed under the License is distributed on an
  36106. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36107. * KIND, either express or implied. See the License for the
  36108. * specific language governing permissions and limitations
  36109. * under the License.
  36110. */
  36111. function IndicatorAxis(dim, scale, radiusExtent) {
  36112. Axis.call(this, dim, scale, radiusExtent);
  36113. /**
  36114. * Axis type
  36115. * - 'category'
  36116. * - 'value'
  36117. * - 'time'
  36118. * - 'log'
  36119. * @type {string}
  36120. */
  36121. this.type = 'value';
  36122. this.angle = 0;
  36123. /**
  36124. * Indicator name
  36125. * @type {string}
  36126. */
  36127. this.name = '';
  36128. /**
  36129. * @type {module:echarts/model/Model}
  36130. */
  36131. this.model;
  36132. }
  36133. inherits(IndicatorAxis, Axis);
  36134. /*
  36135. * Licensed to the Apache Software Foundation (ASF) under one
  36136. * or more contributor license agreements. See the NOTICE file
  36137. * distributed with this work for additional information
  36138. * regarding copyright ownership. The ASF licenses this file
  36139. * to you under the Apache License, Version 2.0 (the
  36140. * "License"); you may not use this file except in compliance
  36141. * with the License. You may obtain a copy of the License at
  36142. *
  36143. * http://www.apache.org/licenses/LICENSE-2.0
  36144. *
  36145. * Unless required by applicable law or agreed to in writing,
  36146. * software distributed under the License is distributed on an
  36147. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36148. * KIND, either express or implied. See the License for the
  36149. * specific language governing permissions and limitations
  36150. * under the License.
  36151. */
  36152. // TODO clockwise
  36153. function Radar(radarModel, ecModel, api) {
  36154. this._model = radarModel;
  36155. /**
  36156. * Radar dimensions
  36157. * @type {Array.<string>}
  36158. */
  36159. this.dimensions = [];
  36160. this._indicatorAxes = map(radarModel.getIndicatorModels(), function (indicatorModel, idx) {
  36161. var dim = 'indicator_' + idx;
  36162. var indicatorAxis = new IndicatorAxis(dim, new IntervalScale());
  36163. indicatorAxis.name = indicatorModel.get('name');
  36164. // Inject model and axis
  36165. indicatorAxis.model = indicatorModel;
  36166. indicatorModel.axis = indicatorAxis;
  36167. this.dimensions.push(dim);
  36168. return indicatorAxis;
  36169. }, this);
  36170. this.resize(radarModel, api);
  36171. /**
  36172. * @type {number}
  36173. * @readOnly
  36174. */
  36175. this.cx;
  36176. /**
  36177. * @type {number}
  36178. * @readOnly
  36179. */
  36180. this.cy;
  36181. /**
  36182. * @type {number}
  36183. * @readOnly
  36184. */
  36185. this.r;
  36186. /**
  36187. * @type {number}
  36188. * @readOnly
  36189. */
  36190. this.startAngle;
  36191. }
  36192. Radar.prototype.getIndicatorAxes = function () {
  36193. return this._indicatorAxes;
  36194. };
  36195. Radar.prototype.dataToPoint = function (value, indicatorIndex) {
  36196. var indicatorAxis = this._indicatorAxes[indicatorIndex];
  36197. return this.coordToPoint(indicatorAxis.dataToCoord(value), indicatorIndex);
  36198. };
  36199. Radar.prototype.coordToPoint = function (coord, indicatorIndex) {
  36200. var indicatorAxis = this._indicatorAxes[indicatorIndex];
  36201. var angle = indicatorAxis.angle;
  36202. var x = this.cx + coord * Math.cos(angle);
  36203. var y = this.cy - coord * Math.sin(angle);
  36204. return [x, y];
  36205. };
  36206. Radar.prototype.pointToData = function (pt) {
  36207. var dx = pt[0] - this.cx;
  36208. var dy = pt[1] - this.cy;
  36209. var radius = Math.sqrt(dx * dx + dy * dy);
  36210. dx /= radius;
  36211. dy /= radius;
  36212. var radian = Math.atan2(-dy, dx);
  36213. // Find the closest angle
  36214. // FIXME index can calculated directly
  36215. var minRadianDiff = Infinity;
  36216. var closestAxis;
  36217. var closestAxisIdx = -1;
  36218. for (var i = 0; i < this._indicatorAxes.length; i++) {
  36219. var indicatorAxis = this._indicatorAxes[i];
  36220. var diff = Math.abs(radian - indicatorAxis.angle);
  36221. if (diff < minRadianDiff) {
  36222. closestAxis = indicatorAxis;
  36223. closestAxisIdx = i;
  36224. minRadianDiff = diff;
  36225. }
  36226. }
  36227. return [closestAxisIdx, +(closestAxis && closestAxis.coodToData(radius))];
  36228. };
  36229. Radar.prototype.resize = function (radarModel, api) {
  36230. var center = radarModel.get('center');
  36231. var viewWidth = api.getWidth();
  36232. var viewHeight = api.getHeight();
  36233. var viewSize = Math.min(viewWidth, viewHeight) / 2;
  36234. this.cx = parsePercent$1(center[0], viewWidth);
  36235. this.cy = parsePercent$1(center[1], viewHeight);
  36236. this.startAngle = radarModel.get('startAngle') * Math.PI / 180;
  36237. this.r = parsePercent$1(radarModel.get('radius'), viewSize);
  36238. each$1(this._indicatorAxes, function (indicatorAxis, idx) {
  36239. indicatorAxis.setExtent(0, this.r);
  36240. var angle = (this.startAngle + idx * Math.PI * 2 / this._indicatorAxes.length);
  36241. // Normalize to [-PI, PI]
  36242. angle = Math.atan2(Math.sin(angle), Math.cos(angle));
  36243. indicatorAxis.angle = angle;
  36244. }, this);
  36245. };
  36246. Radar.prototype.update = function (ecModel, api) {
  36247. var indicatorAxes = this._indicatorAxes;
  36248. var radarModel = this._model;
  36249. each$1(indicatorAxes, function (indicatorAxis) {
  36250. indicatorAxis.scale.setExtent(Infinity, -Infinity);
  36251. });
  36252. ecModel.eachSeriesByType('radar', function (radarSeries, idx) {
  36253. if (radarSeries.get('coordinateSystem') !== 'radar'
  36254. || ecModel.getComponent('radar', radarSeries.get('radarIndex')) !== radarModel
  36255. ) {
  36256. return;
  36257. }
  36258. var data = radarSeries.getData();
  36259. each$1(indicatorAxes, function (indicatorAxis) {
  36260. indicatorAxis.scale.unionExtentFromData(data, data.mapDimension(indicatorAxis.dim));
  36261. });
  36262. }, this);
  36263. var splitNumber = radarModel.get('splitNumber');
  36264. function increaseInterval(interval) {
  36265. var exp10 = Math.pow(10, Math.floor(Math.log(interval) / Math.LN10));
  36266. // Increase interval
  36267. var f = interval / exp10;
  36268. if (f === 2) {
  36269. f = 5;
  36270. }
  36271. else { // f is 2 or 5
  36272. f *= 2;
  36273. }
  36274. return f * exp10;
  36275. }
  36276. // Force all the axis fixing the maxSplitNumber.
  36277. each$1(indicatorAxes, function (indicatorAxis, idx) {
  36278. var rawExtent = getScaleExtent(indicatorAxis.scale, indicatorAxis.model);
  36279. niceScaleExtent(indicatorAxis.scale, indicatorAxis.model);
  36280. var axisModel = indicatorAxis.model;
  36281. var scale = indicatorAxis.scale;
  36282. var fixedMin = axisModel.getMin();
  36283. var fixedMax = axisModel.getMax();
  36284. var interval = scale.getInterval();
  36285. if (fixedMin != null && fixedMax != null) {
  36286. // User set min, max, divide to get new interval
  36287. scale.setExtent(+fixedMin, +fixedMax);
  36288. scale.setInterval(
  36289. (fixedMax - fixedMin) / splitNumber
  36290. );
  36291. }
  36292. else if (fixedMin != null) {
  36293. var max;
  36294. // User set min, expand extent on the other side
  36295. do {
  36296. max = fixedMin + interval * splitNumber;
  36297. scale.setExtent(+fixedMin, max);
  36298. // Interval must been set after extent
  36299. // FIXME
  36300. scale.setInterval(interval);
  36301. interval = increaseInterval(interval);
  36302. } while (max < rawExtent[1] && isFinite(max) && isFinite(rawExtent[1]));
  36303. }
  36304. else if (fixedMax != null) {
  36305. var min;
  36306. // User set min, expand extent on the other side
  36307. do {
  36308. min = fixedMax - interval * splitNumber;
  36309. scale.setExtent(min, +fixedMax);
  36310. scale.setInterval(interval);
  36311. interval = increaseInterval(interval);
  36312. } while (min > rawExtent[0] && isFinite(min) && isFinite(rawExtent[0]));
  36313. }
  36314. else {
  36315. var nicedSplitNumber = scale.getTicks().length - 1;
  36316. if (nicedSplitNumber > splitNumber) {
  36317. interval = increaseInterval(interval);
  36318. }
  36319. // PENDING
  36320. var center = Math.round((rawExtent[0] + rawExtent[1]) / 2 / interval) * interval;
  36321. var halfSplitNumber = Math.round(splitNumber / 2);
  36322. scale.setExtent(
  36323. round$1(center - halfSplitNumber * interval),
  36324. round$1(center + (splitNumber - halfSplitNumber) * interval)
  36325. );
  36326. scale.setInterval(interval);
  36327. }
  36328. });
  36329. };
  36330. /**
  36331. * Radar dimensions is based on the data
  36332. * @type {Array}
  36333. */
  36334. Radar.dimensions = [];
  36335. Radar.create = function (ecModel, api) {
  36336. var radarList = [];
  36337. ecModel.eachComponent('radar', function (radarModel) {
  36338. var radar = new Radar(radarModel, ecModel, api);
  36339. radarList.push(radar);
  36340. radarModel.coordinateSystem = radar;
  36341. });
  36342. ecModel.eachSeriesByType('radar', function (radarSeries) {
  36343. if (radarSeries.get('coordinateSystem') === 'radar') {
  36344. // Inject coordinate system
  36345. radarSeries.coordinateSystem = radarList[radarSeries.get('radarIndex') || 0];
  36346. }
  36347. });
  36348. return radarList;
  36349. };
  36350. CoordinateSystemManager.register('radar', Radar);
  36351. /*
  36352. * Licensed to the Apache Software Foundation (ASF) under one
  36353. * or more contributor license agreements. See the NOTICE file
  36354. * distributed with this work for additional information
  36355. * regarding copyright ownership. The ASF licenses this file
  36356. * to you under the Apache License, Version 2.0 (the
  36357. * "License"); you may not use this file except in compliance
  36358. * with the License. You may obtain a copy of the License at
  36359. *
  36360. * http://www.apache.org/licenses/LICENSE-2.0
  36361. *
  36362. * Unless required by applicable law or agreed to in writing,
  36363. * software distributed under the License is distributed on an
  36364. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36365. * KIND, either express or implied. See the License for the
  36366. * specific language governing permissions and limitations
  36367. * under the License.
  36368. */
  36369. var valueAxisDefault = axisDefault.valueAxis;
  36370. function defaultsShow(opt, show) {
  36371. return defaults({
  36372. show: show
  36373. }, opt);
  36374. }
  36375. var RadarModel = extendComponentModel({
  36376. type: 'radar',
  36377. optionUpdated: function () {
  36378. var boundaryGap = this.get('boundaryGap');
  36379. var splitNumber = this.get('splitNumber');
  36380. var scale = this.get('scale');
  36381. var axisLine = this.get('axisLine');
  36382. var axisTick = this.get('axisTick');
  36383. var axisLabel = this.get('axisLabel');
  36384. var nameTextStyle = this.get('name');
  36385. var showName = this.get('name.show');
  36386. var nameFormatter = this.get('name.formatter');
  36387. var nameGap = this.get('nameGap');
  36388. var triggerEvent = this.get('triggerEvent');
  36389. var indicatorModels = map(this.get('indicator') || [], function (indicatorOpt) {
  36390. // PENDING
  36391. if (indicatorOpt.max != null && indicatorOpt.max > 0 && !indicatorOpt.min) {
  36392. indicatorOpt.min = 0;
  36393. }
  36394. else if (indicatorOpt.min != null && indicatorOpt.min < 0 && !indicatorOpt.max) {
  36395. indicatorOpt.max = 0;
  36396. }
  36397. var iNameTextStyle = nameTextStyle;
  36398. if(indicatorOpt.color != null) {
  36399. iNameTextStyle = defaults({color: indicatorOpt.color}, nameTextStyle);
  36400. }
  36401. // Use same configuration
  36402. indicatorOpt = merge(clone(indicatorOpt), {
  36403. boundaryGap: boundaryGap,
  36404. splitNumber: splitNumber,
  36405. scale: scale,
  36406. axisLine: axisLine,
  36407. axisTick: axisTick,
  36408. axisLabel: axisLabel,
  36409. // Competitable with 2 and use text
  36410. name: indicatorOpt.text,
  36411. nameLocation: 'end',
  36412. nameGap: nameGap,
  36413. // min: 0,
  36414. nameTextStyle: iNameTextStyle,
  36415. triggerEvent: triggerEvent
  36416. }, false);
  36417. if (!showName) {
  36418. indicatorOpt.name = '';
  36419. }
  36420. if (typeof nameFormatter === 'string') {
  36421. var indName = indicatorOpt.name;
  36422. indicatorOpt.name = nameFormatter.replace('{value}', indName != null ? indName : '');
  36423. }
  36424. else if (typeof nameFormatter === 'function') {
  36425. indicatorOpt.name = nameFormatter(
  36426. indicatorOpt.name, indicatorOpt
  36427. );
  36428. }
  36429. var model = extend(
  36430. new Model(indicatorOpt, null, this.ecModel),
  36431. axisModelCommonMixin
  36432. );
  36433. // For triggerEvent.
  36434. model.mainType = 'radar';
  36435. model.componentIndex = this.componentIndex;
  36436. return model;
  36437. }, this);
  36438. this.getIndicatorModels = function () {
  36439. return indicatorModels;
  36440. };
  36441. },
  36442. defaultOption: {
  36443. zlevel: 0,
  36444. z: 0,
  36445. center: ['50%', '50%'],
  36446. radius: '75%',
  36447. startAngle: 90,
  36448. name: {
  36449. show: true
  36450. // formatter: null
  36451. // textStyle: {}
  36452. },
  36453. boundaryGap: [0, 0],
  36454. splitNumber: 5,
  36455. nameGap: 15,
  36456. scale: false,
  36457. // Polygon or circle
  36458. shape: 'polygon',
  36459. axisLine: merge(
  36460. {
  36461. lineStyle: {
  36462. color: '#bbb'
  36463. }
  36464. },
  36465. valueAxisDefault.axisLine
  36466. ),
  36467. axisLabel: defaultsShow(valueAxisDefault.axisLabel, false),
  36468. axisTick: defaultsShow(valueAxisDefault.axisTick, false),
  36469. splitLine: defaultsShow(valueAxisDefault.splitLine, true),
  36470. splitArea: defaultsShow(valueAxisDefault.splitArea, true),
  36471. // {text, min, max}
  36472. indicator: []
  36473. }
  36474. });
  36475. /*
  36476. * Licensed to the Apache Software Foundation (ASF) under one
  36477. * or more contributor license agreements. See the NOTICE file
  36478. * distributed with this work for additional information
  36479. * regarding copyright ownership. The ASF licenses this file
  36480. * to you under the Apache License, Version 2.0 (the
  36481. * "License"); you may not use this file except in compliance
  36482. * with the License. You may obtain a copy of the License at
  36483. *
  36484. * http://www.apache.org/licenses/LICENSE-2.0
  36485. *
  36486. * Unless required by applicable law or agreed to in writing,
  36487. * software distributed under the License is distributed on an
  36488. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36489. * KIND, either express or implied. See the License for the
  36490. * specific language governing permissions and limitations
  36491. * under the License.
  36492. */
  36493. var axisBuilderAttrs$1 = [
  36494. 'axisLine', 'axisTickLabel', 'axisName'
  36495. ];
  36496. extendComponentView({
  36497. type: 'radar',
  36498. render: function (radarModel, ecModel, api) {
  36499. var group = this.group;
  36500. group.removeAll();
  36501. this._buildAxes(radarModel);
  36502. this._buildSplitLineAndArea(radarModel);
  36503. },
  36504. _buildAxes: function (radarModel) {
  36505. var radar = radarModel.coordinateSystem;
  36506. var indicatorAxes = radar.getIndicatorAxes();
  36507. var axisBuilders = map(indicatorAxes, function (indicatorAxis) {
  36508. var axisBuilder = new AxisBuilder(indicatorAxis.model, {
  36509. position: [radar.cx, radar.cy],
  36510. rotation: indicatorAxis.angle,
  36511. labelDirection: -1,
  36512. tickDirection: -1,
  36513. nameDirection: 1
  36514. });
  36515. return axisBuilder;
  36516. });
  36517. each$1(axisBuilders, function (axisBuilder) {
  36518. each$1(axisBuilderAttrs$1, axisBuilder.add, axisBuilder);
  36519. this.group.add(axisBuilder.getGroup());
  36520. }, this);
  36521. },
  36522. _buildSplitLineAndArea: function (radarModel) {
  36523. var radar = radarModel.coordinateSystem;
  36524. var indicatorAxes = radar.getIndicatorAxes();
  36525. if (!indicatorAxes.length) {
  36526. return;
  36527. }
  36528. var shape = radarModel.get('shape');
  36529. var splitLineModel = radarModel.getModel('splitLine');
  36530. var splitAreaModel = radarModel.getModel('splitArea');
  36531. var lineStyleModel = splitLineModel.getModel('lineStyle');
  36532. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  36533. var showSplitLine = splitLineModel.get('show');
  36534. var showSplitArea = splitAreaModel.get('show');
  36535. var splitLineColors = lineStyleModel.get('color');
  36536. var splitAreaColors = areaStyleModel.get('color');
  36537. splitLineColors = isArray(splitLineColors) ? splitLineColors : [splitLineColors];
  36538. splitAreaColors = isArray(splitAreaColors) ? splitAreaColors : [splitAreaColors];
  36539. var splitLines = [];
  36540. var splitAreas = [];
  36541. function getColorIndex(areaOrLine, areaOrLineColorList, idx) {
  36542. var colorIndex = idx % areaOrLineColorList.length;
  36543. areaOrLine[colorIndex] = areaOrLine[colorIndex] || [];
  36544. return colorIndex;
  36545. }
  36546. if (shape === 'circle') {
  36547. var ticksRadius = indicatorAxes[0].getTicksCoords();
  36548. var cx = radar.cx;
  36549. var cy = radar.cy;
  36550. for (var i = 0; i < ticksRadius.length; i++) {
  36551. if (showSplitLine) {
  36552. var colorIndex = getColorIndex(splitLines, splitLineColors, i);
  36553. splitLines[colorIndex].push(new Circle({
  36554. shape: {
  36555. cx: cx,
  36556. cy: cy,
  36557. r: ticksRadius[i].coord
  36558. }
  36559. }));
  36560. }
  36561. if (showSplitArea && i < ticksRadius.length - 1) {
  36562. var colorIndex = getColorIndex(splitAreas, splitAreaColors, i);
  36563. splitAreas[colorIndex].push(new Ring({
  36564. shape: {
  36565. cx: cx,
  36566. cy: cy,
  36567. r0: ticksRadius[i].coord,
  36568. r: ticksRadius[i + 1].coord
  36569. }
  36570. }));
  36571. }
  36572. }
  36573. }
  36574. // Polyyon
  36575. else {
  36576. var realSplitNumber;
  36577. var axesTicksPoints = map(indicatorAxes, function (indicatorAxis, idx) {
  36578. var ticksCoords = indicatorAxis.getTicksCoords();
  36579. realSplitNumber = realSplitNumber == null
  36580. ? ticksCoords.length - 1
  36581. : Math.min(ticksCoords.length - 1, realSplitNumber);
  36582. return map(ticksCoords, function (tickCoord) {
  36583. return radar.coordToPoint(tickCoord.coord, idx);
  36584. });
  36585. });
  36586. var prevPoints = [];
  36587. for (var i = 0; i <= realSplitNumber; i++) {
  36588. var points = [];
  36589. for (var j = 0; j < indicatorAxes.length; j++) {
  36590. points.push(axesTicksPoints[j][i]);
  36591. }
  36592. // Close
  36593. if (points[0]) {
  36594. points.push(points[0].slice());
  36595. }
  36596. else {
  36597. if (__DEV__) {
  36598. console.error('Can\'t draw value axis ' + i);
  36599. }
  36600. }
  36601. if (showSplitLine) {
  36602. var colorIndex = getColorIndex(splitLines, splitLineColors, i);
  36603. splitLines[colorIndex].push(new Polyline({
  36604. shape: {
  36605. points: points
  36606. }
  36607. }));
  36608. }
  36609. if (showSplitArea && prevPoints) {
  36610. var colorIndex = getColorIndex(splitAreas, splitAreaColors, i - 1);
  36611. splitAreas[colorIndex].push(new Polygon({
  36612. shape: {
  36613. points: points.concat(prevPoints)
  36614. }
  36615. }));
  36616. }
  36617. prevPoints = points.slice().reverse();
  36618. }
  36619. }
  36620. var lineStyle = lineStyleModel.getLineStyle();
  36621. var areaStyle = areaStyleModel.getAreaStyle();
  36622. // Add splitArea before splitLine
  36623. each$1(splitAreas, function (splitAreas, idx) {
  36624. this.group.add(mergePath(
  36625. splitAreas, {
  36626. style: defaults({
  36627. stroke: 'none',
  36628. fill: splitAreaColors[idx % splitAreaColors.length]
  36629. }, areaStyle),
  36630. silent: true
  36631. }
  36632. ));
  36633. }, this);
  36634. each$1(splitLines, function (splitLines, idx) {
  36635. this.group.add(mergePath(
  36636. splitLines, {
  36637. style: defaults({
  36638. fill: 'none',
  36639. stroke: splitLineColors[idx % splitLineColors.length]
  36640. }, lineStyle),
  36641. silent: true
  36642. }
  36643. ));
  36644. }, this);
  36645. }
  36646. });
  36647. /*
  36648. * Licensed to the Apache Software Foundation (ASF) under one
  36649. * or more contributor license agreements. See the NOTICE file
  36650. * distributed with this work for additional information
  36651. * regarding copyright ownership. The ASF licenses this file
  36652. * to you under the Apache License, Version 2.0 (the
  36653. * "License"); you may not use this file except in compliance
  36654. * with the License. You may obtain a copy of the License at
  36655. *
  36656. * http://www.apache.org/licenses/LICENSE-2.0
  36657. *
  36658. * Unless required by applicable law or agreed to in writing,
  36659. * software distributed under the License is distributed on an
  36660. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36661. * KIND, either express or implied. See the License for the
  36662. * specific language governing permissions and limitations
  36663. * under the License.
  36664. */
  36665. /*
  36666. * Licensed to the Apache Software Foundation (ASF) under one
  36667. * or more contributor license agreements. See the NOTICE file
  36668. * distributed with this work for additional information
  36669. * regarding copyright ownership. The ASF licenses this file
  36670. * to you under the Apache License, Version 2.0 (the
  36671. * "License"); you may not use this file except in compliance
  36672. * with the License. You may obtain a copy of the License at
  36673. *
  36674. * http://www.apache.org/licenses/LICENSE-2.0
  36675. *
  36676. * Unless required by applicable law or agreed to in writing,
  36677. * software distributed under the License is distributed on an
  36678. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36679. * KIND, either express or implied. See the License for the
  36680. * specific language governing permissions and limitations
  36681. * under the License.
  36682. */
  36683. var RadarSeries = SeriesModel.extend({
  36684. type: 'series.radar',
  36685. dependencies: ['radar'],
  36686. // Overwrite
  36687. init: function (option) {
  36688. RadarSeries.superApply(this, 'init', arguments);
  36689. // Enable legend selection for each data item
  36690. // Use a function instead of direct access because data reference may changed
  36691. this.legendDataProvider = function () {
  36692. return this.getRawData();
  36693. };
  36694. },
  36695. getInitialData: function (option, ecModel) {
  36696. return createListSimply(this, {
  36697. generateCoord: 'indicator_',
  36698. generateCoordCount: Infinity
  36699. });
  36700. },
  36701. formatTooltip: function (dataIndex) {
  36702. var data = this.getData();
  36703. var coordSys = this.coordinateSystem;
  36704. var indicatorAxes = coordSys.getIndicatorAxes();
  36705. var name = this.getData().getName(dataIndex);
  36706. return encodeHTML(name === '' ? this.name : name) + '<br/>'
  36707. + map(indicatorAxes, function (axis, idx) {
  36708. var val = data.get(data.mapDimension(axis.dim), dataIndex);
  36709. return encodeHTML(axis.name + ' : ' + val);
  36710. }).join('<br />');
  36711. },
  36712. defaultOption: {
  36713. zlevel: 0,
  36714. z: 2,
  36715. coordinateSystem: 'radar',
  36716. legendHoverLink: true,
  36717. radarIndex: 0,
  36718. lineStyle: {
  36719. width: 2,
  36720. type: 'solid'
  36721. },
  36722. label: {
  36723. position: 'top'
  36724. },
  36725. // areaStyle: {
  36726. // },
  36727. // itemStyle: {}
  36728. symbol: 'emptyCircle',
  36729. symbolSize: 4
  36730. // symbolRotate: null
  36731. }
  36732. });
  36733. /*
  36734. * Licensed to the Apache Software Foundation (ASF) under one
  36735. * or more contributor license agreements. See the NOTICE file
  36736. * distributed with this work for additional information
  36737. * regarding copyright ownership. The ASF licenses this file
  36738. * to you under the Apache License, Version 2.0 (the
  36739. * "License"); you may not use this file except in compliance
  36740. * with the License. You may obtain a copy of the License at
  36741. *
  36742. * http://www.apache.org/licenses/LICENSE-2.0
  36743. *
  36744. * Unless required by applicable law or agreed to in writing,
  36745. * software distributed under the License is distributed on an
  36746. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36747. * KIND, either express or implied. See the License for the
  36748. * specific language governing permissions and limitations
  36749. * under the License.
  36750. */
  36751. function normalizeSymbolSize(symbolSize) {
  36752. if (!isArray(symbolSize)) {
  36753. symbolSize = [+symbolSize, +symbolSize];
  36754. }
  36755. return symbolSize;
  36756. }
  36757. extendChartView({
  36758. type: 'radar',
  36759. render: function (seriesModel, ecModel, api) {
  36760. var polar = seriesModel.coordinateSystem;
  36761. var group = this.group;
  36762. var data = seriesModel.getData();
  36763. var oldData = this._data;
  36764. function createSymbol$$1(data, idx) {
  36765. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  36766. var color = data.getItemVisual(idx, 'color');
  36767. if (symbolType === 'none') {
  36768. return;
  36769. }
  36770. var symbolSize = normalizeSymbolSize(
  36771. data.getItemVisual(idx, 'symbolSize')
  36772. );
  36773. var symbolPath = createSymbol(
  36774. symbolType, -1, -1, 2, 2, color
  36775. );
  36776. symbolPath.attr({
  36777. style: {
  36778. strokeNoScale: true
  36779. },
  36780. z2: 100,
  36781. scale: [symbolSize[0] / 2, symbolSize[1] / 2]
  36782. });
  36783. return symbolPath;
  36784. }
  36785. function updateSymbols(oldPoints, newPoints, symbolGroup, data, idx, isInit) {
  36786. // Simply rerender all
  36787. symbolGroup.removeAll();
  36788. for (var i = 0; i < newPoints.length - 1; i++) {
  36789. var symbolPath = createSymbol$$1(data, idx);
  36790. if (symbolPath) {
  36791. symbolPath.__dimIdx = i;
  36792. if (oldPoints[i]) {
  36793. symbolPath.attr('position', oldPoints[i]);
  36794. graphic[isInit ? 'initProps' : 'updateProps'](
  36795. symbolPath, {
  36796. position: newPoints[i]
  36797. }, seriesModel, idx
  36798. );
  36799. }
  36800. else {
  36801. symbolPath.attr('position', newPoints[i]);
  36802. }
  36803. symbolGroup.add(symbolPath);
  36804. }
  36805. }
  36806. }
  36807. function getInitialPoints(points) {
  36808. return map(points, function (pt) {
  36809. return [polar.cx, polar.cy];
  36810. });
  36811. }
  36812. data.diff(oldData)
  36813. .add(function (idx) {
  36814. var points = data.getItemLayout(idx);
  36815. if (!points) {
  36816. return;
  36817. }
  36818. var polygon = new Polygon();
  36819. var polyline = new Polyline();
  36820. var target = {
  36821. shape: {
  36822. points: points
  36823. }
  36824. };
  36825. polygon.shape.points = getInitialPoints(points);
  36826. polyline.shape.points = getInitialPoints(points);
  36827. initProps(polygon, target, seriesModel, idx);
  36828. initProps(polyline, target, seriesModel, idx);
  36829. var itemGroup = new Group();
  36830. var symbolGroup = new Group();
  36831. itemGroup.add(polyline);
  36832. itemGroup.add(polygon);
  36833. itemGroup.add(symbolGroup);
  36834. updateSymbols(
  36835. polyline.shape.points, points, symbolGroup, data, idx, true
  36836. );
  36837. data.setItemGraphicEl(idx, itemGroup);
  36838. })
  36839. .update(function (newIdx, oldIdx) {
  36840. var itemGroup = oldData.getItemGraphicEl(oldIdx);
  36841. var polyline = itemGroup.childAt(0);
  36842. var polygon = itemGroup.childAt(1);
  36843. var symbolGroup = itemGroup.childAt(2);
  36844. var target = {
  36845. shape: {
  36846. points: data.getItemLayout(newIdx)
  36847. }
  36848. };
  36849. if (!target.shape.points) {
  36850. return;
  36851. }
  36852. updateSymbols(
  36853. polyline.shape.points, target.shape.points, symbolGroup, data, newIdx, false
  36854. );
  36855. updateProps(polyline, target, seriesModel);
  36856. updateProps(polygon, target, seriesModel);
  36857. data.setItemGraphicEl(newIdx, itemGroup);
  36858. })
  36859. .remove(function (idx) {
  36860. group.remove(oldData.getItemGraphicEl(idx));
  36861. })
  36862. .execute();
  36863. data.eachItemGraphicEl(function (itemGroup, idx) {
  36864. var itemModel = data.getItemModel(idx);
  36865. var polyline = itemGroup.childAt(0);
  36866. var polygon = itemGroup.childAt(1);
  36867. var symbolGroup = itemGroup.childAt(2);
  36868. var color = data.getItemVisual(idx, 'color');
  36869. group.add(itemGroup);
  36870. polyline.useStyle(
  36871. defaults(
  36872. itemModel.getModel('lineStyle').getLineStyle(),
  36873. {
  36874. fill: 'none',
  36875. stroke: color
  36876. }
  36877. )
  36878. );
  36879. polyline.hoverStyle = itemModel.getModel('emphasis.lineStyle').getLineStyle();
  36880. var areaStyleModel = itemModel.getModel('areaStyle');
  36881. var hoverAreaStyleModel = itemModel.getModel('emphasis.areaStyle');
  36882. var polygonIgnore = areaStyleModel.isEmpty() && areaStyleModel.parentModel.isEmpty();
  36883. var hoverPolygonIgnore = hoverAreaStyleModel.isEmpty() && hoverAreaStyleModel.parentModel.isEmpty();
  36884. hoverPolygonIgnore = hoverPolygonIgnore && polygonIgnore;
  36885. polygon.ignore = polygonIgnore;
  36886. polygon.useStyle(
  36887. defaults(
  36888. areaStyleModel.getAreaStyle(),
  36889. {
  36890. fill: color,
  36891. opacity: 0.7
  36892. }
  36893. )
  36894. );
  36895. polygon.hoverStyle = hoverAreaStyleModel.getAreaStyle();
  36896. var itemStyle = itemModel.getModel('itemStyle').getItemStyle(['color']);
  36897. var itemHoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  36898. var labelModel = itemModel.getModel('label');
  36899. var labelHoverModel = itemModel.getModel('emphasis.label');
  36900. symbolGroup.eachChild(function (symbolPath) {
  36901. symbolPath.setStyle(itemStyle);
  36902. symbolPath.hoverStyle = clone(itemHoverStyle);
  36903. setLabelStyle(
  36904. symbolPath.style, symbolPath.hoverStyle, labelModel, labelHoverModel,
  36905. {
  36906. labelFetcher: data.hostModel,
  36907. labelDataIndex: idx,
  36908. labelDimIndex: symbolPath.__dimIdx,
  36909. defaultText: data.get(data.dimensions[symbolPath.__dimIdx], idx),
  36910. autoColor: color,
  36911. isRectText: true
  36912. }
  36913. );
  36914. });
  36915. function onEmphasis() {
  36916. polygon.attr('ignore', hoverPolygonIgnore);
  36917. }
  36918. function onNormal() {
  36919. polygon.attr('ignore', polygonIgnore);
  36920. }
  36921. itemGroup.off('mouseover').off('mouseout').off('normal').off('emphasis');
  36922. itemGroup.on('emphasis', onEmphasis)
  36923. .on('mouseover', onEmphasis)
  36924. .on('normal', onNormal)
  36925. .on('mouseout', onNormal);
  36926. setHoverStyle(itemGroup);
  36927. });
  36928. this._data = data;
  36929. },
  36930. remove: function () {
  36931. this.group.removeAll();
  36932. this._data = null;
  36933. },
  36934. dispose: function () {}
  36935. });
  36936. /*
  36937. * Licensed to the Apache Software Foundation (ASF) under one
  36938. * or more contributor license agreements. See the NOTICE file
  36939. * distributed with this work for additional information
  36940. * regarding copyright ownership. The ASF licenses this file
  36941. * to you under the Apache License, Version 2.0 (the
  36942. * "License"); you may not use this file except in compliance
  36943. * with the License. You may obtain a copy of the License at
  36944. *
  36945. * http://www.apache.org/licenses/LICENSE-2.0
  36946. *
  36947. * Unless required by applicable law or agreed to in writing,
  36948. * software distributed under the License is distributed on an
  36949. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36950. * KIND, either express or implied. See the License for the
  36951. * specific language governing permissions and limitations
  36952. * under the License.
  36953. */
  36954. var radarLayout = function (ecModel) {
  36955. ecModel.eachSeriesByType('radar', function (seriesModel) {
  36956. var data = seriesModel.getData();
  36957. var points = [];
  36958. var coordSys = seriesModel.coordinateSystem;
  36959. if (!coordSys) {
  36960. return;
  36961. }
  36962. function pointsConverter(val, idx) {
  36963. points[idx] = points[idx] || [];
  36964. points[idx][i] = coordSys.dataToPoint(val, i);
  36965. }
  36966. var axes = coordSys.getIndicatorAxes();
  36967. for (var i = 0; i < axes.length; i++) {
  36968. data.each(data.mapDimension(axes[i].dim), pointsConverter);
  36969. }
  36970. data.each(function (idx) {
  36971. // Close polygon
  36972. points[idx][0] && points[idx].push(points[idx][0].slice());
  36973. data.setItemLayout(idx, points[idx]);
  36974. });
  36975. });
  36976. };
  36977. /*
  36978. * Licensed to the Apache Software Foundation (ASF) under one
  36979. * or more contributor license agreements. See the NOTICE file
  36980. * distributed with this work for additional information
  36981. * regarding copyright ownership. The ASF licenses this file
  36982. * to you under the Apache License, Version 2.0 (the
  36983. * "License"); you may not use this file except in compliance
  36984. * with the License. You may obtain a copy of the License at
  36985. *
  36986. * http://www.apache.org/licenses/LICENSE-2.0
  36987. *
  36988. * Unless required by applicable law or agreed to in writing,
  36989. * software distributed under the License is distributed on an
  36990. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36991. * KIND, either express or implied. See the License for the
  36992. * specific language governing permissions and limitations
  36993. * under the License.
  36994. */
  36995. // Backward compat for radar chart in 2
  36996. var backwardCompat$1 = function (option) {
  36997. var polarOptArr = option.polar;
  36998. if (polarOptArr) {
  36999. if (!isArray(polarOptArr)) {
  37000. polarOptArr = [polarOptArr];
  37001. }
  37002. var polarNotRadar = [];
  37003. each$1(polarOptArr, function (polarOpt, idx) {
  37004. if (polarOpt.indicator) {
  37005. if (polarOpt.type && !polarOpt.shape) {
  37006. polarOpt.shape = polarOpt.type;
  37007. }
  37008. option.radar = option.radar || [];
  37009. if (!isArray(option.radar)) {
  37010. option.radar = [option.radar];
  37011. }
  37012. option.radar.push(polarOpt);
  37013. }
  37014. else {
  37015. polarNotRadar.push(polarOpt);
  37016. }
  37017. });
  37018. option.polar = polarNotRadar;
  37019. }
  37020. each$1(option.series, function (seriesOpt) {
  37021. if (seriesOpt && seriesOpt.type === 'radar' && seriesOpt.polarIndex) {
  37022. seriesOpt.radarIndex = seriesOpt.polarIndex;
  37023. }
  37024. });
  37025. };
  37026. /*
  37027. * Licensed to the Apache Software Foundation (ASF) under one
  37028. * or more contributor license agreements. See the NOTICE file
  37029. * distributed with this work for additional information
  37030. * regarding copyright ownership. The ASF licenses this file
  37031. * to you under the Apache License, Version 2.0 (the
  37032. * "License"); you may not use this file except in compliance
  37033. * with the License. You may obtain a copy of the License at
  37034. *
  37035. * http://www.apache.org/licenses/LICENSE-2.0
  37036. *
  37037. * Unless required by applicable law or agreed to in writing,
  37038. * software distributed under the License is distributed on an
  37039. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37040. * KIND, either express or implied. See the License for the
  37041. * specific language governing permissions and limitations
  37042. * under the License.
  37043. */
  37044. // Must use radar component
  37045. registerVisual(dataColor('radar'));
  37046. registerVisual(visualSymbol('radar', 'circle'));
  37047. registerLayout(radarLayout);
  37048. registerProcessor(dataFilter('radar'));
  37049. registerPreprocessor(backwardCompat$1);
  37050. /*
  37051. * Licensed to the Apache Software Foundation (ASF) under one
  37052. * or more contributor license agreements. See the NOTICE file
  37053. * distributed with this work for additional information
  37054. * regarding copyright ownership. The ASF licenses this file
  37055. * to you under the Apache License, Version 2.0 (the
  37056. * "License"); you may not use this file except in compliance
  37057. * with the License. You may obtain a copy of the License at
  37058. *
  37059. * http://www.apache.org/licenses/LICENSE-2.0
  37060. *
  37061. * Unless required by applicable law or agreed to in writing,
  37062. * software distributed under the License is distributed on an
  37063. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37064. * KIND, either express or implied. See the License for the
  37065. * specific language governing permissions and limitations
  37066. * under the License.
  37067. */
  37068. /**
  37069. * Simple view coordinate system
  37070. * Mapping given x, y to transformd view x, y
  37071. */
  37072. var v2ApplyTransform$1 = applyTransform;
  37073. // Dummy transform node
  37074. function TransformDummy() {
  37075. Transformable.call(this);
  37076. }
  37077. mixin(TransformDummy, Transformable);
  37078. function View(name) {
  37079. /**
  37080. * @type {string}
  37081. */
  37082. this.name = name;
  37083. /**
  37084. * @type {Object}
  37085. */
  37086. this.zoomLimit;
  37087. Transformable.call(this);
  37088. this._roamTransformable = new TransformDummy();
  37089. this._rawTransformable = new TransformDummy();
  37090. this._center;
  37091. this._zoom;
  37092. }
  37093. View.prototype = {
  37094. constructor: View,
  37095. type: 'view',
  37096. /**
  37097. * @param {Array.<string>}
  37098. * @readOnly
  37099. */
  37100. dimensions: ['x', 'y'],
  37101. /**
  37102. * Set bounding rect
  37103. * @param {number} x
  37104. * @param {number} y
  37105. * @param {number} width
  37106. * @param {number} height
  37107. */
  37108. // PENDING to getRect
  37109. setBoundingRect: function (x, y, width, height) {
  37110. this._rect = new BoundingRect(x, y, width, height);
  37111. return this._rect;
  37112. },
  37113. /**
  37114. * @return {module:zrender/core/BoundingRect}
  37115. */
  37116. // PENDING to getRect
  37117. getBoundingRect: function () {
  37118. return this._rect;
  37119. },
  37120. /**
  37121. * @param {number} x
  37122. * @param {number} y
  37123. * @param {number} width
  37124. * @param {number} height
  37125. */
  37126. setViewRect: function (x, y, width, height) {
  37127. this.transformTo(x, y, width, height);
  37128. this._viewRect = new BoundingRect(x, y, width, height);
  37129. },
  37130. /**
  37131. * Transformed to particular position and size
  37132. * @param {number} x
  37133. * @param {number} y
  37134. * @param {number} width
  37135. * @param {number} height
  37136. */
  37137. transformTo: function (x, y, width, height) {
  37138. var rect = this.getBoundingRect();
  37139. var rawTransform = this._rawTransformable;
  37140. rawTransform.transform = rect.calculateTransform(
  37141. new BoundingRect(x, y, width, height)
  37142. );
  37143. rawTransform.decomposeTransform();
  37144. this._updateTransform();
  37145. },
  37146. /**
  37147. * Set center of view
  37148. * @param {Array.<number>} [centerCoord]
  37149. */
  37150. setCenter: function (centerCoord) {
  37151. if (!centerCoord) {
  37152. return;
  37153. }
  37154. this._center = centerCoord;
  37155. this._updateCenterAndZoom();
  37156. },
  37157. /**
  37158. * @param {number} zoom
  37159. */
  37160. setZoom: function (zoom) {
  37161. zoom = zoom || 1;
  37162. var zoomLimit = this.zoomLimit;
  37163. if (zoomLimit) {
  37164. if (zoomLimit.max != null) {
  37165. zoom = Math.min(zoomLimit.max, zoom);
  37166. }
  37167. if (zoomLimit.min != null) {
  37168. zoom = Math.max(zoomLimit.min, zoom);
  37169. }
  37170. }
  37171. this._zoom = zoom;
  37172. this._updateCenterAndZoom();
  37173. },
  37174. /**
  37175. * Get default center without roam
  37176. */
  37177. getDefaultCenter: function () {
  37178. // Rect before any transform
  37179. var rawRect = this.getBoundingRect();
  37180. var cx = rawRect.x + rawRect.width / 2;
  37181. var cy = rawRect.y + rawRect.height / 2;
  37182. return [cx, cy];
  37183. },
  37184. getCenter: function () {
  37185. return this._center || this.getDefaultCenter();
  37186. },
  37187. getZoom: function () {
  37188. return this._zoom || 1;
  37189. },
  37190. /**
  37191. * @return {Array.<number}
  37192. */
  37193. getRoamTransform: function () {
  37194. return this._roamTransformable.getLocalTransform();
  37195. },
  37196. /**
  37197. * Remove roam
  37198. */
  37199. _updateCenterAndZoom: function () {
  37200. // Must update after view transform updated
  37201. var rawTransformMatrix = this._rawTransformable.getLocalTransform();
  37202. var roamTransform = this._roamTransformable;
  37203. var defaultCenter = this.getDefaultCenter();
  37204. var center = this.getCenter();
  37205. var zoom = this.getZoom();
  37206. center = applyTransform([], center, rawTransformMatrix);
  37207. defaultCenter = applyTransform([], defaultCenter, rawTransformMatrix);
  37208. roamTransform.origin = center;
  37209. roamTransform.position = [
  37210. defaultCenter[0] - center[0],
  37211. defaultCenter[1] - center[1]
  37212. ];
  37213. roamTransform.scale = [zoom, zoom];
  37214. this._updateTransform();
  37215. },
  37216. /**
  37217. * Update transform from roam and mapLocation
  37218. * @private
  37219. */
  37220. _updateTransform: function () {
  37221. var roamTransformable = this._roamTransformable;
  37222. var rawTransformable = this._rawTransformable;
  37223. rawTransformable.parent = roamTransformable;
  37224. roamTransformable.updateTransform();
  37225. rawTransformable.updateTransform();
  37226. copy$1(this.transform || (this.transform = []), rawTransformable.transform || create$1());
  37227. this._rawTransform = rawTransformable.getLocalTransform();
  37228. this.invTransform = this.invTransform || [];
  37229. invert(this.invTransform, this.transform);
  37230. this.decomposeTransform();
  37231. },
  37232. /**
  37233. * @return {module:zrender/core/BoundingRect}
  37234. */
  37235. getViewRect: function () {
  37236. return this._viewRect;
  37237. },
  37238. /**
  37239. * Get view rect after roam transform
  37240. * @return {module:zrender/core/BoundingRect}
  37241. */
  37242. getViewRectAfterRoam: function () {
  37243. var rect = this.getBoundingRect().clone();
  37244. rect.applyTransform(this.transform);
  37245. return rect;
  37246. },
  37247. /**
  37248. * Convert a single (lon, lat) data item to (x, y) point.
  37249. * @param {Array.<number>} data
  37250. * @param {boolean} noRoam
  37251. * @param {Array.<number>} [out]
  37252. * @return {Array.<number>}
  37253. */
  37254. dataToPoint: function (data, noRoam, out) {
  37255. var transform = noRoam ? this._rawTransform : this.transform;
  37256. out = out || [];
  37257. return transform
  37258. ? v2ApplyTransform$1(out, data, transform)
  37259. : copy(out, data);
  37260. },
  37261. /**
  37262. * Convert a (x, y) point to (lon, lat) data
  37263. * @param {Array.<number>} point
  37264. * @return {Array.<number>}
  37265. */
  37266. pointToData: function (point) {
  37267. var invTransform = this.invTransform;
  37268. return invTransform
  37269. ? v2ApplyTransform$1([], point, invTransform)
  37270. : [point[0], point[1]];
  37271. },
  37272. /**
  37273. * @implements
  37274. * see {module:echarts/CoodinateSystem}
  37275. */
  37276. convertToPixel: curry(doConvert$1, 'dataToPoint'),
  37277. /**
  37278. * @implements
  37279. * see {module:echarts/CoodinateSystem}
  37280. */
  37281. convertFromPixel: curry(doConvert$1, 'pointToData'),
  37282. /**
  37283. * @implements
  37284. * see {module:echarts/CoodinateSystem}
  37285. */
  37286. containPoint: function (point) {
  37287. return this.getViewRectAfterRoam().contain(point[0], point[1]);
  37288. }
  37289. /**
  37290. * @return {number}
  37291. */
  37292. // getScalarScale: function () {
  37293. // // Use determinant square root of transform to mutiply scalar
  37294. // var m = this.transform;
  37295. // var det = Math.sqrt(Math.abs(m[0] * m[3] - m[2] * m[1]));
  37296. // return det;
  37297. // }
  37298. };
  37299. mixin(View, Transformable);
  37300. function doConvert$1(methodName, ecModel, finder, value) {
  37301. var seriesModel = finder.seriesModel;
  37302. var coordSys = seriesModel ? seriesModel.coordinateSystem : null; // e.g., graph.
  37303. return coordSys === this ? coordSys[methodName](value) : null;
  37304. }
  37305. /*
  37306. * Licensed to the Apache Software Foundation (ASF) under one
  37307. * or more contributor license agreements. See the NOTICE file
  37308. * distributed with this work for additional information
  37309. * regarding copyright ownership. The ASF licenses this file
  37310. * to you under the Apache License, Version 2.0 (the
  37311. * "License"); you may not use this file except in compliance
  37312. * with the License. You may obtain a copy of the License at
  37313. *
  37314. * http://www.apache.org/licenses/LICENSE-2.0
  37315. *
  37316. * Unless required by applicable law or agreed to in writing,
  37317. * software distributed under the License is distributed on an
  37318. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37319. * KIND, either express or implied. See the License for the
  37320. * specific language governing permissions and limitations
  37321. * under the License.
  37322. */
  37323. // Fix for 南海诸岛
  37324. var geoCoord = [126, 25];
  37325. var points$1 = [
  37326. [[0,3.5],[7,11.2],[15,11.9],[30,7],[42,0.7],[52,0.7],
  37327. [56,7.7],[59,0.7],[64,0.7],[64,0],[5,0],[0,3.5]],
  37328. [[13,16.1],[19,14.7],[16,21.7],[11,23.1],[13,16.1]],
  37329. [[12,32.2],[14,38.5],[15,38.5],[13,32.2],[12,32.2]],
  37330. [[16,47.6],[12,53.2],[13,53.2],[18,47.6],[16,47.6]],
  37331. [[6,64.4],[8,70],[9,70],[8,64.4],[6,64.4]],
  37332. [[23,82.6],[29,79.8],[30,79.8],[25,82.6],[23,82.6]],
  37333. [[37,70.7],[43,62.3],[44,62.3],[39,70.7],[37,70.7]],
  37334. [[48,51.1],[51,45.5],[53,45.5],[50,51.1],[48,51.1]],
  37335. [[51,35],[51,28.7],[53,28.7],[53,35],[51,35]],
  37336. [[52,22.4],[55,17.5],[56,17.5],[53,22.4],[52,22.4]],
  37337. [[58,12.6],[62,7],[63,7],[60,12.6],[58,12.6]],
  37338. [[0,3.5],[0,93.1],[64,93.1],[64,0],[63,0],[63,92.4],
  37339. [1,92.4],[1,3.5],[0,3.5]]
  37340. ];
  37341. for (var i$1 = 0; i$1 < points$1.length; i$1++) {
  37342. for (var k = 0; k < points$1[i$1].length; k++) {
  37343. points$1[i$1][k][0] /= 10.5;
  37344. points$1[i$1][k][1] /= -10.5 / 0.75;
  37345. points$1[i$1][k][0] += geoCoord[0];
  37346. points$1[i$1][k][1] += geoCoord[1];
  37347. }
  37348. }
  37349. var fixNanhai = function (geo) {
  37350. if (geo.map === 'china') {
  37351. geo.regions.push(new Region(
  37352. '南海诸岛',
  37353. map(points$1, function (exterior) {
  37354. return {
  37355. type: 'polygon',
  37356. exterior: exterior
  37357. };
  37358. }), geoCoord
  37359. ));
  37360. }
  37361. };
  37362. /*
  37363. * Licensed to the Apache Software Foundation (ASF) under one
  37364. * or more contributor license agreements. See the NOTICE file
  37365. * distributed with this work for additional information
  37366. * regarding copyright ownership. The ASF licenses this file
  37367. * to you under the Apache License, Version 2.0 (the
  37368. * "License"); you may not use this file except in compliance
  37369. * with the License. You may obtain a copy of the License at
  37370. *
  37371. * http://www.apache.org/licenses/LICENSE-2.0
  37372. *
  37373. * Unless required by applicable law or agreed to in writing,
  37374. * software distributed under the License is distributed on an
  37375. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37376. * KIND, either express or implied. See the License for the
  37377. * specific language governing permissions and limitations
  37378. * under the License.
  37379. */
  37380. var coordsOffsetMap = {
  37381. '南海诸岛' : [32, 80],
  37382. // 全国
  37383. '广东': [0, -10],
  37384. '香港': [10, 5],
  37385. '澳门': [-10, 10],
  37386. //'北京': [-10, 0],
  37387. '天津': [5, 5]
  37388. };
  37389. var fixTextCoord = function (geo) {
  37390. each$1(geo.regions, function (region) {
  37391. var coordFix = coordsOffsetMap[region.name];
  37392. if (coordFix) {
  37393. var cp = region.center;
  37394. cp[0] += coordFix[0] / 10.5;
  37395. cp[1] += -coordFix[1] / (10.5 / 0.75);
  37396. }
  37397. });
  37398. };
  37399. /*
  37400. * Licensed to the Apache Software Foundation (ASF) under one
  37401. * or more contributor license agreements. See the NOTICE file
  37402. * distributed with this work for additional information
  37403. * regarding copyright ownership. The ASF licenses this file
  37404. * to you under the Apache License, Version 2.0 (the
  37405. * "License"); you may not use this file except in compliance
  37406. * with the License. You may obtain a copy of the License at
  37407. *
  37408. * http://www.apache.org/licenses/LICENSE-2.0
  37409. *
  37410. * Unless required by applicable law or agreed to in writing,
  37411. * software distributed under the License is distributed on an
  37412. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37413. * KIND, either express or implied. See the License for the
  37414. * specific language governing permissions and limitations
  37415. * under the License.
  37416. */
  37417. var geoCoordMap = {
  37418. 'Russia': [100, 60],
  37419. 'United States': [-99, 38],
  37420. 'United States of America': [-99, 38]
  37421. };
  37422. var fixGeoCoord = function (geo) {
  37423. each$1(geo.regions, function (region) {
  37424. var geoCoord = geoCoordMap[region.name];
  37425. if (geoCoord) {
  37426. var cp = region.center;
  37427. cp[0] = geoCoord[0];
  37428. cp[1] = geoCoord[1];
  37429. }
  37430. });
  37431. };
  37432. /*
  37433. * Licensed to the Apache Software Foundation (ASF) under one
  37434. * or more contributor license agreements. See the NOTICE file
  37435. * distributed with this work for additional information
  37436. * regarding copyright ownership. The ASF licenses this file
  37437. * to you under the Apache License, Version 2.0 (the
  37438. * "License"); you may not use this file except in compliance
  37439. * with the License. You may obtain a copy of the License at
  37440. *
  37441. * http://www.apache.org/licenses/LICENSE-2.0
  37442. *
  37443. * Unless required by applicable law or agreed to in writing,
  37444. * software distributed under the License is distributed on an
  37445. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37446. * KIND, either express or implied. See the License for the
  37447. * specific language governing permissions and limitations
  37448. * under the License.
  37449. */
  37450. // Fix for 钓鱼岛
  37451. // var Region = require('../Region');
  37452. // var zrUtil = require('zrender/src/core/util');
  37453. // var geoCoord = [126, 25];
  37454. var points$2 = [
  37455. [
  37456. [123.45165252685547, 25.73527164402261],
  37457. [123.49731445312499, 25.73527164402261],
  37458. [123.49731445312499, 25.750734064600884],
  37459. [123.45165252685547, 25.750734064600884],
  37460. [123.45165252685547, 25.73527164402261]
  37461. ]
  37462. ];
  37463. var fixDiaoyuIsland = function (geo) {
  37464. if (geo.map === 'china') {
  37465. for (var i = 0, len = geo.regions.length; i < len; ++i) {
  37466. if (geo.regions[i].name === '台湾') {
  37467. geo.regions[i].geometries.push({
  37468. type: 'polygon',
  37469. exterior: points$2[0]
  37470. });
  37471. }
  37472. }
  37473. }
  37474. };
  37475. /*
  37476. * Licensed to the Apache Software Foundation (ASF) under one
  37477. * or more contributor license agreements. See the NOTICE file
  37478. * distributed with this work for additional information
  37479. * regarding copyright ownership. The ASF licenses this file
  37480. * to you under the Apache License, Version 2.0 (the
  37481. * "License"); you may not use this file except in compliance
  37482. * with the License. You may obtain a copy of the License at
  37483. *
  37484. * http://www.apache.org/licenses/LICENSE-2.0
  37485. *
  37486. * Unless required by applicable law or agreed to in writing,
  37487. * software distributed under the License is distributed on an
  37488. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37489. * KIND, either express or implied. See the License for the
  37490. * specific language governing permissions and limitations
  37491. * under the License.
  37492. */
  37493. // Geo fix functions
  37494. var geoFixFuncs = [
  37495. fixNanhai,
  37496. fixTextCoord,
  37497. fixGeoCoord,
  37498. fixDiaoyuIsland
  37499. ];
  37500. /**
  37501. * [Geo description]
  37502. * @param {string} name Geo name
  37503. * @param {string} map Map type
  37504. * @param {Object} geoJson
  37505. * @param {Object} [specialAreas]
  37506. * Specify the positioned areas by left, top, width, height
  37507. * @param {Object.<string, string>} [nameMap]
  37508. * Specify name alias
  37509. */
  37510. function Geo(name, map$$1, geoJson, specialAreas, nameMap) {
  37511. View.call(this, name);
  37512. /**
  37513. * Map type
  37514. * @type {string}
  37515. */
  37516. this.map = map$$1;
  37517. this._nameCoordMap = createHashMap();
  37518. this.loadGeoJson(geoJson, specialAreas, nameMap);
  37519. }
  37520. Geo.prototype = {
  37521. constructor: Geo,
  37522. type: 'geo',
  37523. /**
  37524. * @param {Array.<string>}
  37525. * @readOnly
  37526. */
  37527. dimensions: ['lng', 'lat'],
  37528. /**
  37529. * If contain given lng,lat coord
  37530. * @param {Array.<number>}
  37531. * @readOnly
  37532. */
  37533. containCoord: function (coord) {
  37534. var regions = this.regions;
  37535. for (var i = 0; i < regions.length; i++) {
  37536. if (regions[i].contain(coord)) {
  37537. return true;
  37538. }
  37539. }
  37540. return false;
  37541. },
  37542. /**
  37543. * @param {Object} geoJson
  37544. * @param {Object} [specialAreas]
  37545. * Specify the positioned areas by left, top, width, height
  37546. * @param {Object.<string, string>} [nameMap]
  37547. * Specify name alias
  37548. */
  37549. loadGeoJson: function (geoJson, specialAreas, nameMap) {
  37550. // https://jsperf.com/try-catch-performance-overhead
  37551. try {
  37552. this.regions = geoJson ? parseGeoJson$1(geoJson) : [];
  37553. }
  37554. catch (e) {
  37555. throw 'Invalid geoJson format\n' + e.message;
  37556. }
  37557. specialAreas = specialAreas || {};
  37558. nameMap = nameMap || {};
  37559. var regions = this.regions;
  37560. var regionsMap = createHashMap();
  37561. for (var i = 0; i < regions.length; i++) {
  37562. var regionName = regions[i].name;
  37563. // Try use the alias in nameMap
  37564. regionName = nameMap.hasOwnProperty(regionName) ? nameMap[regionName] : regionName;
  37565. regions[i].name = regionName;
  37566. regionsMap.set(regionName, regions[i]);
  37567. // Add geoJson
  37568. this.addGeoCoord(regionName, regions[i].center);
  37569. // Some area like Alaska in USA map needs to be tansformed
  37570. // to look better
  37571. var specialArea = specialAreas[regionName];
  37572. if (specialArea) {
  37573. regions[i].transformTo(
  37574. specialArea.left, specialArea.top, specialArea.width, specialArea.height
  37575. );
  37576. }
  37577. }
  37578. this._regionsMap = regionsMap;
  37579. this._rect = null;
  37580. each$1(geoFixFuncs, function (fixFunc) {
  37581. fixFunc(this);
  37582. }, this);
  37583. },
  37584. // Overwrite
  37585. transformTo: function (x, y, width, height) {
  37586. var rect = this.getBoundingRect();
  37587. rect = rect.clone();
  37588. // Longitute is inverted
  37589. rect.y = -rect.y - rect.height;
  37590. var rawTransformable = this._rawTransformable;
  37591. rawTransformable.transform = rect.calculateTransform(
  37592. new BoundingRect(x, y, width, height)
  37593. );
  37594. rawTransformable.decomposeTransform();
  37595. var scale = rawTransformable.scale;
  37596. scale[1] = -scale[1];
  37597. rawTransformable.updateTransform();
  37598. this._updateTransform();
  37599. },
  37600. /**
  37601. * @param {string} name
  37602. * @return {module:echarts/coord/geo/Region}
  37603. */
  37604. getRegion: function (name) {
  37605. return this._regionsMap.get(name);
  37606. },
  37607. getRegionByCoord: function (coord) {
  37608. var regions = this.regions;
  37609. for (var i = 0; i < regions.length; i++) {
  37610. if (regions[i].contain(coord)) {
  37611. return regions[i];
  37612. }
  37613. }
  37614. },
  37615. /**
  37616. * Add geoCoord for indexing by name
  37617. * @param {string} name
  37618. * @param {Array.<number>} geoCoord
  37619. */
  37620. addGeoCoord: function (name, geoCoord) {
  37621. this._nameCoordMap.set(name, geoCoord);
  37622. },
  37623. /**
  37624. * Get geoCoord by name
  37625. * @param {string} name
  37626. * @return {Array.<number>}
  37627. */
  37628. getGeoCoord: function (name) {
  37629. return this._nameCoordMap.get(name);
  37630. },
  37631. // Overwrite
  37632. getBoundingRect: function () {
  37633. if (this._rect) {
  37634. return this._rect;
  37635. }
  37636. var rect;
  37637. var regions = this.regions;
  37638. for (var i = 0; i < regions.length; i++) {
  37639. var regionRect = regions[i].getBoundingRect();
  37640. rect = rect || regionRect.clone();
  37641. rect.union(regionRect);
  37642. }
  37643. // FIXME Always return new ?
  37644. return (this._rect = rect || new BoundingRect(0, 0, 0, 0));
  37645. },
  37646. /**
  37647. * @param {string|Array.<number>} data
  37648. * @param {boolean} noRoam
  37649. * @param {Array.<number>} [out]
  37650. * @return {Array.<number>}
  37651. */
  37652. dataToPoint: function (data, noRoam, out) {
  37653. if (typeof data === 'string') {
  37654. // Map area name to geoCoord
  37655. data = this.getGeoCoord(data);
  37656. }
  37657. if (data) {
  37658. return View.prototype.dataToPoint.call(this, data, noRoam, out);
  37659. }
  37660. },
  37661. /**
  37662. * @inheritDoc
  37663. */
  37664. convertToPixel: curry(doConvert, 'dataToPoint'),
  37665. /**
  37666. * @inheritDoc
  37667. */
  37668. convertFromPixel: curry(doConvert, 'pointToData')
  37669. };
  37670. mixin(Geo, View);
  37671. function doConvert(methodName, ecModel, finder, value) {
  37672. var geoModel = finder.geoModel;
  37673. var seriesModel = finder.seriesModel;
  37674. var coordSys = geoModel
  37675. ? geoModel.coordinateSystem
  37676. : seriesModel
  37677. ? (
  37678. seriesModel.coordinateSystem // For map.
  37679. || (seriesModel.getReferringComponents('geo')[0] || {}).coordinateSystem
  37680. )
  37681. : null;
  37682. return coordSys === this ? coordSys[methodName](value) : null;
  37683. }
  37684. /*
  37685. * Licensed to the Apache Software Foundation (ASF) under one
  37686. * or more contributor license agreements. See the NOTICE file
  37687. * distributed with this work for additional information
  37688. * regarding copyright ownership. The ASF licenses this file
  37689. * to you under the Apache License, Version 2.0 (the
  37690. * "License"); you may not use this file except in compliance
  37691. * with the License. You may obtain a copy of the License at
  37692. *
  37693. * http://www.apache.org/licenses/LICENSE-2.0
  37694. *
  37695. * Unless required by applicable law or agreed to in writing,
  37696. * software distributed under the License is distributed on an
  37697. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37698. * KIND, either express or implied. See the License for the
  37699. * specific language governing permissions and limitations
  37700. * under the License.
  37701. */
  37702. /**
  37703. * Resize method bound to the geo
  37704. * @param {module:echarts/coord/geo/GeoModel|module:echarts/chart/map/MapModel} geoModel
  37705. * @param {module:echarts/ExtensionAPI} api
  37706. */
  37707. function resizeGeo(geoModel, api) {
  37708. var boundingCoords = geoModel.get('boundingCoords');
  37709. if (boundingCoords != null) {
  37710. var leftTop = boundingCoords[0];
  37711. var rightBottom = boundingCoords[1];
  37712. if (isNaN(leftTop[0]) || isNaN(leftTop[1]) || isNaN(rightBottom[0]) || isNaN(rightBottom[1])) {
  37713. if (__DEV__) {
  37714. console.error('Invalid boundingCoords');
  37715. }
  37716. }
  37717. else {
  37718. this.setBoundingRect(leftTop[0], leftTop[1], rightBottom[0] - leftTop[0], rightBottom[1] - leftTop[1]);
  37719. }
  37720. }
  37721. var rect = this.getBoundingRect();
  37722. var boxLayoutOption;
  37723. var center = geoModel.get('layoutCenter');
  37724. var size = geoModel.get('layoutSize');
  37725. var viewWidth = api.getWidth();
  37726. var viewHeight = api.getHeight();
  37727. var aspectScale = geoModel.get('aspectScale') || 0.75;
  37728. var aspect = rect.width / rect.height * aspectScale;
  37729. var useCenterAndSize = false;
  37730. if (center && size) {
  37731. center = [
  37732. parsePercent$1(center[0], viewWidth),
  37733. parsePercent$1(center[1], viewHeight)
  37734. ];
  37735. size = parsePercent$1(size, Math.min(viewWidth, viewHeight));
  37736. if (!isNaN(center[0]) && !isNaN(center[1]) && !isNaN(size)) {
  37737. useCenterAndSize = true;
  37738. }
  37739. else {
  37740. if (__DEV__) {
  37741. console.warn('Given layoutCenter or layoutSize data are invalid. Use left/top/width/height instead.');
  37742. }
  37743. }
  37744. }
  37745. var viewRect;
  37746. if (useCenterAndSize) {
  37747. var viewRect = {};
  37748. if (aspect > 1) {
  37749. // Width is same with size
  37750. viewRect.width = size;
  37751. viewRect.height = size / aspect;
  37752. }
  37753. else {
  37754. viewRect.height = size;
  37755. viewRect.width = size * aspect;
  37756. }
  37757. viewRect.y = center[1] - viewRect.height / 2;
  37758. viewRect.x = center[0] - viewRect.width / 2;
  37759. }
  37760. else {
  37761. // Use left/top/width/height
  37762. boxLayoutOption = geoModel.getBoxLayoutParams();
  37763. // 0.75 rate
  37764. boxLayoutOption.aspect = aspect;
  37765. viewRect = getLayoutRect(boxLayoutOption, {
  37766. width: viewWidth,
  37767. height: viewHeight
  37768. });
  37769. }
  37770. this.setViewRect(viewRect.x, viewRect.y, viewRect.width, viewRect.height);
  37771. this.setCenter(geoModel.get('center'));
  37772. this.setZoom(geoModel.get('zoom'));
  37773. }
  37774. /**
  37775. * @param {module:echarts/coord/Geo} geo
  37776. * @param {module:echarts/model/Model} model
  37777. * @inner
  37778. */
  37779. function setGeoCoords(geo, model) {
  37780. each$1(model.get('geoCoord'), function (geoCoord, name) {
  37781. geo.addGeoCoord(name, geoCoord);
  37782. });
  37783. }
  37784. if (__DEV__) {
  37785. var mapNotExistsError = function (name) {
  37786. console.error('Map ' + name + ' not exists. You can download map file on http://echarts.baidu.com/download-map.html');
  37787. };
  37788. }
  37789. var geoCreator = {
  37790. // For deciding which dimensions to use when creating list data
  37791. dimensions: Geo.prototype.dimensions,
  37792. create: function (ecModel, api) {
  37793. var geoList = [];
  37794. // FIXME Create each time may be slow
  37795. ecModel.eachComponent('geo', function (geoModel, idx) {
  37796. var name = geoModel.get('map');
  37797. var mapData = getMap(name);
  37798. if (__DEV__) {
  37799. if (!mapData) {
  37800. mapNotExistsError(name);
  37801. }
  37802. }
  37803. var geo = new Geo(
  37804. name + idx, name,
  37805. mapData && mapData.geoJson, mapData && mapData.specialAreas,
  37806. geoModel.get('nameMap')
  37807. );
  37808. geo.zoomLimit = geoModel.get('scaleLimit');
  37809. geoList.push(geo);
  37810. setGeoCoords(geo, geoModel);
  37811. geoModel.coordinateSystem = geo;
  37812. geo.model = geoModel;
  37813. // Inject resize method
  37814. geo.resize = resizeGeo;
  37815. geo.resize(geoModel, api);
  37816. });
  37817. ecModel.eachSeries(function (seriesModel) {
  37818. var coordSys = seriesModel.get('coordinateSystem');
  37819. if (coordSys === 'geo') {
  37820. var geoIndex = seriesModel.get('geoIndex') || 0;
  37821. seriesModel.coordinateSystem = geoList[geoIndex];
  37822. }
  37823. });
  37824. // If has map series
  37825. var mapModelGroupBySeries = {};
  37826. ecModel.eachSeriesByType('map', function (seriesModel) {
  37827. if (!seriesModel.getHostGeoModel()) {
  37828. var mapType = seriesModel.getMapType();
  37829. mapModelGroupBySeries[mapType] = mapModelGroupBySeries[mapType] || [];
  37830. mapModelGroupBySeries[mapType].push(seriesModel);
  37831. }
  37832. });
  37833. each$1(mapModelGroupBySeries, function (mapSeries, mapType) {
  37834. var mapData = getMap(mapType);
  37835. if (__DEV__) {
  37836. if (!mapData) {
  37837. mapNotExistsError(mapSeries[0].get('map'));
  37838. }
  37839. }
  37840. var nameMapList = map(mapSeries, function (singleMapSeries) {
  37841. return singleMapSeries.get('nameMap');
  37842. });
  37843. var geo = new Geo(
  37844. mapType, mapType,
  37845. mapData && mapData.geoJson, mapData && mapData.specialAreas,
  37846. mergeAll(nameMapList)
  37847. );
  37848. geo.zoomLimit = retrieve.apply(null, map(mapSeries, function (singleMapSeries) {
  37849. return singleMapSeries.get('scaleLimit');
  37850. }));
  37851. geoList.push(geo);
  37852. // Inject resize method
  37853. geo.resize = resizeGeo;
  37854. geo.resize(mapSeries[0], api);
  37855. each$1(mapSeries, function (singleMapSeries) {
  37856. singleMapSeries.coordinateSystem = geo;
  37857. setGeoCoords(geo, singleMapSeries);
  37858. });
  37859. });
  37860. return geoList;
  37861. },
  37862. /**
  37863. * Fill given regions array
  37864. * @param {Array.<Object>} originRegionArr
  37865. * @param {string} mapName
  37866. * @param {Object} [nameMap]
  37867. * @return {Array}
  37868. */
  37869. getFilledRegions: function (originRegionArr, mapName, nameMap) {
  37870. // Not use the original
  37871. var regionsArr = (originRegionArr || []).slice();
  37872. nameMap = nameMap || {};
  37873. var map$$1 = getMap(mapName);
  37874. var geoJson = map$$1 && map$$1.geoJson;
  37875. if (!geoJson) {
  37876. if (__DEV__) {
  37877. mapNotExistsError(mapName);
  37878. }
  37879. return originRegionArr;
  37880. }
  37881. var dataNameMap = createHashMap();
  37882. var features = geoJson.features;
  37883. for (var i = 0; i < regionsArr.length; i++) {
  37884. dataNameMap.set(regionsArr[i].name, regionsArr[i]);
  37885. }
  37886. for (var i = 0; i < features.length; i++) {
  37887. var name = features[i].properties.name;
  37888. if (!dataNameMap.get(name)) {
  37889. if (nameMap.hasOwnProperty(name)) {
  37890. name = nameMap[name];
  37891. }
  37892. regionsArr.push({
  37893. name: name
  37894. });
  37895. }
  37896. }
  37897. return regionsArr;
  37898. }
  37899. };
  37900. registerCoordinateSystem('geo', geoCreator);
  37901. /*
  37902. * Licensed to the Apache Software Foundation (ASF) under one
  37903. * or more contributor license agreements. See the NOTICE file
  37904. * distributed with this work for additional information
  37905. * regarding copyright ownership. The ASF licenses this file
  37906. * to you under the Apache License, Version 2.0 (the
  37907. * "License"); you may not use this file except in compliance
  37908. * with the License. You may obtain a copy of the License at
  37909. *
  37910. * http://www.apache.org/licenses/LICENSE-2.0
  37911. *
  37912. * Unless required by applicable law or agreed to in writing,
  37913. * software distributed under the License is distributed on an
  37914. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37915. * KIND, either express or implied. See the License for the
  37916. * specific language governing permissions and limitations
  37917. * under the License.
  37918. */
  37919. var MapSeries = SeriesModel.extend({
  37920. type: 'series.map',
  37921. dependencies: ['geo'],
  37922. layoutMode: 'box',
  37923. /**
  37924. * Only first map series of same mapType will drawMap
  37925. * @type {boolean}
  37926. */
  37927. needsDrawMap: false,
  37928. /**
  37929. * Group of all map series with same mapType
  37930. * @type {boolean}
  37931. */
  37932. seriesGroup: [],
  37933. init: function (option) {
  37934. // this._fillOption(option, this.getMapType());
  37935. // this.option = option;
  37936. MapSeries.superApply(this, 'init', arguments);
  37937. this.updateSelectedMap(this._createSelectableList());
  37938. },
  37939. getInitialData: function (option) {
  37940. return createListSimply(this, ['value']);
  37941. },
  37942. mergeOption: function (newOption) {
  37943. // this._fillOption(newOption, this.getMapType());
  37944. MapSeries.superApply(this, 'mergeOption', arguments);
  37945. this.updateSelectedMap(this._createSelectableList());
  37946. },
  37947. _createSelectableList: function () {
  37948. var data = this.getRawData();
  37949. var valueDim = data.mapDimension('value');
  37950. var targetList = [];
  37951. for (var i = 0, len = data.count(); i < len; i++) {
  37952. targetList.push({
  37953. name: data.getName(i),
  37954. value: data.get(valueDim, i),
  37955. selected: retrieveRawAttr(data, i, 'selected')
  37956. });
  37957. }
  37958. targetList = geoCreator.getFilledRegions(targetList, this.getMapType(), this.option.nameMap);
  37959. return targetList;
  37960. },
  37961. /**
  37962. * If no host geo model, return null, which means using a
  37963. * inner exclusive geo model.
  37964. */
  37965. getHostGeoModel: function () {
  37966. var geoIndex = this.option.geoIndex;
  37967. return geoIndex != null
  37968. ? this.dependentModels.geo[geoIndex]
  37969. : null;
  37970. },
  37971. getMapType: function () {
  37972. return (this.getHostGeoModel() || this).option.map;
  37973. },
  37974. _fillOption: function (option, mapName) {
  37975. // Shallow clone
  37976. // option = zrUtil.extend({}, option);
  37977. // option.data = geoCreator.getFilledRegions(option.data, mapName, option.nameMap);
  37978. // return option;
  37979. },
  37980. getRawValue: function (dataIndex) {
  37981. // Use value stored in data instead because it is calculated from multiple series
  37982. // FIXME Provide all value of multiple series ?
  37983. var data = this.getData();
  37984. return data.get(data.mapDimension('value'), dataIndex);
  37985. },
  37986. /**
  37987. * Get model of region
  37988. * @param {string} name
  37989. * @return {module:echarts/model/Model}
  37990. */
  37991. getRegionModel: function (regionName) {
  37992. var data = this.getData();
  37993. return data.getItemModel(data.indexOfName(regionName));
  37994. },
  37995. /**
  37996. * Map tooltip formatter
  37997. *
  37998. * @param {number} dataIndex
  37999. */
  38000. formatTooltip: function (dataIndex) {
  38001. // FIXME orignalData and data is a bit confusing
  38002. var data = this.getData();
  38003. var formattedValue = addCommas(this.getRawValue(dataIndex));
  38004. var name = data.getName(dataIndex);
  38005. var seriesGroup = this.seriesGroup;
  38006. var seriesNames = [];
  38007. for (var i = 0; i < seriesGroup.length; i++) {
  38008. var otherIndex = seriesGroup[i].originalData.indexOfName(name);
  38009. var valueDim = data.mapDimension('value');
  38010. if (!isNaN(seriesGroup[i].originalData.get(valueDim, otherIndex))) {
  38011. seriesNames.push(
  38012. encodeHTML(seriesGroup[i].name)
  38013. );
  38014. }
  38015. }
  38016. return seriesNames.join(', ') + '<br />'
  38017. + encodeHTML(name + ' : ' + formattedValue);
  38018. },
  38019. /**
  38020. * @implement
  38021. */
  38022. getTooltipPosition: function (dataIndex) {
  38023. if (dataIndex != null) {
  38024. var name = this.getData().getName(dataIndex);
  38025. var geo = this.coordinateSystem;
  38026. var region = geo.getRegion(name);
  38027. return region && geo.dataToPoint(region.center);
  38028. }
  38029. },
  38030. setZoom: function (zoom) {
  38031. this.option.zoom = zoom;
  38032. },
  38033. setCenter: function (center) {
  38034. this.option.center = center;
  38035. },
  38036. defaultOption: {
  38037. // 一级层叠
  38038. zlevel: 0,
  38039. // 二级层叠
  38040. z: 2,
  38041. coordinateSystem: 'geo',
  38042. // map should be explicitly specified since ec3.
  38043. map: '',
  38044. // If `geoIndex` is not specified, a exclusive geo will be
  38045. // created. Otherwise use the specified geo component, and
  38046. // `map` and `mapType` are ignored.
  38047. // geoIndex: 0,
  38048. // 'center' | 'left' | 'right' | 'x%' | {number}
  38049. left: 'center',
  38050. // 'center' | 'top' | 'bottom' | 'x%' | {number}
  38051. top: 'center',
  38052. // right
  38053. // bottom
  38054. // width:
  38055. // height
  38056. // Aspect is width / height. Inited to be geoJson bbox aspect
  38057. // This parameter is used for scale this aspect
  38058. aspectScale: 0.75,
  38059. ///// Layout with center and size
  38060. // If you wan't to put map in a fixed size box with right aspect ratio
  38061. // This two properties may more conveninet
  38062. // layoutCenter: [50%, 50%]
  38063. // layoutSize: 100
  38064. // 数值合并方式,默认加和,可选为:
  38065. // 'sum' | 'average' | 'max' | 'min'
  38066. // mapValueCalculation: 'sum',
  38067. // 地图数值计算结果小数精度
  38068. // mapValuePrecision: 0,
  38069. // 显示图例颜色标识(系列标识的小圆点),图例开启时有效
  38070. showLegendSymbol: true,
  38071. // 选择模式,默认关闭,可选single,multiple
  38072. // selectedMode: false,
  38073. dataRangeHoverLink: true,
  38074. // 是否开启缩放及漫游模式
  38075. // roam: false,
  38076. // Define left-top, right-bottom coords to control view
  38077. // For example, [ [180, 90], [-180, -90] ],
  38078. // higher priority than center and zoom
  38079. boundingCoords: null,
  38080. // Default on center of map
  38081. center: null,
  38082. zoom: 1,
  38083. scaleLimit: null,
  38084. label: {
  38085. show: false,
  38086. color: '#000'
  38087. },
  38088. // scaleLimit: null,
  38089. itemStyle: {
  38090. borderWidth: 0.5,
  38091. borderColor: '#444',
  38092. areaColor: '#eee'
  38093. },
  38094. emphasis: {
  38095. label: {
  38096. show: true,
  38097. color: 'rgb(100,0,0)'
  38098. },
  38099. itemStyle: {
  38100. areaColor: 'rgba(255,215,0,0.8)'
  38101. }
  38102. }
  38103. }
  38104. });
  38105. mixin(MapSeries, selectableMixin);
  38106. /*
  38107. * Licensed to the Apache Software Foundation (ASF) under one
  38108. * or more contributor license agreements. See the NOTICE file
  38109. * distributed with this work for additional information
  38110. * regarding copyright ownership. The ASF licenses this file
  38111. * to you under the Apache License, Version 2.0 (the
  38112. * "License"); you may not use this file except in compliance
  38113. * with the License. You may obtain a copy of the License at
  38114. *
  38115. * http://www.apache.org/licenses/LICENSE-2.0
  38116. *
  38117. * Unless required by applicable law or agreed to in writing,
  38118. * software distributed under the License is distributed on an
  38119. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38120. * KIND, either express or implied. See the License for the
  38121. * specific language governing permissions and limitations
  38122. * under the License.
  38123. */
  38124. var ATTR = '\0_ec_interaction_mutex';
  38125. function take(zr, resourceKey, userKey) {
  38126. var store = getStore(zr);
  38127. store[resourceKey] = userKey;
  38128. }
  38129. function release(zr, resourceKey, userKey) {
  38130. var store = getStore(zr);
  38131. var uKey = store[resourceKey];
  38132. if (uKey === userKey) {
  38133. store[resourceKey] = null;
  38134. }
  38135. }
  38136. function isTaken(zr, resourceKey) {
  38137. return !!getStore(zr)[resourceKey];
  38138. }
  38139. function getStore(zr) {
  38140. return zr[ATTR] || (zr[ATTR] = {});
  38141. }
  38142. /**
  38143. * payload: {
  38144. * type: 'takeGlobalCursor',
  38145. * key: 'dataZoomSelect', or 'brush', or ...,
  38146. * If no userKey, release global cursor.
  38147. * }
  38148. */
  38149. registerAction(
  38150. {type: 'takeGlobalCursor', event: 'globalCursorTaken', update: 'update'},
  38151. function () {}
  38152. );
  38153. /*
  38154. * Licensed to the Apache Software Foundation (ASF) under one
  38155. * or more contributor license agreements. See the NOTICE file
  38156. * distributed with this work for additional information
  38157. * regarding copyright ownership. The ASF licenses this file
  38158. * to you under the Apache License, Version 2.0 (the
  38159. * "License"); you may not use this file except in compliance
  38160. * with the License. You may obtain a copy of the License at
  38161. *
  38162. * http://www.apache.org/licenses/LICENSE-2.0
  38163. *
  38164. * Unless required by applicable law or agreed to in writing,
  38165. * software distributed under the License is distributed on an
  38166. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38167. * KIND, either express or implied. See the License for the
  38168. * specific language governing permissions and limitations
  38169. * under the License.
  38170. */
  38171. /**
  38172. * @alias module:echarts/component/helper/RoamController
  38173. * @constructor
  38174. * @mixin {module:zrender/mixin/Eventful}
  38175. *
  38176. * @param {module:zrender/zrender~ZRender} zr
  38177. */
  38178. function RoamController(zr) {
  38179. /**
  38180. * @type {Function}
  38181. */
  38182. this.pointerChecker;
  38183. /**
  38184. * @type {module:zrender}
  38185. */
  38186. this._zr = zr;
  38187. /**
  38188. * @type {Object}
  38189. */
  38190. this._opt = {};
  38191. // Avoid two roamController bind the same handler
  38192. var bind$$1 = bind;
  38193. var mousedownHandler = bind$$1(mousedown, this);
  38194. var mousemoveHandler = bind$$1(mousemove, this);
  38195. var mouseupHandler = bind$$1(mouseup, this);
  38196. var mousewheelHandler = bind$$1(mousewheel, this);
  38197. var pinchHandler = bind$$1(pinch, this);
  38198. Eventful.call(this);
  38199. /**
  38200. * @param {Function} pointerChecker
  38201. * input: x, y
  38202. * output: boolean
  38203. */
  38204. this.setPointerChecker = function (pointerChecker) {
  38205. this.pointerChecker = pointerChecker;
  38206. };
  38207. /**
  38208. * Notice: only enable needed types. For example, if 'zoom'
  38209. * is not needed, 'zoom' should not be enabled, otherwise
  38210. * default mousewheel behaviour (scroll page) will be disabled.
  38211. *
  38212. * @param {boolean|string} [controlType=true] Specify the control type,
  38213. * which can be null/undefined or true/false
  38214. * or 'pan/move' or 'zoom'/'scale'
  38215. * @param {Object} [opt]
  38216. * @param {Object} [opt.zoomOnMouseWheel=true]
  38217. * @param {Object} [opt.moveOnMouseMove=true]
  38218. * @param {Object} [opt.preventDefaultMouseMove=true] When pan.
  38219. */
  38220. this.enable = function (controlType, opt) {
  38221. // Disable previous first
  38222. this.disable();
  38223. this._opt = defaults(clone(opt) || {}, {
  38224. zoomOnMouseWheel: true,
  38225. moveOnMouseMove: true,
  38226. preventDefaultMouseMove: true
  38227. });
  38228. if (controlType == null) {
  38229. controlType = true;
  38230. }
  38231. if (controlType === true || (controlType === 'move' || controlType === 'pan')) {
  38232. zr.on('mousedown', mousedownHandler);
  38233. zr.on('mousemove', mousemoveHandler);
  38234. zr.on('mouseup', mouseupHandler);
  38235. }
  38236. if (controlType === true || (controlType === 'scale' || controlType === 'zoom')) {
  38237. zr.on('mousewheel', mousewheelHandler);
  38238. zr.on('pinch', pinchHandler);
  38239. }
  38240. };
  38241. this.disable = function () {
  38242. zr.off('mousedown', mousedownHandler);
  38243. zr.off('mousemove', mousemoveHandler);
  38244. zr.off('mouseup', mouseupHandler);
  38245. zr.off('mousewheel', mousewheelHandler);
  38246. zr.off('pinch', pinchHandler);
  38247. };
  38248. this.dispose = this.disable;
  38249. this.isDragging = function () {
  38250. return this._dragging;
  38251. };
  38252. this.isPinching = function () {
  38253. return this._pinching;
  38254. };
  38255. }
  38256. mixin(RoamController, Eventful);
  38257. function mousedown(e) {
  38258. if (notLeftMouse(e)
  38259. || (e.target && e.target.draggable)
  38260. ) {
  38261. return;
  38262. }
  38263. var x = e.offsetX;
  38264. var y = e.offsetY;
  38265. // Only check on mosedown, but not mousemove.
  38266. // Mouse can be out of target when mouse moving.
  38267. if (this.pointerChecker && this.pointerChecker(e, x, y)) {
  38268. this._x = x;
  38269. this._y = y;
  38270. this._dragging = true;
  38271. }
  38272. }
  38273. function mousemove(e) {
  38274. if (notLeftMouse(e)
  38275. || !checkKeyBinding(this, 'moveOnMouseMove', e)
  38276. || !this._dragging
  38277. || e.gestureEvent === 'pinch'
  38278. || isTaken(this._zr, 'globalPan')
  38279. ) {
  38280. return;
  38281. }
  38282. var x = e.offsetX;
  38283. var y = e.offsetY;
  38284. var oldX = this._x;
  38285. var oldY = this._y;
  38286. var dx = x - oldX;
  38287. var dy = y - oldY;
  38288. this._x = x;
  38289. this._y = y;
  38290. this._opt.preventDefaultMouseMove && stop(e.event);
  38291. this.trigger('pan', dx, dy, oldX, oldY, x, y);
  38292. }
  38293. function mouseup(e) {
  38294. if (!notLeftMouse(e)) {
  38295. this._dragging = false;
  38296. }
  38297. }
  38298. function mousewheel(e) {
  38299. // wheelDelta maybe -0 in chrome mac.
  38300. if (!checkKeyBinding(this, 'zoomOnMouseWheel', e) || e.wheelDelta === 0) {
  38301. return;
  38302. }
  38303. // Convenience:
  38304. // Mac and VM Windows on Mac: scroll up: zoom out.
  38305. // Windows: scroll up: zoom in.
  38306. var zoomDelta = e.wheelDelta > 0 ? 1.1 : 1 / 1.1;
  38307. zoom.call(this, e, zoomDelta, e.offsetX, e.offsetY);
  38308. }
  38309. function pinch(e) {
  38310. if (isTaken(this._zr, 'globalPan')) {
  38311. return;
  38312. }
  38313. var zoomDelta = e.pinchScale > 1 ? 1.1 : 1 / 1.1;
  38314. zoom.call(this, e, zoomDelta, e.pinchX, e.pinchY);
  38315. }
  38316. function zoom(e, zoomDelta, zoomX, zoomY) {
  38317. if (this.pointerChecker && this.pointerChecker(e, zoomX, zoomY)) {
  38318. // When mouse is out of roamController rect,
  38319. // default befavoius should not be be disabled, otherwise
  38320. // page sliding is disabled, contrary to expectation.
  38321. stop(e.event);
  38322. this.trigger('zoom', zoomDelta, zoomX, zoomY);
  38323. }
  38324. }
  38325. function checkKeyBinding(roamController, prop, e) {
  38326. var setting = roamController._opt[prop];
  38327. return setting
  38328. && (!isString(setting) || e.event[setting + 'Key']);
  38329. }
  38330. /*
  38331. * Licensed to the Apache Software Foundation (ASF) under one
  38332. * or more contributor license agreements. See the NOTICE file
  38333. * distributed with this work for additional information
  38334. * regarding copyright ownership. The ASF licenses this file
  38335. * to you under the Apache License, Version 2.0 (the
  38336. * "License"); you may not use this file except in compliance
  38337. * with the License. You may obtain a copy of the License at
  38338. *
  38339. * http://www.apache.org/licenses/LICENSE-2.0
  38340. *
  38341. * Unless required by applicable law or agreed to in writing,
  38342. * software distributed under the License is distributed on an
  38343. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38344. * KIND, either express or implied. See the License for the
  38345. * specific language governing permissions and limitations
  38346. * under the License.
  38347. */
  38348. /**
  38349. * For geo and graph.
  38350. *
  38351. * @param {Object} controllerHost
  38352. * @param {module:zrender/Element} controllerHost.target
  38353. */
  38354. function updateViewOnPan(controllerHost, dx, dy) {
  38355. var target = controllerHost.target;
  38356. var pos = target.position;
  38357. pos[0] += dx;
  38358. pos[1] += dy;
  38359. target.dirty();
  38360. }
  38361. /**
  38362. * For geo and graph.
  38363. *
  38364. * @param {Object} controllerHost
  38365. * @param {module:zrender/Element} controllerHost.target
  38366. * @param {number} controllerHost.zoom
  38367. * @param {number} controllerHost.zoomLimit like: {min: 1, max: 2}
  38368. */
  38369. function updateViewOnZoom(controllerHost, zoomDelta, zoomX, zoomY) {
  38370. var target = controllerHost.target;
  38371. var zoomLimit = controllerHost.zoomLimit;
  38372. var pos = target.position;
  38373. var scale = target.scale;
  38374. var newZoom = controllerHost.zoom = controllerHost.zoom || 1;
  38375. newZoom *= zoomDelta;
  38376. if (zoomLimit) {
  38377. var zoomMin = zoomLimit.min || 0;
  38378. var zoomMax = zoomLimit.max || Infinity;
  38379. newZoom = Math.max(
  38380. Math.min(zoomMax, newZoom),
  38381. zoomMin
  38382. );
  38383. }
  38384. var zoomScale = newZoom / controllerHost.zoom;
  38385. controllerHost.zoom = newZoom;
  38386. // Keep the mouse center when scaling
  38387. pos[0] -= (zoomX - pos[0]) * (zoomScale - 1);
  38388. pos[1] -= (zoomY - pos[1]) * (zoomScale - 1);
  38389. scale[0] *= zoomScale;
  38390. scale[1] *= zoomScale;
  38391. target.dirty();
  38392. }
  38393. /*
  38394. * Licensed to the Apache Software Foundation (ASF) under one
  38395. * or more contributor license agreements. See the NOTICE file
  38396. * distributed with this work for additional information
  38397. * regarding copyright ownership. The ASF licenses this file
  38398. * to you under the Apache License, Version 2.0 (the
  38399. * "License"); you may not use this file except in compliance
  38400. * with the License. You may obtain a copy of the License at
  38401. *
  38402. * http://www.apache.org/licenses/LICENSE-2.0
  38403. *
  38404. * Unless required by applicable law or agreed to in writing,
  38405. * software distributed under the License is distributed on an
  38406. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38407. * KIND, either express or implied. See the License for the
  38408. * specific language governing permissions and limitations
  38409. * under the License.
  38410. */
  38411. var IRRELEVANT_EXCLUDES = {'axisPointer': 1, 'tooltip': 1, 'brush': 1};
  38412. /**
  38413. * Avoid that: mouse click on a elements that is over geo or graph,
  38414. * but roam is triggered.
  38415. */
  38416. function onIrrelevantElement(e, api, targetCoordSysModel) {
  38417. var model = api.getComponentByElement(e.topTarget);
  38418. // If model is axisModel, it works only if it is injected with coordinateSystem.
  38419. var coordSys = model && model.coordinateSystem;
  38420. return model
  38421. && model !== targetCoordSysModel
  38422. && !IRRELEVANT_EXCLUDES[model.mainType]
  38423. && (coordSys && coordSys.model !== targetCoordSysModel);
  38424. }
  38425. /*
  38426. * Licensed to the Apache Software Foundation (ASF) under one
  38427. * or more contributor license agreements. See the NOTICE file
  38428. * distributed with this work for additional information
  38429. * regarding copyright ownership. The ASF licenses this file
  38430. * to you under the Apache License, Version 2.0 (the
  38431. * "License"); you may not use this file except in compliance
  38432. * with the License. You may obtain a copy of the License at
  38433. *
  38434. * http://www.apache.org/licenses/LICENSE-2.0
  38435. *
  38436. * Unless required by applicable law or agreed to in writing,
  38437. * software distributed under the License is distributed on an
  38438. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38439. * KIND, either express or implied. See the License for the
  38440. * specific language governing permissions and limitations
  38441. * under the License.
  38442. */
  38443. function getFixedItemStyle(model, scale) {
  38444. var itemStyle = model.getItemStyle();
  38445. var areaColor = model.get('areaColor');
  38446. // If user want the color not to be changed when hover,
  38447. // they should both set areaColor and color to be null.
  38448. if (areaColor != null) {
  38449. itemStyle.fill = areaColor;
  38450. }
  38451. return itemStyle;
  38452. }
  38453. function updateMapSelectHandler(mapDraw, mapOrGeoModel, group, api, fromView) {
  38454. group.off('click');
  38455. group.off('mousedown');
  38456. if (mapOrGeoModel.get('selectedMode')) {
  38457. group.on('mousedown', function () {
  38458. mapDraw._mouseDownFlag = true;
  38459. });
  38460. group.on('click', function (e) {
  38461. if (!mapDraw._mouseDownFlag) {
  38462. return;
  38463. }
  38464. mapDraw._mouseDownFlag = false;
  38465. var el = e.target;
  38466. while (!el.__regions) {
  38467. el = el.parent;
  38468. }
  38469. if (!el) {
  38470. return;
  38471. }
  38472. var action = {
  38473. type: (mapOrGeoModel.mainType === 'geo' ? 'geo' : 'map') + 'ToggleSelect',
  38474. batch: map(el.__regions, function (region) {
  38475. return {
  38476. name: region.name,
  38477. from: fromView.uid
  38478. };
  38479. })
  38480. };
  38481. action[mapOrGeoModel.mainType + 'Id'] = mapOrGeoModel.id;
  38482. api.dispatchAction(action);
  38483. updateMapSelected(mapOrGeoModel, group);
  38484. });
  38485. }
  38486. }
  38487. function updateMapSelected(mapOrGeoModel, group) {
  38488. // FIXME
  38489. group.eachChild(function (otherRegionEl) {
  38490. each$1(otherRegionEl.__regions, function (region) {
  38491. otherRegionEl.trigger(mapOrGeoModel.isSelected(region.name) ? 'emphasis' : 'normal');
  38492. });
  38493. });
  38494. }
  38495. /**
  38496. * @alias module:echarts/component/helper/MapDraw
  38497. * @param {module:echarts/ExtensionAPI} api
  38498. * @param {boolean} updateGroup
  38499. */
  38500. function MapDraw(api, updateGroup) {
  38501. var group = new Group();
  38502. /**
  38503. * @type {module:echarts/component/helper/RoamController}
  38504. * @private
  38505. */
  38506. this._controller = new RoamController(api.getZr());
  38507. /**
  38508. * @type {Object} {target, zoom, zoomLimit}
  38509. * @private
  38510. */
  38511. this._controllerHost = {target: updateGroup ? group : null};
  38512. /**
  38513. * @type {module:zrender/container/Group}
  38514. * @readOnly
  38515. */
  38516. this.group = group;
  38517. /**
  38518. * @type {boolean}
  38519. * @private
  38520. */
  38521. this._updateGroup = updateGroup;
  38522. /**
  38523. * This flag is used to make sure that only one among
  38524. * `pan`, `zoom`, `click` can occurs, otherwise 'selected'
  38525. * action may be triggered when `pan`, which is unexpected.
  38526. * @type {booelan}
  38527. */
  38528. this._mouseDownFlag;
  38529. }
  38530. MapDraw.prototype = {
  38531. constructor: MapDraw,
  38532. draw: function (mapOrGeoModel, ecModel, api, fromView, payload) {
  38533. var isGeo = mapOrGeoModel.mainType === 'geo';
  38534. // Map series has data. GEO model that controlled by map series
  38535. // will be assigned with map data. Other GEO model has no data.
  38536. var data = mapOrGeoModel.getData && mapOrGeoModel.getData();
  38537. isGeo && ecModel.eachComponent({mainType: 'series', subType: 'map'}, function (mapSeries) {
  38538. if (!data && mapSeries.getHostGeoModel() === mapOrGeoModel) {
  38539. data = mapSeries.getData();
  38540. }
  38541. });
  38542. var geo = mapOrGeoModel.coordinateSystem;
  38543. var group = this.group;
  38544. var scale = geo.scale;
  38545. var groupNewProp = {
  38546. position: geo.position,
  38547. scale: scale
  38548. };
  38549. // No animation when first draw or in action
  38550. if (!group.childAt(0) || payload) {
  38551. group.attr(groupNewProp);
  38552. }
  38553. else {
  38554. updateProps(group, groupNewProp, mapOrGeoModel);
  38555. }
  38556. group.removeAll();
  38557. var itemStyleAccessPath = ['itemStyle'];
  38558. var hoverItemStyleAccessPath = ['emphasis', 'itemStyle'];
  38559. var labelAccessPath = ['label'];
  38560. var hoverLabelAccessPath = ['emphasis', 'label'];
  38561. var nameMap = createHashMap();
  38562. each$1(geo.regions, function (region) {
  38563. // Consider in GeoJson properties.name may be duplicated, for example,
  38564. // there is multiple region named "United Kindom" or "France" (so many
  38565. // colonies). And it is not appropriate to merge them in geo, which
  38566. // will make them share the same label and bring trouble in label
  38567. // location calculation.
  38568. var regionGroup = nameMap.get(region.name)
  38569. || nameMap.set(region.name, new Group());
  38570. var compoundPath = new CompoundPath({
  38571. shape: {
  38572. paths: []
  38573. }
  38574. });
  38575. regionGroup.add(compoundPath);
  38576. var regionModel = mapOrGeoModel.getRegionModel(region.name) || mapOrGeoModel;
  38577. var itemStyleModel = regionModel.getModel(itemStyleAccessPath);
  38578. var hoverItemStyleModel = regionModel.getModel(hoverItemStyleAccessPath);
  38579. var itemStyle = getFixedItemStyle(itemStyleModel, scale);
  38580. var hoverItemStyle = getFixedItemStyle(hoverItemStyleModel, scale);
  38581. var labelModel = regionModel.getModel(labelAccessPath);
  38582. var hoverLabelModel = regionModel.getModel(hoverLabelAccessPath);
  38583. var dataIdx;
  38584. // Use the itemStyle in data if has data
  38585. if (data) {
  38586. dataIdx = data.indexOfName(region.name);
  38587. // Only visual color of each item will be used. It can be encoded by dataRange
  38588. // But visual color of series is used in symbol drawing
  38589. //
  38590. // Visual color for each series is for the symbol draw
  38591. var visualColor = data.getItemVisual(dataIdx, 'color', true);
  38592. if (visualColor) {
  38593. itemStyle.fill = visualColor;
  38594. }
  38595. }
  38596. each$1(region.geometries, function (geometry) {
  38597. if (geometry.type !== 'polygon') {
  38598. return;
  38599. }
  38600. compoundPath.shape.paths.push(new Polygon({
  38601. shape: {
  38602. points: geometry.exterior
  38603. }
  38604. }));
  38605. for (var i = 0; i < (geometry.interiors ? geometry.interiors.length : 0); i++) {
  38606. compoundPath.shape.paths.push(new Polygon({
  38607. shape: {
  38608. points: geometry.interiors[i]
  38609. }
  38610. }));
  38611. }
  38612. });
  38613. compoundPath.setStyle(itemStyle);
  38614. compoundPath.style.strokeNoScale = true;
  38615. compoundPath.culling = true;
  38616. // Label
  38617. var showLabel = labelModel.get('show');
  38618. var hoverShowLabel = hoverLabelModel.get('show');
  38619. var isDataNaN = data && isNaN(data.get(data.mapDimension('value'), dataIdx));
  38620. var itemLayout = data && data.getItemLayout(dataIdx);
  38621. // In the following cases label will be drawn
  38622. // 1. In map series and data value is NaN
  38623. // 2. In geo component
  38624. // 4. Region has no series legendSymbol, which will be add a showLabel flag in mapSymbolLayout
  38625. if (
  38626. (isGeo || isDataNaN && (showLabel || hoverShowLabel))
  38627. || (itemLayout && itemLayout.showLabel)
  38628. ) {
  38629. var query = !isGeo ? dataIdx : region.name;
  38630. var labelFetcher;
  38631. // Consider dataIdx not found.
  38632. if (!data || dataIdx >= 0) {
  38633. labelFetcher = mapOrGeoModel;
  38634. }
  38635. var textEl = new Text({
  38636. position: region.center.slice(),
  38637. scale: [1 / scale[0], 1 / scale[1]],
  38638. z2: 10,
  38639. silent: true
  38640. });
  38641. setLabelStyle(
  38642. textEl.style, textEl.hoverStyle = {}, labelModel, hoverLabelModel,
  38643. {
  38644. labelFetcher: labelFetcher,
  38645. labelDataIndex: query,
  38646. defaultText: region.name,
  38647. useInsideStyle: false
  38648. },
  38649. {
  38650. textAlign: 'center',
  38651. textVerticalAlign: 'middle'
  38652. }
  38653. );
  38654. regionGroup.add(textEl);
  38655. }
  38656. // setItemGraphicEl, setHoverStyle after all polygons and labels
  38657. // are added to the rigionGroup
  38658. if (data) {
  38659. data.setItemGraphicEl(dataIdx, regionGroup);
  38660. }
  38661. else {
  38662. var regionModel = mapOrGeoModel.getRegionModel(region.name);
  38663. // Package custom mouse event for geo component
  38664. compoundPath.eventData = {
  38665. componentType: 'geo',
  38666. geoIndex: mapOrGeoModel.componentIndex,
  38667. name: region.name,
  38668. region: (regionModel && regionModel.option) || {}
  38669. };
  38670. }
  38671. var groupRegions = regionGroup.__regions || (regionGroup.__regions = []);
  38672. groupRegions.push(region);
  38673. setHoverStyle(
  38674. regionGroup,
  38675. hoverItemStyle,
  38676. {hoverSilentOnTouch: !!mapOrGeoModel.get('selectedMode')}
  38677. );
  38678. group.add(regionGroup);
  38679. });
  38680. this._updateController(mapOrGeoModel, ecModel, api);
  38681. updateMapSelectHandler(this, mapOrGeoModel, group, api, fromView);
  38682. updateMapSelected(mapOrGeoModel, group);
  38683. },
  38684. remove: function () {
  38685. this.group.removeAll();
  38686. this._controller.dispose();
  38687. this._controllerHost = {};
  38688. },
  38689. _updateController: function (mapOrGeoModel, ecModel, api) {
  38690. var geo = mapOrGeoModel.coordinateSystem;
  38691. var controller = this._controller;
  38692. var controllerHost = this._controllerHost;
  38693. controllerHost.zoomLimit = mapOrGeoModel.get('scaleLimit');
  38694. controllerHost.zoom = geo.getZoom();
  38695. // roamType is will be set default true if it is null
  38696. controller.enable(mapOrGeoModel.get('roam') || false);
  38697. var mainType = mapOrGeoModel.mainType;
  38698. function makeActionBase() {
  38699. var action = {
  38700. type: 'geoRoam',
  38701. componentType: mainType
  38702. };
  38703. action[mainType + 'Id'] = mapOrGeoModel.id;
  38704. return action;
  38705. }
  38706. controller.off('pan').on('pan', function (dx, dy) {
  38707. this._mouseDownFlag = false;
  38708. updateViewOnPan(controllerHost, dx, dy);
  38709. api.dispatchAction(extend(makeActionBase(), {
  38710. dx: dx,
  38711. dy: dy
  38712. }));
  38713. }, this);
  38714. controller.off('zoom').on('zoom', function (zoom, mouseX, mouseY) {
  38715. this._mouseDownFlag = false;
  38716. updateViewOnZoom(controllerHost, zoom, mouseX, mouseY);
  38717. api.dispatchAction(extend(makeActionBase(), {
  38718. zoom: zoom,
  38719. originX: mouseX,
  38720. originY: mouseY
  38721. }));
  38722. if (this._updateGroup) {
  38723. var group = this.group;
  38724. var scale = group.scale;
  38725. group.traverse(function (el) {
  38726. if (el.type === 'text') {
  38727. el.attr('scale', [1 / scale[0], 1 / scale[1]]);
  38728. }
  38729. });
  38730. }
  38731. }, this);
  38732. controller.setPointerChecker(function (e, x, y) {
  38733. return geo.getViewRectAfterRoam().contain(x, y)
  38734. && !onIrrelevantElement(e, api, mapOrGeoModel);
  38735. });
  38736. }
  38737. };
  38738. /*
  38739. * Licensed to the Apache Software Foundation (ASF) under one
  38740. * or more contributor license agreements. See the NOTICE file
  38741. * distributed with this work for additional information
  38742. * regarding copyright ownership. The ASF licenses this file
  38743. * to you under the Apache License, Version 2.0 (the
  38744. * "License"); you may not use this file except in compliance
  38745. * with the License. You may obtain a copy of the License at
  38746. *
  38747. * http://www.apache.org/licenses/LICENSE-2.0
  38748. *
  38749. * Unless required by applicable law or agreed to in writing,
  38750. * software distributed under the License is distributed on an
  38751. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38752. * KIND, either express or implied. See the License for the
  38753. * specific language governing permissions and limitations
  38754. * under the License.
  38755. */
  38756. extendChartView({
  38757. type: 'map',
  38758. render: function (mapModel, ecModel, api, payload) {
  38759. // Not render if it is an toggleSelect action from self
  38760. if (payload && payload.type === 'mapToggleSelect'
  38761. && payload.from === this.uid
  38762. ) {
  38763. return;
  38764. }
  38765. var group = this.group;
  38766. group.removeAll();
  38767. if (mapModel.getHostGeoModel()) {
  38768. return;
  38769. }
  38770. // Not update map if it is an roam action from self
  38771. if (!(payload && payload.type === 'geoRoam'
  38772. && payload.componentType === 'series'
  38773. && payload.seriesId === mapModel.id
  38774. )
  38775. ) {
  38776. if (mapModel.needsDrawMap) {
  38777. var mapDraw = this._mapDraw || new MapDraw(api, true);
  38778. group.add(mapDraw.group);
  38779. mapDraw.draw(mapModel, ecModel, api, this, payload);
  38780. this._mapDraw = mapDraw;
  38781. }
  38782. else {
  38783. // Remove drawed map
  38784. this._mapDraw && this._mapDraw.remove();
  38785. this._mapDraw = null;
  38786. }
  38787. }
  38788. else {
  38789. var mapDraw = this._mapDraw;
  38790. mapDraw && group.add(mapDraw.group);
  38791. }
  38792. mapModel.get('showLegendSymbol') && ecModel.getComponent('legend')
  38793. && this._renderSymbols(mapModel, ecModel, api);
  38794. },
  38795. remove: function () {
  38796. this._mapDraw && this._mapDraw.remove();
  38797. this._mapDraw = null;
  38798. this.group.removeAll();
  38799. },
  38800. dispose: function () {
  38801. this._mapDraw && this._mapDraw.remove();
  38802. this._mapDraw = null;
  38803. },
  38804. _renderSymbols: function (mapModel, ecModel, api) {
  38805. var originalData = mapModel.originalData;
  38806. var group = this.group;
  38807. originalData.each(originalData.mapDimension('value'), function (value, idx) {
  38808. if (isNaN(value)) {
  38809. return;
  38810. }
  38811. var layout = originalData.getItemLayout(idx);
  38812. if (!layout || !layout.point) {
  38813. // Not exists in map
  38814. return;
  38815. }
  38816. var point = layout.point;
  38817. var offset = layout.offset;
  38818. var circle = new Circle({
  38819. style: {
  38820. // Because the special of map draw.
  38821. // Which needs statistic of multiple series and draw on one map.
  38822. // And each series also need a symbol with legend color
  38823. //
  38824. // Layout and visual are put one the different data
  38825. fill: mapModel.getData().getVisual('color')
  38826. },
  38827. shape: {
  38828. cx: point[0] + offset * 9,
  38829. cy: point[1],
  38830. r: 3
  38831. },
  38832. silent: true,
  38833. // Do not overlap the first series, on which labels are displayed.
  38834. z2: !offset ? 10 : 8
  38835. });
  38836. // First data on the same region
  38837. if (!offset) {
  38838. var fullData = mapModel.mainSeries.getData();
  38839. var name = originalData.getName(idx);
  38840. var fullIndex = fullData.indexOfName(name);
  38841. var itemModel = originalData.getItemModel(idx);
  38842. var labelModel = itemModel.getModel('label');
  38843. var hoverLabelModel = itemModel.getModel('emphasis.label');
  38844. var polygonGroups = fullData.getItemGraphicEl(fullIndex);
  38845. var normalText = retrieve2(
  38846. mapModel.getFormattedLabel(idx, 'normal'),
  38847. name
  38848. );
  38849. var emphasisText = retrieve2(
  38850. mapModel.getFormattedLabel(idx, 'emphasis'),
  38851. normalText
  38852. );
  38853. var onEmphasis = function () {
  38854. var hoverStyle = setTextStyle({}, hoverLabelModel, {
  38855. text: hoverLabelModel.get('show') ? emphasisText : null
  38856. }, {isRectText: true, useInsideStyle: false}, true);
  38857. circle.style.extendFrom(hoverStyle);
  38858. // Make label upper than others if overlaps.
  38859. circle.__mapOriginalZ2 = circle.z2;
  38860. circle.z2 += 1;
  38861. };
  38862. var onNormal = function () {
  38863. setTextStyle(circle.style, labelModel, {
  38864. text: labelModel.get('show') ? normalText : null,
  38865. textPosition: labelModel.getShallow('position') || 'bottom'
  38866. }, {isRectText: true, useInsideStyle: false});
  38867. if (circle.__mapOriginalZ2 != null) {
  38868. circle.z2 = circle.__mapOriginalZ2;
  38869. circle.__mapOriginalZ2 = null;
  38870. }
  38871. };
  38872. polygonGroups.on('mouseover', onEmphasis)
  38873. .on('mouseout', onNormal)
  38874. .on('emphasis', onEmphasis)
  38875. .on('normal', onNormal);
  38876. onNormal();
  38877. }
  38878. group.add(circle);
  38879. });
  38880. }
  38881. });
  38882. /*
  38883. * Licensed to the Apache Software Foundation (ASF) under one
  38884. * or more contributor license agreements. See the NOTICE file
  38885. * distributed with this work for additional information
  38886. * regarding copyright ownership. The ASF licenses this file
  38887. * to you under the Apache License, Version 2.0 (the
  38888. * "License"); you may not use this file except in compliance
  38889. * with the License. You may obtain a copy of the License at
  38890. *
  38891. * http://www.apache.org/licenses/LICENSE-2.0
  38892. *
  38893. * Unless required by applicable law or agreed to in writing,
  38894. * software distributed under the License is distributed on an
  38895. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38896. * KIND, either express or implied. See the License for the
  38897. * specific language governing permissions and limitations
  38898. * under the License.
  38899. */
  38900. /**
  38901. * @param {module:echarts/coord/View} view
  38902. * @param {Object} payload
  38903. * @param {Object} [zoomLimit]
  38904. */
  38905. function updateCenterAndZoom(
  38906. view, payload, zoomLimit
  38907. ) {
  38908. var previousZoom = view.getZoom();
  38909. var center = view.getCenter();
  38910. var zoom = payload.zoom;
  38911. var point = view.dataToPoint(center);
  38912. if (payload.dx != null && payload.dy != null) {
  38913. point[0] -= payload.dx;
  38914. point[1] -= payload.dy;
  38915. var center = view.pointToData(point);
  38916. view.setCenter(center);
  38917. }
  38918. if (zoom != null) {
  38919. if (zoomLimit) {
  38920. var zoomMin = zoomLimit.min || 0;
  38921. var zoomMax = zoomLimit.max || Infinity;
  38922. zoom = Math.max(
  38923. Math.min(previousZoom * zoom, zoomMax),
  38924. zoomMin
  38925. ) / previousZoom;
  38926. }
  38927. // Zoom on given point(originX, originY)
  38928. view.scale[0] *= zoom;
  38929. view.scale[1] *= zoom;
  38930. var position = view.position;
  38931. var fixX = (payload.originX - position[0]) * (zoom - 1);
  38932. var fixY = (payload.originY - position[1]) * (zoom - 1);
  38933. position[0] -= fixX;
  38934. position[1] -= fixY;
  38935. view.updateTransform();
  38936. // Get the new center
  38937. var center = view.pointToData(point);
  38938. view.setCenter(center);
  38939. view.setZoom(zoom * previousZoom);
  38940. }
  38941. return {
  38942. center: view.getCenter(),
  38943. zoom: view.getZoom()
  38944. };
  38945. }
  38946. /*
  38947. * Licensed to the Apache Software Foundation (ASF) under one
  38948. * or more contributor license agreements. See the NOTICE file
  38949. * distributed with this work for additional information
  38950. * regarding copyright ownership. The ASF licenses this file
  38951. * to you under the Apache License, Version 2.0 (the
  38952. * "License"); you may not use this file except in compliance
  38953. * with the License. You may obtain a copy of the License at
  38954. *
  38955. * http://www.apache.org/licenses/LICENSE-2.0
  38956. *
  38957. * Unless required by applicable law or agreed to in writing,
  38958. * software distributed under the License is distributed on an
  38959. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38960. * KIND, either express or implied. See the License for the
  38961. * specific language governing permissions and limitations
  38962. * under the License.
  38963. */
  38964. /**
  38965. * @payload
  38966. * @property {string} [componentType=series]
  38967. * @property {number} [dx]
  38968. * @property {number} [dy]
  38969. * @property {number} [zoom]
  38970. * @property {number} [originX]
  38971. * @property {number} [originY]
  38972. */
  38973. registerAction({
  38974. type: 'geoRoam',
  38975. event: 'geoRoam',
  38976. update: 'updateTransform'
  38977. }, function (payload, ecModel) {
  38978. var componentType = payload.componentType || 'series';
  38979. ecModel.eachComponent(
  38980. { mainType: componentType, query: payload },
  38981. function (componentModel) {
  38982. var geo = componentModel.coordinateSystem;
  38983. if (geo.type !== 'geo') {
  38984. return;
  38985. }
  38986. var res = updateCenterAndZoom(
  38987. geo, payload, componentModel.get('scaleLimit')
  38988. );
  38989. componentModel.setCenter
  38990. && componentModel.setCenter(res.center);
  38991. componentModel.setZoom
  38992. && componentModel.setZoom(res.zoom);
  38993. // All map series with same `map` use the same geo coordinate system
  38994. // So the center and zoom must be in sync. Include the series not selected by legend
  38995. if (componentType === 'series') {
  38996. each$1(componentModel.seriesGroup, function (seriesModel) {
  38997. seriesModel.setCenter(res.center);
  38998. seriesModel.setZoom(res.zoom);
  38999. });
  39000. }
  39001. }
  39002. );
  39003. });
  39004. /*
  39005. * Licensed to the Apache Software Foundation (ASF) under one
  39006. * or more contributor license agreements. See the NOTICE file
  39007. * distributed with this work for additional information
  39008. * regarding copyright ownership. The ASF licenses this file
  39009. * to you under the Apache License, Version 2.0 (the
  39010. * "License"); you may not use this file except in compliance
  39011. * with the License. You may obtain a copy of the License at
  39012. *
  39013. * http://www.apache.org/licenses/LICENSE-2.0
  39014. *
  39015. * Unless required by applicable law or agreed to in writing,
  39016. * software distributed under the License is distributed on an
  39017. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39018. * KIND, either express or implied. See the License for the
  39019. * specific language governing permissions and limitations
  39020. * under the License.
  39021. */
  39022. var mapSymbolLayout = function (ecModel) {
  39023. var processedMapType = {};
  39024. ecModel.eachSeriesByType('map', function (mapSeries) {
  39025. var mapType = mapSeries.getMapType();
  39026. if (mapSeries.getHostGeoModel() || processedMapType[mapType]) {
  39027. return;
  39028. }
  39029. var mapSymbolOffsets = {};
  39030. each$1(mapSeries.seriesGroup, function (subMapSeries) {
  39031. var geo = subMapSeries.coordinateSystem;
  39032. var data = subMapSeries.originalData;
  39033. if (subMapSeries.get('showLegendSymbol') && ecModel.getComponent('legend')) {
  39034. data.each(data.mapDimension('value'), function (value, idx) {
  39035. var name = data.getName(idx);
  39036. var region = geo.getRegion(name);
  39037. // If input series.data is [11, 22, '-'/null/undefined, 44],
  39038. // it will be filled with NaN: [11, 22, NaN, 44] and NaN will
  39039. // not be drawn. So here must validate if value is NaN.
  39040. if (!region || isNaN(value)) {
  39041. return;
  39042. }
  39043. var offset = mapSymbolOffsets[name] || 0;
  39044. var point = geo.dataToPoint(region.center);
  39045. mapSymbolOffsets[name] = offset + 1;
  39046. data.setItemLayout(idx, {
  39047. point: point,
  39048. offset: offset
  39049. });
  39050. });
  39051. }
  39052. });
  39053. // Show label of those region not has legendSymbol(which is offset 0)
  39054. var data = mapSeries.getData();
  39055. data.each(function (idx) {
  39056. var name = data.getName(idx);
  39057. var layout = data.getItemLayout(idx) || {};
  39058. layout.showLabel = !mapSymbolOffsets[name];
  39059. data.setItemLayout(idx, layout);
  39060. });
  39061. processedMapType[mapType] = true;
  39062. });
  39063. };
  39064. /*
  39065. * Licensed to the Apache Software Foundation (ASF) under one
  39066. * or more contributor license agreements. See the NOTICE file
  39067. * distributed with this work for additional information
  39068. * regarding copyright ownership. The ASF licenses this file
  39069. * to you under the Apache License, Version 2.0 (the
  39070. * "License"); you may not use this file except in compliance
  39071. * with the License. You may obtain a copy of the License at
  39072. *
  39073. * http://www.apache.org/licenses/LICENSE-2.0
  39074. *
  39075. * Unless required by applicable law or agreed to in writing,
  39076. * software distributed under the License is distributed on an
  39077. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39078. * KIND, either express or implied. See the License for the
  39079. * specific language governing permissions and limitations
  39080. * under the License.
  39081. */
  39082. var mapVisual = function (ecModel) {
  39083. ecModel.eachSeriesByType('map', function (seriesModel) {
  39084. var colorList = seriesModel.get('color');
  39085. var itemStyleModel = seriesModel.getModel('itemStyle');
  39086. var areaColor = itemStyleModel.get('areaColor');
  39087. var color = itemStyleModel.get('color')
  39088. || colorList[seriesModel.seriesIndex % colorList.length];
  39089. seriesModel.getData().setVisual({
  39090. 'areaColor': areaColor,
  39091. 'color': color
  39092. });
  39093. });
  39094. };
  39095. /*
  39096. * Licensed to the Apache Software Foundation (ASF) under one
  39097. * or more contributor license agreements. See the NOTICE file
  39098. * distributed with this work for additional information
  39099. * regarding copyright ownership. The ASF licenses this file
  39100. * to you under the Apache License, Version 2.0 (the
  39101. * "License"); you may not use this file except in compliance
  39102. * with the License. You may obtain a copy of the License at
  39103. *
  39104. * http://www.apache.org/licenses/LICENSE-2.0
  39105. *
  39106. * Unless required by applicable law or agreed to in writing,
  39107. * software distributed under the License is distributed on an
  39108. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39109. * KIND, either express or implied. See the License for the
  39110. * specific language governing permissions and limitations
  39111. * under the License.
  39112. */
  39113. // FIXME 公用?
  39114. /**
  39115. * @param {Array.<module:echarts/data/List>} datas
  39116. * @param {string} statisticType 'average' 'sum'
  39117. * @inner
  39118. */
  39119. function dataStatistics(datas, statisticType) {
  39120. var dataNameMap = {};
  39121. each$1(datas, function (data) {
  39122. data.each(data.mapDimension('value'), function (value, idx) {
  39123. // Add prefix to avoid conflict with Object.prototype.
  39124. var mapKey = 'ec-' + data.getName(idx);
  39125. dataNameMap[mapKey] = dataNameMap[mapKey] || [];
  39126. if (!isNaN(value)) {
  39127. dataNameMap[mapKey].push(value);
  39128. }
  39129. });
  39130. });
  39131. return datas[0].map(datas[0].mapDimension('value'), function (value, idx) {
  39132. var mapKey = 'ec-' + datas[0].getName(idx);
  39133. var sum = 0;
  39134. var min = Infinity;
  39135. var max = -Infinity;
  39136. var len = dataNameMap[mapKey].length;
  39137. for (var i = 0; i < len; i++) {
  39138. min = Math.min(min, dataNameMap[mapKey][i]);
  39139. max = Math.max(max, dataNameMap[mapKey][i]);
  39140. sum += dataNameMap[mapKey][i];
  39141. }
  39142. var result;
  39143. if (statisticType === 'min') {
  39144. result = min;
  39145. }
  39146. else if (statisticType === 'max') {
  39147. result = max;
  39148. }
  39149. else if (statisticType === 'average') {
  39150. result = sum / len;
  39151. }
  39152. else {
  39153. result = sum;
  39154. }
  39155. return len === 0 ? NaN : result;
  39156. });
  39157. }
  39158. var mapDataStatistic = function (ecModel) {
  39159. var seriesGroups = {};
  39160. ecModel.eachSeriesByType('map', function (seriesModel) {
  39161. var hostGeoModel = seriesModel.getHostGeoModel();
  39162. var key = hostGeoModel ? 'o' + hostGeoModel.id : 'i' + seriesModel.getMapType();
  39163. (seriesGroups[key] = seriesGroups[key] || []).push(seriesModel);
  39164. });
  39165. each$1(seriesGroups, function (seriesList, key) {
  39166. var data = dataStatistics(
  39167. map(seriesList, function (seriesModel) {
  39168. return seriesModel.getData();
  39169. }),
  39170. seriesList[0].get('mapValueCalculation')
  39171. );
  39172. for (var i = 0; i < seriesList.length; i++) {
  39173. seriesList[i].originalData = seriesList[i].getData();
  39174. }
  39175. // FIXME Put where?
  39176. for (var i = 0; i < seriesList.length; i++) {
  39177. seriesList[i].seriesGroup = seriesList;
  39178. seriesList[i].needsDrawMap = i === 0 && !seriesList[i].getHostGeoModel();
  39179. seriesList[i].setData(data.cloneShallow());
  39180. seriesList[i].mainSeries = seriesList[0];
  39181. }
  39182. });
  39183. };
  39184. /*
  39185. * Licensed to the Apache Software Foundation (ASF) under one
  39186. * or more contributor license agreements. See the NOTICE file
  39187. * distributed with this work for additional information
  39188. * regarding copyright ownership. The ASF licenses this file
  39189. * to you under the Apache License, Version 2.0 (the
  39190. * "License"); you may not use this file except in compliance
  39191. * with the License. You may obtain a copy of the License at
  39192. *
  39193. * http://www.apache.org/licenses/LICENSE-2.0
  39194. *
  39195. * Unless required by applicable law or agreed to in writing,
  39196. * software distributed under the License is distributed on an
  39197. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39198. * KIND, either express or implied. See the License for the
  39199. * specific language governing permissions and limitations
  39200. * under the License.
  39201. */
  39202. var backwardCompat$2 = function (option) {
  39203. // Save geoCoord
  39204. var mapSeries = [];
  39205. each$1(option.series, function (seriesOpt) {
  39206. if (seriesOpt && seriesOpt.type === 'map') {
  39207. mapSeries.push(seriesOpt);
  39208. seriesOpt.map = seriesOpt.map || seriesOpt.mapType;
  39209. // Put x, y, width, height, x2, y2 in the top level
  39210. defaults(seriesOpt, seriesOpt.mapLocation);
  39211. }
  39212. });
  39213. };
  39214. /*
  39215. * Licensed to the Apache Software Foundation (ASF) under one
  39216. * or more contributor license agreements. See the NOTICE file
  39217. * distributed with this work for additional information
  39218. * regarding copyright ownership. The ASF licenses this file
  39219. * to you under the Apache License, Version 2.0 (the
  39220. * "License"); you may not use this file except in compliance
  39221. * with the License. You may obtain a copy of the License at
  39222. *
  39223. * http://www.apache.org/licenses/LICENSE-2.0
  39224. *
  39225. * Unless required by applicable law or agreed to in writing,
  39226. * software distributed under the License is distributed on an
  39227. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39228. * KIND, either express or implied. See the License for the
  39229. * specific language governing permissions and limitations
  39230. * under the License.
  39231. */
  39232. registerLayout(mapSymbolLayout);
  39233. registerVisual(mapVisual);
  39234. registerProcessor(PRIORITY.PROCESSOR.STATISTIC, mapDataStatistic);
  39235. registerPreprocessor(backwardCompat$2);
  39236. createDataSelectAction('map', [{
  39237. type: 'mapToggleSelect',
  39238. event: 'mapselectchanged',
  39239. method: 'toggleSelected'
  39240. }, {
  39241. type: 'mapSelect',
  39242. event: 'mapselected',
  39243. method: 'select'
  39244. }, {
  39245. type: 'mapUnSelect',
  39246. event: 'mapunselected',
  39247. method: 'unSelect'
  39248. }]);
  39249. /*
  39250. * Licensed to the Apache Software Foundation (ASF) under one
  39251. * or more contributor license agreements. See the NOTICE file
  39252. * distributed with this work for additional information
  39253. * regarding copyright ownership. The ASF licenses this file
  39254. * to you under the Apache License, Version 2.0 (the
  39255. * "License"); you may not use this file except in compliance
  39256. * with the License. You may obtain a copy of the License at
  39257. *
  39258. * http://www.apache.org/licenses/LICENSE-2.0
  39259. *
  39260. * Unless required by applicable law or agreed to in writing,
  39261. * software distributed under the License is distributed on an
  39262. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39263. * KIND, either express or implied. See the License for the
  39264. * specific language governing permissions and limitations
  39265. * under the License.
  39266. */
  39267. /**
  39268. * Link lists and struct (graph or tree)
  39269. */
  39270. var each$7 = each$1;
  39271. var DATAS = '\0__link_datas';
  39272. var MAIN_DATA = '\0__link_mainData';
  39273. // Caution:
  39274. // In most case, either list or its shallow clones (see list.cloneShallow)
  39275. // is active in echarts process. So considering heap memory consumption,
  39276. // we do not clone tree or graph, but share them among list and its shallow clones.
  39277. // But in some rare case, we have to keep old list (like do animation in chart). So
  39278. // please take care that both the old list and the new list share the same tree/graph.
  39279. /**
  39280. * @param {Object} opt
  39281. * @param {module:echarts/data/List} opt.mainData
  39282. * @param {Object} [opt.struct] For example, instance of Graph or Tree.
  39283. * @param {string} [opt.structAttr] designation: list[structAttr] = struct;
  39284. * @param {Object} [opt.datas] {dataType: data},
  39285. * like: {node: nodeList, edge: edgeList}.
  39286. * Should contain mainData.
  39287. * @param {Object} [opt.datasAttr] {dataType: attr},
  39288. * designation: struct[datasAttr[dataType]] = list;
  39289. */
  39290. function linkList(opt) {
  39291. var mainData = opt.mainData;
  39292. var datas = opt.datas;
  39293. if (!datas) {
  39294. datas = {main: mainData};
  39295. opt.datasAttr = {main: 'data'};
  39296. }
  39297. opt.datas = opt.mainData = null;
  39298. linkAll(mainData, datas, opt);
  39299. // Porxy data original methods.
  39300. each$7(datas, function (data) {
  39301. each$7(mainData.TRANSFERABLE_METHODS, function (methodName) {
  39302. data.wrapMethod(methodName, curry(transferInjection, opt));
  39303. });
  39304. });
  39305. // Beyond transfer, additional features should be added to `cloneShallow`.
  39306. mainData.wrapMethod('cloneShallow', curry(cloneShallowInjection, opt));
  39307. // Only mainData trigger change, because struct.update may trigger
  39308. // another changable methods, which may bring about dead lock.
  39309. each$7(mainData.CHANGABLE_METHODS, function (methodName) {
  39310. mainData.wrapMethod(methodName, curry(changeInjection, opt));
  39311. });
  39312. // Make sure datas contains mainData.
  39313. assert$1(datas[mainData.dataType] === mainData);
  39314. }
  39315. function transferInjection(opt, res) {
  39316. if (isMainData(this)) {
  39317. // Transfer datas to new main data.
  39318. var datas = extend({}, this[DATAS]);
  39319. datas[this.dataType] = res;
  39320. linkAll(res, datas, opt);
  39321. }
  39322. else {
  39323. // Modify the reference in main data to point newData.
  39324. linkSingle(res, this.dataType, this[MAIN_DATA], opt);
  39325. }
  39326. return res;
  39327. }
  39328. function changeInjection(opt, res) {
  39329. opt.struct && opt.struct.update(this);
  39330. return res;
  39331. }
  39332. function cloneShallowInjection(opt, res) {
  39333. // cloneShallow, which brings about some fragilities, may be inappropriate
  39334. // to be exposed as an API. So for implementation simplicity we can make
  39335. // the restriction that cloneShallow of not-mainData should not be invoked
  39336. // outside, but only be invoked here.
  39337. each$7(res[DATAS], function (data, dataType) {
  39338. data !== res && linkSingle(data.cloneShallow(), dataType, res, opt);
  39339. });
  39340. return res;
  39341. }
  39342. /**
  39343. * Supplement method to List.
  39344. *
  39345. * @public
  39346. * @param {string} [dataType] If not specified, return mainData.
  39347. * @return {module:echarts/data/List}
  39348. */
  39349. function getLinkedData(dataType) {
  39350. var mainData = this[MAIN_DATA];
  39351. return (dataType == null || mainData == null)
  39352. ? mainData
  39353. : mainData[DATAS][dataType];
  39354. }
  39355. function isMainData(data) {
  39356. return data[MAIN_DATA] === data;
  39357. }
  39358. function linkAll(mainData, datas, opt) {
  39359. mainData[DATAS] = {};
  39360. each$7(datas, function (data, dataType) {
  39361. linkSingle(data, dataType, mainData, opt);
  39362. });
  39363. }
  39364. function linkSingle(data, dataType, mainData, opt) {
  39365. mainData[DATAS][dataType] = data;
  39366. data[MAIN_DATA] = mainData;
  39367. data.dataType = dataType;
  39368. if (opt.struct) {
  39369. data[opt.structAttr] = opt.struct;
  39370. opt.struct[opt.datasAttr[dataType]] = data;
  39371. }
  39372. // Supplement method.
  39373. data.getLinkedData = getLinkedData;
  39374. }
  39375. /*
  39376. * Licensed to the Apache Software Foundation (ASF) under one
  39377. * or more contributor license agreements. See the NOTICE file
  39378. * distributed with this work for additional information
  39379. * regarding copyright ownership. The ASF licenses this file
  39380. * to you under the Apache License, Version 2.0 (the
  39381. * "License"); you may not use this file except in compliance
  39382. * with the License. You may obtain a copy of the License at
  39383. *
  39384. * http://www.apache.org/licenses/LICENSE-2.0
  39385. *
  39386. * Unless required by applicable law or agreed to in writing,
  39387. * software distributed under the License is distributed on an
  39388. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39389. * KIND, either express or implied. See the License for the
  39390. * specific language governing permissions and limitations
  39391. * under the License.
  39392. */
  39393. /**
  39394. * Tree data structure
  39395. *
  39396. * @module echarts/data/Tree
  39397. */
  39398. /**
  39399. * @constructor module:echarts/data/Tree~TreeNode
  39400. * @param {string} name
  39401. * @param {module:echarts/data/Tree} hostTree
  39402. */
  39403. var TreeNode = function (name, hostTree) {
  39404. /**
  39405. * @type {string}
  39406. */
  39407. this.name = name || '';
  39408. /**
  39409. * Depth of node
  39410. *
  39411. * @type {number}
  39412. * @readOnly
  39413. */
  39414. this.depth = 0;
  39415. /**
  39416. * Height of the subtree rooted at this node.
  39417. * @type {number}
  39418. * @readOnly
  39419. */
  39420. this.height = 0;
  39421. /**
  39422. * @type {module:echarts/data/Tree~TreeNode}
  39423. * @readOnly
  39424. */
  39425. this.parentNode = null;
  39426. /**
  39427. * Reference to list item.
  39428. * Do not persistent dataIndex outside,
  39429. * besause it may be changed by list.
  39430. * If dataIndex -1,
  39431. * this node is logical deleted (filtered) in list.
  39432. *
  39433. * @type {Object}
  39434. * @readOnly
  39435. */
  39436. this.dataIndex = -1;
  39437. /**
  39438. * @type {Array.<module:echarts/data/Tree~TreeNode>}
  39439. * @readOnly
  39440. */
  39441. this.children = [];
  39442. /**
  39443. * @type {Array.<module:echarts/data/Tree~TreeNode>}
  39444. * @pubilc
  39445. */
  39446. this.viewChildren = [];
  39447. /**
  39448. * @type {moduel:echarts/data/Tree}
  39449. * @readOnly
  39450. */
  39451. this.hostTree = hostTree;
  39452. };
  39453. TreeNode.prototype = {
  39454. constructor: TreeNode,
  39455. /**
  39456. * The node is removed.
  39457. * @return {boolean} is removed.
  39458. */
  39459. isRemoved: function () {
  39460. return this.dataIndex < 0;
  39461. },
  39462. /**
  39463. * Travel this subtree (include this node).
  39464. * Usage:
  39465. * node.eachNode(function () { ... }); // preorder
  39466. * node.eachNode('preorder', function () { ... }); // preorder
  39467. * node.eachNode('postorder', function () { ... }); // postorder
  39468. * node.eachNode(
  39469. * {order: 'postorder', attr: 'viewChildren'},
  39470. * function () { ... }
  39471. * ); // postorder
  39472. *
  39473. * @param {(Object|string)} options If string, means order.
  39474. * @param {string=} options.order 'preorder' or 'postorder'
  39475. * @param {string=} options.attr 'children' or 'viewChildren'
  39476. * @param {Function} cb If in preorder and return false,
  39477. * its subtree will not be visited.
  39478. * @param {Object} [context]
  39479. */
  39480. eachNode: function (options, cb, context) {
  39481. if (typeof options === 'function') {
  39482. context = cb;
  39483. cb = options;
  39484. options = null;
  39485. }
  39486. options = options || {};
  39487. if (isString(options)) {
  39488. options = {order: options};
  39489. }
  39490. var order = options.order || 'preorder';
  39491. var children = this[options.attr || 'children'];
  39492. var suppressVisitSub;
  39493. order === 'preorder' && (suppressVisitSub = cb.call(context, this));
  39494. for (var i = 0; !suppressVisitSub && i < children.length; i++) {
  39495. children[i].eachNode(options, cb, context);
  39496. }
  39497. order === 'postorder' && cb.call(context, this);
  39498. },
  39499. /**
  39500. * Update depth and height of this subtree.
  39501. *
  39502. * @param {number} depth
  39503. */
  39504. updateDepthAndHeight: function (depth) {
  39505. var height = 0;
  39506. this.depth = depth;
  39507. for (var i = 0; i < this.children.length; i++) {
  39508. var child = this.children[i];
  39509. child.updateDepthAndHeight(depth + 1);
  39510. if (child.height > height) {
  39511. height = child.height;
  39512. }
  39513. }
  39514. this.height = height + 1;
  39515. },
  39516. /**
  39517. * @param {string} id
  39518. * @return {module:echarts/data/Tree~TreeNode}
  39519. */
  39520. getNodeById: function (id) {
  39521. if (this.getId() === id) {
  39522. return this;
  39523. }
  39524. for (var i = 0, children = this.children, len = children.length; i < len; i++) {
  39525. var res = children[i].getNodeById(id);
  39526. if (res) {
  39527. return res;
  39528. }
  39529. }
  39530. },
  39531. /**
  39532. * @param {module:echarts/data/Tree~TreeNode} node
  39533. * @return {boolean}
  39534. */
  39535. contains: function (node) {
  39536. if (node === this) {
  39537. return true;
  39538. }
  39539. for (var i = 0, children = this.children, len = children.length; i < len; i++) {
  39540. var res = children[i].contains(node);
  39541. if (res) {
  39542. return res;
  39543. }
  39544. }
  39545. },
  39546. /**
  39547. * @param {boolean} includeSelf Default false.
  39548. * @return {Array.<module:echarts/data/Tree~TreeNode>} order: [root, child, grandchild, ...]
  39549. */
  39550. getAncestors: function (includeSelf) {
  39551. var ancestors = [];
  39552. var node = includeSelf ? this : this.parentNode;
  39553. while (node) {
  39554. ancestors.push(node);
  39555. node = node.parentNode;
  39556. }
  39557. ancestors.reverse();
  39558. return ancestors;
  39559. },
  39560. /**
  39561. * @param {string|Array=} [dimension='value'] Default 'value'. can be 0, 1, 2, 3
  39562. * @return {number} Value.
  39563. */
  39564. getValue: function (dimension) {
  39565. var data = this.hostTree.data;
  39566. return data.get(data.getDimension(dimension || 'value'), this.dataIndex);
  39567. },
  39568. /**
  39569. * @param {Object} layout
  39570. * @param {boolean=} [merge=false]
  39571. */
  39572. setLayout: function (layout, merge$$1) {
  39573. this.dataIndex >= 0
  39574. && this.hostTree.data.setItemLayout(this.dataIndex, layout, merge$$1);
  39575. },
  39576. /**
  39577. * @return {Object} layout
  39578. */
  39579. getLayout: function () {
  39580. return this.hostTree.data.getItemLayout(this.dataIndex);
  39581. },
  39582. /**
  39583. * @param {string} [path]
  39584. * @return {module:echarts/model/Model}
  39585. */
  39586. getModel: function (path) {
  39587. if (this.dataIndex < 0) {
  39588. return;
  39589. }
  39590. var hostTree = this.hostTree;
  39591. var itemModel = hostTree.data.getItemModel(this.dataIndex);
  39592. var levelModel = this.getLevelModel();
  39593. var leavesModel;
  39594. if (!levelModel && (this.children.length === 0 || (this.children.length !== 0 && this.isExpand === false))) {
  39595. leavesModel = this.getLeavesModel();
  39596. }
  39597. return itemModel.getModel(path, (levelModel || leavesModel || hostTree.hostModel).getModel(path));
  39598. },
  39599. /**
  39600. * @return {module:echarts/model/Model}
  39601. */
  39602. getLevelModel: function () {
  39603. return (this.hostTree.levelModels || [])[this.depth];
  39604. },
  39605. /**
  39606. * @return {module:echarts/model/Model}
  39607. */
  39608. getLeavesModel: function () {
  39609. return this.hostTree.leavesModel;
  39610. },
  39611. /**
  39612. * @example
  39613. * setItemVisual('color', color);
  39614. * setItemVisual({
  39615. * 'color': color
  39616. * });
  39617. */
  39618. setVisual: function (key, value) {
  39619. this.dataIndex >= 0
  39620. && this.hostTree.data.setItemVisual(this.dataIndex, key, value);
  39621. },
  39622. /**
  39623. * Get item visual
  39624. */
  39625. getVisual: function (key, ignoreParent) {
  39626. return this.hostTree.data.getItemVisual(this.dataIndex, key, ignoreParent);
  39627. },
  39628. /**
  39629. * @public
  39630. * @return {number}
  39631. */
  39632. getRawIndex: function () {
  39633. return this.hostTree.data.getRawIndex(this.dataIndex);
  39634. },
  39635. /**
  39636. * @public
  39637. * @return {string}
  39638. */
  39639. getId: function () {
  39640. return this.hostTree.data.getId(this.dataIndex);
  39641. },
  39642. /**
  39643. * if this is an ancestor of another node
  39644. *
  39645. * @public
  39646. * @param {TreeNode} node another node
  39647. * @return {boolean} if is ancestor
  39648. */
  39649. isAncestorOf: function (node) {
  39650. var parent = node.parentNode;
  39651. while (parent) {
  39652. if (parent === this) {
  39653. return true;
  39654. }
  39655. parent = parent.parentNode;
  39656. }
  39657. return false;
  39658. },
  39659. /**
  39660. * if this is an descendant of another node
  39661. *
  39662. * @public
  39663. * @param {TreeNode} node another node
  39664. * @return {boolean} if is descendant
  39665. */
  39666. isDescendantOf: function (node) {
  39667. return node !== this && node.isAncestorOf(this);
  39668. }
  39669. };
  39670. /**
  39671. * @constructor
  39672. * @alias module:echarts/data/Tree
  39673. * @param {module:echarts/model/Model} hostModel
  39674. * @param {Array.<Object>} levelOptions
  39675. * @param {Object} leavesOption
  39676. */
  39677. function Tree(hostModel, levelOptions, leavesOption) {
  39678. /**
  39679. * @type {module:echarts/data/Tree~TreeNode}
  39680. * @readOnly
  39681. */
  39682. this.root;
  39683. /**
  39684. * @type {module:echarts/data/List}
  39685. * @readOnly
  39686. */
  39687. this.data;
  39688. /**
  39689. * Index of each item is the same as the raw index of coresponding list item.
  39690. * @private
  39691. * @type {Array.<module:echarts/data/Tree~TreeNode}
  39692. */
  39693. this._nodes = [];
  39694. /**
  39695. * @private
  39696. * @readOnly
  39697. * @type {module:echarts/model/Model}
  39698. */
  39699. this.hostModel = hostModel;
  39700. /**
  39701. * @private
  39702. * @readOnly
  39703. * @type {Array.<module:echarts/model/Model}
  39704. */
  39705. this.levelModels = map(levelOptions || [], function (levelDefine) {
  39706. return new Model(levelDefine, hostModel, hostModel.ecModel);
  39707. });
  39708. this.leavesModel = new Model(leavesOption || {}, hostModel, hostModel.ecModel);
  39709. }
  39710. Tree.prototype = {
  39711. constructor: Tree,
  39712. type: 'tree',
  39713. /**
  39714. * Travel this subtree (include this node).
  39715. * Usage:
  39716. * node.eachNode(function () { ... }); // preorder
  39717. * node.eachNode('preorder', function () { ... }); // preorder
  39718. * node.eachNode('postorder', function () { ... }); // postorder
  39719. * node.eachNode(
  39720. * {order: 'postorder', attr: 'viewChildren'},
  39721. * function () { ... }
  39722. * ); // postorder
  39723. *
  39724. * @param {(Object|string)} options If string, means order.
  39725. * @param {string=} options.order 'preorder' or 'postorder'
  39726. * @param {string=} options.attr 'children' or 'viewChildren'
  39727. * @param {Function} cb
  39728. * @param {Object} [context]
  39729. */
  39730. eachNode: function(options, cb, context) {
  39731. this.root.eachNode(options, cb, context);
  39732. },
  39733. /**
  39734. * @param {number} dataIndex
  39735. * @return {module:echarts/data/Tree~TreeNode}
  39736. */
  39737. getNodeByDataIndex: function (dataIndex) {
  39738. var rawIndex = this.data.getRawIndex(dataIndex);
  39739. return this._nodes[rawIndex];
  39740. },
  39741. /**
  39742. * @param {string} name
  39743. * @return {module:echarts/data/Tree~TreeNode}
  39744. */
  39745. getNodeByName: function (name) {
  39746. return this.root.getNodeByName(name);
  39747. },
  39748. /**
  39749. * Update item available by list,
  39750. * when list has been performed options like 'filterSelf' or 'map'.
  39751. */
  39752. update: function () {
  39753. var data = this.data;
  39754. var nodes = this._nodes;
  39755. for (var i = 0, len = nodes.length; i < len; i++) {
  39756. nodes[i].dataIndex = -1;
  39757. }
  39758. for (var i = 0, len = data.count(); i < len; i++) {
  39759. nodes[data.getRawIndex(i)].dataIndex = i;
  39760. }
  39761. },
  39762. /**
  39763. * Clear all layouts
  39764. */
  39765. clearLayouts: function () {
  39766. this.data.clearItemLayouts();
  39767. }
  39768. };
  39769. /**
  39770. * data node format:
  39771. * {
  39772. * name: ...
  39773. * value: ...
  39774. * children: [
  39775. * {
  39776. * name: ...
  39777. * value: ...
  39778. * children: ...
  39779. * },
  39780. * ...
  39781. * ]
  39782. * }
  39783. *
  39784. * @static
  39785. * @param {Object} dataRoot Root node.
  39786. * @param {module:echarts/model/Model} hostModel
  39787. * @param {Object} treeOptions
  39788. * @param {Array.<Object>} treeOptions.levels
  39789. * @param {Array.<Object>} treeOptions.leaves
  39790. * @return module:echarts/data/Tree
  39791. */
  39792. Tree.createTree = function (dataRoot, hostModel, treeOptions) {
  39793. var tree = new Tree(hostModel, treeOptions.levels, treeOptions.leaves);
  39794. var listData = [];
  39795. var dimMax = 1;
  39796. buildHierarchy(dataRoot);
  39797. function buildHierarchy(dataNode, parentNode) {
  39798. var value = dataNode.value;
  39799. dimMax = Math.max(dimMax, isArray(value) ? value.length : 1);
  39800. listData.push(dataNode);
  39801. var node = new TreeNode(dataNode.name, tree);
  39802. parentNode
  39803. ? addChild(node, parentNode)
  39804. : (tree.root = node);
  39805. tree._nodes.push(node);
  39806. var children = dataNode.children;
  39807. if (children) {
  39808. for (var i = 0; i < children.length; i++) {
  39809. buildHierarchy(children[i], node);
  39810. }
  39811. }
  39812. }
  39813. tree.root.updateDepthAndHeight(0);
  39814. var dimensionsInfo = createDimensions(listData, {
  39815. coordDimensions: ['value'],
  39816. dimensionsCount: dimMax
  39817. });
  39818. var list = new List(dimensionsInfo, hostModel);
  39819. list.initData(listData);
  39820. linkList({
  39821. mainData: list,
  39822. struct: tree,
  39823. structAttr: 'tree'
  39824. });
  39825. tree.update();
  39826. return tree;
  39827. };
  39828. /**
  39829. * It is needed to consider the mess of 'list', 'hostModel' when creating a TreeNote,
  39830. * so this function is not ready and not necessary to be public.
  39831. *
  39832. * @param {(module:echarts/data/Tree~TreeNode|Object)} child
  39833. */
  39834. function addChild(child, node) {
  39835. var children = node.children;
  39836. if (child.parentNode === node) {
  39837. return;
  39838. }
  39839. children.push(child);
  39840. child.parentNode = node;
  39841. }
  39842. /*
  39843. * Licensed to the Apache Software Foundation (ASF) under one
  39844. * or more contributor license agreements. See the NOTICE file
  39845. * distributed with this work for additional information
  39846. * regarding copyright ownership. The ASF licenses this file
  39847. * to you under the Apache License, Version 2.0 (the
  39848. * "License"); you may not use this file except in compliance
  39849. * with the License. You may obtain a copy of the License at
  39850. *
  39851. * http://www.apache.org/licenses/LICENSE-2.0
  39852. *
  39853. * Unless required by applicable law or agreed to in writing,
  39854. * software distributed under the License is distributed on an
  39855. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39856. * KIND, either express or implied. See the License for the
  39857. * specific language governing permissions and limitations
  39858. * under the License.
  39859. */
  39860. /**
  39861. * @file Create data struct and define tree view's series model
  39862. */
  39863. SeriesModel.extend({
  39864. type: 'series.tree',
  39865. layoutInfo: null,
  39866. // can support the position parameters 'left', 'top','right','bottom', 'width',
  39867. // 'height' in the setOption() with 'merge' mode normal.
  39868. layoutMode: 'box',
  39869. /**
  39870. * Init a tree data structure from data in option series
  39871. * @param {Object} option the object used to config echarts view
  39872. * @return {module:echarts/data/List} storage initial data
  39873. */
  39874. getInitialData: function (option) {
  39875. //create an virtual root
  39876. var root = {name: option.name, children: option.data};
  39877. var leaves = option.leaves || {};
  39878. var treeOption = {};
  39879. treeOption.leaves = leaves;
  39880. var tree = Tree.createTree(root, this, treeOption);
  39881. var treeDepth = 0;
  39882. tree.eachNode('preorder', function (node) {
  39883. if (node.depth > treeDepth) {
  39884. treeDepth = node.depth;
  39885. }
  39886. });
  39887. var expandAndCollapse = option.expandAndCollapse;
  39888. var expandTreeDepth = (expandAndCollapse && option.initialTreeDepth >= 0)
  39889. ? option.initialTreeDepth : treeDepth;
  39890. tree.root.eachNode('preorder', function (node) {
  39891. var item = node.hostTree.data.getRawDataItem(node.dataIndex);
  39892. // add item.collapsed != null, because users can collapse node original in the series.data.
  39893. node.isExpand = (item && item.collapsed != null)
  39894. ? !item.collapsed
  39895. : node.depth <= expandTreeDepth;
  39896. });
  39897. return tree.data;
  39898. },
  39899. /**
  39900. * Make the configuration 'orient' backward compatibly, with 'horizontal = LR', 'vertical = TB'.
  39901. * @returns {string} orient
  39902. */
  39903. getOrient: function () {
  39904. var orient = this.get('orient');
  39905. if (orient === 'horizontal') {
  39906. orient = 'LR';
  39907. }
  39908. else if (orient === 'vertical') {
  39909. orient = 'TB';
  39910. }
  39911. return orient;
  39912. },
  39913. /**
  39914. * @override
  39915. * @param {number} dataIndex
  39916. */
  39917. formatTooltip: function (dataIndex) {
  39918. var tree = this.getData().tree;
  39919. var realRoot = tree.root.children[0];
  39920. var node = tree.getNodeByDataIndex(dataIndex);
  39921. var value = node.getValue();
  39922. var name = node.name;
  39923. while (node && (node !== realRoot)) {
  39924. name = node.parentNode.name + '.' + name;
  39925. node = node.parentNode;
  39926. }
  39927. return encodeHTML(name + (
  39928. (isNaN(value) || value == null) ? '' : ' : ' + value
  39929. ));
  39930. },
  39931. defaultOption: {
  39932. zlevel: 0,
  39933. z: 2,
  39934. // the position of the whole view
  39935. left: '12%',
  39936. top: '12%',
  39937. right: '12%',
  39938. bottom: '12%',
  39939. // the layout of the tree, two value can be selected, 'orthogonal' or 'radial'
  39940. layout: 'orthogonal',
  39941. // The orient of orthoginal layout, can be setted to 'LR', 'TB', 'RL', 'BT'.
  39942. // and the backward compatibility configuration 'horizontal = LR', 'vertical = TB'.
  39943. orient: 'LR',
  39944. symbol: 'emptyCircle',
  39945. symbolSize: 7,
  39946. expandAndCollapse: true,
  39947. initialTreeDepth: 2,
  39948. lineStyle: {
  39949. color: '#ccc',
  39950. width: 1.5,
  39951. curveness: 0.5
  39952. },
  39953. itemStyle: {
  39954. color: 'lightsteelblue',
  39955. borderColor: '#c23531',
  39956. borderWidth: 1.5
  39957. },
  39958. label: {
  39959. show: true,
  39960. color: '#555'
  39961. },
  39962. leaves: {
  39963. label: {
  39964. show: true
  39965. }
  39966. },
  39967. animationEasing: 'linear',
  39968. animationDuration: 700,
  39969. animationDurationUpdate: 1000
  39970. }
  39971. });
  39972. /*
  39973. * Licensed to the Apache Software Foundation (ASF) under one
  39974. * or more contributor license agreements. See the NOTICE file
  39975. * distributed with this work for additional information
  39976. * regarding copyright ownership. The ASF licenses this file
  39977. * to you under the Apache License, Version 2.0 (the
  39978. * "License"); you may not use this file except in compliance
  39979. * with the License. You may obtain a copy of the License at
  39980. *
  39981. * http://www.apache.org/licenses/LICENSE-2.0
  39982. *
  39983. * Unless required by applicable law or agreed to in writing,
  39984. * software distributed under the License is distributed on an
  39985. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39986. * KIND, either express or implied. See the License for the
  39987. * specific language governing permissions and limitations
  39988. * under the License.
  39989. */
  39990. /**
  39991. * @file The layout algorithm of node-link tree diagrams. Here we using Reingold-Tilford algorithm to drawing
  39992. * the tree.
  39993. * @see https://github.com/d3/d3-hierarchy
  39994. */
  39995. /**
  39996. * Initialize all computational message for following algorithm
  39997. * @param {module:echarts/data/Tree~TreeNode} root The virtual root of the tree
  39998. */
  39999. function init$2(root) {
  40000. root.hierNode = {
  40001. defaultAncestor: null,
  40002. ancestor: root,
  40003. prelim: 0,
  40004. modifier: 0,
  40005. change: 0,
  40006. shift: 0,
  40007. i: 0,
  40008. thread: null
  40009. };
  40010. var nodes = [root];
  40011. var node;
  40012. var children;
  40013. while (node = nodes.pop()) { // jshint ignore:line
  40014. children = node.children;
  40015. if (node.isExpand && children.length) {
  40016. var n = children.length;
  40017. for (var i = n - 1; i >= 0; i--) {
  40018. var child = children[i];
  40019. child.hierNode = {
  40020. defaultAncestor: null,
  40021. ancestor: child,
  40022. prelim: 0,
  40023. modifier: 0,
  40024. change: 0,
  40025. shift: 0,
  40026. i: i,
  40027. thread: null
  40028. };
  40029. nodes.push(child);
  40030. }
  40031. }
  40032. }
  40033. }
  40034. /**
  40035. * Computes a preliminary x coordinate for node. Before that, this function is
  40036. * applied recursively to the children of node, as well as the function
  40037. * apportion(). After spacing out the children by calling executeShifts(), the
  40038. * node is placed to the midpoint of its outermost children.
  40039. * @param {module:echarts/data/Tree~TreeNode} node
  40040. * @param {Function} separation
  40041. */
  40042. function firstWalk(node, separation) {
  40043. var children = node.isExpand ? node.children : [];
  40044. var siblings = node.parentNode.children;
  40045. var subtreeW = node.hierNode.i ? siblings[node.hierNode.i -1] : null;
  40046. if (children.length) {
  40047. executeShifts(node);
  40048. var midPoint = (children[0].hierNode.prelim + children[children.length - 1].hierNode.prelim) / 2;
  40049. if (subtreeW) {
  40050. node.hierNode.prelim = subtreeW.hierNode.prelim + separation(node, subtreeW);
  40051. node.hierNode.modifier = node.hierNode.prelim - midPoint;
  40052. }
  40053. else {
  40054. node.hierNode.prelim = midPoint;
  40055. }
  40056. }
  40057. else if (subtreeW) {
  40058. node.hierNode.prelim = subtreeW.hierNode.prelim + separation(node, subtreeW);
  40059. }
  40060. node.parentNode.hierNode.defaultAncestor = apportion(node, subtreeW, node.parentNode.hierNode.defaultAncestor || siblings[0], separation);
  40061. }
  40062. /**
  40063. * Computes all real x-coordinates by summing up the modifiers recursively.
  40064. * @param {module:echarts/data/Tree~TreeNode} node
  40065. */
  40066. function secondWalk(node) {
  40067. var nodeX = node.hierNode.prelim + node.parentNode.hierNode.modifier;
  40068. node.setLayout({x: nodeX}, true);
  40069. node.hierNode.modifier += node.parentNode.hierNode.modifier;
  40070. }
  40071. function separation(cb) {
  40072. return arguments.length ? cb : defaultSeparation;
  40073. }
  40074. /**
  40075. * Transform the common coordinate to radial coordinate
  40076. * @param {number} x
  40077. * @param {number} y
  40078. * @return {Object}
  40079. */
  40080. function radialCoordinate(x, y) {
  40081. var radialCoor = {};
  40082. x -= Math.PI / 2;
  40083. radialCoor.x = y * Math.cos(x);
  40084. radialCoor.y = y * Math.sin(x);
  40085. return radialCoor;
  40086. }
  40087. /**
  40088. * Get the layout position of the whole view
  40089. * @param {module:echarts/model/Series} seriesModel the model object of sankey series
  40090. * @param {module:echarts/ExtensionAPI} api provide the API list that the developer can call
  40091. * @return {module:zrender/core/BoundingRect} size of rect to draw the sankey view
  40092. */
  40093. function getViewRect(seriesModel, api) {
  40094. return getLayoutRect(
  40095. seriesModel.getBoxLayoutParams(), {
  40096. width: api.getWidth(),
  40097. height: api.getHeight()
  40098. }
  40099. );
  40100. }
  40101. /**
  40102. * All other shifts, applied to the smaller subtrees between w- and w+, are
  40103. * performed by this function.
  40104. * @param {module:echarts/data/Tree~TreeNode} node
  40105. */
  40106. function executeShifts(node) {
  40107. var children = node.children;
  40108. var n = children.length;
  40109. var shift = 0;
  40110. var change = 0;
  40111. while (--n >= 0) {
  40112. var child = children[n];
  40113. child.hierNode.prelim += shift;
  40114. child.hierNode.modifier += shift;
  40115. change += child.hierNode.change;
  40116. shift += child.hierNode.shift + change;
  40117. }
  40118. }
  40119. /**
  40120. * The core of the algorithm. Here, a new subtree is combined with the
  40121. * previous subtrees. Threads are used to traverse the inside and outside
  40122. * contours of the left and right subtree up to the highest common level.
  40123. * Whenever two nodes of the inside contours conflict, we compute the left
  40124. * one of the greatest uncommon ancestors using the function nextAncestor()
  40125. * and call moveSubtree() to shift the subtree and prepare the shifts of
  40126. * smaller subtrees. Finally, we add a new thread (if necessary).
  40127. * @param {module:echarts/data/Tree~TreeNode} subtreeV
  40128. * @param {module:echarts/data/Tree~TreeNode} subtreeW
  40129. * @param {module:echarts/data/Tree~TreeNode} ancestor
  40130. * @param {Function} separation
  40131. * @return {module:echarts/data/Tree~TreeNode}
  40132. */
  40133. function apportion(subtreeV, subtreeW, ancestor, separation) {
  40134. if (subtreeW) {
  40135. var nodeOutRight = subtreeV;
  40136. var nodeInRight = subtreeV;
  40137. var nodeOutLeft = nodeInRight.parentNode.children[0];
  40138. var nodeInLeft = subtreeW;
  40139. var sumOutRight = nodeOutRight.hierNode.modifier;
  40140. var sumInRight = nodeInRight.hierNode.modifier;
  40141. var sumOutLeft = nodeOutLeft.hierNode.modifier;
  40142. var sumInLeft = nodeInLeft.hierNode.modifier;
  40143. while (nodeInLeft = nextRight(nodeInLeft), nodeInRight = nextLeft(nodeInRight), nodeInLeft && nodeInRight) {
  40144. nodeOutRight = nextRight(nodeOutRight);
  40145. nodeOutLeft = nextLeft(nodeOutLeft);
  40146. nodeOutRight.hierNode.ancestor = subtreeV;
  40147. var shift = nodeInLeft.hierNode.prelim + sumInLeft - nodeInRight.hierNode.prelim
  40148. - sumInRight + separation(nodeInLeft, nodeInRight);
  40149. if (shift > 0) {
  40150. moveSubtree(nextAncestor(nodeInLeft, subtreeV, ancestor), subtreeV, shift);
  40151. sumInRight += shift;
  40152. sumOutRight += shift;
  40153. }
  40154. sumInLeft += nodeInLeft.hierNode.modifier;
  40155. sumInRight += nodeInRight.hierNode.modifier;
  40156. sumOutRight += nodeOutRight.hierNode.modifier;
  40157. sumOutLeft += nodeOutLeft.hierNode.modifier;
  40158. }
  40159. if (nodeInLeft && !nextRight(nodeOutRight)) {
  40160. nodeOutRight.hierNode.thread = nodeInLeft;
  40161. nodeOutRight.hierNode.modifier += sumInLeft - sumOutRight;
  40162. }
  40163. if (nodeInRight && !nextLeft(nodeOutLeft)) {
  40164. nodeOutLeft.hierNode.thread = nodeInRight;
  40165. nodeOutLeft.hierNode.modifier += sumInRight - sumOutLeft;
  40166. ancestor = subtreeV;
  40167. }
  40168. }
  40169. return ancestor;
  40170. }
  40171. /**
  40172. * This function is used to traverse the right contour of a subtree.
  40173. * It returns the rightmost child of node or the thread of node. The function
  40174. * returns null if and only if node is on the highest depth of its subtree.
  40175. * @param {module:echarts/data/Tree~TreeNode} node
  40176. * @return {module:echarts/data/Tree~TreeNode}
  40177. */
  40178. function nextRight(node) {
  40179. var children = node.children;
  40180. return children.length && node.isExpand ? children[children.length - 1] : node.hierNode.thread;
  40181. }
  40182. /**
  40183. * This function is used to traverse the left contour of a subtree (or a subforest).
  40184. * It returns the leftmost child of node or the thread of node. The function
  40185. * returns null if and only if node is on the highest depth of its subtree.
  40186. * @param {module:echarts/data/Tree~TreeNode} node
  40187. * @return {module:echarts/data/Tree~TreeNode}
  40188. */
  40189. function nextLeft(node) {
  40190. var children = node.children;
  40191. return children.length && node.isExpand ? children[0] : node.hierNode.thread;
  40192. }
  40193. /**
  40194. * If nodeInLeft’s ancestor is a sibling of node, returns nodeInLeft’s ancestor.
  40195. * Otherwise, returns the specified ancestor.
  40196. * @param {module:echarts/data/Tree~TreeNode} nodeInLeft
  40197. * @param {module:echarts/data/Tree~TreeNode} node
  40198. * @param {module:echarts/data/Tree~TreeNode} ancestor
  40199. * @return {module:echarts/data/Tree~TreeNode}
  40200. */
  40201. function nextAncestor(nodeInLeft, node, ancestor) {
  40202. return nodeInLeft.hierNode.ancestor.parentNode === node.parentNode
  40203. ? nodeInLeft.hierNode.ancestor : ancestor;
  40204. }
  40205. /**
  40206. * Shifts the current subtree rooted at wr. This is done by increasing prelim(w+) and modifier(w+) by shift.
  40207. * @param {module:echarts/data/Tree~TreeNode} wl
  40208. * @param {module:echarts/data/Tree~TreeNode} wr
  40209. * @param {number} shift [description]
  40210. */
  40211. function moveSubtree(wl, wr,shift) {
  40212. var change = shift / (wr.hierNode.i - wl.hierNode.i);
  40213. wr.hierNode.change -= change;
  40214. wr.hierNode.shift += shift;
  40215. wr.hierNode.modifier += shift;
  40216. wr.hierNode.prelim += shift;
  40217. wl.hierNode.change += change;
  40218. }
  40219. function defaultSeparation(node1, node2) {
  40220. return node1.parentNode === node2.parentNode ? 1 : 2;
  40221. }
  40222. /*
  40223. * Licensed to the Apache Software Foundation (ASF) under one
  40224. * or more contributor license agreements. See the NOTICE file
  40225. * distributed with this work for additional information
  40226. * regarding copyright ownership. The ASF licenses this file
  40227. * to you under the Apache License, Version 2.0 (the
  40228. * "License"); you may not use this file except in compliance
  40229. * with the License. You may obtain a copy of the License at
  40230. *
  40231. * http://www.apache.org/licenses/LICENSE-2.0
  40232. *
  40233. * Unless required by applicable law or agreed to in writing,
  40234. * software distributed under the License is distributed on an
  40235. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40236. * KIND, either express or implied. See the License for the
  40237. * specific language governing permissions and limitations
  40238. * under the License.
  40239. */
  40240. /**
  40241. * @file This file used to draw tree view
  40242. */
  40243. extendChartView({
  40244. type: 'tree',
  40245. /**
  40246. * Init the chart
  40247. * @override
  40248. * @param {module:echarts/model/Global} ecModel
  40249. * @param {module:echarts/ExtensionAPI} api
  40250. */
  40251. init: function (ecModel, api) {
  40252. /**
  40253. * @private
  40254. * @type {module:echarts/data/Tree}
  40255. */
  40256. this._oldTree;
  40257. /**
  40258. * @private
  40259. * @type {module:zrender/container/Group}
  40260. */
  40261. this._mainGroup = new Group();
  40262. this.group.add(this._mainGroup);
  40263. },
  40264. render: function (seriesModel, ecModel, api, payload) {
  40265. var data = seriesModel.getData();
  40266. var layoutInfo = seriesModel.layoutInfo;
  40267. var group = this._mainGroup;
  40268. var layout = seriesModel.get('layout');
  40269. if (layout === 'radial') {
  40270. group.attr('position', [layoutInfo.x + layoutInfo.width / 2, layoutInfo.y + layoutInfo.height / 2]);
  40271. }
  40272. else {
  40273. group.attr('position', [layoutInfo.x, layoutInfo.y]);
  40274. }
  40275. var oldData = this._data;
  40276. var seriesScope = {
  40277. expandAndCollapse: seriesModel.get('expandAndCollapse'),
  40278. layout: layout,
  40279. orient: seriesModel.getOrient(),
  40280. curvature: seriesModel.get('lineStyle.curveness'),
  40281. symbolRotate: seriesModel.get('symbolRotate'),
  40282. symbolOffset: seriesModel.get('symbolOffset'),
  40283. hoverAnimation: seriesModel.get('hoverAnimation'),
  40284. useNameLabel: true,
  40285. fadeIn: true
  40286. };
  40287. data.diff(oldData)
  40288. .add(function (newIdx) {
  40289. if (symbolNeedsDraw$1(data, newIdx)) {
  40290. // create node and edge
  40291. updateNode(data, newIdx, null, group, seriesModel, seriesScope);
  40292. }
  40293. })
  40294. .update(function (newIdx, oldIdx) {
  40295. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  40296. if (!symbolNeedsDraw$1(data, newIdx)) {
  40297. symbolEl && removeNode(oldData, oldIdx, symbolEl, group, seriesModel, seriesScope);
  40298. return;
  40299. }
  40300. // update node and edge
  40301. updateNode(data, newIdx, symbolEl, group, seriesModel, seriesScope);
  40302. })
  40303. .remove(function (oldIdx) {
  40304. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  40305. // When remove a collapsed node of subtree, since the collapsed
  40306. // node haven't been initialized with a symbol element,
  40307. // you can't found it's symbol element through index.
  40308. // so if we want to remove the symbol element we should insure
  40309. // that the symbol element is not null.
  40310. if (symbolEl) {
  40311. removeNode(oldData, oldIdx, symbolEl, group, seriesModel, seriesScope);
  40312. }
  40313. })
  40314. .execute();
  40315. if (seriesScope.expandAndCollapse === true) {
  40316. data.eachItemGraphicEl(function (el, dataIndex) {
  40317. el.off('click').on('click', function () {
  40318. api.dispatchAction({
  40319. type: 'treeExpandAndCollapse',
  40320. seriesId: seriesModel.id,
  40321. dataIndex: dataIndex
  40322. });
  40323. });
  40324. });
  40325. }
  40326. this._data = data;
  40327. },
  40328. dispose: function () {},
  40329. remove: function () {
  40330. this._mainGroup.removeAll();
  40331. this._data = null;
  40332. }
  40333. });
  40334. function symbolNeedsDraw$1(data, dataIndex) {
  40335. var layout = data.getItemLayout(dataIndex);
  40336. return layout
  40337. && !isNaN(layout.x) && !isNaN(layout.y)
  40338. && data.getItemVisual(dataIndex, 'symbol') !== 'none';
  40339. }
  40340. function getTreeNodeStyle(node, itemModel, seriesScope) {
  40341. seriesScope.itemModel = itemModel;
  40342. seriesScope.itemStyle = itemModel.getModel('itemStyle').getItemStyle();
  40343. seriesScope.hoverItemStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  40344. seriesScope.lineStyle = itemModel.getModel('lineStyle').getLineStyle();
  40345. seriesScope.labelModel = itemModel.getModel('label');
  40346. seriesScope.hoverLabelModel = itemModel.getModel('emphasis.label');
  40347. if (node.isExpand === false && node.children.length !== 0) {
  40348. seriesScope.symbolInnerColor = seriesScope.itemStyle.fill;
  40349. }
  40350. else {
  40351. seriesScope.symbolInnerColor = '#fff';
  40352. }
  40353. return seriesScope;
  40354. }
  40355. function updateNode(data, dataIndex, symbolEl, group, seriesModel, seriesScope) {
  40356. var isInit = !symbolEl;
  40357. var node = data.tree.getNodeByDataIndex(dataIndex);
  40358. var itemModel = node.getModel();
  40359. var seriesScope = getTreeNodeStyle(node, itemModel, seriesScope);
  40360. var virtualRoot = data.tree.root;
  40361. var source = node.parentNode === virtualRoot ? node : node.parentNode || node;
  40362. var sourceSymbolEl = data.getItemGraphicEl(source.dataIndex);
  40363. var sourceLayout = source.getLayout();
  40364. var sourceOldLayout = sourceSymbolEl
  40365. ? {
  40366. x: sourceSymbolEl.position[0],
  40367. y: sourceSymbolEl.position[1],
  40368. rawX: sourceSymbolEl.__radialOldRawX,
  40369. rawY: sourceSymbolEl.__radialOldRawY
  40370. }
  40371. : sourceLayout;
  40372. var targetLayout = node.getLayout();
  40373. if (isInit) {
  40374. symbolEl = new SymbolClz$1(data, dataIndex, seriesScope);
  40375. symbolEl.attr('position', [sourceOldLayout.x, sourceOldLayout.y]);
  40376. }
  40377. else {
  40378. symbolEl.updateData(data, dataIndex, seriesScope);
  40379. }
  40380. symbolEl.__radialOldRawX = symbolEl.__radialRawX;
  40381. symbolEl.__radialOldRawY = symbolEl.__radialRawY;
  40382. symbolEl.__radialRawX = targetLayout.rawX;
  40383. symbolEl.__radialRawY = targetLayout.rawY;
  40384. group.add(symbolEl);
  40385. data.setItemGraphicEl(dataIndex, symbolEl);
  40386. updateProps(symbolEl, {
  40387. position: [targetLayout.x, targetLayout.y]
  40388. }, seriesModel);
  40389. var symbolPath = symbolEl.getSymbolPath();
  40390. if (seriesScope.layout === 'radial') {
  40391. var realRoot = virtualRoot.children[0];
  40392. var rootLayout = realRoot.getLayout();
  40393. var length = realRoot.children.length;
  40394. var rad;
  40395. var isLeft;
  40396. if (targetLayout.x === rootLayout.x && node.isExpand === true) {
  40397. var center = {};
  40398. center.x = (realRoot.children[0].getLayout().x + realRoot.children[length - 1].getLayout().x) / 2;
  40399. center.y = (realRoot.children[0].getLayout().y + realRoot.children[length - 1].getLayout().y) / 2;
  40400. rad = Math.atan2(center.y - rootLayout.y, center.x - rootLayout.x);
  40401. if (rad < 0) {
  40402. rad = Math.PI * 2 + rad;
  40403. }
  40404. isLeft = center.x < rootLayout.x;
  40405. if (isLeft) {
  40406. rad = rad - Math.PI;
  40407. }
  40408. }
  40409. else {
  40410. rad = Math.atan2(targetLayout.y - rootLayout.y, targetLayout.x - rootLayout.x);
  40411. if (rad < 0) {
  40412. rad = Math.PI * 2 + rad;
  40413. }
  40414. if (node.children.length === 0 || (node.children.length !== 0 && node.isExpand === false)) {
  40415. isLeft = targetLayout.x < rootLayout.x;
  40416. if (isLeft) {
  40417. rad = rad - Math.PI;
  40418. }
  40419. }
  40420. else {
  40421. isLeft = targetLayout.x > rootLayout.x;
  40422. if (!isLeft) {
  40423. rad = rad - Math.PI;
  40424. }
  40425. }
  40426. }
  40427. var textPosition = isLeft ? 'left' : 'right';
  40428. symbolPath.setStyle({
  40429. textPosition: textPosition,
  40430. textRotation: -rad,
  40431. textOrigin: 'center',
  40432. verticalAlign: 'middle'
  40433. });
  40434. }
  40435. if (node.parentNode && node.parentNode !== virtualRoot) {
  40436. var edge = symbolEl.__edge;
  40437. if (!edge) {
  40438. edge = symbolEl.__edge = new BezierCurve({
  40439. shape: getEdgeShape(seriesScope, sourceOldLayout, sourceOldLayout),
  40440. style: defaults({opacity: 0}, seriesScope.lineStyle)
  40441. });
  40442. }
  40443. updateProps(edge, {
  40444. shape: getEdgeShape(seriesScope, sourceLayout, targetLayout),
  40445. style: {opacity: 1}
  40446. }, seriesModel);
  40447. group.add(edge);
  40448. }
  40449. }
  40450. function removeNode(data, dataIndex, symbolEl, group, seriesModel, seriesScope) {
  40451. var node = data.tree.getNodeByDataIndex(dataIndex);
  40452. var virtualRoot = data.tree.root;
  40453. var itemModel = node.getModel();
  40454. var seriesScope = getTreeNodeStyle(node, itemModel, seriesScope);
  40455. var source = node.parentNode === virtualRoot ? node : node.parentNode || node;
  40456. var sourceLayout;
  40457. while (sourceLayout = source.getLayout(), sourceLayout == null) {
  40458. source = source.parentNode === virtualRoot ? source : source.parentNode || source;
  40459. }
  40460. updateProps(symbolEl, {
  40461. position: [sourceLayout.x + 1, sourceLayout.y + 1]
  40462. }, seriesModel, function () {
  40463. group.remove(symbolEl);
  40464. data.setItemGraphicEl(dataIndex, null);
  40465. });
  40466. symbolEl.fadeOut(null, {keepLabel: true});
  40467. var edge = symbolEl.__edge;
  40468. if (edge) {
  40469. updateProps(edge, {
  40470. shape: getEdgeShape(seriesScope, sourceLayout, sourceLayout),
  40471. style: {
  40472. opacity: 0
  40473. }
  40474. }, seriesModel, function () {
  40475. group.remove(edge);
  40476. });
  40477. }
  40478. }
  40479. function getEdgeShape(seriesScope, sourceLayout, targetLayout) {
  40480. var cpx1;
  40481. var cpy1;
  40482. var cpx2;
  40483. var cpy2;
  40484. var orient = seriesScope.orient;
  40485. if (seriesScope.layout === 'radial') {
  40486. var x1 = sourceLayout.rawX;
  40487. var y1 = sourceLayout.rawY;
  40488. var x2 = targetLayout.rawX;
  40489. var y2 = targetLayout.rawY;
  40490. var radialCoor1 = radialCoordinate(x1, y1);
  40491. var radialCoor2 = radialCoordinate(x1, y1 + (y2 - y1) * seriesScope.curvature);
  40492. var radialCoor3 = radialCoordinate(x2, y2 + (y1 - y2) * seriesScope.curvature);
  40493. var radialCoor4 = radialCoordinate(x2, y2);
  40494. return {
  40495. x1: radialCoor1.x,
  40496. y1: radialCoor1.y,
  40497. x2: radialCoor4.x,
  40498. y2: radialCoor4.y,
  40499. cpx1: radialCoor2.x,
  40500. cpy1: radialCoor2.y,
  40501. cpx2: radialCoor3.x,
  40502. cpy2: radialCoor3.y
  40503. };
  40504. }
  40505. else {
  40506. var x1 = sourceLayout.x;
  40507. var y1 = sourceLayout.y;
  40508. var x2 = targetLayout.x;
  40509. var y2 = targetLayout.y;
  40510. if (orient === 'LR' || orient === 'RL') {
  40511. cpx1 = x1 + (x2 - x1) * seriesScope.curvature;
  40512. cpy1 = y1;
  40513. cpx2 = x2 + (x1 - x2) * seriesScope.curvature;
  40514. cpy2 = y2;
  40515. }
  40516. if (orient === 'TB' || orient === 'BT') {
  40517. cpx1 = x1;
  40518. cpy1 = y1 + (y2 - y1) * seriesScope.curvature;
  40519. cpx2 = x2;
  40520. cpy2 = y2 + (y1 - y2) * seriesScope.curvature;
  40521. }
  40522. return {
  40523. x1: x1,
  40524. y1: y1,
  40525. x2: x2,
  40526. y2: y2,
  40527. cpx1: cpx1,
  40528. cpy1: cpy1,
  40529. cpx2: cpx2,
  40530. cpy2: cpy2
  40531. };
  40532. }
  40533. }
  40534. /*
  40535. * Licensed to the Apache Software Foundation (ASF) under one
  40536. * or more contributor license agreements. See the NOTICE file
  40537. * distributed with this work for additional information
  40538. * regarding copyright ownership. The ASF licenses this file
  40539. * to you under the Apache License, Version 2.0 (the
  40540. * "License"); you may not use this file except in compliance
  40541. * with the License. You may obtain a copy of the License at
  40542. *
  40543. * http://www.apache.org/licenses/LICENSE-2.0
  40544. *
  40545. * Unless required by applicable law or agreed to in writing,
  40546. * software distributed under the License is distributed on an
  40547. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40548. * KIND, either express or implied. See the License for the
  40549. * specific language governing permissions and limitations
  40550. * under the License.
  40551. */
  40552. registerAction({
  40553. type: 'treeExpandAndCollapse',
  40554. event: 'treeExpandAndCollapse',
  40555. update: 'update'
  40556. }, function (payload, ecModel) {
  40557. ecModel.eachComponent({mainType: 'series', subType: 'tree', query: payload}, function (seriesModel) {
  40558. var dataIndex = payload.dataIndex;
  40559. var tree = seriesModel.getData().tree;
  40560. var node = tree.getNodeByDataIndex(dataIndex);
  40561. node.isExpand = !node.isExpand;
  40562. });
  40563. });
  40564. /*
  40565. * Licensed to the Apache Software Foundation (ASF) under one
  40566. * or more contributor license agreements. See the NOTICE file
  40567. * distributed with this work for additional information
  40568. * regarding copyright ownership. The ASF licenses this file
  40569. * to you under the Apache License, Version 2.0 (the
  40570. * "License"); you may not use this file except in compliance
  40571. * with the License. You may obtain a copy of the License at
  40572. *
  40573. * http://www.apache.org/licenses/LICENSE-2.0
  40574. *
  40575. * Unless required by applicable law or agreed to in writing,
  40576. * software distributed under the License is distributed on an
  40577. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40578. * KIND, either express or implied. See the License for the
  40579. * specific language governing permissions and limitations
  40580. * under the License.
  40581. */
  40582. /**
  40583. * Traverse the tree from bottom to top and do something
  40584. * @param {module:echarts/data/Tree~TreeNode} root The real root of the tree
  40585. * @param {Function} callback
  40586. */
  40587. function eachAfter (root, callback, separation) {
  40588. var nodes = [root];
  40589. var next = [];
  40590. var node;
  40591. while (node = nodes.pop()) { // jshint ignore:line
  40592. next.push(node);
  40593. if (node.isExpand) {
  40594. var children = node.children;
  40595. if (children.length) {
  40596. for (var i = 0; i < children.length; i++) {
  40597. nodes.push(children[i]);
  40598. }
  40599. }
  40600. }
  40601. }
  40602. while (node = next.pop()) { // jshint ignore:line
  40603. callback(node, separation);
  40604. }
  40605. }
  40606. /**
  40607. * Traverse the tree from top to bottom and do something
  40608. * @param {module:echarts/data/Tree~TreeNode} root The real root of the tree
  40609. * @param {Function} callback
  40610. */
  40611. function eachBefore (root, callback) {
  40612. var nodes = [root];
  40613. var node;
  40614. while (node = nodes.pop()) { // jshint ignore:line
  40615. callback(node);
  40616. if (node.isExpand) {
  40617. var children = node.children;
  40618. if (children.length) {
  40619. for (var i = children.length - 1; i >= 0; i--) {
  40620. nodes.push(children[i]);
  40621. }
  40622. }
  40623. }
  40624. }
  40625. }
  40626. /*
  40627. * Licensed to the Apache Software Foundation (ASF) under one
  40628. * or more contributor license agreements. See the NOTICE file
  40629. * distributed with this work for additional information
  40630. * regarding copyright ownership. The ASF licenses this file
  40631. * to you under the Apache License, Version 2.0 (the
  40632. * "License"); you may not use this file except in compliance
  40633. * with the License. You may obtain a copy of the License at
  40634. *
  40635. * http://www.apache.org/licenses/LICENSE-2.0
  40636. *
  40637. * Unless required by applicable law or agreed to in writing,
  40638. * software distributed under the License is distributed on an
  40639. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40640. * KIND, either express or implied. See the License for the
  40641. * specific language governing permissions and limitations
  40642. * under the License.
  40643. */
  40644. var treeLayout = function (ecModel, api) {
  40645. ecModel.eachSeriesByType('tree', function (seriesModel) {
  40646. commonLayout(seriesModel, api);
  40647. });
  40648. };
  40649. function commonLayout(seriesModel, api) {
  40650. var layoutInfo = getViewRect(seriesModel, api);
  40651. seriesModel.layoutInfo = layoutInfo;
  40652. var layout = seriesModel.get('layout');
  40653. var width = 0;
  40654. var height = 0;
  40655. var separation$$1 = null;
  40656. if (layout === 'radial') {
  40657. width = 2 * Math.PI;
  40658. height = Math.min(layoutInfo.height, layoutInfo.width) / 2;
  40659. separation$$1 = separation(function (node1, node2) {
  40660. return (node1.parentNode === node2.parentNode ? 1 : 2) / node1.depth;
  40661. });
  40662. }
  40663. else {
  40664. width = layoutInfo.width;
  40665. height = layoutInfo.height;
  40666. separation$$1 = separation();
  40667. }
  40668. var virtualRoot = seriesModel.getData().tree.root;
  40669. var realRoot = virtualRoot.children[0];
  40670. if (realRoot) {
  40671. init$2(virtualRoot);
  40672. eachAfter(realRoot, firstWalk, separation$$1);
  40673. virtualRoot.hierNode.modifier = - realRoot.hierNode.prelim;
  40674. eachBefore(realRoot, secondWalk);
  40675. var left = realRoot;
  40676. var right = realRoot;
  40677. var bottom = realRoot;
  40678. eachBefore(realRoot, function (node) {
  40679. var x = node.getLayout().x;
  40680. if (x < left.getLayout().x) {
  40681. left = node;
  40682. }
  40683. if (x > right.getLayout().x) {
  40684. right = node;
  40685. }
  40686. if (node.depth > bottom.depth) {
  40687. bottom = node;
  40688. }
  40689. });
  40690. var delta = left === right ? 1 : separation$$1(left, right) / 2;
  40691. var tx = delta - left.getLayout().x;
  40692. var kx = 0;
  40693. var ky = 0;
  40694. var coorX = 0;
  40695. var coorY = 0;
  40696. if (layout === 'radial') {
  40697. kx = width / (right.getLayout().x + delta + tx);
  40698. // here we use (node.depth - 1), bucause the real root's depth is 1
  40699. ky = height / ((bottom.depth - 1) || 1);
  40700. eachBefore(realRoot, function (node) {
  40701. coorX = (node.getLayout().x + tx) * kx;
  40702. coorY = (node.depth - 1) * ky;
  40703. var finalCoor = radialCoordinate(coorX, coorY);
  40704. node.setLayout({x: finalCoor.x, y: finalCoor.y, rawX: coorX, rawY: coorY}, true);
  40705. });
  40706. }
  40707. else {
  40708. var orient = seriesModel.getOrient();
  40709. if (orient === 'RL' || orient === 'LR') {
  40710. ky = height / (right.getLayout().x + delta + tx);
  40711. kx = width / ((bottom.depth - 1) || 1);
  40712. eachBefore(realRoot, function (node) {
  40713. coorY = (node.getLayout().x + tx) * ky;
  40714. coorX = orient === 'LR'
  40715. ? (node.depth - 1) * kx
  40716. : width - (node.depth - 1) * kx;
  40717. node.setLayout({x: coorX, y: coorY}, true);
  40718. });
  40719. }
  40720. else if (orient === 'TB' || orient === 'BT') {
  40721. kx = width / (right.getLayout().x + delta + tx);
  40722. ky = height / ((bottom.depth - 1) || 1);
  40723. eachBefore(realRoot, function (node) {
  40724. coorX = (node.getLayout().x + tx) * kx;
  40725. coorY = orient === 'TB'
  40726. ? (node.depth - 1) * ky
  40727. : height - (node.depth - 1) * ky;
  40728. node.setLayout({x: coorX, y: coorY}, true);
  40729. });
  40730. }
  40731. }
  40732. }
  40733. }
  40734. /*
  40735. * Licensed to the Apache Software Foundation (ASF) under one
  40736. * or more contributor license agreements. See the NOTICE file
  40737. * distributed with this work for additional information
  40738. * regarding copyright ownership. The ASF licenses this file
  40739. * to you under the Apache License, Version 2.0 (the
  40740. * "License"); you may not use this file except in compliance
  40741. * with the License. You may obtain a copy of the License at
  40742. *
  40743. * http://www.apache.org/licenses/LICENSE-2.0
  40744. *
  40745. * Unless required by applicable law or agreed to in writing,
  40746. * software distributed under the License is distributed on an
  40747. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40748. * KIND, either express or implied. See the License for the
  40749. * specific language governing permissions and limitations
  40750. * under the License.
  40751. */
  40752. registerVisual(visualSymbol('tree', 'circle'));
  40753. registerLayout(treeLayout);
  40754. /*
  40755. * Licensed to the Apache Software Foundation (ASF) under one
  40756. * or more contributor license agreements. See the NOTICE file
  40757. * distributed with this work for additional information
  40758. * regarding copyright ownership. The ASF licenses this file
  40759. * to you under the Apache License, Version 2.0 (the
  40760. * "License"); you may not use this file except in compliance
  40761. * with the License. You may obtain a copy of the License at
  40762. *
  40763. * http://www.apache.org/licenses/LICENSE-2.0
  40764. *
  40765. * Unless required by applicable law or agreed to in writing,
  40766. * software distributed under the License is distributed on an
  40767. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40768. * KIND, either express or implied. See the License for the
  40769. * specific language governing permissions and limitations
  40770. * under the License.
  40771. */
  40772. function retrieveTargetInfo(payload, validPayloadTypes, seriesModel) {
  40773. if (payload && indexOf(validPayloadTypes, payload.type) >= 0) {
  40774. var root = seriesModel.getData().tree.root;
  40775. var targetNode = payload.targetNode;
  40776. if (targetNode && root.contains(targetNode)) {
  40777. return {node: targetNode};
  40778. }
  40779. var targetNodeId = payload.targetNodeId;
  40780. if (targetNodeId != null && (targetNode = root.getNodeById(targetNodeId))) {
  40781. return {node: targetNode};
  40782. }
  40783. }
  40784. }
  40785. // Not includes the given node at the last item.
  40786. function getPathToRoot(node) {
  40787. var path = [];
  40788. while (node) {
  40789. node = node.parentNode;
  40790. node && path.push(node);
  40791. }
  40792. return path.reverse();
  40793. }
  40794. function aboveViewRoot(viewRoot, node) {
  40795. var viewPath = getPathToRoot(viewRoot);
  40796. return indexOf(viewPath, node) >= 0;
  40797. }
  40798. // From root to the input node (the input node will be included).
  40799. function wrapTreePathInfo(node, seriesModel) {
  40800. var treePathInfo = [];
  40801. while (node) {
  40802. var nodeDataIndex = node.dataIndex;
  40803. treePathInfo.push({
  40804. name: node.name,
  40805. dataIndex: nodeDataIndex,
  40806. value: seriesModel.getRawValue(nodeDataIndex)
  40807. });
  40808. node = node.parentNode;
  40809. }
  40810. treePathInfo.reverse();
  40811. return treePathInfo;
  40812. }
  40813. /*
  40814. * Licensed to the Apache Software Foundation (ASF) under one
  40815. * or more contributor license agreements. See the NOTICE file
  40816. * distributed with this work for additional information
  40817. * regarding copyright ownership. The ASF licenses this file
  40818. * to you under the Apache License, Version 2.0 (the
  40819. * "License"); you may not use this file except in compliance
  40820. * with the License. You may obtain a copy of the License at
  40821. *
  40822. * http://www.apache.org/licenses/LICENSE-2.0
  40823. *
  40824. * Unless required by applicable law or agreed to in writing,
  40825. * software distributed under the License is distributed on an
  40826. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40827. * KIND, either express or implied. See the License for the
  40828. * specific language governing permissions and limitations
  40829. * under the License.
  40830. */
  40831. SeriesModel.extend({
  40832. type: 'series.treemap',
  40833. layoutMode: 'box',
  40834. dependencies: ['grid', 'polar'],
  40835. /**
  40836. * @type {module:echarts/data/Tree~Node}
  40837. */
  40838. _viewRoot: null,
  40839. defaultOption: {
  40840. // Disable progressive rendering
  40841. progressive: 0,
  40842. hoverLayerThreshold: Infinity,
  40843. // center: ['50%', '50%'], // not supported in ec3.
  40844. // size: ['80%', '80%'], // deprecated, compatible with ec2.
  40845. left: 'center',
  40846. top: 'middle',
  40847. right: null,
  40848. bottom: null,
  40849. width: '80%',
  40850. height: '80%',
  40851. sort: true, // Can be null or false or true
  40852. // (order by desc default, asc not supported yet (strange effect))
  40853. clipWindow: 'origin', // Size of clipped window when zooming. 'origin' or 'fullscreen'
  40854. squareRatio: 0.5 * (1 + Math.sqrt(5)), // golden ratio
  40855. leafDepth: null, // Nodes on depth from root are regarded as leaves.
  40856. // Count from zero (zero represents only view root).
  40857. drillDownIcon: '▶', // Use html character temporarily because it is complicated
  40858. // to align specialized icon. ▷▶❒❐▼✚
  40859. zoomToNodeRatio: 0.32 * 0.32, // Be effective when using zoomToNode. Specify the proportion of the
  40860. // target node area in the view area.
  40861. roam: true, // true, false, 'scale' or 'zoom', 'move'.
  40862. nodeClick: 'zoomToNode', // Leaf node click behaviour: 'zoomToNode', 'link', false.
  40863. // If leafDepth is set and clicking a node which has children but
  40864. // be on left depth, the behaviour would be changing root. Otherwise
  40865. // use behavious defined above.
  40866. animation: true,
  40867. animationDurationUpdate: 900,
  40868. animationEasing: 'quinticInOut',
  40869. breadcrumb: {
  40870. show: true,
  40871. height: 22,
  40872. left: 'center',
  40873. top: 'bottom',
  40874. // right
  40875. // bottom
  40876. emptyItemWidth: 25, // Width of empty node.
  40877. itemStyle: {
  40878. color: 'rgba(0,0,0,0.7)', //'#5793f3',
  40879. borderColor: 'rgba(255,255,255,0.7)',
  40880. borderWidth: 1,
  40881. shadowColor: 'rgba(150,150,150,1)',
  40882. shadowBlur: 3,
  40883. shadowOffsetX: 0,
  40884. shadowOffsetY: 0,
  40885. textStyle: {
  40886. color: '#fff'
  40887. }
  40888. },
  40889. emphasis: {
  40890. textStyle: {}
  40891. }
  40892. },
  40893. label: {
  40894. show: true,
  40895. // Do not use textDistance, for ellipsis rect just the same as treemap node rect.
  40896. distance: 0,
  40897. padding: 5,
  40898. position: 'inside', // Can be [5, '5%'] or position stirng like 'insideTopLeft', ...
  40899. // formatter: null,
  40900. color: '#fff',
  40901. ellipsis: true
  40902. // align
  40903. // verticalAlign
  40904. },
  40905. upperLabel: { // Label when node is parent.
  40906. show: false,
  40907. position: [0, '50%'],
  40908. height: 20,
  40909. // formatter: null,
  40910. color: '#fff',
  40911. ellipsis: true,
  40912. // align: null,
  40913. verticalAlign: 'middle'
  40914. },
  40915. itemStyle: {
  40916. color: null, // Can be 'none' if not necessary.
  40917. colorAlpha: null, // Can be 'none' if not necessary.
  40918. colorSaturation: null, // Can be 'none' if not necessary.
  40919. borderWidth: 0,
  40920. gapWidth: 0,
  40921. borderColor: '#fff',
  40922. borderColorSaturation: null // If specified, borderColor will be ineffective, and the
  40923. // border color is evaluated by color of current node and
  40924. // borderColorSaturation.
  40925. },
  40926. emphasis: {
  40927. upperLabel: {
  40928. show: true,
  40929. position: [0, '50%'],
  40930. color: '#fff',
  40931. ellipsis: true,
  40932. verticalAlign: 'middle'
  40933. }
  40934. },
  40935. visualDimension: 0, // Can be 0, 1, 2, 3.
  40936. visualMin: null,
  40937. visualMax: null,
  40938. color: [], // + treemapSeries.color should not be modified. Please only modified
  40939. // level[n].color (if necessary).
  40940. // + Specify color list of each level. level[0].color would be global
  40941. // color list if not specified. (see method `setDefault`).
  40942. // + But set as a empty array to forbid fetch color from global palette
  40943. // when using nodeModel.get('color'), otherwise nodes on deep level
  40944. // will always has color palette set and are not able to inherit color
  40945. // from parent node.
  40946. // + TreemapSeries.color can not be set as 'none', otherwise effect
  40947. // legend color fetching (see seriesColor.js).
  40948. colorAlpha: null, // Array. Specify color alpha range of each level, like [0.2, 0.8]
  40949. colorSaturation: null, // Array. Specify color saturation of each level, like [0.2, 0.5]
  40950. colorMappingBy: 'index', // 'value' or 'index' or 'id'.
  40951. visibleMin: 10, // If area less than this threshold (unit: pixel^2), node will not
  40952. // be rendered. Only works when sort is 'asc' or 'desc'.
  40953. childrenVisibleMin: null, // If area of a node less than this threshold (unit: pixel^2),
  40954. // grandchildren will not show.
  40955. // Why grandchildren? If not grandchildren but children,
  40956. // some siblings show children and some not,
  40957. // the appearance may be mess and not consistent,
  40958. levels: [] // Each item: {
  40959. // visibleMin, itemStyle, visualDimension, label
  40960. // }
  40961. // data: {
  40962. // value: [],
  40963. // children: [],
  40964. // link: 'http://xxx.xxx.xxx',
  40965. // target: 'blank' or 'self'
  40966. // }
  40967. },
  40968. /**
  40969. * @override
  40970. */
  40971. getInitialData: function (option, ecModel) {
  40972. // Create a virtual root.
  40973. var root = {name: option.name, children: option.data};
  40974. completeTreeValue(root);
  40975. var levels = option.levels || [];
  40976. levels = option.levels = setDefault(levels, ecModel);
  40977. var treeOption = {};
  40978. treeOption.levels = levels;
  40979. // Make sure always a new tree is created when setOption,
  40980. // in TreemapView, we check whether oldTree === newTree
  40981. // to choose mappings approach among old shapes and new shapes.
  40982. return Tree.createTree(root, this, treeOption).data;
  40983. },
  40984. optionUpdated: function () {
  40985. this.resetViewRoot();
  40986. },
  40987. /**
  40988. * @override
  40989. * @param {number} dataIndex
  40990. * @param {boolean} [mutipleSeries=false]
  40991. */
  40992. formatTooltip: function (dataIndex) {
  40993. var data = this.getData();
  40994. var value = this.getRawValue(dataIndex);
  40995. var formattedValue = isArray(value)
  40996. ? addCommas(value[0]) : addCommas(value);
  40997. var name = data.getName(dataIndex);
  40998. return encodeHTML(name + ': ' + formattedValue);
  40999. },
  41000. /**
  41001. * Add tree path to tooltip param
  41002. *
  41003. * @override
  41004. * @param {number} dataIndex
  41005. * @return {Object}
  41006. */
  41007. getDataParams: function (dataIndex) {
  41008. var params = SeriesModel.prototype.getDataParams.apply(this, arguments);
  41009. var node = this.getData().tree.getNodeByDataIndex(dataIndex);
  41010. params.treePathInfo = wrapTreePathInfo(node, this);
  41011. return params;
  41012. },
  41013. /**
  41014. * @public
  41015. * @param {Object} layoutInfo {
  41016. * x: containerGroup x
  41017. * y: containerGroup y
  41018. * width: containerGroup width
  41019. * height: containerGroup height
  41020. * }
  41021. */
  41022. setLayoutInfo: function (layoutInfo) {
  41023. /**
  41024. * @readOnly
  41025. * @type {Object}
  41026. */
  41027. this.layoutInfo = this.layoutInfo || {};
  41028. extend(this.layoutInfo, layoutInfo);
  41029. },
  41030. /**
  41031. * @param {string} id
  41032. * @return {number} index
  41033. */
  41034. mapIdToIndex: function (id) {
  41035. // A feature is implemented:
  41036. // index is monotone increasing with the sequence of
  41037. // input id at the first time.
  41038. // This feature can make sure that each data item and its
  41039. // mapped color have the same index between data list and
  41040. // color list at the beginning, which is useful for user
  41041. // to adjust data-color mapping.
  41042. /**
  41043. * @private
  41044. * @type {Object}
  41045. */
  41046. var idIndexMap = this._idIndexMap;
  41047. if (!idIndexMap) {
  41048. idIndexMap = this._idIndexMap = createHashMap();
  41049. /**
  41050. * @private
  41051. * @type {number}
  41052. */
  41053. this._idIndexMapCount = 0;
  41054. }
  41055. var index = idIndexMap.get(id);
  41056. if (index == null) {
  41057. idIndexMap.set(id, index = this._idIndexMapCount++);
  41058. }
  41059. return index;
  41060. },
  41061. getViewRoot: function () {
  41062. return this._viewRoot;
  41063. },
  41064. /**
  41065. * @param {module:echarts/data/Tree~Node} [viewRoot]
  41066. */
  41067. resetViewRoot: function (viewRoot) {
  41068. viewRoot
  41069. ? (this._viewRoot = viewRoot)
  41070. : (viewRoot = this._viewRoot);
  41071. var root = this.getRawData().tree.root;
  41072. if (!viewRoot
  41073. || (viewRoot !== root && !root.contains(viewRoot))
  41074. ) {
  41075. this._viewRoot = root;
  41076. }
  41077. }
  41078. });
  41079. /**
  41080. * @param {Object} dataNode
  41081. */
  41082. function completeTreeValue(dataNode) {
  41083. // Postorder travel tree.
  41084. // If value of none-leaf node is not set,
  41085. // calculate it by suming up the value of all children.
  41086. var sum = 0;
  41087. each$1(dataNode.children, function (child) {
  41088. completeTreeValue(child);
  41089. var childValue = child.value;
  41090. isArray(childValue) && (childValue = childValue[0]);
  41091. sum += childValue;
  41092. });
  41093. var thisValue = dataNode.value;
  41094. if (isArray(thisValue)) {
  41095. thisValue = thisValue[0];
  41096. }
  41097. if (thisValue == null || isNaN(thisValue)) {
  41098. thisValue = sum;
  41099. }
  41100. // Value should not less than 0.
  41101. if (thisValue < 0) {
  41102. thisValue = 0;
  41103. }
  41104. isArray(dataNode.value)
  41105. ? (dataNode.value[0] = thisValue)
  41106. : (dataNode.value = thisValue);
  41107. }
  41108. /**
  41109. * set default to level configuration
  41110. */
  41111. function setDefault(levels, ecModel) {
  41112. var globalColorList = ecModel.get('color');
  41113. if (!globalColorList) {
  41114. return;
  41115. }
  41116. levels = levels || [];
  41117. var hasColorDefine;
  41118. each$1(levels, function (levelDefine) {
  41119. var model = new Model(levelDefine);
  41120. var modelColor = model.get('color');
  41121. if (model.get('itemStyle.color')
  41122. || (modelColor && modelColor !== 'none')
  41123. ) {
  41124. hasColorDefine = true;
  41125. }
  41126. });
  41127. if (!hasColorDefine) {
  41128. var level0 = levels[0] || (levels[0] = {});
  41129. level0.color = globalColorList.slice();
  41130. }
  41131. return levels;
  41132. }
  41133. /*
  41134. * Licensed to the Apache Software Foundation (ASF) under one
  41135. * or more contributor license agreements. See the NOTICE file
  41136. * distributed with this work for additional information
  41137. * regarding copyright ownership. The ASF licenses this file
  41138. * to you under the Apache License, Version 2.0 (the
  41139. * "License"); you may not use this file except in compliance
  41140. * with the License. You may obtain a copy of the License at
  41141. *
  41142. * http://www.apache.org/licenses/LICENSE-2.0
  41143. *
  41144. * Unless required by applicable law or agreed to in writing,
  41145. * software distributed under the License is distributed on an
  41146. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41147. * KIND, either express or implied. See the License for the
  41148. * specific language governing permissions and limitations
  41149. * under the License.
  41150. */
  41151. var TEXT_PADDING = 8;
  41152. var ITEM_GAP = 8;
  41153. var ARRAY_LENGTH = 5;
  41154. function Breadcrumb(containerGroup) {
  41155. /**
  41156. * @private
  41157. * @type {module:zrender/container/Group}
  41158. */
  41159. this.group = new Group();
  41160. containerGroup.add(this.group);
  41161. }
  41162. Breadcrumb.prototype = {
  41163. constructor: Breadcrumb,
  41164. render: function (seriesModel, api, targetNode, onSelect) {
  41165. var model = seriesModel.getModel('breadcrumb');
  41166. var thisGroup = this.group;
  41167. thisGroup.removeAll();
  41168. if (!model.get('show') || !targetNode) {
  41169. return;
  41170. }
  41171. var normalStyleModel = model.getModel('itemStyle');
  41172. // var emphasisStyleModel = model.getModel('emphasis.itemStyle');
  41173. var textStyleModel = normalStyleModel.getModel('textStyle');
  41174. var layoutParam = {
  41175. pos: {
  41176. left: model.get('left'),
  41177. right: model.get('right'),
  41178. top: model.get('top'),
  41179. bottom: model.get('bottom')
  41180. },
  41181. box: {
  41182. width: api.getWidth(),
  41183. height: api.getHeight()
  41184. },
  41185. emptyItemWidth: model.get('emptyItemWidth'),
  41186. totalWidth: 0,
  41187. renderList: []
  41188. };
  41189. this._prepare(targetNode, layoutParam, textStyleModel);
  41190. this._renderContent(seriesModel, layoutParam, normalStyleModel, textStyleModel, onSelect);
  41191. positionElement(thisGroup, layoutParam.pos, layoutParam.box);
  41192. },
  41193. /**
  41194. * Prepare render list and total width
  41195. * @private
  41196. */
  41197. _prepare: function (targetNode, layoutParam, textStyleModel) {
  41198. for (var node = targetNode; node; node = node.parentNode) {
  41199. var text = node.getModel().get('name');
  41200. var textRect = textStyleModel.getTextRect(text);
  41201. var itemWidth = Math.max(
  41202. textRect.width + TEXT_PADDING * 2,
  41203. layoutParam.emptyItemWidth
  41204. );
  41205. layoutParam.totalWidth += itemWidth + ITEM_GAP;
  41206. layoutParam.renderList.push({node: node, text: text, width: itemWidth});
  41207. }
  41208. },
  41209. /**
  41210. * @private
  41211. */
  41212. _renderContent: function (
  41213. seriesModel, layoutParam, normalStyleModel, textStyleModel, onSelect
  41214. ) {
  41215. // Start rendering.
  41216. var lastX = 0;
  41217. var emptyItemWidth = layoutParam.emptyItemWidth;
  41218. var height = seriesModel.get('breadcrumb.height');
  41219. var availableSize = getAvailableSize(layoutParam.pos, layoutParam.box);
  41220. var totalWidth = layoutParam.totalWidth;
  41221. var renderList = layoutParam.renderList;
  41222. for (var i = renderList.length - 1; i >= 0; i--) {
  41223. var item = renderList[i];
  41224. var itemNode = item.node;
  41225. var itemWidth = item.width;
  41226. var text = item.text;
  41227. // Hdie text and shorten width if necessary.
  41228. if (totalWidth > availableSize.width) {
  41229. totalWidth -= itemWidth - emptyItemWidth;
  41230. itemWidth = emptyItemWidth;
  41231. text = null;
  41232. }
  41233. var el = new Polygon({
  41234. shape: {
  41235. points: makeItemPoints(
  41236. lastX, 0, itemWidth, height,
  41237. i === renderList.length - 1, i === 0
  41238. )
  41239. },
  41240. style: defaults(
  41241. normalStyleModel.getItemStyle(),
  41242. {
  41243. lineJoin: 'bevel',
  41244. text: text,
  41245. textFill: textStyleModel.getTextColor(),
  41246. textFont: textStyleModel.getFont()
  41247. }
  41248. ),
  41249. z: 10,
  41250. onclick: curry(onSelect, itemNode)
  41251. });
  41252. this.group.add(el);
  41253. packEventData(el, seriesModel, itemNode);
  41254. lastX += itemWidth + ITEM_GAP;
  41255. }
  41256. },
  41257. /**
  41258. * @override
  41259. */
  41260. remove: function () {
  41261. this.group.removeAll();
  41262. }
  41263. };
  41264. function makeItemPoints(x, y, itemWidth, itemHeight, head, tail) {
  41265. var points = [
  41266. [head ? x : x - ARRAY_LENGTH, y],
  41267. [x + itemWidth, y],
  41268. [x + itemWidth, y + itemHeight],
  41269. [head ? x : x - ARRAY_LENGTH, y + itemHeight]
  41270. ];
  41271. !tail && points.splice(2, 0, [x + itemWidth + ARRAY_LENGTH, y + itemHeight / 2]);
  41272. !head && points.push([x, y + itemHeight / 2]);
  41273. return points;
  41274. }
  41275. // Package custom mouse event.
  41276. function packEventData(el, seriesModel, itemNode) {
  41277. el.eventData = {
  41278. componentType: 'series',
  41279. componentSubType: 'treemap',
  41280. seriesIndex: seriesModel.componentIndex,
  41281. seriesName: seriesModel.name,
  41282. seriesType: 'treemap',
  41283. selfType: 'breadcrumb', // Distinguish with click event on treemap node.
  41284. nodeData: {
  41285. dataIndex: itemNode && itemNode.dataIndex,
  41286. name: itemNode && itemNode.name
  41287. },
  41288. treePathInfo: itemNode && wrapTreePathInfo(itemNode, seriesModel)
  41289. };
  41290. }
  41291. /*
  41292. * Licensed to the Apache Software Foundation (ASF) under one
  41293. * or more contributor license agreements. See the NOTICE file
  41294. * distributed with this work for additional information
  41295. * regarding copyright ownership. The ASF licenses this file
  41296. * to you under the Apache License, Version 2.0 (the
  41297. * "License"); you may not use this file except in compliance
  41298. * with the License. You may obtain a copy of the License at
  41299. *
  41300. * http://www.apache.org/licenses/LICENSE-2.0
  41301. *
  41302. * Unless required by applicable law or agreed to in writing,
  41303. * software distributed under the License is distributed on an
  41304. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41305. * KIND, either express or implied. See the License for the
  41306. * specific language governing permissions and limitations
  41307. * under the License.
  41308. */
  41309. /**
  41310. * @param {number} [time=500] Time in ms
  41311. * @param {string} [easing='linear']
  41312. * @param {number} [delay=0]
  41313. * @param {Function} [callback]
  41314. *
  41315. * @example
  41316. * // Animate position
  41317. * animation
  41318. * .createWrap()
  41319. * .add(el1, {position: [10, 10]})
  41320. * .add(el2, {shape: {width: 500}, style: {fill: 'red'}}, 400)
  41321. * .done(function () { // done })
  41322. * .start('cubicOut');
  41323. */
  41324. function createWrap() {
  41325. var storage = [];
  41326. var elExistsMap = {};
  41327. var doneCallback;
  41328. return {
  41329. /**
  41330. * Caution: a el can only be added once, otherwise 'done'
  41331. * might not be called. This method checks this (by el.id),
  41332. * suppresses adding and returns false when existing el found.
  41333. *
  41334. * @param {modele:zrender/Element} el
  41335. * @param {Object} target
  41336. * @param {number} [time=500]
  41337. * @param {number} [delay=0]
  41338. * @param {string} [easing='linear']
  41339. * @return {boolean} Whether adding succeeded.
  41340. *
  41341. * @example
  41342. * add(el, target, time, delay, easing);
  41343. * add(el, target, time, easing);
  41344. * add(el, target, time);
  41345. * add(el, target);
  41346. */
  41347. add: function (el, target, time, delay, easing) {
  41348. if (isString(delay)) {
  41349. easing = delay;
  41350. delay = 0;
  41351. }
  41352. if (elExistsMap[el.id]) {
  41353. return false;
  41354. }
  41355. elExistsMap[el.id] = 1;
  41356. storage.push(
  41357. {el: el, target: target, time: time, delay: delay, easing: easing}
  41358. );
  41359. return true;
  41360. },
  41361. /**
  41362. * Only execute when animation finished. Will not execute when any
  41363. * of 'stop' or 'stopAnimation' called.
  41364. *
  41365. * @param {Function} callback
  41366. */
  41367. done: function (callback) {
  41368. doneCallback = callback;
  41369. return this;
  41370. },
  41371. /**
  41372. * Will stop exist animation firstly.
  41373. */
  41374. start: function () {
  41375. var count = storage.length;
  41376. for (var i = 0, len = storage.length; i < len; i++) {
  41377. var item = storage[i];
  41378. item.el.animateTo(item.target, item.time, item.delay, item.easing, done);
  41379. }
  41380. return this;
  41381. function done() {
  41382. count--;
  41383. if (!count) {
  41384. storage.length = 0;
  41385. elExistsMap = {};
  41386. doneCallback && doneCallback();
  41387. }
  41388. }
  41389. }
  41390. };
  41391. }
  41392. /*
  41393. * Licensed to the Apache Software Foundation (ASF) under one
  41394. * or more contributor license agreements. See the NOTICE file
  41395. * distributed with this work for additional information
  41396. * regarding copyright ownership. The ASF licenses this file
  41397. * to you under the Apache License, Version 2.0 (the
  41398. * "License"); you may not use this file except in compliance
  41399. * with the License. You may obtain a copy of the License at
  41400. *
  41401. * http://www.apache.org/licenses/LICENSE-2.0
  41402. *
  41403. * Unless required by applicable law or agreed to in writing,
  41404. * software distributed under the License is distributed on an
  41405. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41406. * KIND, either express or implied. See the License for the
  41407. * specific language governing permissions and limitations
  41408. * under the License.
  41409. */
  41410. var bind$1 = bind;
  41411. var Group$2 = Group;
  41412. var Rect$1 = Rect;
  41413. var each$8 = each$1;
  41414. var DRAG_THRESHOLD = 3;
  41415. var PATH_LABEL_NOAMAL = ['label'];
  41416. var PATH_LABEL_EMPHASIS = ['emphasis', 'label'];
  41417. var PATH_UPPERLABEL_NORMAL = ['upperLabel'];
  41418. var PATH_UPPERLABEL_EMPHASIS = ['emphasis', 'upperLabel'];
  41419. var Z_BASE = 10; // Should bigger than every z.
  41420. var Z_BG = 1;
  41421. var Z_CONTENT = 2;
  41422. var getItemStyleEmphasis = makeStyleMapper([
  41423. ['fill', 'color'],
  41424. // `borderColor` and `borderWidth` has been occupied,
  41425. // so use `stroke` to indicate the stroke of the rect.
  41426. ['stroke', 'strokeColor'],
  41427. ['lineWidth', 'strokeWidth'],
  41428. ['shadowBlur'],
  41429. ['shadowOffsetX'],
  41430. ['shadowOffsetY'],
  41431. ['shadowColor']
  41432. ]);
  41433. var getItemStyleNormal = function (model) {
  41434. // Normal style props should include emphasis style props.
  41435. var itemStyle = getItemStyleEmphasis(model);
  41436. // Clear styles set by emphasis.
  41437. itemStyle.stroke = itemStyle.fill = itemStyle.lineWidth = null;
  41438. return itemStyle;
  41439. };
  41440. extendChartView({
  41441. type: 'treemap',
  41442. /**
  41443. * @override
  41444. */
  41445. init: function (o, api) {
  41446. /**
  41447. * @private
  41448. * @type {module:zrender/container/Group}
  41449. */
  41450. this._containerGroup;
  41451. /**
  41452. * @private
  41453. * @type {Object.<string, Array.<module:zrender/container/Group>>}
  41454. */
  41455. this._storage = createStorage();
  41456. /**
  41457. * @private
  41458. * @type {module:echarts/data/Tree}
  41459. */
  41460. this._oldTree;
  41461. /**
  41462. * @private
  41463. * @type {module:echarts/chart/treemap/Breadcrumb}
  41464. */
  41465. this._breadcrumb;
  41466. /**
  41467. * @private
  41468. * @type {module:echarts/component/helper/RoamController}
  41469. */
  41470. this._controller;
  41471. /**
  41472. * 'ready', 'animating'
  41473. * @private
  41474. */
  41475. this._state = 'ready';
  41476. },
  41477. /**
  41478. * @override
  41479. */
  41480. render: function (seriesModel, ecModel, api, payload) {
  41481. var models = ecModel.findComponents({
  41482. mainType: 'series', subType: 'treemap', query: payload
  41483. });
  41484. if (indexOf(models, seriesModel) < 0) {
  41485. return;
  41486. }
  41487. this.seriesModel = seriesModel;
  41488. this.api = api;
  41489. this.ecModel = ecModel;
  41490. var types = ['treemapZoomToNode', 'treemapRootToNode'];
  41491. var targetInfo = retrieveTargetInfo(payload, types, seriesModel);
  41492. var payloadType = payload && payload.type;
  41493. var layoutInfo = seriesModel.layoutInfo;
  41494. var isInit = !this._oldTree;
  41495. var thisStorage = this._storage;
  41496. // Mark new root when action is treemapRootToNode.
  41497. var reRoot = (payloadType === 'treemapRootToNode' && targetInfo && thisStorage)
  41498. ? {
  41499. rootNodeGroup: thisStorage.nodeGroup[targetInfo.node.getRawIndex()],
  41500. direction: payload.direction
  41501. }
  41502. : null;
  41503. var containerGroup = this._giveContainerGroup(layoutInfo);
  41504. var renderResult = this._doRender(containerGroup, seriesModel, reRoot);
  41505. (
  41506. !isInit && (
  41507. !payloadType
  41508. || payloadType === 'treemapZoomToNode'
  41509. || payloadType === 'treemapRootToNode'
  41510. )
  41511. )
  41512. ? this._doAnimation(containerGroup, renderResult, seriesModel, reRoot)
  41513. : renderResult.renderFinally();
  41514. this._resetController(api);
  41515. this._renderBreadcrumb(seriesModel, api, targetInfo);
  41516. },
  41517. /**
  41518. * @private
  41519. */
  41520. _giveContainerGroup: function (layoutInfo) {
  41521. var containerGroup = this._containerGroup;
  41522. if (!containerGroup) {
  41523. // FIXME
  41524. // 加一层containerGroup是为了clip,但是现在clip功能并没有实现。
  41525. containerGroup = this._containerGroup = new Group$2();
  41526. this._initEvents(containerGroup);
  41527. this.group.add(containerGroup);
  41528. }
  41529. containerGroup.attr('position', [layoutInfo.x, layoutInfo.y]);
  41530. return containerGroup;
  41531. },
  41532. /**
  41533. * @private
  41534. */
  41535. _doRender: function (containerGroup, seriesModel, reRoot) {
  41536. var thisTree = seriesModel.getData().tree;
  41537. var oldTree = this._oldTree;
  41538. // Clear last shape records.
  41539. var lastsForAnimation = createStorage();
  41540. var thisStorage = createStorage();
  41541. var oldStorage = this._storage;
  41542. var willInvisibleEls = [];
  41543. var doRenderNode = curry(
  41544. renderNode, seriesModel,
  41545. thisStorage, oldStorage, reRoot,
  41546. lastsForAnimation, willInvisibleEls
  41547. );
  41548. // Notice: when thisTree and oldTree are the same tree (see list.cloneShallow),
  41549. // the oldTree is actually losted, so we can not find all of the old graphic
  41550. // elements from tree. So we use this stragegy: make element storage, move
  41551. // from old storage to new storage, clear old storage.
  41552. dualTravel(
  41553. thisTree.root ? [thisTree.root] : [],
  41554. (oldTree && oldTree.root) ? [oldTree.root] : [],
  41555. containerGroup,
  41556. thisTree === oldTree || !oldTree,
  41557. 0
  41558. );
  41559. // Process all removing.
  41560. var willDeleteEls = clearStorage(oldStorage);
  41561. this._oldTree = thisTree;
  41562. this._storage = thisStorage;
  41563. return {
  41564. lastsForAnimation: lastsForAnimation,
  41565. willDeleteEls: willDeleteEls,
  41566. renderFinally: renderFinally
  41567. };
  41568. function dualTravel(thisViewChildren, oldViewChildren, parentGroup, sameTree, depth) {
  41569. // When 'render' is triggered by action,
  41570. // 'this' and 'old' may be the same tree,
  41571. // we use rawIndex in that case.
  41572. if (sameTree) {
  41573. oldViewChildren = thisViewChildren;
  41574. each$8(thisViewChildren, function (child, index) {
  41575. !child.isRemoved() && processNode(index, index);
  41576. });
  41577. }
  41578. // Diff hierarchically (diff only in each subtree, but not whole).
  41579. // because, consistency of view is important.
  41580. else {
  41581. (new DataDiffer(oldViewChildren, thisViewChildren, getKey, getKey))
  41582. .add(processNode)
  41583. .update(processNode)
  41584. .remove(curry(processNode, null))
  41585. .execute();
  41586. }
  41587. function getKey(node) {
  41588. // Identify by name or raw index.
  41589. return node.getId();
  41590. }
  41591. function processNode(newIndex, oldIndex) {
  41592. var thisNode = newIndex != null ? thisViewChildren[newIndex] : null;
  41593. var oldNode = oldIndex != null ? oldViewChildren[oldIndex] : null;
  41594. var group = doRenderNode(thisNode, oldNode, parentGroup, depth);
  41595. group && dualTravel(
  41596. thisNode && thisNode.viewChildren || [],
  41597. oldNode && oldNode.viewChildren || [],
  41598. group,
  41599. sameTree,
  41600. depth + 1
  41601. );
  41602. }
  41603. }
  41604. function clearStorage(storage) {
  41605. var willDeleteEls = createStorage();
  41606. storage && each$8(storage, function (store, storageName) {
  41607. var delEls = willDeleteEls[storageName];
  41608. each$8(store, function (el) {
  41609. el && (delEls.push(el), el.__tmWillDelete = 1);
  41610. });
  41611. });
  41612. return willDeleteEls;
  41613. }
  41614. function renderFinally() {
  41615. each$8(willDeleteEls, function (els) {
  41616. each$8(els, function (el) {
  41617. el.parent && el.parent.remove(el);
  41618. });
  41619. });
  41620. each$8(willInvisibleEls, function (el) {
  41621. el.invisible = true;
  41622. // Setting invisible is for optimizing, so no need to set dirty,
  41623. // just mark as invisible.
  41624. el.dirty();
  41625. });
  41626. }
  41627. },
  41628. /**
  41629. * @private
  41630. */
  41631. _doAnimation: function (containerGroup, renderResult, seriesModel, reRoot) {
  41632. if (!seriesModel.get('animation')) {
  41633. return;
  41634. }
  41635. var duration = seriesModel.get('animationDurationUpdate');
  41636. var easing = seriesModel.get('animationEasing');
  41637. var animationWrap = createWrap();
  41638. // Make delete animations.
  41639. each$8(renderResult.willDeleteEls, function (store, storageName) {
  41640. each$8(store, function (el, rawIndex) {
  41641. if (el.invisible) {
  41642. return;
  41643. }
  41644. var parent = el.parent; // Always has parent, and parent is nodeGroup.
  41645. var target;
  41646. if (reRoot && reRoot.direction === 'drillDown') {
  41647. target = parent === reRoot.rootNodeGroup
  41648. // This is the content element of view root.
  41649. // Only `content` will enter this branch, because
  41650. // `background` and `nodeGroup` will not be deleted.
  41651. ? {
  41652. shape: {
  41653. x: 0,
  41654. y: 0,
  41655. width: parent.__tmNodeWidth,
  41656. height: parent.__tmNodeHeight
  41657. },
  41658. style: {
  41659. opacity: 0
  41660. }
  41661. }
  41662. // Others.
  41663. : {style: {opacity: 0}};
  41664. }
  41665. else {
  41666. var targetX = 0;
  41667. var targetY = 0;
  41668. if (!parent.__tmWillDelete) {
  41669. // Let node animate to right-bottom corner, cooperating with fadeout,
  41670. // which is appropriate for user understanding.
  41671. // Divided by 2 for reRoot rolling up effect.
  41672. targetX = parent.__tmNodeWidth / 2;
  41673. targetY = parent.__tmNodeHeight / 2;
  41674. }
  41675. target = storageName === 'nodeGroup'
  41676. ? {position: [targetX, targetY], style: {opacity: 0}}
  41677. : {
  41678. shape: {x: targetX, y: targetY, width: 0, height: 0},
  41679. style: {opacity: 0}
  41680. };
  41681. }
  41682. target && animationWrap.add(el, target, duration, easing);
  41683. });
  41684. });
  41685. // Make other animations
  41686. each$8(this._storage, function (store, storageName) {
  41687. each$8(store, function (el, rawIndex) {
  41688. var last = renderResult.lastsForAnimation[storageName][rawIndex];
  41689. var target = {};
  41690. if (!last) {
  41691. return;
  41692. }
  41693. if (storageName === 'nodeGroup') {
  41694. if (last.old) {
  41695. target.position = el.position.slice();
  41696. el.attr('position', last.old);
  41697. }
  41698. }
  41699. else {
  41700. if (last.old) {
  41701. target.shape = extend({}, el.shape);
  41702. el.setShape(last.old);
  41703. }
  41704. if (last.fadein) {
  41705. el.setStyle('opacity', 0);
  41706. target.style = {opacity: 1};
  41707. }
  41708. // When animation is stopped for succedent animation starting,
  41709. // el.style.opacity might not be 1
  41710. else if (el.style.opacity !== 1) {
  41711. target.style = {opacity: 1};
  41712. }
  41713. }
  41714. animationWrap.add(el, target, duration, easing);
  41715. });
  41716. }, this);
  41717. this._state = 'animating';
  41718. animationWrap
  41719. .done(bind$1(function () {
  41720. this._state = 'ready';
  41721. renderResult.renderFinally();
  41722. }, this))
  41723. .start();
  41724. },
  41725. /**
  41726. * @private
  41727. */
  41728. _resetController: function (api) {
  41729. var controller = this._controller;
  41730. // Init controller.
  41731. if (!controller) {
  41732. controller = this._controller = new RoamController(api.getZr());
  41733. controller.enable(this.seriesModel.get('roam'));
  41734. controller.on('pan', bind$1(this._onPan, this));
  41735. controller.on('zoom', bind$1(this._onZoom, this));
  41736. }
  41737. var rect = new BoundingRect(0, 0, api.getWidth(), api.getHeight());
  41738. controller.setPointerChecker(function (e, x, y) {
  41739. return rect.contain(x, y);
  41740. });
  41741. },
  41742. /**
  41743. * @private
  41744. */
  41745. _clearController: function () {
  41746. var controller = this._controller;
  41747. if (controller) {
  41748. controller.dispose();
  41749. controller = null;
  41750. }
  41751. },
  41752. /**
  41753. * @private
  41754. */
  41755. _onPan: function (dx, dy) {
  41756. if (this._state !== 'animating'
  41757. && (Math.abs(dx) > DRAG_THRESHOLD || Math.abs(dy) > DRAG_THRESHOLD)
  41758. ) {
  41759. // These param must not be cached.
  41760. var root = this.seriesModel.getData().tree.root;
  41761. if (!root) {
  41762. return;
  41763. }
  41764. var rootLayout = root.getLayout();
  41765. if (!rootLayout) {
  41766. return;
  41767. }
  41768. this.api.dispatchAction({
  41769. type: 'treemapMove',
  41770. from: this.uid,
  41771. seriesId: this.seriesModel.id,
  41772. rootRect: {
  41773. x: rootLayout.x + dx, y: rootLayout.y + dy,
  41774. width: rootLayout.width, height: rootLayout.height
  41775. }
  41776. });
  41777. }
  41778. },
  41779. /**
  41780. * @private
  41781. */
  41782. _onZoom: function (scale, mouseX, mouseY) {
  41783. if (this._state !== 'animating') {
  41784. // These param must not be cached.
  41785. var root = this.seriesModel.getData().tree.root;
  41786. if (!root) {
  41787. return;
  41788. }
  41789. var rootLayout = root.getLayout();
  41790. if (!rootLayout) {
  41791. return;
  41792. }
  41793. var rect = new BoundingRect(
  41794. rootLayout.x, rootLayout.y, rootLayout.width, rootLayout.height
  41795. );
  41796. var layoutInfo = this.seriesModel.layoutInfo;
  41797. // Transform mouse coord from global to containerGroup.
  41798. mouseX -= layoutInfo.x;
  41799. mouseY -= layoutInfo.y;
  41800. // Scale root bounding rect.
  41801. var m = create$1();
  41802. translate(m, m, [-mouseX, -mouseY]);
  41803. scale$1(m, m, [scale, scale]);
  41804. translate(m, m, [mouseX, mouseY]);
  41805. rect.applyTransform(m);
  41806. this.api.dispatchAction({
  41807. type: 'treemapRender',
  41808. from: this.uid,
  41809. seriesId: this.seriesModel.id,
  41810. rootRect: {
  41811. x: rect.x, y: rect.y,
  41812. width: rect.width, height: rect.height
  41813. }
  41814. });
  41815. }
  41816. },
  41817. /**
  41818. * @private
  41819. */
  41820. _initEvents: function (containerGroup) {
  41821. containerGroup.on('click', function (e) {
  41822. if (this._state !== 'ready') {
  41823. return;
  41824. }
  41825. var nodeClick = this.seriesModel.get('nodeClick', true);
  41826. if (!nodeClick) {
  41827. return;
  41828. }
  41829. var targetInfo = this.findTarget(e.offsetX, e.offsetY);
  41830. if (!targetInfo) {
  41831. return;
  41832. }
  41833. var node = targetInfo.node;
  41834. if (node.getLayout().isLeafRoot) {
  41835. this._rootToNode(targetInfo);
  41836. }
  41837. else {
  41838. if (nodeClick === 'zoomToNode') {
  41839. this._zoomToNode(targetInfo);
  41840. }
  41841. else if (nodeClick === 'link') {
  41842. var itemModel = node.hostTree.data.getItemModel(node.dataIndex);
  41843. var link = itemModel.get('link', true);
  41844. var linkTarget = itemModel.get('target', true) || 'blank';
  41845. link && window.open(link, linkTarget);
  41846. }
  41847. }
  41848. }, this);
  41849. },
  41850. /**
  41851. * @private
  41852. */
  41853. _renderBreadcrumb: function (seriesModel, api, targetInfo) {
  41854. if (!targetInfo) {
  41855. targetInfo = seriesModel.get('leafDepth', true) != null
  41856. ? {node: seriesModel.getViewRoot()}
  41857. // FIXME
  41858. // better way?
  41859. // Find breadcrumb tail on center of containerGroup.
  41860. : this.findTarget(api.getWidth() / 2, api.getHeight() / 2);
  41861. if (!targetInfo) {
  41862. targetInfo = {node: seriesModel.getData().tree.root};
  41863. }
  41864. }
  41865. (this._breadcrumb || (this._breadcrumb = new Breadcrumb(this.group)))
  41866. .render(seriesModel, api, targetInfo.node, bind$1(onSelect, this));
  41867. function onSelect(node) {
  41868. if (this._state !== 'animating') {
  41869. aboveViewRoot(seriesModel.getViewRoot(), node)
  41870. ? this._rootToNode({node: node})
  41871. : this._zoomToNode({node: node});
  41872. }
  41873. }
  41874. },
  41875. /**
  41876. * @override
  41877. */
  41878. remove: function () {
  41879. this._clearController();
  41880. this._containerGroup && this._containerGroup.removeAll();
  41881. this._storage = createStorage();
  41882. this._state = 'ready';
  41883. this._breadcrumb && this._breadcrumb.remove();
  41884. },
  41885. dispose: function () {
  41886. this._clearController();
  41887. },
  41888. /**
  41889. * @private
  41890. */
  41891. _zoomToNode: function (targetInfo) {
  41892. this.api.dispatchAction({
  41893. type: 'treemapZoomToNode',
  41894. from: this.uid,
  41895. seriesId: this.seriesModel.id,
  41896. targetNode: targetInfo.node
  41897. });
  41898. },
  41899. /**
  41900. * @private
  41901. */
  41902. _rootToNode: function (targetInfo) {
  41903. this.api.dispatchAction({
  41904. type: 'treemapRootToNode',
  41905. from: this.uid,
  41906. seriesId: this.seriesModel.id,
  41907. targetNode: targetInfo.node
  41908. });
  41909. },
  41910. /**
  41911. * @public
  41912. * @param {number} x Global coord x.
  41913. * @param {number} y Global coord y.
  41914. * @return {Object} info If not found, return undefined;
  41915. * @return {number} info.node Target node.
  41916. * @return {number} info.offsetX x refer to target node.
  41917. * @return {number} info.offsetY y refer to target node.
  41918. */
  41919. findTarget: function (x, y) {
  41920. var targetInfo;
  41921. var viewRoot = this.seriesModel.getViewRoot();
  41922. viewRoot.eachNode({attr: 'viewChildren', order: 'preorder'}, function (node) {
  41923. var bgEl = this._storage.background[node.getRawIndex()];
  41924. // If invisible, there might be no element.
  41925. if (bgEl) {
  41926. var point = bgEl.transformCoordToLocal(x, y);
  41927. var shape = bgEl.shape;
  41928. // For performance consideration, dont use 'getBoundingRect'.
  41929. if (shape.x <= point[0]
  41930. && point[0] <= shape.x + shape.width
  41931. && shape.y <= point[1]
  41932. && point[1] <= shape.y + shape.height
  41933. ) {
  41934. targetInfo = {node: node, offsetX: point[0], offsetY: point[1]};
  41935. }
  41936. else {
  41937. return false; // Suppress visit subtree.
  41938. }
  41939. }
  41940. }, this);
  41941. return targetInfo;
  41942. }
  41943. });
  41944. /**
  41945. * @inner
  41946. */
  41947. function createStorage() {
  41948. return {nodeGroup: [], background: [], content: []};
  41949. }
  41950. /**
  41951. * @inner
  41952. * @return Return undefined means do not travel further.
  41953. */
  41954. function renderNode(
  41955. seriesModel, thisStorage, oldStorage, reRoot,
  41956. lastsForAnimation, willInvisibleEls,
  41957. thisNode, oldNode, parentGroup, depth
  41958. ) {
  41959. // Whether under viewRoot.
  41960. if (!thisNode) {
  41961. // Deleting nodes will be performed finally. This method just find
  41962. // element from old storage, or create new element, set them to new
  41963. // storage, and set styles.
  41964. return;
  41965. }
  41966. // -------------------------------------------------------------------
  41967. // Start of closure variables available in "Procedures in renderNode".
  41968. var thisLayout = thisNode.getLayout();
  41969. if (!thisLayout || !thisLayout.isInView) {
  41970. return;
  41971. }
  41972. var thisWidth = thisLayout.width;
  41973. var thisHeight = thisLayout.height;
  41974. var borderWidth = thisLayout.borderWidth;
  41975. var thisInvisible = thisLayout.invisible;
  41976. var thisRawIndex = thisNode.getRawIndex();
  41977. var oldRawIndex = oldNode && oldNode.getRawIndex();
  41978. var thisViewChildren = thisNode.viewChildren;
  41979. var upperHeight = thisLayout.upperHeight;
  41980. var isParent = thisViewChildren && thisViewChildren.length;
  41981. var itemStyleNormalModel = thisNode.getModel('itemStyle');
  41982. var itemStyleEmphasisModel = thisNode.getModel('emphasis.itemStyle');
  41983. // End of closure ariables available in "Procedures in renderNode".
  41984. // -----------------------------------------------------------------
  41985. // Node group
  41986. var group = giveGraphic('nodeGroup', Group$2);
  41987. if (!group) {
  41988. return;
  41989. }
  41990. parentGroup.add(group);
  41991. // x,y are not set when el is above view root.
  41992. group.attr('position', [thisLayout.x || 0, thisLayout.y || 0]);
  41993. group.__tmNodeWidth = thisWidth;
  41994. group.__tmNodeHeight = thisHeight;
  41995. if (thisLayout.isAboveViewRoot) {
  41996. return group;
  41997. }
  41998. // Background
  41999. var bg = giveGraphic('background', Rect$1, depth, Z_BG);
  42000. bg && renderBackground(group, bg, isParent && thisLayout.upperHeight);
  42001. // No children, render content.
  42002. if (!isParent) {
  42003. var content = giveGraphic('content', Rect$1, depth, Z_CONTENT);
  42004. content && renderContent(group, content);
  42005. }
  42006. return group;
  42007. // ----------------------------
  42008. // | Procedures in renderNode |
  42009. // ----------------------------
  42010. function renderBackground(group, bg, useUpperLabel) {
  42011. // For tooltip.
  42012. bg.dataIndex = thisNode.dataIndex;
  42013. bg.seriesIndex = seriesModel.seriesIndex;
  42014. bg.setShape({x: 0, y: 0, width: thisWidth, height: thisHeight});
  42015. var visualBorderColor = thisNode.getVisual('borderColor', true);
  42016. var emphasisBorderColor = itemStyleEmphasisModel.get('borderColor');
  42017. updateStyle(bg, function () {
  42018. var normalStyle = getItemStyleNormal(itemStyleNormalModel);
  42019. normalStyle.fill = visualBorderColor;
  42020. var emphasisStyle = getItemStyleEmphasis(itemStyleEmphasisModel);
  42021. emphasisStyle.fill = emphasisBorderColor;
  42022. if (useUpperLabel) {
  42023. var upperLabelWidth = thisWidth - 2 * borderWidth;
  42024. prepareText(
  42025. normalStyle, emphasisStyle, visualBorderColor, upperLabelWidth, upperHeight,
  42026. {x: borderWidth, y: 0, width: upperLabelWidth, height: upperHeight}
  42027. );
  42028. }
  42029. // For old bg.
  42030. else {
  42031. normalStyle.text = emphasisStyle.text = null;
  42032. }
  42033. bg.setStyle(normalStyle);
  42034. setHoverStyle(bg, emphasisStyle);
  42035. });
  42036. group.add(bg);
  42037. }
  42038. function renderContent(group, content) {
  42039. // For tooltip.
  42040. content.dataIndex = thisNode.dataIndex;
  42041. content.seriesIndex = seriesModel.seriesIndex;
  42042. var contentWidth = Math.max(thisWidth - 2 * borderWidth, 0);
  42043. var contentHeight = Math.max(thisHeight - 2 * borderWidth, 0);
  42044. content.culling = true;
  42045. content.setShape({
  42046. x: borderWidth,
  42047. y: borderWidth,
  42048. width: contentWidth,
  42049. height: contentHeight
  42050. });
  42051. var visualColor = thisNode.getVisual('color', true);
  42052. updateStyle(content, function () {
  42053. var normalStyle = getItemStyleNormal(itemStyleNormalModel);
  42054. normalStyle.fill = visualColor;
  42055. var emphasisStyle = getItemStyleEmphasis(itemStyleEmphasisModel);
  42056. prepareText(normalStyle, emphasisStyle, visualColor, contentWidth, contentHeight);
  42057. content.setStyle(normalStyle);
  42058. setHoverStyle(content, emphasisStyle);
  42059. });
  42060. group.add(content);
  42061. }
  42062. function updateStyle(element, cb) {
  42063. if (!thisInvisible) {
  42064. // If invisible, do not set visual, otherwise the element will
  42065. // change immediately before animation. We think it is OK to
  42066. // remain its origin color when moving out of the view window.
  42067. cb();
  42068. if (!element.__tmWillVisible) {
  42069. element.invisible = false;
  42070. }
  42071. }
  42072. else {
  42073. // Delay invisible setting utill animation finished,
  42074. // avoid element vanish suddenly before animation.
  42075. !element.invisible && willInvisibleEls.push(element);
  42076. }
  42077. }
  42078. function prepareText(normalStyle, emphasisStyle, visualColor, width, height, upperLabelRect) {
  42079. var nodeModel = thisNode.getModel();
  42080. var text = retrieve(
  42081. seriesModel.getFormattedLabel(
  42082. thisNode.dataIndex, 'normal', null, null, upperLabelRect ? 'upperLabel' : 'label'
  42083. ),
  42084. nodeModel.get('name')
  42085. );
  42086. if (!upperLabelRect && thisLayout.isLeafRoot) {
  42087. var iconChar = seriesModel.get('drillDownIcon', true);
  42088. text = iconChar ? iconChar + ' ' + text : text;
  42089. }
  42090. var normalLabelModel = nodeModel.getModel(
  42091. upperLabelRect ? PATH_UPPERLABEL_NORMAL : PATH_LABEL_NOAMAL
  42092. );
  42093. var emphasisLabelModel = nodeModel.getModel(
  42094. upperLabelRect ? PATH_UPPERLABEL_EMPHASIS : PATH_LABEL_EMPHASIS
  42095. );
  42096. var isShow = normalLabelModel.getShallow('show');
  42097. setLabelStyle(
  42098. normalStyle, emphasisStyle, normalLabelModel, emphasisLabelModel,
  42099. {
  42100. defaultText: isShow ? text : null,
  42101. autoColor: visualColor,
  42102. isRectText: true
  42103. }
  42104. );
  42105. upperLabelRect && (normalStyle.textRect = clone(upperLabelRect));
  42106. normalStyle.truncate = (isShow && normalLabelModel.get('ellipsis'))
  42107. ? {
  42108. outerWidth: width,
  42109. outerHeight: height,
  42110. minChar: 2
  42111. }
  42112. : null;
  42113. }
  42114. function giveGraphic(storageName, Ctor, depth, z) {
  42115. var element = oldRawIndex != null && oldStorage[storageName][oldRawIndex];
  42116. var lasts = lastsForAnimation[storageName];
  42117. if (element) {
  42118. // Remove from oldStorage
  42119. oldStorage[storageName][oldRawIndex] = null;
  42120. prepareAnimationWhenHasOld(lasts, element, storageName);
  42121. }
  42122. // If invisible and no old element, do not create new element (for optimizing).
  42123. else if (!thisInvisible) {
  42124. element = new Ctor({z: calculateZ(depth, z)});
  42125. element.__tmDepth = depth;
  42126. element.__tmStorageName = storageName;
  42127. prepareAnimationWhenNoOld(lasts, element, storageName);
  42128. }
  42129. // Set to thisStorage
  42130. return (thisStorage[storageName][thisRawIndex] = element);
  42131. }
  42132. function prepareAnimationWhenHasOld(lasts, element, storageName) {
  42133. var lastCfg = lasts[thisRawIndex] = {};
  42134. lastCfg.old = storageName === 'nodeGroup'
  42135. ? element.position.slice()
  42136. : extend({}, element.shape);
  42137. }
  42138. // If a element is new, we need to find the animation start point carefully,
  42139. // otherwise it will looks strange when 'zoomToNode'.
  42140. function prepareAnimationWhenNoOld(lasts, element, storageName) {
  42141. var lastCfg = lasts[thisRawIndex] = {};
  42142. var parentNode = thisNode.parentNode;
  42143. if (parentNode && (!reRoot || reRoot.direction === 'drillDown')) {
  42144. var parentOldX = 0;
  42145. var parentOldY = 0;
  42146. // New nodes appear from right-bottom corner in 'zoomToNode' animation.
  42147. // For convenience, get old bounding rect from background.
  42148. var parentOldBg = lastsForAnimation.background[parentNode.getRawIndex()];
  42149. if (!reRoot && parentOldBg && parentOldBg.old) {
  42150. parentOldX = parentOldBg.old.width;
  42151. parentOldY = parentOldBg.old.height;
  42152. }
  42153. // When no parent old shape found, its parent is new too,
  42154. // so we can just use {x:0, y:0}.
  42155. lastCfg.old = storageName === 'nodeGroup'
  42156. ? [0, parentOldY]
  42157. : {x: parentOldX, y: parentOldY, width: 0, height: 0};
  42158. }
  42159. // Fade in, user can be aware that these nodes are new.
  42160. lastCfg.fadein = storageName !== 'nodeGroup';
  42161. }
  42162. }
  42163. // We can not set all backgroud with the same z, Because the behaviour of
  42164. // drill down and roll up differ background creation sequence from tree
  42165. // hierarchy sequence, which cause that lowser background element overlap
  42166. // upper ones. So we calculate z based on depth.
  42167. // Moreover, we try to shrink down z interval to [0, 1] to avoid that
  42168. // treemap with large z overlaps other components.
  42169. function calculateZ(depth, zInLevel) {
  42170. var zb = depth * Z_BASE + zInLevel;
  42171. return (zb - 1) / zb;
  42172. }
  42173. /*
  42174. * Licensed to the Apache Software Foundation (ASF) under one
  42175. * or more contributor license agreements. See the NOTICE file
  42176. * distributed with this work for additional information
  42177. * regarding copyright ownership. The ASF licenses this file
  42178. * to you under the Apache License, Version 2.0 (the
  42179. * "License"); you may not use this file except in compliance
  42180. * with the License. You may obtain a copy of the License at
  42181. *
  42182. * http://www.apache.org/licenses/LICENSE-2.0
  42183. *
  42184. * Unless required by applicable law or agreed to in writing,
  42185. * software distributed under the License is distributed on an
  42186. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42187. * KIND, either express or implied. See the License for the
  42188. * specific language governing permissions and limitations
  42189. * under the License.
  42190. */
  42191. /**
  42192. * @file Treemap action
  42193. */
  42194. var noop$1 = function () {};
  42195. var actionTypes = [
  42196. 'treemapZoomToNode',
  42197. 'treemapRender',
  42198. 'treemapMove'
  42199. ];
  42200. for (var i$2 = 0; i$2 < actionTypes.length; i$2++) {
  42201. registerAction({type: actionTypes[i$2], update: 'updateView'}, noop$1);
  42202. }
  42203. registerAction(
  42204. {type: 'treemapRootToNode', update: 'updateView'},
  42205. function (payload, ecModel) {
  42206. ecModel.eachComponent(
  42207. {mainType: 'series', subType: 'treemap', query: payload},
  42208. handleRootToNode
  42209. );
  42210. function handleRootToNode(model, index) {
  42211. var types = ['treemapZoomToNode', 'treemapRootToNode'];
  42212. var targetInfo = retrieveTargetInfo(payload, types, model);
  42213. if (targetInfo) {
  42214. var originViewRoot = model.getViewRoot();
  42215. if (originViewRoot) {
  42216. payload.direction = aboveViewRoot(originViewRoot, targetInfo.node)
  42217. ? 'rollUp' : 'drillDown';
  42218. }
  42219. model.resetViewRoot(targetInfo.node);
  42220. }
  42221. }
  42222. }
  42223. );
  42224. /*
  42225. * Licensed to the Apache Software Foundation (ASF) under one
  42226. * or more contributor license agreements. See the NOTICE file
  42227. * distributed with this work for additional information
  42228. * regarding copyright ownership. The ASF licenses this file
  42229. * to you under the Apache License, Version 2.0 (the
  42230. * "License"); you may not use this file except in compliance
  42231. * with the License. You may obtain a copy of the License at
  42232. *
  42233. * http://www.apache.org/licenses/LICENSE-2.0
  42234. *
  42235. * Unless required by applicable law or agreed to in writing,
  42236. * software distributed under the License is distributed on an
  42237. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42238. * KIND, either express or implied. See the License for the
  42239. * specific language governing permissions and limitations
  42240. * under the License.
  42241. */
  42242. var each$9 = each$1;
  42243. var isObject$5 = isObject$1;
  42244. var CATEGORY_DEFAULT_VISUAL_INDEX = -1;
  42245. /**
  42246. * @param {Object} option
  42247. * @param {string} [option.type] See visualHandlers.
  42248. * @param {string} [option.mappingMethod] 'linear' or 'piecewise' or 'category' or 'fixed'
  42249. * @param {Array.<number>=} [option.dataExtent] [minExtent, maxExtent],
  42250. * required when mappingMethod is 'linear'
  42251. * @param {Array.<Object>=} [option.pieceList] [
  42252. * {value: someValue},
  42253. * {interval: [min1, max1], visual: {...}},
  42254. * {interval: [min2, max2]}
  42255. * ],
  42256. * required when mappingMethod is 'piecewise'.
  42257. * Visual for only each piece can be specified.
  42258. * @param {Array.<string|Object>=} [option.categories] ['cate1', 'cate2']
  42259. * required when mappingMethod is 'category'.
  42260. * If no option.categories, categories is set
  42261. * as [0, 1, 2, ...].
  42262. * @param {boolean} [option.loop=false] Whether loop mapping when mappingMethod is 'category'.
  42263. * @param {(Array|Object|*)} [option.visual] Visual data.
  42264. * when mappingMethod is 'category',
  42265. * visual data can be array or object
  42266. * (like: {cate1: '#222', none: '#fff'})
  42267. * or primary types (which represents
  42268. * defualt category visual), otherwise visual
  42269. * can be array or primary (which will be
  42270. * normalized to array).
  42271. *
  42272. */
  42273. var VisualMapping = function (option) {
  42274. var mappingMethod = option.mappingMethod;
  42275. var visualType = option.type;
  42276. /**
  42277. * @readOnly
  42278. * @type {Object}
  42279. */
  42280. var thisOption = this.option = clone(option);
  42281. /**
  42282. * @readOnly
  42283. * @type {string}
  42284. */
  42285. this.type = visualType;
  42286. /**
  42287. * @readOnly
  42288. * @type {string}
  42289. */
  42290. this.mappingMethod = mappingMethod;
  42291. /**
  42292. * @private
  42293. * @type {Function}
  42294. */
  42295. this._normalizeData = normalizers[mappingMethod];
  42296. var visualHandler = visualHandlers[visualType];
  42297. /**
  42298. * @public
  42299. * @type {Function}
  42300. */
  42301. this.applyVisual = visualHandler.applyVisual;
  42302. /**
  42303. * @public
  42304. * @type {Function}
  42305. */
  42306. this.getColorMapper = visualHandler.getColorMapper;
  42307. /**
  42308. * @private
  42309. * @type {Function}
  42310. */
  42311. this._doMap = visualHandler._doMap[mappingMethod];
  42312. if (mappingMethod === 'piecewise') {
  42313. normalizeVisualRange(thisOption);
  42314. preprocessForPiecewise(thisOption);
  42315. }
  42316. else if (mappingMethod === 'category') {
  42317. thisOption.categories
  42318. ? preprocessForSpecifiedCategory(thisOption)
  42319. // categories is ordinal when thisOption.categories not specified,
  42320. // which need no more preprocess except normalize visual.
  42321. : normalizeVisualRange(thisOption, true);
  42322. }
  42323. else { // mappingMethod === 'linear' or 'fixed'
  42324. assert$1(mappingMethod !== 'linear' || thisOption.dataExtent);
  42325. normalizeVisualRange(thisOption);
  42326. }
  42327. };
  42328. VisualMapping.prototype = {
  42329. constructor: VisualMapping,
  42330. mapValueToVisual: function (value) {
  42331. var normalized = this._normalizeData(value);
  42332. return this._doMap(normalized, value);
  42333. },
  42334. getNormalizer: function () {
  42335. return bind(this._normalizeData, this);
  42336. }
  42337. };
  42338. var visualHandlers = VisualMapping.visualHandlers = {
  42339. color: {
  42340. applyVisual: makeApplyVisual('color'),
  42341. /**
  42342. * Create a mapper function
  42343. * @return {Function}
  42344. */
  42345. getColorMapper: function () {
  42346. var thisOption = this.option;
  42347. return bind(
  42348. thisOption.mappingMethod === 'category'
  42349. ? function (value, isNormalized) {
  42350. !isNormalized && (value = this._normalizeData(value));
  42351. return doMapCategory.call(this, value);
  42352. }
  42353. : function (value, isNormalized, out) {
  42354. // If output rgb array
  42355. // which will be much faster and useful in pixel manipulation
  42356. var returnRGBArray = !!out;
  42357. !isNormalized && (value = this._normalizeData(value));
  42358. out = fastLerp(value, thisOption.parsedVisual, out);
  42359. return returnRGBArray ? out : stringify(out, 'rgba');
  42360. },
  42361. this
  42362. );
  42363. },
  42364. _doMap: {
  42365. linear: function (normalized) {
  42366. return stringify(
  42367. fastLerp(normalized, this.option.parsedVisual),
  42368. 'rgba'
  42369. );
  42370. },
  42371. category: doMapCategory,
  42372. piecewise: function (normalized, value) {
  42373. var result = getSpecifiedVisual.call(this, value);
  42374. if (result == null) {
  42375. result = stringify(
  42376. fastLerp(normalized, this.option.parsedVisual),
  42377. 'rgba'
  42378. );
  42379. }
  42380. return result;
  42381. },
  42382. fixed: doMapFixed
  42383. }
  42384. },
  42385. colorHue: makePartialColorVisualHandler(function (color, value) {
  42386. return modifyHSL(color, value);
  42387. }),
  42388. colorSaturation: makePartialColorVisualHandler(function (color, value) {
  42389. return modifyHSL(color, null, value);
  42390. }),
  42391. colorLightness: makePartialColorVisualHandler(function (color, value) {
  42392. return modifyHSL(color, null, null, value);
  42393. }),
  42394. colorAlpha: makePartialColorVisualHandler(function (color, value) {
  42395. return modifyAlpha(color, value);
  42396. }),
  42397. opacity: {
  42398. applyVisual: makeApplyVisual('opacity'),
  42399. _doMap: makeDoMap([0, 1])
  42400. },
  42401. liftZ: {
  42402. applyVisual: makeApplyVisual('liftZ'),
  42403. _doMap: {
  42404. linear: doMapFixed,
  42405. category: doMapFixed,
  42406. piecewise: doMapFixed,
  42407. fixed: doMapFixed
  42408. }
  42409. },
  42410. symbol: {
  42411. applyVisual: function (value, getter, setter) {
  42412. var symbolCfg = this.mapValueToVisual(value);
  42413. if (isString(symbolCfg)) {
  42414. setter('symbol', symbolCfg);
  42415. }
  42416. else if (isObject$5(symbolCfg)) {
  42417. for (var name in symbolCfg) {
  42418. if (symbolCfg.hasOwnProperty(name)) {
  42419. setter(name, symbolCfg[name]);
  42420. }
  42421. }
  42422. }
  42423. },
  42424. _doMap: {
  42425. linear: doMapToArray,
  42426. category: doMapCategory,
  42427. piecewise: function (normalized, value) {
  42428. var result = getSpecifiedVisual.call(this, value);
  42429. if (result == null) {
  42430. result = doMapToArray.call(this, normalized);
  42431. }
  42432. return result;
  42433. },
  42434. fixed: doMapFixed
  42435. }
  42436. },
  42437. symbolSize: {
  42438. applyVisual: makeApplyVisual('symbolSize'),
  42439. _doMap: makeDoMap([0, 1])
  42440. }
  42441. };
  42442. function preprocessForPiecewise(thisOption) {
  42443. var pieceList = thisOption.pieceList;
  42444. thisOption.hasSpecialVisual = false;
  42445. each$1(pieceList, function (piece, index) {
  42446. piece.originIndex = index;
  42447. // piece.visual is "result visual value" but not
  42448. // a visual range, so it does not need to be normalized.
  42449. if (piece.visual != null) {
  42450. thisOption.hasSpecialVisual = true;
  42451. }
  42452. });
  42453. }
  42454. function preprocessForSpecifiedCategory(thisOption) {
  42455. // Hash categories.
  42456. var categories = thisOption.categories;
  42457. var visual = thisOption.visual;
  42458. var categoryMap = thisOption.categoryMap = {};
  42459. each$9(categories, function (cate, index) {
  42460. categoryMap[cate] = index;
  42461. });
  42462. // Process visual map input.
  42463. if (!isArray(visual)) {
  42464. var visualArr = [];
  42465. if (isObject$1(visual)) {
  42466. each$9(visual, function (v, cate) {
  42467. var index = categoryMap[cate];
  42468. visualArr[index != null ? index : CATEGORY_DEFAULT_VISUAL_INDEX] = v;
  42469. });
  42470. }
  42471. else { // Is primary type, represents default visual.
  42472. visualArr[CATEGORY_DEFAULT_VISUAL_INDEX] = visual;
  42473. }
  42474. visual = setVisualToOption(thisOption, visualArr);
  42475. }
  42476. // Remove categories that has no visual,
  42477. // then we can mapping them to CATEGORY_DEFAULT_VISUAL_INDEX.
  42478. for (var i = categories.length - 1; i >= 0; i--) {
  42479. if (visual[i] == null) {
  42480. delete categoryMap[categories[i]];
  42481. categories.pop();
  42482. }
  42483. }
  42484. }
  42485. function normalizeVisualRange(thisOption, isCategory) {
  42486. var visual = thisOption.visual;
  42487. var visualArr = [];
  42488. if (isObject$1(visual)) {
  42489. each$9(visual, function (v) {
  42490. visualArr.push(v);
  42491. });
  42492. }
  42493. else if (visual != null) {
  42494. visualArr.push(visual);
  42495. }
  42496. var doNotNeedPair = {color: 1, symbol: 1};
  42497. if (!isCategory
  42498. && visualArr.length === 1
  42499. && !doNotNeedPair.hasOwnProperty(thisOption.type)
  42500. ) {
  42501. // Do not care visualArr.length === 0, which is illegal.
  42502. visualArr[1] = visualArr[0];
  42503. }
  42504. setVisualToOption(thisOption, visualArr);
  42505. }
  42506. function makePartialColorVisualHandler(applyValue) {
  42507. return {
  42508. applyVisual: function (value, getter, setter) {
  42509. value = this.mapValueToVisual(value);
  42510. // Must not be array value
  42511. setter('color', applyValue(getter('color'), value));
  42512. },
  42513. _doMap: makeDoMap([0, 1])
  42514. };
  42515. }
  42516. function doMapToArray(normalized) {
  42517. var visual = this.option.visual;
  42518. return visual[
  42519. Math.round(linearMap(normalized, [0, 1], [0, visual.length - 1], true))
  42520. ] || {};
  42521. }
  42522. function makeApplyVisual(visualType) {
  42523. return function (value, getter, setter) {
  42524. setter(visualType, this.mapValueToVisual(value));
  42525. };
  42526. }
  42527. function doMapCategory(normalized) {
  42528. var visual = this.option.visual;
  42529. return visual[
  42530. (this.option.loop && normalized !== CATEGORY_DEFAULT_VISUAL_INDEX)
  42531. ? normalized % visual.length
  42532. : normalized
  42533. ];
  42534. }
  42535. function doMapFixed() {
  42536. return this.option.visual[0];
  42537. }
  42538. function makeDoMap(sourceExtent) {
  42539. return {
  42540. linear: function (normalized) {
  42541. return linearMap(normalized, sourceExtent, this.option.visual, true);
  42542. },
  42543. category: doMapCategory,
  42544. piecewise: function (normalized, value) {
  42545. var result = getSpecifiedVisual.call(this, value);
  42546. if (result == null) {
  42547. result = linearMap(normalized, sourceExtent, this.option.visual, true);
  42548. }
  42549. return result;
  42550. },
  42551. fixed: doMapFixed
  42552. };
  42553. }
  42554. function getSpecifiedVisual(value) {
  42555. var thisOption = this.option;
  42556. var pieceList = thisOption.pieceList;
  42557. if (thisOption.hasSpecialVisual) {
  42558. var pieceIndex = VisualMapping.findPieceIndex(value, pieceList);
  42559. var piece = pieceList[pieceIndex];
  42560. if (piece && piece.visual) {
  42561. return piece.visual[this.type];
  42562. }
  42563. }
  42564. }
  42565. function setVisualToOption(thisOption, visualArr) {
  42566. thisOption.visual = visualArr;
  42567. if (thisOption.type === 'color') {
  42568. thisOption.parsedVisual = map(visualArr, function (item) {
  42569. return parse(item);
  42570. });
  42571. }
  42572. return visualArr;
  42573. }
  42574. /**
  42575. * Normalizers by mapping methods.
  42576. */
  42577. var normalizers = {
  42578. linear: function (value) {
  42579. return linearMap(value, this.option.dataExtent, [0, 1], true);
  42580. },
  42581. piecewise: function (value) {
  42582. var pieceList = this.option.pieceList;
  42583. var pieceIndex = VisualMapping.findPieceIndex(value, pieceList, true);
  42584. if (pieceIndex != null) {
  42585. return linearMap(pieceIndex, [0, pieceList.length - 1], [0, 1], true);
  42586. }
  42587. },
  42588. category: function (value) {
  42589. var index = this.option.categories
  42590. ? this.option.categoryMap[value]
  42591. : value; // ordinal
  42592. return index == null ? CATEGORY_DEFAULT_VISUAL_INDEX : index;
  42593. },
  42594. fixed: noop
  42595. };
  42596. /**
  42597. * List available visual types.
  42598. *
  42599. * @public
  42600. * @return {Array.<string>}
  42601. */
  42602. VisualMapping.listVisualTypes = function () {
  42603. var visualTypes = [];
  42604. each$1(visualHandlers, function (handler, key) {
  42605. visualTypes.push(key);
  42606. });
  42607. return visualTypes;
  42608. };
  42609. /**
  42610. * @public
  42611. */
  42612. VisualMapping.addVisualHandler = function (name, handler) {
  42613. visualHandlers[name] = handler;
  42614. };
  42615. /**
  42616. * @public
  42617. */
  42618. VisualMapping.isValidType = function (visualType) {
  42619. return visualHandlers.hasOwnProperty(visualType);
  42620. };
  42621. /**
  42622. * Convinent method.
  42623. * Visual can be Object or Array or primary type.
  42624. *
  42625. * @public
  42626. */
  42627. VisualMapping.eachVisual = function (visual, callback, context) {
  42628. if (isObject$1(visual)) {
  42629. each$1(visual, callback, context);
  42630. }
  42631. else {
  42632. callback.call(context, visual);
  42633. }
  42634. };
  42635. VisualMapping.mapVisual = function (visual, callback, context) {
  42636. var isPrimary;
  42637. var newVisual = isArray(visual)
  42638. ? []
  42639. : isObject$1(visual)
  42640. ? {}
  42641. : (isPrimary = true, null);
  42642. VisualMapping.eachVisual(visual, function (v, key) {
  42643. var newVal = callback.call(context, v, key);
  42644. isPrimary ? (newVisual = newVal) : (newVisual[key] = newVal);
  42645. });
  42646. return newVisual;
  42647. };
  42648. /**
  42649. * @public
  42650. * @param {Object} obj
  42651. * @return {Object} new object containers visual values.
  42652. * If no visuals, return null.
  42653. */
  42654. VisualMapping.retrieveVisuals = function (obj) {
  42655. var ret = {};
  42656. var hasVisual;
  42657. obj && each$9(visualHandlers, function (h, visualType) {
  42658. if (obj.hasOwnProperty(visualType)) {
  42659. ret[visualType] = obj[visualType];
  42660. hasVisual = true;
  42661. }
  42662. });
  42663. return hasVisual ? ret : null;
  42664. };
  42665. /**
  42666. * Give order to visual types, considering colorSaturation, colorAlpha depends on color.
  42667. *
  42668. * @public
  42669. * @param {(Object|Array)} visualTypes If Object, like: {color: ..., colorSaturation: ...}
  42670. * IF Array, like: ['color', 'symbol', 'colorSaturation']
  42671. * @return {Array.<string>} Sorted visual types.
  42672. */
  42673. VisualMapping.prepareVisualTypes = function (visualTypes) {
  42674. if (isObject$5(visualTypes)) {
  42675. var types = [];
  42676. each$9(visualTypes, function (item, type) {
  42677. types.push(type);
  42678. });
  42679. visualTypes = types;
  42680. }
  42681. else if (isArray(visualTypes)) {
  42682. visualTypes = visualTypes.slice();
  42683. }
  42684. else {
  42685. return [];
  42686. }
  42687. visualTypes.sort(function (type1, type2) {
  42688. // color should be front of colorSaturation, colorAlpha, ...
  42689. // symbol and symbolSize do not matter.
  42690. return (type2 === 'color' && type1 !== 'color' && type1.indexOf('color') === 0)
  42691. ? 1 : -1;
  42692. });
  42693. return visualTypes;
  42694. };
  42695. /**
  42696. * 'color', 'colorSaturation', 'colorAlpha', ... are depends on 'color'.
  42697. * Other visuals are only depends on themself.
  42698. *
  42699. * @public
  42700. * @param {string} visualType1
  42701. * @param {string} visualType2
  42702. * @return {boolean}
  42703. */
  42704. VisualMapping.dependsOn = function (visualType1, visualType2) {
  42705. return visualType2 === 'color'
  42706. ? !!(visualType1 && visualType1.indexOf(visualType2) === 0)
  42707. : visualType1 === visualType2;
  42708. };
  42709. /**
  42710. * @param {number} value
  42711. * @param {Array.<Object>} pieceList [{value: ..., interval: [min, max]}, ...]
  42712. * Always from small to big.
  42713. * @param {boolean} [findClosestWhenOutside=false]
  42714. * @return {number} index
  42715. */
  42716. VisualMapping.findPieceIndex = function (value, pieceList, findClosestWhenOutside) {
  42717. var possibleI;
  42718. var abs = Infinity;
  42719. // value has the higher priority.
  42720. for (var i = 0, len = pieceList.length; i < len; i++) {
  42721. var pieceValue = pieceList[i].value;
  42722. if (pieceValue != null) {
  42723. if (pieceValue === value
  42724. // FIXME
  42725. // It is supposed to compare value according to value type of dimension,
  42726. // but currently value type can exactly be string or number.
  42727. // Compromise for numeric-like string (like '12'), especially
  42728. // in the case that visualMap.categories is ['22', '33'].
  42729. || (typeof pieceValue === 'string' && pieceValue === value + '')
  42730. ) {
  42731. return i;
  42732. }
  42733. findClosestWhenOutside && updatePossible(pieceValue, i);
  42734. }
  42735. }
  42736. for (var i = 0, len = pieceList.length; i < len; i++) {
  42737. var piece = pieceList[i];
  42738. var interval = piece.interval;
  42739. var close = piece.close;
  42740. if (interval) {
  42741. if (interval[0] === -Infinity) {
  42742. if (littleThan(close[1], value, interval[1])) {
  42743. return i;
  42744. }
  42745. }
  42746. else if (interval[1] === Infinity) {
  42747. if (littleThan(close[0], interval[0], value)) {
  42748. return i;
  42749. }
  42750. }
  42751. else if (
  42752. littleThan(close[0], interval[0], value)
  42753. && littleThan(close[1], value, interval[1])
  42754. ) {
  42755. return i;
  42756. }
  42757. findClosestWhenOutside && updatePossible(interval[0], i);
  42758. findClosestWhenOutside && updatePossible(interval[1], i);
  42759. }
  42760. }
  42761. if (findClosestWhenOutside) {
  42762. return value === Infinity
  42763. ? pieceList.length - 1
  42764. : value === -Infinity
  42765. ? 0
  42766. : possibleI;
  42767. }
  42768. function updatePossible(val, index) {
  42769. var newAbs = Math.abs(val - value);
  42770. if (newAbs < abs) {
  42771. abs = newAbs;
  42772. possibleI = index;
  42773. }
  42774. }
  42775. };
  42776. function littleThan(close, a, b) {
  42777. return close ? a <= b : a < b;
  42778. }
  42779. /*
  42780. * Licensed to the Apache Software Foundation (ASF) under one
  42781. * or more contributor license agreements. See the NOTICE file
  42782. * distributed with this work for additional information
  42783. * regarding copyright ownership. The ASF licenses this file
  42784. * to you under the Apache License, Version 2.0 (the
  42785. * "License"); you may not use this file except in compliance
  42786. * with the License. You may obtain a copy of the License at
  42787. *
  42788. * http://www.apache.org/licenses/LICENSE-2.0
  42789. *
  42790. * Unless required by applicable law or agreed to in writing,
  42791. * software distributed under the License is distributed on an
  42792. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42793. * KIND, either express or implied. See the License for the
  42794. * specific language governing permissions and limitations
  42795. * under the License.
  42796. */
  42797. var isArray$2 = isArray;
  42798. var ITEM_STYLE_NORMAL = 'itemStyle';
  42799. var treemapVisual = {
  42800. seriesType: 'treemap',
  42801. reset: function (seriesModel, ecModel, api, payload) {
  42802. var tree = seriesModel.getData().tree;
  42803. var root = tree.root;
  42804. var seriesItemStyleModel = seriesModel.getModel(ITEM_STYLE_NORMAL);
  42805. if (root.isRemoved()) {
  42806. return;
  42807. }
  42808. var levelItemStyles = map(tree.levelModels, function (levelModel) {
  42809. return levelModel ? levelModel.get(ITEM_STYLE_NORMAL) : null;
  42810. });
  42811. travelTree(
  42812. root, // Visual should calculate from tree root but not view root.
  42813. {},
  42814. levelItemStyles,
  42815. seriesItemStyleModel,
  42816. seriesModel.getViewRoot().getAncestors(),
  42817. seriesModel
  42818. );
  42819. }
  42820. };
  42821. function travelTree(
  42822. node, designatedVisual, levelItemStyles, seriesItemStyleModel,
  42823. viewRootAncestors, seriesModel
  42824. ) {
  42825. var nodeModel = node.getModel();
  42826. var nodeLayout = node.getLayout();
  42827. // Optimize
  42828. if (!nodeLayout || nodeLayout.invisible || !nodeLayout.isInView) {
  42829. return;
  42830. }
  42831. var nodeItemStyleModel = node.getModel(ITEM_STYLE_NORMAL);
  42832. var levelItemStyle = levelItemStyles[node.depth];
  42833. var visuals = buildVisuals(
  42834. nodeItemStyleModel, designatedVisual, levelItemStyle, seriesItemStyleModel
  42835. );
  42836. // calculate border color
  42837. var borderColor = nodeItemStyleModel.get('borderColor');
  42838. var borderColorSaturation = nodeItemStyleModel.get('borderColorSaturation');
  42839. var thisNodeColor;
  42840. if (borderColorSaturation != null) {
  42841. // For performance, do not always execute 'calculateColor'.
  42842. thisNodeColor = calculateColor(visuals, node);
  42843. borderColor = calculateBorderColor(borderColorSaturation, thisNodeColor);
  42844. }
  42845. node.setVisual('borderColor', borderColor);
  42846. var viewChildren = node.viewChildren;
  42847. if (!viewChildren || !viewChildren.length) {
  42848. thisNodeColor = calculateColor(visuals, node);
  42849. // Apply visual to this node.
  42850. node.setVisual('color', thisNodeColor);
  42851. }
  42852. else {
  42853. var mapping = buildVisualMapping(
  42854. node, nodeModel, nodeLayout, nodeItemStyleModel, visuals, viewChildren
  42855. );
  42856. // Designate visual to children.
  42857. each$1(viewChildren, function (child, index) {
  42858. // If higher than viewRoot, only ancestors of viewRoot is needed to visit.
  42859. if (child.depth >= viewRootAncestors.length
  42860. || child === viewRootAncestors[child.depth]
  42861. ) {
  42862. var childVisual = mapVisual$1(
  42863. nodeModel, visuals, child, index, mapping, seriesModel
  42864. );
  42865. travelTree(
  42866. child, childVisual, levelItemStyles, seriesItemStyleModel,
  42867. viewRootAncestors, seriesModel
  42868. );
  42869. }
  42870. });
  42871. }
  42872. }
  42873. function buildVisuals(
  42874. nodeItemStyleModel, designatedVisual, levelItemStyle, seriesItemStyleModel
  42875. ) {
  42876. var visuals = extend({}, designatedVisual);
  42877. each$1(['color', 'colorAlpha', 'colorSaturation'], function (visualName) {
  42878. // Priority: thisNode > thisLevel > parentNodeDesignated > seriesModel
  42879. var val = nodeItemStyleModel.get(visualName, true); // Ignore parent
  42880. val == null && levelItemStyle && (val = levelItemStyle[visualName]);
  42881. val == null && (val = designatedVisual[visualName]);
  42882. val == null && (val = seriesItemStyleModel.get(visualName));
  42883. val != null && (visuals[visualName] = val);
  42884. });
  42885. return visuals;
  42886. }
  42887. function calculateColor(visuals) {
  42888. var color = getValueVisualDefine(visuals, 'color');
  42889. if (color) {
  42890. var colorAlpha = getValueVisualDefine(visuals, 'colorAlpha');
  42891. var colorSaturation = getValueVisualDefine(visuals, 'colorSaturation');
  42892. if (colorSaturation) {
  42893. color = modifyHSL(color, null, null, colorSaturation);
  42894. }
  42895. if (colorAlpha) {
  42896. color = modifyAlpha(color, colorAlpha);
  42897. }
  42898. return color;
  42899. }
  42900. }
  42901. function calculateBorderColor(borderColorSaturation, thisNodeColor) {
  42902. return thisNodeColor != null
  42903. ? modifyHSL(thisNodeColor, null, null, borderColorSaturation)
  42904. : null;
  42905. }
  42906. function getValueVisualDefine(visuals, name) {
  42907. var value = visuals[name];
  42908. if (value != null && value !== 'none') {
  42909. return value;
  42910. }
  42911. }
  42912. function buildVisualMapping(
  42913. node, nodeModel, nodeLayout, nodeItemStyleModel, visuals, viewChildren
  42914. ) {
  42915. if (!viewChildren || !viewChildren.length) {
  42916. return;
  42917. }
  42918. var rangeVisual = getRangeVisual(nodeModel, 'color')
  42919. || (
  42920. visuals.color != null
  42921. && visuals.color !== 'none'
  42922. && (
  42923. getRangeVisual(nodeModel, 'colorAlpha')
  42924. || getRangeVisual(nodeModel, 'colorSaturation')
  42925. )
  42926. );
  42927. if (!rangeVisual) {
  42928. return;
  42929. }
  42930. var visualMin = nodeModel.get('visualMin');
  42931. var visualMax = nodeModel.get('visualMax');
  42932. var dataExtent = nodeLayout.dataExtent.slice();
  42933. visualMin != null && visualMin < dataExtent[0] && (dataExtent[0] = visualMin);
  42934. visualMax != null && visualMax > dataExtent[1] && (dataExtent[1] = visualMax);
  42935. var colorMappingBy = nodeModel.get('colorMappingBy');
  42936. var opt = {
  42937. type: rangeVisual.name,
  42938. dataExtent: dataExtent,
  42939. visual: rangeVisual.range
  42940. };
  42941. if (opt.type === 'color'
  42942. && (colorMappingBy === 'index' || colorMappingBy === 'id')
  42943. ) {
  42944. opt.mappingMethod = 'category';
  42945. opt.loop = true;
  42946. // categories is ordinal, so do not set opt.categories.
  42947. }
  42948. else {
  42949. opt.mappingMethod = 'linear';
  42950. }
  42951. var mapping = new VisualMapping(opt);
  42952. mapping.__drColorMappingBy = colorMappingBy;
  42953. return mapping;
  42954. }
  42955. // Notice: If we dont have the attribute 'colorRange', but only use
  42956. // attribute 'color' to represent both concepts of 'colorRange' and 'color',
  42957. // (It means 'colorRange' when 'color' is Array, means 'color' when not array),
  42958. // this problem will be encountered:
  42959. // If a level-1 node dont have children, and its siblings has children,
  42960. // and colorRange is set on level-1, then the node can not be colored.
  42961. // So we separate 'colorRange' and 'color' to different attributes.
  42962. function getRangeVisual(nodeModel, name) {
  42963. // 'colorRange', 'colorARange', 'colorSRange'.
  42964. // If not exsits on this node, fetch from levels and series.
  42965. var range = nodeModel.get(name);
  42966. return (isArray$2(range) && range.length) ? {name: name, range: range} : null;
  42967. }
  42968. function mapVisual$1(nodeModel, visuals, child, index, mapping, seriesModel) {
  42969. var childVisuals = extend({}, visuals);
  42970. if (mapping) {
  42971. var mappingType = mapping.type;
  42972. var colorMappingBy = mappingType === 'color' && mapping.__drColorMappingBy;
  42973. var value =
  42974. colorMappingBy === 'index'
  42975. ? index
  42976. : colorMappingBy === 'id'
  42977. ? seriesModel.mapIdToIndex(child.getId())
  42978. : child.getValue(nodeModel.get('visualDimension'));
  42979. childVisuals[mappingType] = mapping.mapValueToVisual(value);
  42980. }
  42981. return childVisuals;
  42982. }
  42983. /*
  42984. * Licensed to the Apache Software Foundation (ASF) under one
  42985. * or more contributor license agreements. See the NOTICE file
  42986. * distributed with this work for additional information
  42987. * regarding copyright ownership. The ASF licenses this file
  42988. * to you under the Apache License, Version 2.0 (the
  42989. * "License"); you may not use this file except in compliance
  42990. * with the License. You may obtain a copy of the License at
  42991. *
  42992. * http://www.apache.org/licenses/LICENSE-2.0
  42993. *
  42994. * Unless required by applicable law or agreed to in writing,
  42995. * software distributed under the License is distributed on an
  42996. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42997. * KIND, either express or implied. See the License for the
  42998. * specific language governing permissions and limitations
  42999. * under the License.
  43000. */
  43001. var mathMax$4 = Math.max;
  43002. var mathMin$4 = Math.min;
  43003. var retrieveValue = retrieve;
  43004. var each$10 = each$1;
  43005. var PATH_BORDER_WIDTH = ['itemStyle', 'borderWidth'];
  43006. var PATH_GAP_WIDTH = ['itemStyle', 'gapWidth'];
  43007. var PATH_UPPER_LABEL_SHOW = ['upperLabel', 'show'];
  43008. var PATH_UPPER_LABEL_HEIGHT = ['upperLabel', 'height'];
  43009. /**
  43010. * @public
  43011. */
  43012. var treemapLayout = {
  43013. seriesType: 'treemap',
  43014. reset: function (seriesModel, ecModel, api, payload) {
  43015. // Layout result in each node:
  43016. // {x, y, width, height, area, borderWidth}
  43017. var ecWidth = api.getWidth();
  43018. var ecHeight = api.getHeight();
  43019. var seriesOption = seriesModel.option;
  43020. var layoutInfo = getLayoutRect(
  43021. seriesModel.getBoxLayoutParams(),
  43022. {
  43023. width: api.getWidth(),
  43024. height: api.getHeight()
  43025. }
  43026. );
  43027. var size = seriesOption.size || []; // Compatible with ec2.
  43028. var containerWidth = parsePercent$1(
  43029. retrieveValue(layoutInfo.width, size[0]),
  43030. ecWidth
  43031. );
  43032. var containerHeight = parsePercent$1(
  43033. retrieveValue(layoutInfo.height, size[1]),
  43034. ecHeight
  43035. );
  43036. // Fetch payload info.
  43037. var payloadType = payload && payload.type;
  43038. var types = ['treemapZoomToNode', 'treemapRootToNode'];
  43039. var targetInfo = retrieveTargetInfo(payload, types, seriesModel);
  43040. var rootRect = (payloadType === 'treemapRender' || payloadType === 'treemapMove')
  43041. ? payload.rootRect : null;
  43042. var viewRoot = seriesModel.getViewRoot();
  43043. var viewAbovePath = getPathToRoot(viewRoot);
  43044. if (payloadType !== 'treemapMove') {
  43045. var rootSize = payloadType === 'treemapZoomToNode'
  43046. ? estimateRootSize(
  43047. seriesModel, targetInfo, viewRoot, containerWidth, containerHeight
  43048. )
  43049. : rootRect
  43050. ? [rootRect.width, rootRect.height]
  43051. : [containerWidth, containerHeight];
  43052. var sort = seriesOption.sort;
  43053. if (sort && sort !== 'asc' && sort !== 'desc') {
  43054. sort = 'desc';
  43055. }
  43056. var options = {
  43057. squareRatio: seriesOption.squareRatio,
  43058. sort: sort,
  43059. leafDepth: seriesOption.leafDepth
  43060. };
  43061. // layout should be cleared because using updateView but not update.
  43062. viewRoot.hostTree.clearLayouts();
  43063. // TODO
  43064. // optimize: if out of view clip, do not layout.
  43065. // But take care that if do not render node out of view clip,
  43066. // how to calculate start po
  43067. var viewRootLayout = {
  43068. x: 0, y: 0,
  43069. width: rootSize[0], height: rootSize[1],
  43070. area: rootSize[0] * rootSize[1]
  43071. };
  43072. viewRoot.setLayout(viewRootLayout);
  43073. squarify(viewRoot, options, false, 0);
  43074. // Supplement layout.
  43075. var viewRootLayout = viewRoot.getLayout();
  43076. each$10(viewAbovePath, function (node, index) {
  43077. var childValue = (viewAbovePath[index + 1] || viewRoot).getValue();
  43078. node.setLayout(extend(
  43079. {dataExtent: [childValue, childValue], borderWidth: 0, upperHeight: 0},
  43080. viewRootLayout
  43081. ));
  43082. });
  43083. }
  43084. var treeRoot = seriesModel.getData().tree.root;
  43085. treeRoot.setLayout(
  43086. calculateRootPosition(layoutInfo, rootRect, targetInfo),
  43087. true
  43088. );
  43089. seriesModel.setLayoutInfo(layoutInfo);
  43090. // FIXME
  43091. // 现在没有clip功能,暂时取ec高宽。
  43092. prunning(
  43093. treeRoot,
  43094. // Transform to base element coordinate system.
  43095. new BoundingRect(-layoutInfo.x, -layoutInfo.y, ecWidth, ecHeight),
  43096. viewAbovePath,
  43097. viewRoot,
  43098. 0
  43099. );
  43100. }
  43101. };
  43102. /**
  43103. * Layout treemap with squarify algorithm.
  43104. * @see https://graphics.ethz.ch/teaching/scivis_common/Literature/squarifiedTreeMaps.pdf
  43105. * @see https://github.com/mbostock/d3/blob/master/src/layout/treemap.js
  43106. *
  43107. * @protected
  43108. * @param {module:echarts/data/Tree~TreeNode} node
  43109. * @param {Object} options
  43110. * @param {string} options.sort 'asc' or 'desc'
  43111. * @param {number} options.squareRatio
  43112. * @param {boolean} hideChildren
  43113. * @param {number} depth
  43114. */
  43115. function squarify(node, options, hideChildren, depth) {
  43116. var width;
  43117. var height;
  43118. if (node.isRemoved()) {
  43119. return;
  43120. }
  43121. var thisLayout = node.getLayout();
  43122. width = thisLayout.width;
  43123. height = thisLayout.height;
  43124. // Considering border and gap
  43125. var nodeModel = node.getModel();
  43126. var borderWidth = nodeModel.get(PATH_BORDER_WIDTH);
  43127. var halfGapWidth = nodeModel.get(PATH_GAP_WIDTH) / 2;
  43128. var upperLabelHeight = getUpperLabelHeight(nodeModel);
  43129. var upperHeight = Math.max(borderWidth, upperLabelHeight);
  43130. var layoutOffset = borderWidth - halfGapWidth;
  43131. var layoutOffsetUpper = upperHeight - halfGapWidth;
  43132. var nodeModel = node.getModel();
  43133. node.setLayout({
  43134. borderWidth: borderWidth,
  43135. upperHeight: upperHeight,
  43136. upperLabelHeight: upperLabelHeight
  43137. }, true);
  43138. width = mathMax$4(width - 2 * layoutOffset, 0);
  43139. height = mathMax$4(height - layoutOffset - layoutOffsetUpper, 0);
  43140. var totalArea = width * height;
  43141. var viewChildren = initChildren(
  43142. node, nodeModel, totalArea, options, hideChildren, depth
  43143. );
  43144. if (!viewChildren.length) {
  43145. return;
  43146. }
  43147. var rect = {x: layoutOffset, y: layoutOffsetUpper, width: width, height: height};
  43148. var rowFixedLength = mathMin$4(width, height);
  43149. var best = Infinity; // the best row score so far
  43150. var row = [];
  43151. row.area = 0;
  43152. for (var i = 0, len = viewChildren.length; i < len;) {
  43153. var child = viewChildren[i];
  43154. row.push(child);
  43155. row.area += child.getLayout().area;
  43156. var score = worst(row, rowFixedLength, options.squareRatio);
  43157. // continue with this orientation
  43158. if (score <= best) {
  43159. i++;
  43160. best = score;
  43161. }
  43162. // abort, and try a different orientation
  43163. else {
  43164. row.area -= row.pop().getLayout().area;
  43165. position(row, rowFixedLength, rect, halfGapWidth, false);
  43166. rowFixedLength = mathMin$4(rect.width, rect.height);
  43167. row.length = row.area = 0;
  43168. best = Infinity;
  43169. }
  43170. }
  43171. if (row.length) {
  43172. position(row, rowFixedLength, rect, halfGapWidth, true);
  43173. }
  43174. if (!hideChildren) {
  43175. var childrenVisibleMin = nodeModel.get('childrenVisibleMin');
  43176. if (childrenVisibleMin != null && totalArea < childrenVisibleMin) {
  43177. hideChildren = true;
  43178. }
  43179. }
  43180. for (var i = 0, len = viewChildren.length; i < len; i++) {
  43181. squarify(viewChildren[i], options, hideChildren, depth + 1);
  43182. }
  43183. }
  43184. /**
  43185. * Set area to each child, and calculate data extent for visual coding.
  43186. */
  43187. function initChildren(node, nodeModel, totalArea, options, hideChildren, depth) {
  43188. var viewChildren = node.children || [];
  43189. var orderBy = options.sort;
  43190. orderBy !== 'asc' && orderBy !== 'desc' && (orderBy = null);
  43191. var overLeafDepth = options.leafDepth != null && options.leafDepth <= depth;
  43192. // leafDepth has higher priority.
  43193. if (hideChildren && !overLeafDepth) {
  43194. return (node.viewChildren = []);
  43195. }
  43196. // Sort children, order by desc.
  43197. viewChildren = filter(viewChildren, function (child) {
  43198. return !child.isRemoved();
  43199. });
  43200. sort$1(viewChildren, orderBy);
  43201. var info = statistic(nodeModel, viewChildren, orderBy);
  43202. if (info.sum === 0) {
  43203. return (node.viewChildren = []);
  43204. }
  43205. info.sum = filterByThreshold(nodeModel, totalArea, info.sum, orderBy, viewChildren);
  43206. if (info.sum === 0) {
  43207. return (node.viewChildren = []);
  43208. }
  43209. // Set area to each child.
  43210. for (var i = 0, len = viewChildren.length; i < len; i++) {
  43211. var area = viewChildren[i].getValue() / info.sum * totalArea;
  43212. // Do not use setLayout({...}, true), because it is needed to clear last layout.
  43213. viewChildren[i].setLayout({area: area});
  43214. }
  43215. if (overLeafDepth) {
  43216. viewChildren.length && node.setLayout({isLeafRoot: true}, true);
  43217. viewChildren.length = 0;
  43218. }
  43219. node.viewChildren = viewChildren;
  43220. node.setLayout({dataExtent: info.dataExtent}, true);
  43221. return viewChildren;
  43222. }
  43223. /**
  43224. * Consider 'visibleMin'. Modify viewChildren and get new sum.
  43225. */
  43226. function filterByThreshold(nodeModel, totalArea, sum, orderBy, orderedChildren) {
  43227. // visibleMin is not supported yet when no option.sort.
  43228. if (!orderBy) {
  43229. return sum;
  43230. }
  43231. var visibleMin = nodeModel.get('visibleMin');
  43232. var len = orderedChildren.length;
  43233. var deletePoint = len;
  43234. // Always travel from little value to big value.
  43235. for (var i = len - 1; i >= 0; i--) {
  43236. var value = orderedChildren[
  43237. orderBy === 'asc' ? len - i - 1 : i
  43238. ].getValue();
  43239. if (value / sum * totalArea < visibleMin) {
  43240. deletePoint = i;
  43241. sum -= value;
  43242. }
  43243. }
  43244. orderBy === 'asc'
  43245. ? orderedChildren.splice(0, len - deletePoint)
  43246. : orderedChildren.splice(deletePoint, len - deletePoint);
  43247. return sum;
  43248. }
  43249. /**
  43250. * Sort
  43251. */
  43252. function sort$1(viewChildren, orderBy) {
  43253. if (orderBy) {
  43254. viewChildren.sort(function (a, b) {
  43255. var diff = orderBy === 'asc'
  43256. ? a.getValue() - b.getValue() : b.getValue() - a.getValue();
  43257. return diff === 0
  43258. ? (orderBy === 'asc'
  43259. ? a.dataIndex - b.dataIndex : b.dataIndex - a.dataIndex
  43260. )
  43261. : diff;
  43262. });
  43263. }
  43264. return viewChildren;
  43265. }
  43266. /**
  43267. * Statistic
  43268. */
  43269. function statistic(nodeModel, children, orderBy) {
  43270. // Calculate sum.
  43271. var sum = 0;
  43272. for (var i = 0, len = children.length; i < len; i++) {
  43273. sum += children[i].getValue();
  43274. }
  43275. // Statistic data extent for latter visual coding.
  43276. // Notice: data extent should be calculate based on raw children
  43277. // but not filtered view children, otherwise visual mapping will not
  43278. // be stable when zoom (where children is filtered by visibleMin).
  43279. var dimension = nodeModel.get('visualDimension');
  43280. var dataExtent;
  43281. // The same as area dimension.
  43282. if (!children || !children.length) {
  43283. dataExtent = [NaN, NaN];
  43284. }
  43285. else if (dimension === 'value' && orderBy) {
  43286. dataExtent = [
  43287. children[children.length - 1].getValue(),
  43288. children[0].getValue()
  43289. ];
  43290. orderBy === 'asc' && dataExtent.reverse();
  43291. }
  43292. // Other dimension.
  43293. else {
  43294. var dataExtent = [Infinity, -Infinity];
  43295. each$10(children, function (child) {
  43296. var value = child.getValue(dimension);
  43297. value < dataExtent[0] && (dataExtent[0] = value);
  43298. value > dataExtent[1] && (dataExtent[1] = value);
  43299. });
  43300. }
  43301. return {sum: sum, dataExtent: dataExtent};
  43302. }
  43303. /**
  43304. * Computes the score for the specified row,
  43305. * as the worst aspect ratio.
  43306. */
  43307. function worst(row, rowFixedLength, ratio) {
  43308. var areaMax = 0;
  43309. var areaMin = Infinity;
  43310. for (var i = 0, area, len = row.length; i < len; i++) {
  43311. area = row[i].getLayout().area;
  43312. if (area) {
  43313. area < areaMin && (areaMin = area);
  43314. area > areaMax && (areaMax = area);
  43315. }
  43316. }
  43317. var squareArea = row.area * row.area;
  43318. var f = rowFixedLength * rowFixedLength * ratio;
  43319. return squareArea
  43320. ? mathMax$4(
  43321. (f * areaMax) / squareArea,
  43322. squareArea / (f * areaMin)
  43323. )
  43324. : Infinity;
  43325. }
  43326. /**
  43327. * Positions the specified row of nodes. Modifies `rect`.
  43328. */
  43329. function position(row, rowFixedLength, rect, halfGapWidth, flush) {
  43330. // When rowFixedLength === rect.width,
  43331. // it is horizontal subdivision,
  43332. // rowFixedLength is the width of the subdivision,
  43333. // rowOtherLength is the height of the subdivision,
  43334. // and nodes will be positioned from left to right.
  43335. // wh[idx0WhenH] means: when horizontal,
  43336. // wh[idx0WhenH] => wh[0] => 'width'.
  43337. // xy[idx1WhenH] => xy[1] => 'y'.
  43338. var idx0WhenH = rowFixedLength === rect.width ? 0 : 1;
  43339. var idx1WhenH = 1 - idx0WhenH;
  43340. var xy = ['x', 'y'];
  43341. var wh = ['width', 'height'];
  43342. var last = rect[xy[idx0WhenH]];
  43343. var rowOtherLength = rowFixedLength
  43344. ? row.area / rowFixedLength : 0;
  43345. if (flush || rowOtherLength > rect[wh[idx1WhenH]]) {
  43346. rowOtherLength = rect[wh[idx1WhenH]]; // over+underflow
  43347. }
  43348. for (var i = 0, rowLen = row.length; i < rowLen; i++) {
  43349. var node = row[i];
  43350. var nodeLayout = {};
  43351. var step = rowOtherLength
  43352. ? node.getLayout().area / rowOtherLength : 0;
  43353. var wh1 = nodeLayout[wh[idx1WhenH]] = mathMax$4(rowOtherLength - 2 * halfGapWidth, 0);
  43354. // We use Math.max/min to avoid negative width/height when considering gap width.
  43355. var remain = rect[xy[idx0WhenH]] + rect[wh[idx0WhenH]] - last;
  43356. var modWH = (i === rowLen - 1 || remain < step) ? remain : step;
  43357. var wh0 = nodeLayout[wh[idx0WhenH]] = mathMax$4(modWH - 2 * halfGapWidth, 0);
  43358. nodeLayout[xy[idx1WhenH]] = rect[xy[idx1WhenH]] + mathMin$4(halfGapWidth, wh1 / 2);
  43359. nodeLayout[xy[idx0WhenH]] = last + mathMin$4(halfGapWidth, wh0 / 2);
  43360. last += modWH;
  43361. node.setLayout(nodeLayout, true);
  43362. }
  43363. rect[xy[idx1WhenH]] += rowOtherLength;
  43364. rect[wh[idx1WhenH]] -= rowOtherLength;
  43365. }
  43366. // Return [containerWidth, containerHeight] as defualt.
  43367. function estimateRootSize(seriesModel, targetInfo, viewRoot, containerWidth, containerHeight) {
  43368. // If targetInfo.node exists, we zoom to the node,
  43369. // so estimate whold width and heigth by target node.
  43370. var currNode = (targetInfo || {}).node;
  43371. var defaultSize = [containerWidth, containerHeight];
  43372. if (!currNode || currNode === viewRoot) {
  43373. return defaultSize;
  43374. }
  43375. var parent;
  43376. var viewArea = containerWidth * containerHeight;
  43377. var area = viewArea * seriesModel.option.zoomToNodeRatio;
  43378. while (parent = currNode.parentNode) { // jshint ignore:line
  43379. var sum = 0;
  43380. var siblings = parent.children;
  43381. for (var i = 0, len = siblings.length; i < len; i++) {
  43382. sum += siblings[i].getValue();
  43383. }
  43384. var currNodeValue = currNode.getValue();
  43385. if (currNodeValue === 0) {
  43386. return defaultSize;
  43387. }
  43388. area *= sum / currNodeValue;
  43389. // Considering border, suppose aspect ratio is 1.
  43390. var parentModel = parent.getModel();
  43391. var borderWidth = parentModel.get(PATH_BORDER_WIDTH);
  43392. var upperHeight = Math.max(borderWidth, getUpperLabelHeight(parentModel, borderWidth));
  43393. area += 4 * borderWidth * borderWidth
  43394. + (3 * borderWidth + upperHeight) * Math.pow(area, 0.5);
  43395. area > MAX_SAFE_INTEGER && (area = MAX_SAFE_INTEGER);
  43396. currNode = parent;
  43397. }
  43398. area < viewArea && (area = viewArea);
  43399. var scale = Math.pow(area / viewArea, 0.5);
  43400. return [containerWidth * scale, containerHeight * scale];
  43401. }
  43402. // Root postion base on coord of containerGroup
  43403. function calculateRootPosition(layoutInfo, rootRect, targetInfo) {
  43404. if (rootRect) {
  43405. return {x: rootRect.x, y: rootRect.y};
  43406. }
  43407. var defaultPosition = {x: 0, y: 0};
  43408. if (!targetInfo) {
  43409. return defaultPosition;
  43410. }
  43411. // If targetInfo is fetched by 'retrieveTargetInfo',
  43412. // old tree and new tree are the same tree,
  43413. // so the node still exists and we can visit it.
  43414. var targetNode = targetInfo.node;
  43415. var layout = targetNode.getLayout();
  43416. if (!layout) {
  43417. return defaultPosition;
  43418. }
  43419. // Transform coord from local to container.
  43420. var targetCenter = [layout.width / 2, layout.height / 2];
  43421. var node = targetNode;
  43422. while (node) {
  43423. var nodeLayout = node.getLayout();
  43424. targetCenter[0] += nodeLayout.x;
  43425. targetCenter[1] += nodeLayout.y;
  43426. node = node.parentNode;
  43427. }
  43428. return {
  43429. x: layoutInfo.width / 2 - targetCenter[0],
  43430. y: layoutInfo.height / 2 - targetCenter[1]
  43431. };
  43432. }
  43433. // Mark nodes visible for prunning when visual coding and rendering.
  43434. // Prunning depends on layout and root position, so we have to do it after layout.
  43435. function prunning(node, clipRect, viewAbovePath, viewRoot, depth) {
  43436. var nodeLayout = node.getLayout();
  43437. var nodeInViewAbovePath = viewAbovePath[depth];
  43438. var isAboveViewRoot = nodeInViewAbovePath && nodeInViewAbovePath === node;
  43439. if (
  43440. (nodeInViewAbovePath && !isAboveViewRoot)
  43441. || (depth === viewAbovePath.length && node !== viewRoot)
  43442. ) {
  43443. return;
  43444. }
  43445. node.setLayout({
  43446. // isInView means: viewRoot sub tree + viewAbovePath
  43447. isInView: true,
  43448. // invisible only means: outside view clip so that the node can not
  43449. // see but still layout for animation preparation but not render.
  43450. invisible: !isAboveViewRoot && !clipRect.intersect(nodeLayout),
  43451. isAboveViewRoot: isAboveViewRoot
  43452. }, true);
  43453. // Transform to child coordinate.
  43454. var childClipRect = new BoundingRect(
  43455. clipRect.x - nodeLayout.x,
  43456. clipRect.y - nodeLayout.y,
  43457. clipRect.width,
  43458. clipRect.height
  43459. );
  43460. each$10(node.viewChildren || [], function (child) {
  43461. prunning(child, childClipRect, viewAbovePath, viewRoot, depth + 1);
  43462. });
  43463. }
  43464. function getUpperLabelHeight(model) {
  43465. return model.get(PATH_UPPER_LABEL_SHOW) ? model.get(PATH_UPPER_LABEL_HEIGHT) : 0;
  43466. }
  43467. /*
  43468. * Licensed to the Apache Software Foundation (ASF) under one
  43469. * or more contributor license agreements. See the NOTICE file
  43470. * distributed with this work for additional information
  43471. * regarding copyright ownership. The ASF licenses this file
  43472. * to you under the Apache License, Version 2.0 (the
  43473. * "License"); you may not use this file except in compliance
  43474. * with the License. You may obtain a copy of the License at
  43475. *
  43476. * http://www.apache.org/licenses/LICENSE-2.0
  43477. *
  43478. * Unless required by applicable law or agreed to in writing,
  43479. * software distributed under the License is distributed on an
  43480. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43481. * KIND, either express or implied. See the License for the
  43482. * specific language governing permissions and limitations
  43483. * under the License.
  43484. */
  43485. registerVisual(treemapVisual);
  43486. registerLayout(treemapLayout);
  43487. /*
  43488. * Licensed to the Apache Software Foundation (ASF) under one
  43489. * or more contributor license agreements. See the NOTICE file
  43490. * distributed with this work for additional information
  43491. * regarding copyright ownership. The ASF licenses this file
  43492. * to you under the Apache License, Version 2.0 (the
  43493. * "License"); you may not use this file except in compliance
  43494. * with the License. You may obtain a copy of the License at
  43495. *
  43496. * http://www.apache.org/licenses/LICENSE-2.0
  43497. *
  43498. * Unless required by applicable law or agreed to in writing,
  43499. * software distributed under the License is distributed on an
  43500. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43501. * KIND, either express or implied. See the License for the
  43502. * specific language governing permissions and limitations
  43503. * under the License.
  43504. */
  43505. /**
  43506. * Graph data structure
  43507. *
  43508. * @module echarts/data/Graph
  43509. * @author Yi Shen(https://www.github.com/pissang)
  43510. */
  43511. // id may be function name of Object, add a prefix to avoid this problem.
  43512. function generateNodeKey (id) {
  43513. return '_EC_' + id;
  43514. }
  43515. /**
  43516. * @alias module:echarts/data/Graph
  43517. * @constructor
  43518. * @param {boolean} directed
  43519. */
  43520. var Graph = function(directed) {
  43521. /**
  43522. * 是否是有向图
  43523. * @type {boolean}
  43524. * @private
  43525. */
  43526. this._directed = directed || false;
  43527. /**
  43528. * @type {Array.<module:echarts/data/Graph.Node>}
  43529. * @readOnly
  43530. */
  43531. this.nodes = [];
  43532. /**
  43533. * @type {Array.<module:echarts/data/Graph.Edge>}
  43534. * @readOnly
  43535. */
  43536. this.edges = [];
  43537. /**
  43538. * @type {Object.<string, module:echarts/data/Graph.Node>}
  43539. * @private
  43540. */
  43541. this._nodesMap = {};
  43542. /**
  43543. * @type {Object.<string, module:echarts/data/Graph.Edge>}
  43544. * @private
  43545. */
  43546. this._edgesMap = {};
  43547. /**
  43548. * @type {module:echarts/data/List}
  43549. * @readOnly
  43550. */
  43551. this.data;
  43552. /**
  43553. * @type {module:echarts/data/List}
  43554. * @readOnly
  43555. */
  43556. this.edgeData;
  43557. };
  43558. var graphProto = Graph.prototype;
  43559. /**
  43560. * @type {string}
  43561. */
  43562. graphProto.type = 'graph';
  43563. /**
  43564. * If is directed graph
  43565. * @return {boolean}
  43566. */
  43567. graphProto.isDirected = function () {
  43568. return this._directed;
  43569. };
  43570. /**
  43571. * Add a new node
  43572. * @param {string} id
  43573. * @param {number} [dataIndex]
  43574. */
  43575. graphProto.addNode = function (id, dataIndex) {
  43576. id = id || ('' + dataIndex);
  43577. var nodesMap = this._nodesMap;
  43578. if (nodesMap[generateNodeKey(id)]) {
  43579. if (__DEV__) {
  43580. console.error('Graph nodes have duplicate name or id');
  43581. }
  43582. return;
  43583. }
  43584. var node = new Node(id, dataIndex);
  43585. node.hostGraph = this;
  43586. this.nodes.push(node);
  43587. nodesMap[generateNodeKey(id)] = node;
  43588. return node;
  43589. };
  43590. /**
  43591. * Get node by data index
  43592. * @param {number} dataIndex
  43593. * @return {module:echarts/data/Graph~Node}
  43594. */
  43595. graphProto.getNodeByIndex = function (dataIndex) {
  43596. var rawIdx = this.data.getRawIndex(dataIndex);
  43597. return this.nodes[rawIdx];
  43598. };
  43599. /**
  43600. * Get node by id
  43601. * @param {string} id
  43602. * @return {module:echarts/data/Graph.Node}
  43603. */
  43604. graphProto.getNodeById = function (id) {
  43605. return this._nodesMap[generateNodeKey(id)];
  43606. };
  43607. /**
  43608. * Add a new edge
  43609. * @param {number|string|module:echarts/data/Graph.Node} n1
  43610. * @param {number|string|module:echarts/data/Graph.Node} n2
  43611. * @param {number} [dataIndex=-1]
  43612. * @return {module:echarts/data/Graph.Edge}
  43613. */
  43614. graphProto.addEdge = function (n1, n2, dataIndex) {
  43615. var nodesMap = this._nodesMap;
  43616. var edgesMap = this._edgesMap;
  43617. // PNEDING
  43618. if (typeof n1 === 'number') {
  43619. n1 = this.nodes[n1];
  43620. }
  43621. if (typeof n2 === 'number') {
  43622. n2 = this.nodes[n2];
  43623. }
  43624. if (!Node.isInstance(n1)) {
  43625. n1 = nodesMap[generateNodeKey(n1)];
  43626. }
  43627. if (!Node.isInstance(n2)) {
  43628. n2 = nodesMap[generateNodeKey(n2)];
  43629. }
  43630. if (!n1 || !n2) {
  43631. return;
  43632. }
  43633. var key = n1.id + '-' + n2.id;
  43634. // PENDING
  43635. if (edgesMap[key]) {
  43636. return;
  43637. }
  43638. var edge = new Edge(n1, n2, dataIndex);
  43639. edge.hostGraph = this;
  43640. if (this._directed) {
  43641. n1.outEdges.push(edge);
  43642. n2.inEdges.push(edge);
  43643. }
  43644. n1.edges.push(edge);
  43645. if (n1 !== n2) {
  43646. n2.edges.push(edge);
  43647. }
  43648. this.edges.push(edge);
  43649. edgesMap[key] = edge;
  43650. return edge;
  43651. };
  43652. /**
  43653. * Get edge by data index
  43654. * @param {number} dataIndex
  43655. * @return {module:echarts/data/Graph~Node}
  43656. */
  43657. graphProto.getEdgeByIndex = function (dataIndex) {
  43658. var rawIdx = this.edgeData.getRawIndex(dataIndex);
  43659. return this.edges[rawIdx];
  43660. };
  43661. /**
  43662. * Get edge by two linked nodes
  43663. * @param {module:echarts/data/Graph.Node|string} n1
  43664. * @param {module:echarts/data/Graph.Node|string} n2
  43665. * @return {module:echarts/data/Graph.Edge}
  43666. */
  43667. graphProto.getEdge = function (n1, n2) {
  43668. if (Node.isInstance(n1)) {
  43669. n1 = n1.id;
  43670. }
  43671. if (Node.isInstance(n2)) {
  43672. n2 = n2.id;
  43673. }
  43674. var edgesMap = this._edgesMap;
  43675. if (this._directed) {
  43676. return edgesMap[n1 + '-' + n2];
  43677. } else {
  43678. return edgesMap[n1 + '-' + n2]
  43679. || edgesMap[n2 + '-' + n1];
  43680. }
  43681. };
  43682. /**
  43683. * Iterate all nodes
  43684. * @param {Function} cb
  43685. * @param {*} [context]
  43686. */
  43687. graphProto.eachNode = function (cb, context) {
  43688. var nodes = this.nodes;
  43689. var len = nodes.length;
  43690. for (var i = 0; i < len; i++) {
  43691. if (nodes[i].dataIndex >= 0) {
  43692. cb.call(context, nodes[i], i);
  43693. }
  43694. }
  43695. };
  43696. /**
  43697. * Iterate all edges
  43698. * @param {Function} cb
  43699. * @param {*} [context]
  43700. */
  43701. graphProto.eachEdge = function (cb, context) {
  43702. var edges = this.edges;
  43703. var len = edges.length;
  43704. for (var i = 0; i < len; i++) {
  43705. if (edges[i].dataIndex >= 0
  43706. && edges[i].node1.dataIndex >= 0
  43707. && edges[i].node2.dataIndex >= 0
  43708. ) {
  43709. cb.call(context, edges[i], i);
  43710. }
  43711. }
  43712. };
  43713. /**
  43714. * Breadth first traverse
  43715. * @param {Function} cb
  43716. * @param {module:echarts/data/Graph.Node} startNode
  43717. * @param {string} [direction='none'] 'none'|'in'|'out'
  43718. * @param {*} [context]
  43719. */
  43720. graphProto.breadthFirstTraverse = function (
  43721. cb, startNode, direction, context
  43722. ) {
  43723. if (!Node.isInstance(startNode)) {
  43724. startNode = this._nodesMap[generateNodeKey(startNode)];
  43725. }
  43726. if (!startNode) {
  43727. return;
  43728. }
  43729. var edgeType = direction === 'out'
  43730. ? 'outEdges' : (direction === 'in' ? 'inEdges' : 'edges');
  43731. for (var i = 0; i < this.nodes.length; i++) {
  43732. this.nodes[i].__visited = false;
  43733. }
  43734. if (cb.call(context, startNode, null)) {
  43735. return;
  43736. }
  43737. var queue = [startNode];
  43738. while (queue.length) {
  43739. var currentNode = queue.shift();
  43740. var edges = currentNode[edgeType];
  43741. for (var i = 0; i < edges.length; i++) {
  43742. var e = edges[i];
  43743. var otherNode = e.node1 === currentNode
  43744. ? e.node2 : e.node1;
  43745. if (!otherNode.__visited) {
  43746. if (cb.call(context, otherNode, currentNode)) {
  43747. // Stop traversing
  43748. return;
  43749. }
  43750. queue.push(otherNode);
  43751. otherNode.__visited = true;
  43752. }
  43753. }
  43754. }
  43755. };
  43756. // TODO
  43757. // graphProto.depthFirstTraverse = function (
  43758. // cb, startNode, direction, context
  43759. // ) {
  43760. // };
  43761. // Filter update
  43762. graphProto.update = function () {
  43763. var data = this.data;
  43764. var edgeData = this.edgeData;
  43765. var nodes = this.nodes;
  43766. var edges = this.edges;
  43767. for (var i = 0, len = nodes.length; i < len; i++) {
  43768. nodes[i].dataIndex = -1;
  43769. }
  43770. for (var i = 0, len = data.count(); i < len; i++) {
  43771. nodes[data.getRawIndex(i)].dataIndex = i;
  43772. }
  43773. edgeData.filterSelf(function (idx) {
  43774. var edge = edges[edgeData.getRawIndex(idx)];
  43775. return edge.node1.dataIndex >= 0 && edge.node2.dataIndex >= 0;
  43776. });
  43777. // Update edge
  43778. for (var i = 0, len = edges.length; i < len; i++) {
  43779. edges[i].dataIndex = -1;
  43780. }
  43781. for (var i = 0, len = edgeData.count(); i < len; i++) {
  43782. edges[edgeData.getRawIndex(i)].dataIndex = i;
  43783. }
  43784. };
  43785. /**
  43786. * @return {module:echarts/data/Graph}
  43787. */
  43788. graphProto.clone = function () {
  43789. var graph = new Graph(this._directed);
  43790. var nodes = this.nodes;
  43791. var edges = this.edges;
  43792. for (var i = 0; i < nodes.length; i++) {
  43793. graph.addNode(nodes[i].id, nodes[i].dataIndex);
  43794. }
  43795. for (var i = 0; i < edges.length; i++) {
  43796. var e = edges[i];
  43797. graph.addEdge(e.node1.id, e.node2.id, e.dataIndex);
  43798. }
  43799. return graph;
  43800. };
  43801. /**
  43802. * @alias module:echarts/data/Graph.Node
  43803. */
  43804. function Node(id, dataIndex) {
  43805. /**
  43806. * @type {string}
  43807. */
  43808. this.id = id == null ? '' : id;
  43809. /**
  43810. * @type {Array.<module:echarts/data/Graph.Edge>}
  43811. */
  43812. this.inEdges = [];
  43813. /**
  43814. * @type {Array.<module:echarts/data/Graph.Edge>}
  43815. */
  43816. this.outEdges = [];
  43817. /**
  43818. * @type {Array.<module:echarts/data/Graph.Edge>}
  43819. */
  43820. this.edges = [];
  43821. /**
  43822. * @type {module:echarts/data/Graph}
  43823. */
  43824. this.hostGraph;
  43825. /**
  43826. * @type {number}
  43827. */
  43828. this.dataIndex = dataIndex == null ? -1 : dataIndex;
  43829. }
  43830. Node.prototype = {
  43831. constructor: Node,
  43832. /**
  43833. * @return {number}
  43834. */
  43835. degree: function () {
  43836. return this.edges.length;
  43837. },
  43838. /**
  43839. * @return {number}
  43840. */
  43841. inDegree: function () {
  43842. return this.inEdges.length;
  43843. },
  43844. /**
  43845. * @return {number}
  43846. */
  43847. outDegree: function () {
  43848. return this.outEdges.length;
  43849. },
  43850. /**
  43851. * @param {string} [path]
  43852. * @return {module:echarts/model/Model}
  43853. */
  43854. getModel: function (path) {
  43855. if (this.dataIndex < 0) {
  43856. return;
  43857. }
  43858. var graph = this.hostGraph;
  43859. var itemModel = graph.data.getItemModel(this.dataIndex);
  43860. return itemModel.getModel(path);
  43861. }
  43862. };
  43863. /**
  43864. * 图边
  43865. * @alias module:echarts/data/Graph.Edge
  43866. * @param {module:echarts/data/Graph.Node} n1
  43867. * @param {module:echarts/data/Graph.Node} n2
  43868. * @param {number} [dataIndex=-1]
  43869. */
  43870. function Edge(n1, n2, dataIndex) {
  43871. /**
  43872. * 节点1,如果是有向图则为源节点
  43873. * @type {module:echarts/data/Graph.Node}
  43874. */
  43875. this.node1 = n1;
  43876. /**
  43877. * 节点2,如果是有向图则为目标节点
  43878. * @type {module:echarts/data/Graph.Node}
  43879. */
  43880. this.node2 = n2;
  43881. this.dataIndex = dataIndex == null ? -1 : dataIndex;
  43882. }
  43883. /**
  43884. * @param {string} [path]
  43885. * @return {module:echarts/model/Model}
  43886. */
  43887. Edge.prototype.getModel = function (path) {
  43888. if (this.dataIndex < 0) {
  43889. return;
  43890. }
  43891. var graph = this.hostGraph;
  43892. var itemModel = graph.edgeData.getItemModel(this.dataIndex);
  43893. return itemModel.getModel(path);
  43894. };
  43895. var createGraphDataProxyMixin = function (hostName, dataName) {
  43896. return {
  43897. /**
  43898. * @param {string=} [dimension='value'] Default 'value'. can be 'a', 'b', 'c', 'd', 'e'.
  43899. * @return {number}
  43900. */
  43901. getValue: function (dimension) {
  43902. var data = this[hostName][dataName];
  43903. return data.get(data.getDimension(dimension || 'value'), this.dataIndex);
  43904. },
  43905. /**
  43906. * @param {Object|string} key
  43907. * @param {*} [value]
  43908. */
  43909. setVisual: function (key, value) {
  43910. this.dataIndex >= 0
  43911. && this[hostName][dataName].setItemVisual(this.dataIndex, key, value);
  43912. },
  43913. /**
  43914. * @param {string} key
  43915. * @return {boolean}
  43916. */
  43917. getVisual: function (key, ignoreParent) {
  43918. return this[hostName][dataName].getItemVisual(this.dataIndex, key, ignoreParent);
  43919. },
  43920. /**
  43921. * @param {Object} layout
  43922. * @return {boolean} [merge=false]
  43923. */
  43924. setLayout: function (layout, merge$$1) {
  43925. this.dataIndex >= 0
  43926. && this[hostName][dataName].setItemLayout(this.dataIndex, layout, merge$$1);
  43927. },
  43928. /**
  43929. * @return {Object}
  43930. */
  43931. getLayout: function () {
  43932. return this[hostName][dataName].getItemLayout(this.dataIndex);
  43933. },
  43934. /**
  43935. * @return {module:zrender/Element}
  43936. */
  43937. getGraphicEl: function () {
  43938. return this[hostName][dataName].getItemGraphicEl(this.dataIndex);
  43939. },
  43940. /**
  43941. * @return {number}
  43942. */
  43943. getRawIndex: function () {
  43944. return this[hostName][dataName].getRawIndex(this.dataIndex);
  43945. }
  43946. };
  43947. };
  43948. mixin(Node, createGraphDataProxyMixin('hostGraph', 'data'));
  43949. mixin(Edge, createGraphDataProxyMixin('hostGraph', 'edgeData'));
  43950. Graph.Node = Node;
  43951. Graph.Edge = Edge;
  43952. enableClassCheck(Node);
  43953. enableClassCheck(Edge);
  43954. /*
  43955. * Licensed to the Apache Software Foundation (ASF) under one
  43956. * or more contributor license agreements. See the NOTICE file
  43957. * distributed with this work for additional information
  43958. * regarding copyright ownership. The ASF licenses this file
  43959. * to you under the Apache License, Version 2.0 (the
  43960. * "License"); you may not use this file except in compliance
  43961. * with the License. You may obtain a copy of the License at
  43962. *
  43963. * http://www.apache.org/licenses/LICENSE-2.0
  43964. *
  43965. * Unless required by applicable law or agreed to in writing,
  43966. * software distributed under the License is distributed on an
  43967. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43968. * KIND, either express or implied. See the License for the
  43969. * specific language governing permissions and limitations
  43970. * under the License.
  43971. */
  43972. var createGraphFromNodeEdge = function (nodes, edges, seriesModel, directed, beforeLink) {
  43973. // ??? TODO
  43974. // support dataset?
  43975. var graph = new Graph(directed);
  43976. for (var i = 0; i < nodes.length; i++) {
  43977. graph.addNode(retrieve(
  43978. // Id, name, dataIndex
  43979. nodes[i].id, nodes[i].name, i
  43980. ), i);
  43981. }
  43982. var linkNameList = [];
  43983. var validEdges = [];
  43984. var linkCount = 0;
  43985. for (var i = 0; i < edges.length; i++) {
  43986. var link = edges[i];
  43987. var source = link.source;
  43988. var target = link.target;
  43989. // addEdge may fail when source or target not exists
  43990. if (graph.addEdge(source, target, linkCount)) {
  43991. validEdges.push(link);
  43992. linkNameList.push(retrieve(link.id, source + ' > ' + target));
  43993. linkCount++;
  43994. }
  43995. }
  43996. var coordSys = seriesModel.get('coordinateSystem');
  43997. var nodeData;
  43998. if (coordSys === 'cartesian2d' || coordSys === 'polar') {
  43999. nodeData = createListFromArray(nodes, seriesModel);
  44000. }
  44001. else {
  44002. var coordSysCtor = CoordinateSystemManager.get(coordSys);
  44003. var coordDimensions = (coordSysCtor && coordSysCtor.type !== 'view')
  44004. ? (coordSysCtor.dimensions || []) : [];
  44005. // FIXME: Some geo do not need `value` dimenson, whereas `calendar` needs
  44006. // `value` dimension, but graph need `value` dimension. It's better to
  44007. // uniform this behavior.
  44008. if (indexOf(coordDimensions, 'value') < 0) {
  44009. coordDimensions.concat(['value']);
  44010. }
  44011. var dimensionNames = createDimensions(nodes, {
  44012. coordDimensions: coordDimensions
  44013. });
  44014. nodeData = new List(dimensionNames, seriesModel);
  44015. nodeData.initData(nodes);
  44016. }
  44017. var edgeData = new List(['value'], seriesModel);
  44018. edgeData.initData(validEdges, linkNameList);
  44019. beforeLink && beforeLink(nodeData, edgeData);
  44020. linkList({
  44021. mainData: nodeData,
  44022. struct: graph,
  44023. structAttr: 'graph',
  44024. datas: {node: nodeData, edge: edgeData},
  44025. datasAttr: {node: 'data', edge: 'edgeData'}
  44026. });
  44027. // Update dataIndex of nodes and edges because invalid edge may be removed
  44028. graph.update();
  44029. return graph;
  44030. };
  44031. /*
  44032. * Licensed to the Apache Software Foundation (ASF) under one
  44033. * or more contributor license agreements. See the NOTICE file
  44034. * distributed with this work for additional information
  44035. * regarding copyright ownership. The ASF licenses this file
  44036. * to you under the Apache License, Version 2.0 (the
  44037. * "License"); you may not use this file except in compliance
  44038. * with the License. You may obtain a copy of the License at
  44039. *
  44040. * http://www.apache.org/licenses/LICENSE-2.0
  44041. *
  44042. * Unless required by applicable law or agreed to in writing,
  44043. * software distributed under the License is distributed on an
  44044. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44045. * KIND, either express or implied. See the License for the
  44046. * specific language governing permissions and limitations
  44047. * under the License.
  44048. */
  44049. var GraphSeries = extendSeriesModel({
  44050. type: 'series.graph',
  44051. init: function (option) {
  44052. GraphSeries.superApply(this, 'init', arguments);
  44053. // Provide data for legend select
  44054. this.legendDataProvider = function () {
  44055. return this._categoriesData;
  44056. };
  44057. this.fillDataTextStyle(option.edges || option.links);
  44058. this._updateCategoriesData();
  44059. },
  44060. mergeOption: function (option) {
  44061. GraphSeries.superApply(this, 'mergeOption', arguments);
  44062. this.fillDataTextStyle(option.edges || option.links);
  44063. this._updateCategoriesData();
  44064. },
  44065. mergeDefaultAndTheme: function (option) {
  44066. GraphSeries.superApply(this, 'mergeDefaultAndTheme', arguments);
  44067. defaultEmphasis(option, ['edgeLabel'], ['show']);
  44068. },
  44069. getInitialData: function (option, ecModel) {
  44070. var edges = option.edges || option.links || [];
  44071. var nodes = option.data || option.nodes || [];
  44072. var self = this;
  44073. if (nodes && edges) {
  44074. return createGraphFromNodeEdge(nodes, edges, this, true, beforeLink).data;
  44075. }
  44076. function beforeLink(nodeData, edgeData) {
  44077. // Overwrite nodeData.getItemModel to
  44078. nodeData.wrapMethod('getItemModel', function (model) {
  44079. var categoriesModels = self._categoriesModels;
  44080. var categoryIdx = model.getShallow('category');
  44081. var categoryModel = categoriesModels[categoryIdx];
  44082. if (categoryModel) {
  44083. categoryModel.parentModel = model.parentModel;
  44084. model.parentModel = categoryModel;
  44085. }
  44086. return model;
  44087. });
  44088. var edgeLabelModel = self.getModel('edgeLabel');
  44089. // For option `edgeLabel` can be found by label.xxx.xxx on item mode.
  44090. var fakeSeriesModel = new Model(
  44091. {label: edgeLabelModel.option},
  44092. edgeLabelModel.parentModel,
  44093. ecModel
  44094. );
  44095. var emphasisEdgeLabelModel = self.getModel('emphasis.edgeLabel');
  44096. var emphasisFakeSeriesModel = new Model(
  44097. {emphasis: {label: emphasisEdgeLabelModel.option}},
  44098. emphasisEdgeLabelModel.parentModel,
  44099. ecModel
  44100. );
  44101. edgeData.wrapMethod('getItemModel', function (model) {
  44102. model.customizeGetParent(edgeGetParent);
  44103. return model;
  44104. });
  44105. function edgeGetParent(path) {
  44106. path = this.parsePath(path);
  44107. return (path && path[0] === 'label')
  44108. ? fakeSeriesModel
  44109. : (path && path[0] === 'emphasis' && path[1] === 'label')
  44110. ? emphasisFakeSeriesModel
  44111. : this.parentModel;
  44112. }
  44113. }
  44114. },
  44115. /**
  44116. * @return {module:echarts/data/Graph}
  44117. */
  44118. getGraph: function () {
  44119. return this.getData().graph;
  44120. },
  44121. /**
  44122. * @return {module:echarts/data/List}
  44123. */
  44124. getEdgeData: function () {
  44125. return this.getGraph().edgeData;
  44126. },
  44127. /**
  44128. * @return {module:echarts/data/List}
  44129. */
  44130. getCategoriesData: function () {
  44131. return this._categoriesData;
  44132. },
  44133. /**
  44134. * @override
  44135. */
  44136. formatTooltip: function (dataIndex, multipleSeries, dataType) {
  44137. if (dataType === 'edge') {
  44138. var nodeData = this.getData();
  44139. var params = this.getDataParams(dataIndex, dataType);
  44140. var edge = nodeData.graph.getEdgeByIndex(dataIndex);
  44141. var sourceName = nodeData.getName(edge.node1.dataIndex);
  44142. var targetName = nodeData.getName(edge.node2.dataIndex);
  44143. var html = [];
  44144. sourceName != null && html.push(sourceName);
  44145. targetName != null && html.push(targetName);
  44146. html = encodeHTML(html.join(' > '));
  44147. if (params.value) {
  44148. html += ' : ' + encodeHTML(params.value);
  44149. }
  44150. return html;
  44151. }
  44152. else { // dataType === 'node' or empty
  44153. return GraphSeries.superApply(this, 'formatTooltip', arguments);
  44154. }
  44155. },
  44156. _updateCategoriesData: function () {
  44157. var categories = map(this.option.categories || [], function (category) {
  44158. // Data must has value
  44159. return category.value != null ? category : extend({
  44160. value: 0
  44161. }, category);
  44162. });
  44163. var categoriesData = new List(['value'], this);
  44164. categoriesData.initData(categories);
  44165. this._categoriesData = categoriesData;
  44166. this._categoriesModels = categoriesData.mapArray(function (idx) {
  44167. return categoriesData.getItemModel(idx, true);
  44168. });
  44169. },
  44170. setZoom: function (zoom) {
  44171. this.option.zoom = zoom;
  44172. },
  44173. setCenter: function (center) {
  44174. this.option.center = center;
  44175. },
  44176. isAnimationEnabled: function () {
  44177. return GraphSeries.superCall(this, 'isAnimationEnabled')
  44178. // Not enable animation when do force layout
  44179. && !(this.get('layout') === 'force' && this.get('force.layoutAnimation'));
  44180. },
  44181. defaultOption: {
  44182. zlevel: 0,
  44183. z: 2,
  44184. coordinateSystem: 'view',
  44185. // Default option for all coordinate systems
  44186. // xAxisIndex: 0,
  44187. // yAxisIndex: 0,
  44188. // polarIndex: 0,
  44189. // geoIndex: 0,
  44190. legendHoverLink: true,
  44191. hoverAnimation: true,
  44192. layout: null,
  44193. focusNodeAdjacency: false,
  44194. // Configuration of circular layout
  44195. circular: {
  44196. rotateLabel: false
  44197. },
  44198. // Configuration of force directed layout
  44199. force: {
  44200. initLayout: null,
  44201. // Node repulsion. Can be an array to represent range.
  44202. repulsion: [0, 50],
  44203. gravity: 0.1,
  44204. // Edge length. Can be an array to represent range.
  44205. edgeLength: 30,
  44206. layoutAnimation: true
  44207. },
  44208. left: 'center',
  44209. top: 'center',
  44210. // right: null,
  44211. // bottom: null,
  44212. // width: '80%',
  44213. // height: '80%',
  44214. symbol: 'circle',
  44215. symbolSize: 10,
  44216. edgeSymbol: ['none', 'none'],
  44217. edgeSymbolSize: 10,
  44218. edgeLabel: {
  44219. position: 'middle'
  44220. },
  44221. draggable: false,
  44222. roam: false,
  44223. // Default on center of graph
  44224. center: null,
  44225. zoom: 1,
  44226. // Symbol size scale ratio in roam
  44227. nodeScaleRatio: 0.6,
  44228. // cursor: null,
  44229. // categories: [],
  44230. // data: []
  44231. // Or
  44232. // nodes: []
  44233. //
  44234. // links: []
  44235. // Or
  44236. // edges: []
  44237. label: {
  44238. show: false,
  44239. formatter: '{b}'
  44240. },
  44241. itemStyle: {},
  44242. lineStyle: {
  44243. color: '#aaa',
  44244. width: 1,
  44245. curveness: 0,
  44246. opacity: 0.5
  44247. },
  44248. emphasis: {
  44249. label: {
  44250. show: true
  44251. }
  44252. }
  44253. }
  44254. });
  44255. /*
  44256. * Licensed to the Apache Software Foundation (ASF) under one
  44257. * or more contributor license agreements. See the NOTICE file
  44258. * distributed with this work for additional information
  44259. * regarding copyright ownership. The ASF licenses this file
  44260. * to you under the Apache License, Version 2.0 (the
  44261. * "License"); you may not use this file except in compliance
  44262. * with the License. You may obtain a copy of the License at
  44263. *
  44264. * http://www.apache.org/licenses/LICENSE-2.0
  44265. *
  44266. * Unless required by applicable law or agreed to in writing,
  44267. * software distributed under the License is distributed on an
  44268. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44269. * KIND, either express or implied. See the License for the
  44270. * specific language governing permissions and limitations
  44271. * under the License.
  44272. */
  44273. /**
  44274. * Line path for bezier and straight line draw
  44275. */
  44276. var straightLineProto = Line.prototype;
  44277. var bezierCurveProto = BezierCurve.prototype;
  44278. function isLine(shape) {
  44279. return isNaN(+shape.cpx1) || isNaN(+shape.cpy1);
  44280. }
  44281. var LinePath = extendShape({
  44282. type: 'ec-line',
  44283. style: {
  44284. stroke: '#000',
  44285. fill: null
  44286. },
  44287. shape: {
  44288. x1: 0,
  44289. y1: 0,
  44290. x2: 0,
  44291. y2: 0,
  44292. percent: 1,
  44293. cpx1: null,
  44294. cpy1: null
  44295. },
  44296. buildPath: function (ctx, shape) {
  44297. (isLine(shape) ? straightLineProto : bezierCurveProto).buildPath(ctx, shape);
  44298. },
  44299. pointAt: function (t) {
  44300. return isLine(this.shape)
  44301. ? straightLineProto.pointAt.call(this, t)
  44302. : bezierCurveProto.pointAt.call(this, t);
  44303. },
  44304. tangentAt: function (t) {
  44305. var shape = this.shape;
  44306. var p = isLine(shape)
  44307. ? [shape.x2 - shape.x1, shape.y2 - shape.y1]
  44308. : bezierCurveProto.tangentAt.call(this, t);
  44309. return normalize(p, p);
  44310. }
  44311. });
  44312. /*
  44313. * Licensed to the Apache Software Foundation (ASF) under one
  44314. * or more contributor license agreements. See the NOTICE file
  44315. * distributed with this work for additional information
  44316. * regarding copyright ownership. The ASF licenses this file
  44317. * to you under the Apache License, Version 2.0 (the
  44318. * "License"); you may not use this file except in compliance
  44319. * with the License. You may obtain a copy of the License at
  44320. *
  44321. * http://www.apache.org/licenses/LICENSE-2.0
  44322. *
  44323. * Unless required by applicable law or agreed to in writing,
  44324. * software distributed under the License is distributed on an
  44325. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44326. * KIND, either express or implied. See the License for the
  44327. * specific language governing permissions and limitations
  44328. * under the License.
  44329. */
  44330. /**
  44331. * @module echarts/chart/helper/Line
  44332. */
  44333. var SYMBOL_CATEGORIES = ['fromSymbol', 'toSymbol'];
  44334. function makeSymbolTypeKey(symbolCategory) {
  44335. return '_' + symbolCategory + 'Type';
  44336. }
  44337. /**
  44338. * @inner
  44339. */
  44340. function createSymbol$1(name, lineData, idx) {
  44341. var color = lineData.getItemVisual(idx, 'color');
  44342. var symbolType = lineData.getItemVisual(idx, name);
  44343. var symbolSize = lineData.getItemVisual(idx, name + 'Size');
  44344. if (!symbolType || symbolType === 'none') {
  44345. return;
  44346. }
  44347. if (!isArray(symbolSize)) {
  44348. symbolSize = [symbolSize, symbolSize];
  44349. }
  44350. var symbolPath = createSymbol(
  44351. symbolType, -symbolSize[0] / 2, -symbolSize[1] / 2,
  44352. symbolSize[0], symbolSize[1], color
  44353. );
  44354. symbolPath.name = name;
  44355. return symbolPath;
  44356. }
  44357. function createLine(points) {
  44358. var line = new LinePath({
  44359. name: 'line'
  44360. });
  44361. setLinePoints(line.shape, points);
  44362. return line;
  44363. }
  44364. function setLinePoints(targetShape, points) {
  44365. var p1 = points[0];
  44366. var p2 = points[1];
  44367. var cp1 = points[2];
  44368. targetShape.x1 = p1[0];
  44369. targetShape.y1 = p1[1];
  44370. targetShape.x2 = p2[0];
  44371. targetShape.y2 = p2[1];
  44372. targetShape.percent = 1;
  44373. if (cp1) {
  44374. targetShape.cpx1 = cp1[0];
  44375. targetShape.cpy1 = cp1[1];
  44376. }
  44377. else {
  44378. targetShape.cpx1 = NaN;
  44379. targetShape.cpy1 = NaN;
  44380. }
  44381. }
  44382. function updateSymbolAndLabelBeforeLineUpdate () {
  44383. var lineGroup = this;
  44384. var symbolFrom = lineGroup.childOfName('fromSymbol');
  44385. var symbolTo = lineGroup.childOfName('toSymbol');
  44386. var label = lineGroup.childOfName('label');
  44387. // Quick reject
  44388. if (!symbolFrom && !symbolTo && label.ignore) {
  44389. return;
  44390. }
  44391. var invScale = 1;
  44392. var parentNode = this.parent;
  44393. while (parentNode) {
  44394. if (parentNode.scale) {
  44395. invScale /= parentNode.scale[0];
  44396. }
  44397. parentNode = parentNode.parent;
  44398. }
  44399. var line = lineGroup.childOfName('line');
  44400. // If line not changed
  44401. // FIXME Parent scale changed
  44402. if (!this.__dirty && !line.__dirty) {
  44403. return;
  44404. }
  44405. var percent = line.shape.percent;
  44406. var fromPos = line.pointAt(0);
  44407. var toPos = line.pointAt(percent);
  44408. var d = sub([], toPos, fromPos);
  44409. normalize(d, d);
  44410. if (symbolFrom) {
  44411. symbolFrom.attr('position', fromPos);
  44412. var tangent = line.tangentAt(0);
  44413. symbolFrom.attr('rotation', Math.PI / 2 - Math.atan2(
  44414. tangent[1], tangent[0]
  44415. ));
  44416. symbolFrom.attr('scale', [invScale * percent, invScale * percent]);
  44417. }
  44418. if (symbolTo) {
  44419. symbolTo.attr('position', toPos);
  44420. var tangent = line.tangentAt(1);
  44421. symbolTo.attr('rotation', -Math.PI / 2 - Math.atan2(
  44422. tangent[1], tangent[0]
  44423. ));
  44424. symbolTo.attr('scale', [invScale * percent, invScale * percent]);
  44425. }
  44426. if (!label.ignore) {
  44427. label.attr('position', toPos);
  44428. var textPosition;
  44429. var textAlign;
  44430. var textVerticalAlign;
  44431. var distance$$1 = 5 * invScale;
  44432. // End
  44433. if (label.__position === 'end') {
  44434. textPosition = [d[0] * distance$$1 + toPos[0], d[1] * distance$$1 + toPos[1]];
  44435. textAlign = d[0] > 0.8 ? 'left' : (d[0] < -0.8 ? 'right' : 'center');
  44436. textVerticalAlign = d[1] > 0.8 ? 'top' : (d[1] < -0.8 ? 'bottom' : 'middle');
  44437. }
  44438. // Middle
  44439. else if (label.__position === 'middle') {
  44440. var halfPercent = percent / 2;
  44441. var tangent = line.tangentAt(halfPercent);
  44442. var n = [tangent[1], -tangent[0]];
  44443. var cp = line.pointAt(halfPercent);
  44444. if (n[1] > 0) {
  44445. n[0] = -n[0];
  44446. n[1] = -n[1];
  44447. }
  44448. textPosition = [cp[0] + n[0] * distance$$1, cp[1] + n[1] * distance$$1];
  44449. textAlign = 'center';
  44450. textVerticalAlign = 'bottom';
  44451. var rotation = -Math.atan2(tangent[1], tangent[0]);
  44452. if (toPos[0] < fromPos[0]) {
  44453. rotation = Math.PI + rotation;
  44454. }
  44455. label.attr('rotation', rotation);
  44456. }
  44457. // Start
  44458. else {
  44459. textPosition = [-d[0] * distance$$1 + fromPos[0], -d[1] * distance$$1 + fromPos[1]];
  44460. textAlign = d[0] > 0.8 ? 'right' : (d[0] < -0.8 ? 'left' : 'center');
  44461. textVerticalAlign = d[1] > 0.8 ? 'bottom' : (d[1] < -0.8 ? 'top' : 'middle');
  44462. }
  44463. label.attr({
  44464. style: {
  44465. // Use the user specified text align and baseline first
  44466. textVerticalAlign: label.__verticalAlign || textVerticalAlign,
  44467. textAlign: label.__textAlign || textAlign
  44468. },
  44469. position: textPosition,
  44470. scale: [invScale, invScale]
  44471. });
  44472. }
  44473. }
  44474. /**
  44475. * @constructor
  44476. * @extends {module:zrender/graphic/Group}
  44477. * @alias {module:echarts/chart/helper/Line}
  44478. */
  44479. function Line$1(lineData, idx, seriesScope) {
  44480. Group.call(this);
  44481. this._createLine(lineData, idx, seriesScope);
  44482. }
  44483. var lineProto = Line$1.prototype;
  44484. // Update symbol position and rotation
  44485. lineProto.beforeUpdate = updateSymbolAndLabelBeforeLineUpdate;
  44486. lineProto._createLine = function (lineData, idx, seriesScope) {
  44487. var seriesModel = lineData.hostModel;
  44488. var linePoints = lineData.getItemLayout(idx);
  44489. var line = createLine(linePoints);
  44490. line.shape.percent = 0;
  44491. initProps(line, {
  44492. shape: {
  44493. percent: 1
  44494. }
  44495. }, seriesModel, idx);
  44496. this.add(line);
  44497. var label = new Text({
  44498. name: 'label'
  44499. });
  44500. this.add(label);
  44501. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  44502. var symbol = createSymbol$1(symbolCategory, lineData, idx);
  44503. // symbols must added after line to make sure
  44504. // it will be updated after line#update.
  44505. // Or symbol position and rotation update in line#beforeUpdate will be one frame slow
  44506. this.add(symbol);
  44507. this[makeSymbolTypeKey(symbolCategory)] = lineData.getItemVisual(idx, symbolCategory);
  44508. }, this);
  44509. this._updateCommonStl(lineData, idx, seriesScope);
  44510. };
  44511. lineProto.updateData = function (lineData, idx, seriesScope) {
  44512. var seriesModel = lineData.hostModel;
  44513. var line = this.childOfName('line');
  44514. var linePoints = lineData.getItemLayout(idx);
  44515. var target = {
  44516. shape: {}
  44517. };
  44518. setLinePoints(target.shape, linePoints);
  44519. updateProps(line, target, seriesModel, idx);
  44520. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  44521. var symbolType = lineData.getItemVisual(idx, symbolCategory);
  44522. var key = makeSymbolTypeKey(symbolCategory);
  44523. // Symbol changed
  44524. if (this[key] !== symbolType) {
  44525. this.remove(this.childOfName(symbolCategory));
  44526. var symbol = createSymbol$1(symbolCategory, lineData, idx);
  44527. this.add(symbol);
  44528. }
  44529. this[key] = symbolType;
  44530. }, this);
  44531. this._updateCommonStl(lineData, idx, seriesScope);
  44532. };
  44533. lineProto._updateCommonStl = function (lineData, idx, seriesScope) {
  44534. var seriesModel = lineData.hostModel;
  44535. var line = this.childOfName('line');
  44536. var lineStyle = seriesScope && seriesScope.lineStyle;
  44537. var hoverLineStyle = seriesScope && seriesScope.hoverLineStyle;
  44538. var labelModel = seriesScope && seriesScope.labelModel;
  44539. var hoverLabelModel = seriesScope && seriesScope.hoverLabelModel;
  44540. // Optimization for large dataset
  44541. if (!seriesScope || lineData.hasItemOption) {
  44542. var itemModel = lineData.getItemModel(idx);
  44543. lineStyle = itemModel.getModel('lineStyle').getLineStyle();
  44544. hoverLineStyle = itemModel.getModel('emphasis.lineStyle').getLineStyle();
  44545. labelModel = itemModel.getModel('label');
  44546. hoverLabelModel = itemModel.getModel('emphasis.label');
  44547. }
  44548. var visualColor = lineData.getItemVisual(idx, 'color');
  44549. var visualOpacity = retrieve3(
  44550. lineData.getItemVisual(idx, 'opacity'),
  44551. lineStyle.opacity,
  44552. 1
  44553. );
  44554. line.useStyle(defaults(
  44555. {
  44556. strokeNoScale: true,
  44557. fill: 'none',
  44558. stroke: visualColor,
  44559. opacity: visualOpacity
  44560. },
  44561. lineStyle
  44562. ));
  44563. line.hoverStyle = hoverLineStyle;
  44564. // Update symbol
  44565. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  44566. var symbol = this.childOfName(symbolCategory);
  44567. if (symbol) {
  44568. symbol.setColor(visualColor);
  44569. symbol.setStyle({
  44570. opacity: visualOpacity
  44571. });
  44572. }
  44573. }, this);
  44574. var showLabel = labelModel.getShallow('show');
  44575. var hoverShowLabel = hoverLabelModel.getShallow('show');
  44576. var label = this.childOfName('label');
  44577. var defaultLabelColor;
  44578. var baseText;
  44579. // FIXME: the logic below probably should be merged to `graphic.setLabelStyle`.
  44580. if (showLabel || hoverShowLabel) {
  44581. defaultLabelColor = visualColor || '#000';
  44582. baseText = seriesModel.getFormattedLabel(idx, 'normal', lineData.dataType);
  44583. if (baseText == null) {
  44584. var rawVal = seriesModel.getRawValue(idx);
  44585. baseText = rawVal == null
  44586. ? lineData.getName(idx)
  44587. : isFinite(rawVal)
  44588. ? round$1(rawVal)
  44589. : rawVal;
  44590. }
  44591. }
  44592. var normalText = showLabel ? baseText : null;
  44593. var emphasisText = hoverShowLabel
  44594. ? retrieve2(
  44595. seriesModel.getFormattedLabel(idx, 'emphasis', lineData.dataType),
  44596. baseText
  44597. )
  44598. : null;
  44599. var labelStyle = label.style;
  44600. // Always set `textStyle` even if `normalStyle.text` is null, because default
  44601. // values have to be set on `normalStyle`.
  44602. if (normalText != null || emphasisText != null) {
  44603. setTextStyle(label.style, labelModel, {
  44604. text: normalText
  44605. }, {
  44606. autoColor: defaultLabelColor
  44607. });
  44608. label.__textAlign = labelStyle.textAlign;
  44609. label.__verticalAlign = labelStyle.textVerticalAlign;
  44610. // 'start', 'middle', 'end'
  44611. label.__position = labelModel.get('position') || 'middle';
  44612. }
  44613. if (emphasisText != null) {
  44614. // Only these properties supported in this emphasis style here.
  44615. label.hoverStyle = {
  44616. text: emphasisText,
  44617. textFill: hoverLabelModel.getTextColor(true),
  44618. // For merging hover style to normal style, do not use
  44619. // `hoverLabelModel.getFont()` here.
  44620. fontStyle: hoverLabelModel.getShallow('fontStyle'),
  44621. fontWeight: hoverLabelModel.getShallow('fontWeight'),
  44622. fontSize: hoverLabelModel.getShallow('fontSize'),
  44623. fontFamily: hoverLabelModel.getShallow('fontFamily')
  44624. };
  44625. }
  44626. else {
  44627. label.hoverStyle = {
  44628. text: null
  44629. };
  44630. }
  44631. label.ignore = !showLabel && !hoverShowLabel;
  44632. setHoverStyle(this);
  44633. };
  44634. lineProto.highlight = function () {
  44635. this.trigger('emphasis');
  44636. };
  44637. lineProto.downplay = function () {
  44638. this.trigger('normal');
  44639. };
  44640. lineProto.updateLayout = function (lineData, idx) {
  44641. this.setLinePoints(lineData.getItemLayout(idx));
  44642. };
  44643. lineProto.setLinePoints = function (points) {
  44644. var linePath = this.childOfName('line');
  44645. setLinePoints(linePath.shape, points);
  44646. linePath.dirty();
  44647. };
  44648. inherits(Line$1, Group);
  44649. /*
  44650. * Licensed to the Apache Software Foundation (ASF) under one
  44651. * or more contributor license agreements. See the NOTICE file
  44652. * distributed with this work for additional information
  44653. * regarding copyright ownership. The ASF licenses this file
  44654. * to you under the Apache License, Version 2.0 (the
  44655. * "License"); you may not use this file except in compliance
  44656. * with the License. You may obtain a copy of the License at
  44657. *
  44658. * http://www.apache.org/licenses/LICENSE-2.0
  44659. *
  44660. * Unless required by applicable law or agreed to in writing,
  44661. * software distributed under the License is distributed on an
  44662. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44663. * KIND, either express or implied. See the License for the
  44664. * specific language governing permissions and limitations
  44665. * under the License.
  44666. */
  44667. /**
  44668. * @module echarts/chart/helper/LineDraw
  44669. */
  44670. // import IncrementalDisplayable from 'zrender/src/graphic/IncrementalDisplayable';
  44671. /**
  44672. * @alias module:echarts/component/marker/LineDraw
  44673. * @constructor
  44674. */
  44675. function LineDraw(ctor) {
  44676. this._ctor = ctor || Line$1;
  44677. this.group = new Group();
  44678. }
  44679. var lineDrawProto = LineDraw.prototype;
  44680. lineDrawProto.isPersistent = function () {
  44681. return true;
  44682. };
  44683. /**
  44684. * @param {module:echarts/data/List} lineData
  44685. */
  44686. lineDrawProto.updateData = function (lineData) {
  44687. var lineDraw = this;
  44688. var group = lineDraw.group;
  44689. var oldLineData = lineDraw._lineData;
  44690. lineDraw._lineData = lineData;
  44691. // There is no oldLineData only when first rendering or switching from
  44692. // stream mode to normal mode, where previous elements should be removed.
  44693. if (!oldLineData) {
  44694. group.removeAll();
  44695. }
  44696. var seriesScope = makeSeriesScope$1(lineData);
  44697. lineData.diff(oldLineData)
  44698. .add(function (idx) {
  44699. doAdd(lineDraw, lineData, idx, seriesScope);
  44700. })
  44701. .update(function (newIdx, oldIdx) {
  44702. doUpdate(lineDraw, oldLineData, lineData, oldIdx, newIdx, seriesScope);
  44703. })
  44704. .remove(function (idx) {
  44705. group.remove(oldLineData.getItemGraphicEl(idx));
  44706. })
  44707. .execute();
  44708. };
  44709. function doAdd(lineDraw, lineData, idx, seriesScope) {
  44710. var itemLayout = lineData.getItemLayout(idx);
  44711. if (!lineNeedsDraw(itemLayout)) {
  44712. return;
  44713. }
  44714. var el = new lineDraw._ctor(lineData, idx, seriesScope);
  44715. lineData.setItemGraphicEl(idx, el);
  44716. lineDraw.group.add(el);
  44717. }
  44718. function doUpdate(lineDraw, oldLineData, newLineData, oldIdx, newIdx, seriesScope) {
  44719. var itemEl = oldLineData.getItemGraphicEl(oldIdx);
  44720. if (!lineNeedsDraw(newLineData.getItemLayout(newIdx))) {
  44721. lineDraw.group.remove(itemEl);
  44722. return;
  44723. }
  44724. if (!itemEl) {
  44725. itemEl = new lineDraw._ctor(newLineData, newIdx, seriesScope);
  44726. }
  44727. else {
  44728. itemEl.updateData(newLineData, newIdx, seriesScope);
  44729. }
  44730. newLineData.setItemGraphicEl(newIdx, itemEl);
  44731. lineDraw.group.add(itemEl);
  44732. }
  44733. lineDrawProto.updateLayout = function () {
  44734. var lineData = this._lineData;
  44735. // Do not support update layout in incremental mode.
  44736. if (!lineData) {
  44737. return;
  44738. }
  44739. lineData.eachItemGraphicEl(function (el, idx) {
  44740. el.updateLayout(lineData, idx);
  44741. }, this);
  44742. };
  44743. lineDrawProto.incrementalPrepareUpdate = function (lineData) {
  44744. this._seriesScope = makeSeriesScope$1(lineData);
  44745. this._lineData = null;
  44746. this.group.removeAll();
  44747. };
  44748. lineDrawProto.incrementalUpdate = function (taskParams, lineData) {
  44749. function updateIncrementalAndHover(el) {
  44750. if (!el.isGroup) {
  44751. el.incremental = el.useHoverLayer = true;
  44752. }
  44753. }
  44754. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  44755. var itemLayout = lineData.getItemLayout(idx);
  44756. if (lineNeedsDraw(itemLayout)) {
  44757. var el = new this._ctor(lineData, idx, this._seriesScope);
  44758. el.traverse(updateIncrementalAndHover);
  44759. this.group.add(el);
  44760. lineData.setItemGraphicEl(idx, el);
  44761. }
  44762. }
  44763. };
  44764. function makeSeriesScope$1(lineData) {
  44765. var hostModel = lineData.hostModel;
  44766. return {
  44767. lineStyle: hostModel.getModel('lineStyle').getLineStyle(),
  44768. hoverLineStyle: hostModel.getModel('emphasis.lineStyle').getLineStyle(),
  44769. labelModel: hostModel.getModel('label'),
  44770. hoverLabelModel: hostModel.getModel('emphasis.label')
  44771. };
  44772. }
  44773. lineDrawProto.remove = function () {
  44774. this._clearIncremental();
  44775. this._incremental = null;
  44776. this.group.removeAll();
  44777. };
  44778. lineDrawProto._clearIncremental = function () {
  44779. var incremental = this._incremental;
  44780. if (incremental) {
  44781. incremental.clearDisplaybles();
  44782. }
  44783. };
  44784. function isPointNaN(pt) {
  44785. return isNaN(pt[0]) || isNaN(pt[1]);
  44786. }
  44787. function lineNeedsDraw(pts) {
  44788. return !isPointNaN(pts[0]) && !isPointNaN(pts[1]);
  44789. }
  44790. /*
  44791. * Licensed to the Apache Software Foundation (ASF) under one
  44792. * or more contributor license agreements. See the NOTICE file
  44793. * distributed with this work for additional information
  44794. * regarding copyright ownership. The ASF licenses this file
  44795. * to you under the Apache License, Version 2.0 (the
  44796. * "License"); you may not use this file except in compliance
  44797. * with the License. You may obtain a copy of the License at
  44798. *
  44799. * http://www.apache.org/licenses/LICENSE-2.0
  44800. *
  44801. * Unless required by applicable law or agreed to in writing,
  44802. * software distributed under the License is distributed on an
  44803. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44804. * KIND, either express or implied. See the License for the
  44805. * specific language governing permissions and limitations
  44806. * under the License.
  44807. */
  44808. var v1 = [];
  44809. var v2 = [];
  44810. var v3 = [];
  44811. var quadraticAt$1 = quadraticAt;
  44812. var v2DistSquare = distSquare;
  44813. var mathAbs$1 = Math.abs;
  44814. function intersectCurveCircle(curvePoints, center, radius) {
  44815. var p0 = curvePoints[0];
  44816. var p1 = curvePoints[1];
  44817. var p2 = curvePoints[2];
  44818. var d = Infinity;
  44819. var t;
  44820. var radiusSquare = radius * radius;
  44821. var interval = 0.1;
  44822. for (var _t = 0.1; _t <= 0.9; _t += 0.1) {
  44823. v1[0] = quadraticAt$1(p0[0], p1[0], p2[0], _t);
  44824. v1[1] = quadraticAt$1(p0[1], p1[1], p2[1], _t);
  44825. var diff = mathAbs$1(v2DistSquare(v1, center) - radiusSquare);
  44826. if (diff < d) {
  44827. d = diff;
  44828. t = _t;
  44829. }
  44830. }
  44831. // Assume the segment is monotone,Find root through Bisection method
  44832. // At most 32 iteration
  44833. for (var i = 0; i < 32; i++) {
  44834. // var prev = t - interval;
  44835. var next = t + interval;
  44836. // v1[0] = quadraticAt(p0[0], p1[0], p2[0], prev);
  44837. // v1[1] = quadraticAt(p0[1], p1[1], p2[1], prev);
  44838. v2[0] = quadraticAt$1(p0[0], p1[0], p2[0], t);
  44839. v2[1] = quadraticAt$1(p0[1], p1[1], p2[1], t);
  44840. v3[0] = quadraticAt$1(p0[0], p1[0], p2[0], next);
  44841. v3[1] = quadraticAt$1(p0[1], p1[1], p2[1], next);
  44842. var diff = v2DistSquare(v2, center) - radiusSquare;
  44843. if (mathAbs$1(diff) < 1e-2) {
  44844. break;
  44845. }
  44846. // var prevDiff = v2DistSquare(v1, center) - radiusSquare;
  44847. var nextDiff = v2DistSquare(v3, center) - radiusSquare;
  44848. interval /= 2;
  44849. if (diff < 0) {
  44850. if (nextDiff >= 0) {
  44851. t = t + interval;
  44852. }
  44853. else {
  44854. t = t - interval;
  44855. }
  44856. }
  44857. else {
  44858. if (nextDiff >= 0) {
  44859. t = t - interval;
  44860. }
  44861. else {
  44862. t = t + interval;
  44863. }
  44864. }
  44865. }
  44866. return t;
  44867. }
  44868. // Adjust edge to avoid
  44869. var adjustEdge = function (graph, scale$$1) {
  44870. var tmp0 = [];
  44871. var quadraticSubdivide$$1 = quadraticSubdivide;
  44872. var pts = [[], [], []];
  44873. var pts2 = [[], []];
  44874. var v = [];
  44875. scale$$1 /= 2;
  44876. function getSymbolSize(node) {
  44877. var symbolSize = node.getVisual('symbolSize');
  44878. if (symbolSize instanceof Array) {
  44879. symbolSize = (symbolSize[0] + symbolSize[1]) / 2;
  44880. }
  44881. return symbolSize;
  44882. }
  44883. graph.eachEdge(function (edge, idx) {
  44884. var linePoints = edge.getLayout();
  44885. var fromSymbol = edge.getVisual('fromSymbol');
  44886. var toSymbol = edge.getVisual('toSymbol');
  44887. if (!linePoints.__original) {
  44888. linePoints.__original = [
  44889. clone$1(linePoints[0]),
  44890. clone$1(linePoints[1])
  44891. ];
  44892. if (linePoints[2]) {
  44893. linePoints.__original.push(clone$1(linePoints[2]));
  44894. }
  44895. }
  44896. var originalPoints = linePoints.__original;
  44897. // Quadratic curve
  44898. if (linePoints[2] != null) {
  44899. copy(pts[0], originalPoints[0]);
  44900. copy(pts[1], originalPoints[2]);
  44901. copy(pts[2], originalPoints[1]);
  44902. if (fromSymbol && fromSymbol != 'none') {
  44903. var symbolSize = getSymbolSize(edge.node1);
  44904. var t = intersectCurveCircle(pts, originalPoints[0], symbolSize * scale$$1);
  44905. // Subdivide and get the second
  44906. quadraticSubdivide$$1(pts[0][0], pts[1][0], pts[2][0], t, tmp0);
  44907. pts[0][0] = tmp0[3];
  44908. pts[1][0] = tmp0[4];
  44909. quadraticSubdivide$$1(pts[0][1], pts[1][1], pts[2][1], t, tmp0);
  44910. pts[0][1] = tmp0[3];
  44911. pts[1][1] = tmp0[4];
  44912. }
  44913. if (toSymbol && toSymbol != 'none') {
  44914. var symbolSize = getSymbolSize(edge.node2);
  44915. var t = intersectCurveCircle(pts, originalPoints[1], symbolSize * scale$$1);
  44916. // Subdivide and get the first
  44917. quadraticSubdivide$$1(pts[0][0], pts[1][0], pts[2][0], t, tmp0);
  44918. pts[1][0] = tmp0[1];
  44919. pts[2][0] = tmp0[2];
  44920. quadraticSubdivide$$1(pts[0][1], pts[1][1], pts[2][1], t, tmp0);
  44921. pts[1][1] = tmp0[1];
  44922. pts[2][1] = tmp0[2];
  44923. }
  44924. // Copy back to layout
  44925. copy(linePoints[0], pts[0]);
  44926. copy(linePoints[1], pts[2]);
  44927. copy(linePoints[2], pts[1]);
  44928. }
  44929. // Line
  44930. else {
  44931. copy(pts2[0], originalPoints[0]);
  44932. copy(pts2[1], originalPoints[1]);
  44933. sub(v, pts2[1], pts2[0]);
  44934. normalize(v, v);
  44935. if (fromSymbol && fromSymbol != 'none') {
  44936. var symbolSize = getSymbolSize(edge.node1);
  44937. scaleAndAdd(pts2[0], pts2[0], v, symbolSize * scale$$1);
  44938. }
  44939. if (toSymbol && toSymbol != 'none') {
  44940. var symbolSize = getSymbolSize(edge.node2);
  44941. scaleAndAdd(pts2[1], pts2[1], v, -symbolSize * scale$$1);
  44942. }
  44943. copy(linePoints[0], pts2[0]);
  44944. copy(linePoints[1], pts2[1]);
  44945. }
  44946. });
  44947. };
  44948. /*
  44949. * Licensed to the Apache Software Foundation (ASF) under one
  44950. * or more contributor license agreements. See the NOTICE file
  44951. * distributed with this work for additional information
  44952. * regarding copyright ownership. The ASF licenses this file
  44953. * to you under the Apache License, Version 2.0 (the
  44954. * "License"); you may not use this file except in compliance
  44955. * with the License. You may obtain a copy of the License at
  44956. *
  44957. * http://www.apache.org/licenses/LICENSE-2.0
  44958. *
  44959. * Unless required by applicable law or agreed to in writing,
  44960. * software distributed under the License is distributed on an
  44961. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44962. * KIND, either express or implied. See the License for the
  44963. * specific language governing permissions and limitations
  44964. * under the License.
  44965. */
  44966. var nodeOpacityPath = ['itemStyle', 'opacity'];
  44967. var lineOpacityPath = ['lineStyle', 'opacity'];
  44968. function getItemOpacity(item, opacityPath) {
  44969. return item.getVisual('opacity') || item.getModel().get(opacityPath);
  44970. }
  44971. function fadeOutItem(item, opacityPath, opacityRatio) {
  44972. var el = item.getGraphicEl();
  44973. var opacity = getItemOpacity(item, opacityPath);
  44974. if (opacityRatio != null) {
  44975. opacity == null && (opacity = 1);
  44976. opacity *= opacityRatio;
  44977. }
  44978. el.downplay && el.downplay();
  44979. el.traverse(function (child) {
  44980. if (child.type !== 'group') {
  44981. child.setStyle('opacity', opacity);
  44982. }
  44983. });
  44984. }
  44985. function fadeInItem(item, opacityPath) {
  44986. var opacity = getItemOpacity(item, opacityPath);
  44987. var el = item.getGraphicEl();
  44988. el.highlight && el.highlight();
  44989. el.traverse(function (child) {
  44990. if (child.type !== 'group') {
  44991. child.setStyle('opacity', opacity);
  44992. }
  44993. });
  44994. }
  44995. extendChartView({
  44996. type: 'graph',
  44997. init: function (ecModel, api) {
  44998. var symbolDraw = new SymbolDraw();
  44999. var lineDraw = new LineDraw();
  45000. var group = this.group;
  45001. this._controller = new RoamController(api.getZr());
  45002. this._controllerHost = {target: group};
  45003. group.add(symbolDraw.group);
  45004. group.add(lineDraw.group);
  45005. this._symbolDraw = symbolDraw;
  45006. this._lineDraw = lineDraw;
  45007. this._firstRender = true;
  45008. },
  45009. render: function (seriesModel, ecModel, api) {
  45010. var coordSys = seriesModel.coordinateSystem;
  45011. this._model = seriesModel;
  45012. this._nodeScaleRatio = seriesModel.get('nodeScaleRatio');
  45013. var symbolDraw = this._symbolDraw;
  45014. var lineDraw = this._lineDraw;
  45015. var group = this.group;
  45016. if (coordSys.type === 'view') {
  45017. var groupNewProp = {
  45018. position: coordSys.position,
  45019. scale: coordSys.scale
  45020. };
  45021. if (this._firstRender) {
  45022. group.attr(groupNewProp);
  45023. }
  45024. else {
  45025. updateProps(group, groupNewProp, seriesModel);
  45026. }
  45027. }
  45028. // Fix edge contact point with node
  45029. adjustEdge(seriesModel.getGraph(), this._getNodeGlobalScale(seriesModel));
  45030. var data = seriesModel.getData();
  45031. symbolDraw.updateData(data);
  45032. var edgeData = seriesModel.getEdgeData();
  45033. lineDraw.updateData(edgeData);
  45034. this._updateNodeAndLinkScale();
  45035. this._updateController(seriesModel, ecModel, api);
  45036. clearTimeout(this._layoutTimeout);
  45037. var forceLayout = seriesModel.forceLayout;
  45038. var layoutAnimation = seriesModel.get('force.layoutAnimation');
  45039. if (forceLayout) {
  45040. this._startForceLayoutIteration(forceLayout, layoutAnimation);
  45041. }
  45042. data.eachItemGraphicEl(function (el, idx) {
  45043. var itemModel = data.getItemModel(idx);
  45044. // Update draggable
  45045. el.off('drag').off('dragend');
  45046. var draggable = data.getItemModel(idx).get('draggable');
  45047. if (draggable) {
  45048. el.on('drag', function () {
  45049. if (forceLayout) {
  45050. forceLayout.warmUp();
  45051. !this._layouting
  45052. && this._startForceLayoutIteration(forceLayout, layoutAnimation);
  45053. forceLayout.setFixed(idx);
  45054. // Write position back to layout
  45055. data.setItemLayout(idx, el.position);
  45056. }
  45057. }, this).on('dragend', function () {
  45058. if (forceLayout) {
  45059. forceLayout.setUnfixed(idx);
  45060. }
  45061. }, this);
  45062. }
  45063. el.setDraggable(draggable && forceLayout);
  45064. el.off('mouseover', el.__focusNodeAdjacency);
  45065. el.off('mouseout', el.__unfocusNodeAdjacency);
  45066. if (itemModel.get('focusNodeAdjacency')) {
  45067. el.on('mouseover', el.__focusNodeAdjacency = function () {
  45068. api.dispatchAction({
  45069. type: 'focusNodeAdjacency',
  45070. seriesId: seriesModel.id,
  45071. dataIndex: el.dataIndex
  45072. });
  45073. });
  45074. el.on('mouseout', el.__unfocusNodeAdjacency = function () {
  45075. api.dispatchAction({
  45076. type: 'unfocusNodeAdjacency',
  45077. seriesId: seriesModel.id
  45078. });
  45079. });
  45080. }
  45081. }, this);
  45082. data.graph.eachEdge(function (edge) {
  45083. var el = edge.getGraphicEl();
  45084. el.off('mouseover', el.__focusNodeAdjacency);
  45085. el.off('mouseout', el.__unfocusNodeAdjacency);
  45086. if (edge.getModel().get('focusNodeAdjacency')) {
  45087. el.on('mouseover', el.__focusNodeAdjacency = function () {
  45088. api.dispatchAction({
  45089. type: 'focusNodeAdjacency',
  45090. seriesId: seriesModel.id,
  45091. edgeDataIndex: edge.dataIndex
  45092. });
  45093. });
  45094. el.on('mouseout', el.__unfocusNodeAdjacency = function () {
  45095. api.dispatchAction({
  45096. type: 'unfocusNodeAdjacency',
  45097. seriesId: seriesModel.id
  45098. });
  45099. });
  45100. }
  45101. });
  45102. var circularRotateLabel = seriesModel.get('layout') === 'circular'
  45103. && seriesModel.get('circular.rotateLabel');
  45104. var cx = data.getLayout('cx');
  45105. var cy = data.getLayout('cy');
  45106. data.eachItemGraphicEl(function (el, idx) {
  45107. var symbolPath = el.getSymbolPath();
  45108. if (circularRotateLabel) {
  45109. var pos = data.getItemLayout(idx);
  45110. var rad = Math.atan2(pos[1] - cy, pos[0] - cx);
  45111. if (rad < 0) {
  45112. rad = Math.PI * 2 + rad;
  45113. }
  45114. var isLeft = pos[0] < cx;
  45115. if (isLeft) {
  45116. rad = rad - Math.PI;
  45117. }
  45118. var textPosition = isLeft ? 'left' : 'right';
  45119. symbolPath.setStyle({
  45120. textRotation: -rad,
  45121. textPosition: textPosition,
  45122. textOrigin: 'center'
  45123. });
  45124. symbolPath.hoverStyle && (symbolPath.hoverStyle.textPosition = textPosition);
  45125. }
  45126. else {
  45127. symbolPath.setStyle({
  45128. textRotation: 0
  45129. });
  45130. }
  45131. });
  45132. this._firstRender = false;
  45133. },
  45134. dispose: function () {
  45135. this._controller && this._controller.dispose();
  45136. this._controllerHost = {};
  45137. },
  45138. focusNodeAdjacency: function (seriesModel, ecModel, api, payload) {
  45139. var data = this._model.getData();
  45140. var graph = data.graph;
  45141. var dataIndex = payload.dataIndex;
  45142. var edgeDataIndex = payload.edgeDataIndex;
  45143. var node = graph.getNodeByIndex(dataIndex);
  45144. var edge = graph.getEdgeByIndex(edgeDataIndex);
  45145. if (!node && !edge) {
  45146. return;
  45147. }
  45148. graph.eachNode(function (node) {
  45149. fadeOutItem(node, nodeOpacityPath, 0.1);
  45150. });
  45151. graph.eachEdge(function (edge) {
  45152. fadeOutItem(edge, lineOpacityPath, 0.1);
  45153. });
  45154. if (node) {
  45155. fadeInItem(node, nodeOpacityPath);
  45156. each$1(node.edges, function (adjacentEdge) {
  45157. if (adjacentEdge.dataIndex < 0) {
  45158. return;
  45159. }
  45160. fadeInItem(adjacentEdge, lineOpacityPath);
  45161. fadeInItem(adjacentEdge.node1, nodeOpacityPath);
  45162. fadeInItem(adjacentEdge.node2, nodeOpacityPath);
  45163. });
  45164. }
  45165. if (edge) {
  45166. fadeInItem(edge, lineOpacityPath);
  45167. fadeInItem(edge.node1, nodeOpacityPath);
  45168. fadeInItem(edge.node2, nodeOpacityPath);
  45169. }
  45170. },
  45171. unfocusNodeAdjacency: function (seriesModel, ecModel, api, payload) {
  45172. var graph = this._model.getData().graph;
  45173. graph.eachNode(function (node) {
  45174. fadeOutItem(node, nodeOpacityPath);
  45175. });
  45176. graph.eachEdge(function (edge) {
  45177. fadeOutItem(edge, lineOpacityPath);
  45178. });
  45179. },
  45180. _startForceLayoutIteration: function (forceLayout, layoutAnimation) {
  45181. var self = this;
  45182. (function step() {
  45183. forceLayout.step(function (stopped) {
  45184. self.updateLayout(self._model);
  45185. (self._layouting = !stopped) && (
  45186. layoutAnimation
  45187. ? (self._layoutTimeout = setTimeout(step, 16))
  45188. : step()
  45189. );
  45190. });
  45191. })();
  45192. },
  45193. _updateController: function (seriesModel, ecModel, api) {
  45194. var controller = this._controller;
  45195. var controllerHost = this._controllerHost;
  45196. var group = this.group;
  45197. controller.setPointerChecker(function (e, x, y) {
  45198. var rect = group.getBoundingRect();
  45199. rect.applyTransform(group.transform);
  45200. return rect.contain(x, y)
  45201. && !onIrrelevantElement(e, api, seriesModel);
  45202. });
  45203. if (seriesModel.coordinateSystem.type !== 'view') {
  45204. controller.disable();
  45205. return;
  45206. }
  45207. controller.enable(seriesModel.get('roam'));
  45208. controllerHost.zoomLimit = seriesModel.get('scaleLimit');
  45209. controllerHost.zoom = seriesModel.coordinateSystem.getZoom();
  45210. controller
  45211. .off('pan')
  45212. .off('zoom')
  45213. .on('pan', function (dx, dy) {
  45214. updateViewOnPan(controllerHost, dx, dy);
  45215. api.dispatchAction({
  45216. seriesId: seriesModel.id,
  45217. type: 'graphRoam',
  45218. dx: dx,
  45219. dy: dy
  45220. });
  45221. })
  45222. .on('zoom', function (zoom, mouseX, mouseY) {
  45223. updateViewOnZoom(controllerHost, zoom, mouseX, mouseY);
  45224. api.dispatchAction({
  45225. seriesId: seriesModel.id,
  45226. type: 'graphRoam',
  45227. zoom: zoom,
  45228. originX: mouseX,
  45229. originY: mouseY
  45230. });
  45231. this._updateNodeAndLinkScale();
  45232. adjustEdge(seriesModel.getGraph(), this._getNodeGlobalScale(seriesModel));
  45233. this._lineDraw.updateLayout();
  45234. }, this);
  45235. },
  45236. _updateNodeAndLinkScale: function () {
  45237. var seriesModel = this._model;
  45238. var data = seriesModel.getData();
  45239. var nodeScale = this._getNodeGlobalScale(seriesModel);
  45240. var invScale = [nodeScale, nodeScale];
  45241. data.eachItemGraphicEl(function (el, idx) {
  45242. el.attr('scale', invScale);
  45243. });
  45244. },
  45245. _getNodeGlobalScale: function (seriesModel) {
  45246. var coordSys = seriesModel.coordinateSystem;
  45247. if (coordSys.type !== 'view') {
  45248. return 1;
  45249. }
  45250. var nodeScaleRatio = this._nodeScaleRatio;
  45251. var groupScale = coordSys.scale;
  45252. var groupZoom = (groupScale && groupScale[0]) || 1;
  45253. // Scale node when zoom changes
  45254. var roamZoom = coordSys.getZoom();
  45255. var nodeScale = (roamZoom - 1) * nodeScaleRatio + 1;
  45256. return nodeScale / groupZoom;
  45257. },
  45258. updateLayout: function (seriesModel) {
  45259. adjustEdge(seriesModel.getGraph(), this._getNodeGlobalScale(seriesModel));
  45260. this._symbolDraw.updateLayout();
  45261. this._lineDraw.updateLayout();
  45262. },
  45263. remove: function (ecModel, api) {
  45264. this._symbolDraw && this._symbolDraw.remove();
  45265. this._lineDraw && this._lineDraw.remove();
  45266. }
  45267. });
  45268. /*
  45269. * Licensed to the Apache Software Foundation (ASF) under one
  45270. * or more contributor license agreements. See the NOTICE file
  45271. * distributed with this work for additional information
  45272. * regarding copyright ownership. The ASF licenses this file
  45273. * to you under the Apache License, Version 2.0 (the
  45274. * "License"); you may not use this file except in compliance
  45275. * with the License. You may obtain a copy of the License at
  45276. *
  45277. * http://www.apache.org/licenses/LICENSE-2.0
  45278. *
  45279. * Unless required by applicable law or agreed to in writing,
  45280. * software distributed under the License is distributed on an
  45281. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45282. * KIND, either express or implied. See the License for the
  45283. * specific language governing permissions and limitations
  45284. * under the License.
  45285. */
  45286. var actionInfo = {
  45287. type: 'graphRoam',
  45288. event: 'graphRoam',
  45289. update: 'none'
  45290. };
  45291. /**
  45292. * @payload
  45293. * @property {string} name Series name
  45294. * @property {number} [dx]
  45295. * @property {number} [dy]
  45296. * @property {number} [zoom]
  45297. * @property {number} [originX]
  45298. * @property {number} [originY]
  45299. */
  45300. registerAction(actionInfo, function (payload, ecModel) {
  45301. ecModel.eachComponent({mainType: 'series', query: payload}, function (seriesModel) {
  45302. var coordSys = seriesModel.coordinateSystem;
  45303. var res = updateCenterAndZoom(coordSys, payload);
  45304. seriesModel.setCenter
  45305. && seriesModel.setCenter(res.center);
  45306. seriesModel.setZoom
  45307. && seriesModel.setZoom(res.zoom);
  45308. });
  45309. });
  45310. /**
  45311. * @payload
  45312. * @property {number} [seriesIndex]
  45313. * @property {string} [seriesId]
  45314. * @property {string} [seriesName]
  45315. * @property {number} [dataIndex]
  45316. */
  45317. registerAction({
  45318. type: 'focusNodeAdjacency',
  45319. event: 'focusNodeAdjacency',
  45320. update: 'series.graph:focusNodeAdjacency'
  45321. }, function () {});
  45322. /**
  45323. * @payload
  45324. * @property {number} [seriesIndex]
  45325. * @property {string} [seriesId]
  45326. * @property {string} [seriesName]
  45327. */
  45328. registerAction({
  45329. type: 'unfocusNodeAdjacency',
  45330. event: 'unfocusNodeAdjacency',
  45331. update: 'series.graph:unfocusNodeAdjacency'
  45332. }, function () {});
  45333. /*
  45334. * Licensed to the Apache Software Foundation (ASF) under one
  45335. * or more contributor license agreements. See the NOTICE file
  45336. * distributed with this work for additional information
  45337. * regarding copyright ownership. The ASF licenses this file
  45338. * to you under the Apache License, Version 2.0 (the
  45339. * "License"); you may not use this file except in compliance
  45340. * with the License. You may obtain a copy of the License at
  45341. *
  45342. * http://www.apache.org/licenses/LICENSE-2.0
  45343. *
  45344. * Unless required by applicable law or agreed to in writing,
  45345. * software distributed under the License is distributed on an
  45346. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45347. * KIND, either express or implied. See the License for the
  45348. * specific language governing permissions and limitations
  45349. * under the License.
  45350. */
  45351. var categoryFilter = function (ecModel) {
  45352. var legendModels = ecModel.findComponents({
  45353. mainType: 'legend'
  45354. });
  45355. if (!legendModels || !legendModels.length) {
  45356. return;
  45357. }
  45358. ecModel.eachSeriesByType('graph', function (graphSeries) {
  45359. var categoriesData = graphSeries.getCategoriesData();
  45360. var graph = graphSeries.getGraph();
  45361. var data = graph.data;
  45362. var categoryNames = categoriesData.mapArray(categoriesData.getName);
  45363. data.filterSelf(function (idx) {
  45364. var model = data.getItemModel(idx);
  45365. var category = model.getShallow('category');
  45366. if (category != null) {
  45367. if (typeof category === 'number') {
  45368. category = categoryNames[category];
  45369. }
  45370. // If in any legend component the status is not selected.
  45371. for (var i = 0; i < legendModels.length; i++) {
  45372. if (!legendModels[i].isSelected(category)) {
  45373. return false;
  45374. }
  45375. }
  45376. }
  45377. return true;
  45378. });
  45379. }, this);
  45380. };
  45381. /*
  45382. * Licensed to the Apache Software Foundation (ASF) under one
  45383. * or more contributor license agreements. See the NOTICE file
  45384. * distributed with this work for additional information
  45385. * regarding copyright ownership. The ASF licenses this file
  45386. * to you under the Apache License, Version 2.0 (the
  45387. * "License"); you may not use this file except in compliance
  45388. * with the License. You may obtain a copy of the License at
  45389. *
  45390. * http://www.apache.org/licenses/LICENSE-2.0
  45391. *
  45392. * Unless required by applicable law or agreed to in writing,
  45393. * software distributed under the License is distributed on an
  45394. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45395. * KIND, either express or implied. See the License for the
  45396. * specific language governing permissions and limitations
  45397. * under the License.
  45398. */
  45399. var categoryVisual = function (ecModel) {
  45400. var paletteScope = {};
  45401. ecModel.eachSeriesByType('graph', function (seriesModel) {
  45402. var categoriesData = seriesModel.getCategoriesData();
  45403. var data = seriesModel.getData();
  45404. var categoryNameIdxMap = {};
  45405. categoriesData.each(function (idx) {
  45406. var name = categoriesData.getName(idx);
  45407. // Add prefix to avoid conflict with Object.prototype.
  45408. categoryNameIdxMap['ec-' + name] = idx;
  45409. var itemModel = categoriesData.getItemModel(idx);
  45410. var color = itemModel.get('itemStyle.color')
  45411. || seriesModel.getColorFromPalette(name, paletteScope);
  45412. categoriesData.setItemVisual(idx, 'color', color);
  45413. });
  45414. // Assign category color to visual
  45415. if (categoriesData.count()) {
  45416. data.each(function (idx) {
  45417. var model = data.getItemModel(idx);
  45418. var category = model.getShallow('category');
  45419. if (category != null) {
  45420. if (typeof category === 'string') {
  45421. category = categoryNameIdxMap['ec-' + category];
  45422. }
  45423. if (!data.getItemVisual(idx, 'color', true)) {
  45424. data.setItemVisual(
  45425. idx, 'color',
  45426. categoriesData.getItemVisual(category, 'color')
  45427. );
  45428. }
  45429. }
  45430. });
  45431. }
  45432. });
  45433. };
  45434. /*
  45435. * Licensed to the Apache Software Foundation (ASF) under one
  45436. * or more contributor license agreements. See the NOTICE file
  45437. * distributed with this work for additional information
  45438. * regarding copyright ownership. The ASF licenses this file
  45439. * to you under the Apache License, Version 2.0 (the
  45440. * "License"); you may not use this file except in compliance
  45441. * with the License. You may obtain a copy of the License at
  45442. *
  45443. * http://www.apache.org/licenses/LICENSE-2.0
  45444. *
  45445. * Unless required by applicable law or agreed to in writing,
  45446. * software distributed under the License is distributed on an
  45447. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45448. * KIND, either express or implied. See the License for the
  45449. * specific language governing permissions and limitations
  45450. * under the License.
  45451. */
  45452. function normalize$1(a) {
  45453. if (!(a instanceof Array)) {
  45454. a = [a, a];
  45455. }
  45456. return a;
  45457. }
  45458. var edgeVisual = function (ecModel) {
  45459. ecModel.eachSeriesByType('graph', function (seriesModel) {
  45460. var graph = seriesModel.getGraph();
  45461. var edgeData = seriesModel.getEdgeData();
  45462. var symbolType = normalize$1(seriesModel.get('edgeSymbol'));
  45463. var symbolSize = normalize$1(seriesModel.get('edgeSymbolSize'));
  45464. var colorQuery = 'lineStyle.color'.split('.');
  45465. var opacityQuery = 'lineStyle.opacity'.split('.');
  45466. edgeData.setVisual('fromSymbol', symbolType && symbolType[0]);
  45467. edgeData.setVisual('toSymbol', symbolType && symbolType[1]);
  45468. edgeData.setVisual('fromSymbolSize', symbolSize && symbolSize[0]);
  45469. edgeData.setVisual('toSymbolSize', symbolSize && symbolSize[1]);
  45470. edgeData.setVisual('color', seriesModel.get(colorQuery));
  45471. edgeData.setVisual('opacity', seriesModel.get(opacityQuery));
  45472. edgeData.each(function (idx) {
  45473. var itemModel = edgeData.getItemModel(idx);
  45474. var edge = graph.getEdgeByIndex(idx);
  45475. var symbolType = normalize$1(itemModel.getShallow('symbol', true));
  45476. var symbolSize = normalize$1(itemModel.getShallow('symbolSize', true));
  45477. // Edge visual must after node visual
  45478. var color = itemModel.get(colorQuery);
  45479. var opacity = itemModel.get(opacityQuery);
  45480. switch (color) {
  45481. case 'source':
  45482. color = edge.node1.getVisual('color');
  45483. break;
  45484. case 'target':
  45485. color = edge.node2.getVisual('color');
  45486. break;
  45487. }
  45488. symbolType[0] && edge.setVisual('fromSymbol', symbolType[0]);
  45489. symbolType[1] && edge.setVisual('toSymbol', symbolType[1]);
  45490. symbolSize[0] && edge.setVisual('fromSymbolSize', symbolSize[0]);
  45491. symbolSize[1] && edge.setVisual('toSymbolSize', symbolSize[1]);
  45492. edge.setVisual('color', color);
  45493. edge.setVisual('opacity', opacity);
  45494. });
  45495. });
  45496. };
  45497. /*
  45498. * Licensed to the Apache Software Foundation (ASF) under one
  45499. * or more contributor license agreements. See the NOTICE file
  45500. * distributed with this work for additional information
  45501. * regarding copyright ownership. The ASF licenses this file
  45502. * to you under the Apache License, Version 2.0 (the
  45503. * "License"); you may not use this file except in compliance
  45504. * with the License. You may obtain a copy of the License at
  45505. *
  45506. * http://www.apache.org/licenses/LICENSE-2.0
  45507. *
  45508. * Unless required by applicable law or agreed to in writing,
  45509. * software distributed under the License is distributed on an
  45510. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45511. * KIND, either express or implied. See the License for the
  45512. * specific language governing permissions and limitations
  45513. * under the License.
  45514. */
  45515. function simpleLayout$1(seriesModel) {
  45516. var coordSys = seriesModel.coordinateSystem;
  45517. if (coordSys && coordSys.type !== 'view') {
  45518. return;
  45519. }
  45520. var graph = seriesModel.getGraph();
  45521. graph.eachNode(function (node) {
  45522. var model = node.getModel();
  45523. node.setLayout([+model.get('x'), +model.get('y')]);
  45524. });
  45525. simpleLayoutEdge(graph);
  45526. }
  45527. function simpleLayoutEdge(graph) {
  45528. graph.eachEdge(function (edge) {
  45529. var curveness = edge.getModel().get('lineStyle.curveness') || 0;
  45530. var p1 = clone$1(edge.node1.getLayout());
  45531. var p2 = clone$1(edge.node2.getLayout());
  45532. var points = [p1, p2];
  45533. if (+curveness) {
  45534. points.push([
  45535. (p1[0] + p2[0]) / 2 - (p1[1] - p2[1]) * curveness,
  45536. (p1[1] + p2[1]) / 2 - (p2[0] - p1[0]) * curveness
  45537. ]);
  45538. }
  45539. edge.setLayout(points);
  45540. });
  45541. }
  45542. /*
  45543. * Licensed to the Apache Software Foundation (ASF) under one
  45544. * or more contributor license agreements. See the NOTICE file
  45545. * distributed with this work for additional information
  45546. * regarding copyright ownership. The ASF licenses this file
  45547. * to you under the Apache License, Version 2.0 (the
  45548. * "License"); you may not use this file except in compliance
  45549. * with the License. You may obtain a copy of the License at
  45550. *
  45551. * http://www.apache.org/licenses/LICENSE-2.0
  45552. *
  45553. * Unless required by applicable law or agreed to in writing,
  45554. * software distributed under the License is distributed on an
  45555. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45556. * KIND, either express or implied. See the License for the
  45557. * specific language governing permissions and limitations
  45558. * under the License.
  45559. */
  45560. var simpleLayout = function (ecModel, api) {
  45561. ecModel.eachSeriesByType('graph', function (seriesModel) {
  45562. var layout = seriesModel.get('layout');
  45563. var coordSys = seriesModel.coordinateSystem;
  45564. if (coordSys && coordSys.type !== 'view') {
  45565. var data = seriesModel.getData();
  45566. var dimensions = [];
  45567. each$1(coordSys.dimensions, function (coordDim) {
  45568. dimensions = dimensions.concat(data.mapDimension(coordDim, true));
  45569. });
  45570. for (var dataIndex = 0; dataIndex < data.count(); dataIndex++) {
  45571. var value = [];
  45572. var hasValue = false;
  45573. for (var i = 0; i < dimensions.length; i++) {
  45574. var val = data.get(dimensions[i], dataIndex);
  45575. if (!isNaN(val)) {
  45576. hasValue = true;
  45577. }
  45578. value.push(val);
  45579. }
  45580. if (hasValue) {
  45581. data.setItemLayout(dataIndex, coordSys.dataToPoint(value));
  45582. }
  45583. else {
  45584. // Also {Array.<number>}, not undefined to avoid if...else... statement
  45585. data.setItemLayout(dataIndex, [NaN, NaN]);
  45586. }
  45587. }
  45588. simpleLayoutEdge(data.graph);
  45589. }
  45590. else if (!layout || layout === 'none') {
  45591. simpleLayout$1(seriesModel);
  45592. }
  45593. });
  45594. };
  45595. /*
  45596. * Licensed to the Apache Software Foundation (ASF) under one
  45597. * or more contributor license agreements. See the NOTICE file
  45598. * distributed with this work for additional information
  45599. * regarding copyright ownership. The ASF licenses this file
  45600. * to you under the Apache License, Version 2.0 (the
  45601. * "License"); you may not use this file except in compliance
  45602. * with the License. You may obtain a copy of the License at
  45603. *
  45604. * http://www.apache.org/licenses/LICENSE-2.0
  45605. *
  45606. * Unless required by applicable law or agreed to in writing,
  45607. * software distributed under the License is distributed on an
  45608. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45609. * KIND, either express or implied. See the License for the
  45610. * specific language governing permissions and limitations
  45611. * under the License.
  45612. */
  45613. function circularLayout$1(seriesModel) {
  45614. var coordSys = seriesModel.coordinateSystem;
  45615. if (coordSys && coordSys.type !== 'view') {
  45616. return;
  45617. }
  45618. var rect = coordSys.getBoundingRect();
  45619. var nodeData = seriesModel.getData();
  45620. var graph = nodeData.graph;
  45621. var angle = 0;
  45622. var sum = nodeData.getSum('value');
  45623. var unitAngle = Math.PI * 2 / (sum || nodeData.count());
  45624. var cx = rect.width / 2 + rect.x;
  45625. var cy = rect.height / 2 + rect.y;
  45626. var r = Math.min(rect.width, rect.height) / 2;
  45627. graph.eachNode(function (node) {
  45628. var value = node.getValue('value');
  45629. angle += unitAngle * (sum ? value : 1) / 2;
  45630. node.setLayout([
  45631. r * Math.cos(angle) + cx,
  45632. r * Math.sin(angle) + cy
  45633. ]);
  45634. angle += unitAngle * (sum ? value : 1) / 2;
  45635. });
  45636. nodeData.setLayout({
  45637. cx: cx,
  45638. cy: cy
  45639. });
  45640. graph.eachEdge(function (edge) {
  45641. var curveness = edge.getModel().get('lineStyle.curveness') || 0;
  45642. var p1 = clone$1(edge.node1.getLayout());
  45643. var p2 = clone$1(edge.node2.getLayout());
  45644. var cp1;
  45645. var x12 = (p1[0] + p2[0]) / 2;
  45646. var y12 = (p1[1] + p2[1]) / 2;
  45647. if (+curveness) {
  45648. curveness *= 3;
  45649. cp1 = [
  45650. cx * curveness + x12 * (1 - curveness),
  45651. cy * curveness + y12 * (1 - curveness)
  45652. ];
  45653. }
  45654. edge.setLayout([p1, p2, cp1]);
  45655. });
  45656. }
  45657. /*
  45658. * Licensed to the Apache Software Foundation (ASF) under one
  45659. * or more contributor license agreements. See the NOTICE file
  45660. * distributed with this work for additional information
  45661. * regarding copyright ownership. The ASF licenses this file
  45662. * to you under the Apache License, Version 2.0 (the
  45663. * "License"); you may not use this file except in compliance
  45664. * with the License. You may obtain a copy of the License at
  45665. *
  45666. * http://www.apache.org/licenses/LICENSE-2.0
  45667. *
  45668. * Unless required by applicable law or agreed to in writing,
  45669. * software distributed under the License is distributed on an
  45670. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45671. * KIND, either express or implied. See the License for the
  45672. * specific language governing permissions and limitations
  45673. * under the License.
  45674. */
  45675. var circularLayout = function (ecModel) {
  45676. ecModel.eachSeriesByType('graph', function (seriesModel) {
  45677. if (seriesModel.get('layout') === 'circular') {
  45678. circularLayout$1(seriesModel);
  45679. }
  45680. });
  45681. };
  45682. /*
  45683. * Licensed to the Apache Software Foundation (ASF) under one
  45684. * or more contributor license agreements. See the NOTICE file
  45685. * distributed with this work for additional information
  45686. * regarding copyright ownership. The ASF licenses this file
  45687. * to you under the Apache License, Version 2.0 (the
  45688. * "License"); you may not use this file except in compliance
  45689. * with the License. You may obtain a copy of the License at
  45690. *
  45691. * http://www.apache.org/licenses/LICENSE-2.0
  45692. *
  45693. * Unless required by applicable law or agreed to in writing,
  45694. * software distributed under the License is distributed on an
  45695. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45696. * KIND, either express or implied. See the License for the
  45697. * specific language governing permissions and limitations
  45698. * under the License.
  45699. */
  45700. var scaleAndAdd$2 = scaleAndAdd;
  45701. // function adjacentNode(n, e) {
  45702. // return e.n1 === n ? e.n2 : e.n1;
  45703. // }
  45704. function forceLayout$1(nodes, edges, opts) {
  45705. var rect = opts.rect;
  45706. var width = rect.width;
  45707. var height = rect.height;
  45708. var center = [rect.x + width / 2, rect.y + height / 2];
  45709. // var scale = opts.scale || 1;
  45710. var gravity = opts.gravity == null ? 0.1 : opts.gravity;
  45711. // for (var i = 0; i < edges.length; i++) {
  45712. // var e = edges[i];
  45713. // var n1 = e.n1;
  45714. // var n2 = e.n2;
  45715. // n1.edges = n1.edges || [];
  45716. // n2.edges = n2.edges || [];
  45717. // n1.edges.push(e);
  45718. // n2.edges.push(e);
  45719. // }
  45720. // Init position
  45721. for (var i = 0; i < nodes.length; i++) {
  45722. var n = nodes[i];
  45723. if (!n.p) {
  45724. // Use the position from first adjecent node with defined position
  45725. // Or use a random position
  45726. // From d3
  45727. // if (n.edges) {
  45728. // var j = -1;
  45729. // while (++j < n.edges.length) {
  45730. // var e = n.edges[j];
  45731. // var other = adjacentNode(n, e);
  45732. // if (other.p) {
  45733. // n.p = vec2.clone(other.p);
  45734. // break;
  45735. // }
  45736. // }
  45737. // }
  45738. // if (!n.p) {
  45739. n.p = create(
  45740. width * (Math.random() - 0.5) + center[0],
  45741. height * (Math.random() - 0.5) + center[1]
  45742. );
  45743. // }
  45744. }
  45745. n.pp = clone$1(n.p);
  45746. n.edges = null;
  45747. }
  45748. // Formula in 'Graph Drawing by Force-directed Placement'
  45749. // var k = scale * Math.sqrt(width * height / nodes.length);
  45750. // var k2 = k * k;
  45751. var friction = 0.6;
  45752. return {
  45753. warmUp: function () {
  45754. friction = 0.5;
  45755. },
  45756. setFixed: function (idx) {
  45757. nodes[idx].fixed = true;
  45758. },
  45759. setUnfixed: function (idx) {
  45760. nodes[idx].fixed = false;
  45761. },
  45762. step: function (cb) {
  45763. var v12 = [];
  45764. var nLen = nodes.length;
  45765. for (var i = 0; i < edges.length; i++) {
  45766. var e = edges[i];
  45767. var n1 = e.n1;
  45768. var n2 = e.n2;
  45769. sub(v12, n2.p, n1.p);
  45770. var d = len(v12) - e.d;
  45771. var w = n2.w / (n1.w + n2.w);
  45772. if (isNaN(w)) {
  45773. w = 0;
  45774. }
  45775. normalize(v12, v12);
  45776. !n1.fixed && scaleAndAdd$2(n1.p, n1.p, v12, w * d * friction);
  45777. !n2.fixed && scaleAndAdd$2(n2.p, n2.p, v12, -(1 - w) * d * friction);
  45778. }
  45779. // Gravity
  45780. for (var i = 0; i < nLen; i++) {
  45781. var n = nodes[i];
  45782. if (!n.fixed) {
  45783. sub(v12, center, n.p);
  45784. // var d = vec2.len(v12);
  45785. // vec2.scale(v12, v12, 1 / d);
  45786. // var gravityFactor = gravity;
  45787. scaleAndAdd$2(n.p, n.p, v12, gravity * friction);
  45788. }
  45789. }
  45790. // Repulsive
  45791. // PENDING
  45792. for (var i = 0; i < nLen; i++) {
  45793. var n1 = nodes[i];
  45794. for (var j = i + 1; j < nLen; j++) {
  45795. var n2 = nodes[j];
  45796. sub(v12, n2.p, n1.p);
  45797. var d = len(v12);
  45798. if (d === 0) {
  45799. // Random repulse
  45800. set(v12, Math.random() - 0.5, Math.random() - 0.5);
  45801. d = 1;
  45802. }
  45803. var repFact = (n1.rep + n2.rep) / d / d;
  45804. !n1.fixed && scaleAndAdd$2(n1.pp, n1.pp, v12, repFact);
  45805. !n2.fixed && scaleAndAdd$2(n2.pp, n2.pp, v12, -repFact);
  45806. }
  45807. }
  45808. var v = [];
  45809. for (var i = 0; i < nLen; i++) {
  45810. var n = nodes[i];
  45811. if (!n.fixed) {
  45812. sub(v, n.p, n.pp);
  45813. scaleAndAdd$2(n.p, n.p, v, friction);
  45814. copy(n.pp, n.p);
  45815. }
  45816. }
  45817. friction = friction * 0.992;
  45818. cb && cb(nodes, edges, friction < 0.01);
  45819. }
  45820. };
  45821. }
  45822. /*
  45823. * Licensed to the Apache Software Foundation (ASF) under one
  45824. * or more contributor license agreements. See the NOTICE file
  45825. * distributed with this work for additional information
  45826. * regarding copyright ownership. The ASF licenses this file
  45827. * to you under the Apache License, Version 2.0 (the
  45828. * "License"); you may not use this file except in compliance
  45829. * with the License. You may obtain a copy of the License at
  45830. *
  45831. * http://www.apache.org/licenses/LICENSE-2.0
  45832. *
  45833. * Unless required by applicable law or agreed to in writing,
  45834. * software distributed under the License is distributed on an
  45835. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45836. * KIND, either express or implied. See the License for the
  45837. * specific language governing permissions and limitations
  45838. * under the License.
  45839. */
  45840. var forceLayout = function (ecModel) {
  45841. ecModel.eachSeriesByType('graph', function (graphSeries) {
  45842. var coordSys = graphSeries.coordinateSystem;
  45843. if (coordSys && coordSys.type !== 'view') {
  45844. return;
  45845. }
  45846. if (graphSeries.get('layout') === 'force') {
  45847. var preservedPoints = graphSeries.preservedPoints || {};
  45848. var graph = graphSeries.getGraph();
  45849. var nodeData = graph.data;
  45850. var edgeData = graph.edgeData;
  45851. var forceModel = graphSeries.getModel('force');
  45852. var initLayout = forceModel.get('initLayout');
  45853. if (graphSeries.preservedPoints) {
  45854. nodeData.each(function (idx) {
  45855. var id = nodeData.getId(idx);
  45856. nodeData.setItemLayout(idx, preservedPoints[id] || [NaN, NaN]);
  45857. });
  45858. }
  45859. else if (!initLayout || initLayout === 'none') {
  45860. simpleLayout$1(graphSeries);
  45861. }
  45862. else if (initLayout === 'circular') {
  45863. circularLayout$1(graphSeries);
  45864. }
  45865. var nodeDataExtent = nodeData.getDataExtent('value');
  45866. var edgeDataExtent = edgeData.getDataExtent('value');
  45867. // var edgeDataExtent = edgeData.getDataExtent('value');
  45868. var repulsion = forceModel.get('repulsion');
  45869. var edgeLength = forceModel.get('edgeLength');
  45870. if (!isArray(repulsion)) {
  45871. repulsion = [repulsion, repulsion];
  45872. }
  45873. if (!isArray(edgeLength)) {
  45874. edgeLength = [edgeLength, edgeLength];
  45875. }
  45876. // Larger value has smaller length
  45877. edgeLength = [edgeLength[1], edgeLength[0]];
  45878. var nodes = nodeData.mapArray('value', function (value, idx) {
  45879. var point = nodeData.getItemLayout(idx);
  45880. var rep = linearMap(value, nodeDataExtent, repulsion);
  45881. if (isNaN(rep)) {
  45882. rep = (repulsion[0] + repulsion[1]) / 2;
  45883. }
  45884. return {
  45885. w: rep,
  45886. rep: rep,
  45887. fixed: nodeData.getItemModel(idx).get('fixed'),
  45888. p: (!point || isNaN(point[0]) || isNaN(point[1])) ? null : point
  45889. };
  45890. });
  45891. var edges = edgeData.mapArray('value', function (value, idx) {
  45892. var edge = graph.getEdgeByIndex(idx);
  45893. var d = linearMap(value, edgeDataExtent, edgeLength);
  45894. if (isNaN(d)) {
  45895. d = (edgeLength[0] + edgeLength[1]) / 2;
  45896. }
  45897. return {
  45898. n1: nodes[edge.node1.dataIndex],
  45899. n2: nodes[edge.node2.dataIndex],
  45900. d: d,
  45901. curveness: edge.getModel().get('lineStyle.curveness') || 0
  45902. };
  45903. });
  45904. var coordSys = graphSeries.coordinateSystem;
  45905. var rect = coordSys.getBoundingRect();
  45906. var forceInstance = forceLayout$1(nodes, edges, {
  45907. rect: rect,
  45908. gravity: forceModel.get('gravity')
  45909. });
  45910. var oldStep = forceInstance.step;
  45911. forceInstance.step = function (cb) {
  45912. for (var i = 0, l = nodes.length; i < l; i++) {
  45913. if (nodes[i].fixed) {
  45914. // Write back to layout instance
  45915. copy(nodes[i].p, graph.getNodeByIndex(i).getLayout());
  45916. }
  45917. }
  45918. oldStep(function (nodes, edges, stopped) {
  45919. for (var i = 0, l = nodes.length; i < l; i++) {
  45920. if (!nodes[i].fixed) {
  45921. graph.getNodeByIndex(i).setLayout(nodes[i].p);
  45922. }
  45923. preservedPoints[nodeData.getId(i)] = nodes[i].p;
  45924. }
  45925. for (var i = 0, l = edges.length; i < l; i++) {
  45926. var e = edges[i];
  45927. var edge = graph.getEdgeByIndex(i);
  45928. var p1 = e.n1.p;
  45929. var p2 = e.n2.p;
  45930. var points = edge.getLayout();
  45931. points = points ? points.slice() : [];
  45932. points[0] = points[0] || [];
  45933. points[1] = points[1] || [];
  45934. copy(points[0], p1);
  45935. copy(points[1], p2);
  45936. if (+e.curveness) {
  45937. points[2] = [
  45938. (p1[0] + p2[0]) / 2 - (p1[1] - p2[1]) * e.curveness,
  45939. (p1[1] + p2[1]) / 2 - (p2[0] - p1[0]) * e.curveness
  45940. ];
  45941. }
  45942. edge.setLayout(points);
  45943. }
  45944. // Update layout
  45945. cb && cb(stopped);
  45946. });
  45947. };
  45948. graphSeries.forceLayout = forceInstance;
  45949. graphSeries.preservedPoints = preservedPoints;
  45950. // Step to get the layout
  45951. forceInstance.step();
  45952. }
  45953. else {
  45954. // Remove prev injected forceLayout instance
  45955. graphSeries.forceLayout = null;
  45956. }
  45957. });
  45958. };
  45959. /*
  45960. * Licensed to the Apache Software Foundation (ASF) under one
  45961. * or more contributor license agreements. See the NOTICE file
  45962. * distributed with this work for additional information
  45963. * regarding copyright ownership. The ASF licenses this file
  45964. * to you under the Apache License, Version 2.0 (the
  45965. * "License"); you may not use this file except in compliance
  45966. * with the License. You may obtain a copy of the License at
  45967. *
  45968. * http://www.apache.org/licenses/LICENSE-2.0
  45969. *
  45970. * Unless required by applicable law or agreed to in writing,
  45971. * software distributed under the License is distributed on an
  45972. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45973. * KIND, either express or implied. See the License for the
  45974. * specific language governing permissions and limitations
  45975. * under the License.
  45976. */
  45977. // FIXME Where to create the simple view coordinate system
  45978. function getViewRect$1(seriesModel, api, aspect) {
  45979. var option = seriesModel.getBoxLayoutParams();
  45980. option.aspect = aspect;
  45981. return getLayoutRect(option, {
  45982. width: api.getWidth(),
  45983. height: api.getHeight()
  45984. });
  45985. }
  45986. var createView = function (ecModel, api) {
  45987. var viewList = [];
  45988. ecModel.eachSeriesByType('graph', function (seriesModel) {
  45989. var coordSysType = seriesModel.get('coordinateSystem');
  45990. if (!coordSysType || coordSysType === 'view') {
  45991. var data = seriesModel.getData();
  45992. var positions = data.mapArray(function (idx) {
  45993. var itemModel = data.getItemModel(idx);
  45994. return [+itemModel.get('x'), +itemModel.get('y')];
  45995. });
  45996. var min = [];
  45997. var max = [];
  45998. fromPoints(positions, min, max);
  45999. // If width or height is 0
  46000. if (max[0] - min[0] === 0) {
  46001. max[0] += 1;
  46002. min[0] -= 1;
  46003. }
  46004. if (max[1] - min[1] === 0) {
  46005. max[1] += 1;
  46006. min[1] -= 1;
  46007. }
  46008. var aspect = (max[0] - min[0]) / (max[1] - min[1]);
  46009. // FIXME If get view rect after data processed?
  46010. var viewRect = getViewRect$1(seriesModel, api, aspect);
  46011. // Position may be NaN, use view rect instead
  46012. if (isNaN(aspect)) {
  46013. min = [viewRect.x, viewRect.y];
  46014. max = [viewRect.x + viewRect.width, viewRect.y + viewRect.height];
  46015. }
  46016. var bbWidth = max[0] - min[0];
  46017. var bbHeight = max[1] - min[1];
  46018. var viewWidth = viewRect.width;
  46019. var viewHeight = viewRect.height;
  46020. var viewCoordSys = seriesModel.coordinateSystem = new View();
  46021. viewCoordSys.zoomLimit = seriesModel.get('scaleLimit');
  46022. viewCoordSys.setBoundingRect(
  46023. min[0], min[1], bbWidth, bbHeight
  46024. );
  46025. viewCoordSys.setViewRect(
  46026. viewRect.x, viewRect.y, viewWidth, viewHeight
  46027. );
  46028. // Update roam info
  46029. viewCoordSys.setCenter(seriesModel.get('center'));
  46030. viewCoordSys.setZoom(seriesModel.get('zoom'));
  46031. viewList.push(viewCoordSys);
  46032. }
  46033. });
  46034. return viewList;
  46035. };
  46036. /*
  46037. * Licensed to the Apache Software Foundation (ASF) under one
  46038. * or more contributor license agreements. See the NOTICE file
  46039. * distributed with this work for additional information
  46040. * regarding copyright ownership. The ASF licenses this file
  46041. * to you under the Apache License, Version 2.0 (the
  46042. * "License"); you may not use this file except in compliance
  46043. * with the License. You may obtain a copy of the License at
  46044. *
  46045. * http://www.apache.org/licenses/LICENSE-2.0
  46046. *
  46047. * Unless required by applicable law or agreed to in writing,
  46048. * software distributed under the License is distributed on an
  46049. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46050. * KIND, either express or implied. See the License for the
  46051. * specific language governing permissions and limitations
  46052. * under the License.
  46053. */
  46054. registerProcessor(categoryFilter);
  46055. registerVisual(visualSymbol('graph', 'circle', null));
  46056. registerVisual(categoryVisual);
  46057. registerVisual(edgeVisual);
  46058. registerLayout(simpleLayout);
  46059. registerLayout(circularLayout);
  46060. registerLayout(forceLayout);
  46061. // Graph view coordinate system
  46062. registerCoordinateSystem('graphView', {
  46063. create: createView
  46064. });
  46065. /*
  46066. * Licensed to the Apache Software Foundation (ASF) under one
  46067. * or more contributor license agreements. See the NOTICE file
  46068. * distributed with this work for additional information
  46069. * regarding copyright ownership. The ASF licenses this file
  46070. * to you under the Apache License, Version 2.0 (the
  46071. * "License"); you may not use this file except in compliance
  46072. * with the License. You may obtain a copy of the License at
  46073. *
  46074. * http://www.apache.org/licenses/LICENSE-2.0
  46075. *
  46076. * Unless required by applicable law or agreed to in writing,
  46077. * software distributed under the License is distributed on an
  46078. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46079. * KIND, either express or implied. See the License for the
  46080. * specific language governing permissions and limitations
  46081. * under the License.
  46082. */
  46083. var GaugeSeries = SeriesModel.extend({
  46084. type: 'series.gauge',
  46085. getInitialData: function (option, ecModel) {
  46086. var dataOpt = option.data || [];
  46087. if (!isArray(dataOpt)) {
  46088. dataOpt = [dataOpt];
  46089. }
  46090. option.data = dataOpt;
  46091. return createListSimply(this, ['value']);
  46092. },
  46093. defaultOption: {
  46094. zlevel: 0,
  46095. z: 2,
  46096. // 默认全局居中
  46097. center: ['50%', '50%'],
  46098. legendHoverLink: true,
  46099. radius: '75%',
  46100. startAngle: 225,
  46101. endAngle: -45,
  46102. clockwise: true,
  46103. // 最小值
  46104. min: 0,
  46105. // 最大值
  46106. max: 100,
  46107. // 分割段数,默认为10
  46108. splitNumber: 10,
  46109. // 坐标轴线
  46110. axisLine: {
  46111. // 默认显示,属性show控制显示与否
  46112. show: true,
  46113. lineStyle: { // 属性lineStyle控制线条样式
  46114. color: [[0.2, '#91c7ae'], [0.8, '#63869e'], [1, '#c23531']],
  46115. width: 30
  46116. }
  46117. },
  46118. // 分隔线
  46119. splitLine: {
  46120. // 默认显示,属性show控制显示与否
  46121. show: true,
  46122. // 属性length控制线长
  46123. length: 30,
  46124. // 属性lineStyle(详见lineStyle)控制线条样式
  46125. lineStyle: {
  46126. color: '#eee',
  46127. width: 2,
  46128. type: 'solid'
  46129. }
  46130. },
  46131. // 坐标轴小标记
  46132. axisTick: {
  46133. // 属性show控制显示与否,默认不显示
  46134. show: true,
  46135. // 每份split细分多少段
  46136. splitNumber: 5,
  46137. // 属性length控制线长
  46138. length: 8,
  46139. // 属性lineStyle控制线条样式
  46140. lineStyle: {
  46141. color: '#eee',
  46142. width: 1,
  46143. type: 'solid'
  46144. }
  46145. },
  46146. axisLabel: {
  46147. show: true,
  46148. distance: 5,
  46149. // formatter: null,
  46150. color: 'auto'
  46151. },
  46152. pointer: {
  46153. show: true,
  46154. length: '80%',
  46155. width: 8
  46156. },
  46157. itemStyle: {
  46158. color: 'auto'
  46159. },
  46160. title: {
  46161. show: true,
  46162. // x, y,单位px
  46163. offsetCenter: [0, '-40%'],
  46164. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  46165. color: '#333',
  46166. fontSize: 15
  46167. },
  46168. detail: {
  46169. show: true,
  46170. backgroundColor: 'rgba(0,0,0,0)',
  46171. borderWidth: 0,
  46172. borderColor: '#ccc',
  46173. width: 100,
  46174. height: null, // self-adaption
  46175. padding: [5, 10],
  46176. // x, y,单位px
  46177. offsetCenter: [0, '40%'],
  46178. // formatter: null,
  46179. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  46180. color: 'auto',
  46181. fontSize: 30
  46182. }
  46183. }
  46184. });
  46185. /*
  46186. * Licensed to the Apache Software Foundation (ASF) under one
  46187. * or more contributor license agreements. See the NOTICE file
  46188. * distributed with this work for additional information
  46189. * regarding copyright ownership. The ASF licenses this file
  46190. * to you under the Apache License, Version 2.0 (the
  46191. * "License"); you may not use this file except in compliance
  46192. * with the License. You may obtain a copy of the License at
  46193. *
  46194. * http://www.apache.org/licenses/LICENSE-2.0
  46195. *
  46196. * Unless required by applicable law or agreed to in writing,
  46197. * software distributed under the License is distributed on an
  46198. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46199. * KIND, either express or implied. See the License for the
  46200. * specific language governing permissions and limitations
  46201. * under the License.
  46202. */
  46203. var PointerPath = Path.extend({
  46204. type: 'echartsGaugePointer',
  46205. shape: {
  46206. angle: 0,
  46207. width: 10,
  46208. r: 10,
  46209. x: 0,
  46210. y: 0
  46211. },
  46212. buildPath: function (ctx, shape) {
  46213. var mathCos = Math.cos;
  46214. var mathSin = Math.sin;
  46215. var r = shape.r;
  46216. var width = shape.width;
  46217. var angle = shape.angle;
  46218. var x = shape.x - mathCos(angle) * width * (width >= r / 3 ? 1 : 2);
  46219. var y = shape.y - mathSin(angle) * width * (width >= r / 3 ? 1 : 2);
  46220. angle = shape.angle - Math.PI / 2;
  46221. ctx.moveTo(x, y);
  46222. ctx.lineTo(
  46223. shape.x + mathCos(angle) * width,
  46224. shape.y + mathSin(angle) * width
  46225. );
  46226. ctx.lineTo(
  46227. shape.x + mathCos(shape.angle) * r,
  46228. shape.y + mathSin(shape.angle) * r
  46229. );
  46230. ctx.lineTo(
  46231. shape.x - mathCos(angle) * width,
  46232. shape.y - mathSin(angle) * width
  46233. );
  46234. ctx.lineTo(x, y);
  46235. return;
  46236. }
  46237. });
  46238. /*
  46239. * Licensed to the Apache Software Foundation (ASF) under one
  46240. * or more contributor license agreements. See the NOTICE file
  46241. * distributed with this work for additional information
  46242. * regarding copyright ownership. The ASF licenses this file
  46243. * to you under the Apache License, Version 2.0 (the
  46244. * "License"); you may not use this file except in compliance
  46245. * with the License. You may obtain a copy of the License at
  46246. *
  46247. * http://www.apache.org/licenses/LICENSE-2.0
  46248. *
  46249. * Unless required by applicable law or agreed to in writing,
  46250. * software distributed under the License is distributed on an
  46251. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46252. * KIND, either express or implied. See the License for the
  46253. * specific language governing permissions and limitations
  46254. * under the License.
  46255. */
  46256. function parsePosition(seriesModel, api) {
  46257. var center = seriesModel.get('center');
  46258. var width = api.getWidth();
  46259. var height = api.getHeight();
  46260. var size = Math.min(width, height);
  46261. var cx = parsePercent$1(center[0], api.getWidth());
  46262. var cy = parsePercent$1(center[1], api.getHeight());
  46263. var r = parsePercent$1(seriesModel.get('radius'), size / 2);
  46264. return {
  46265. cx: cx,
  46266. cy: cy,
  46267. r: r
  46268. };
  46269. }
  46270. function formatLabel(label, labelFormatter) {
  46271. if (labelFormatter) {
  46272. if (typeof labelFormatter === 'string') {
  46273. label = labelFormatter.replace('{value}', label != null ? label : '');
  46274. }
  46275. else if (typeof labelFormatter === 'function') {
  46276. label = labelFormatter(label);
  46277. }
  46278. }
  46279. return label;
  46280. }
  46281. var PI2$5 = Math.PI * 2;
  46282. var GaugeView = Chart.extend({
  46283. type: 'gauge',
  46284. render: function (seriesModel, ecModel, api) {
  46285. this.group.removeAll();
  46286. var colorList = seriesModel.get('axisLine.lineStyle.color');
  46287. var posInfo = parsePosition(seriesModel, api);
  46288. this._renderMain(
  46289. seriesModel, ecModel, api, colorList, posInfo
  46290. );
  46291. },
  46292. dispose: function () {},
  46293. _renderMain: function (seriesModel, ecModel, api, colorList, posInfo) {
  46294. var group = this.group;
  46295. var axisLineModel = seriesModel.getModel('axisLine');
  46296. var lineStyleModel = axisLineModel.getModel('lineStyle');
  46297. var clockwise = seriesModel.get('clockwise');
  46298. var startAngle = -seriesModel.get('startAngle') / 180 * Math.PI;
  46299. var endAngle = -seriesModel.get('endAngle') / 180 * Math.PI;
  46300. var angleRangeSpan = (endAngle - startAngle) % PI2$5;
  46301. var prevEndAngle = startAngle;
  46302. var axisLineWidth = lineStyleModel.get('width');
  46303. for (var i = 0; i < colorList.length; i++) {
  46304. // Clamp
  46305. var percent = Math.min(Math.max(colorList[i][0], 0), 1);
  46306. var endAngle = startAngle + angleRangeSpan * percent;
  46307. var sector = new Sector({
  46308. shape: {
  46309. startAngle: prevEndAngle,
  46310. endAngle: endAngle,
  46311. cx: posInfo.cx,
  46312. cy: posInfo.cy,
  46313. clockwise: clockwise,
  46314. r0: posInfo.r - axisLineWidth,
  46315. r: posInfo.r
  46316. },
  46317. silent: true
  46318. });
  46319. sector.setStyle({
  46320. fill: colorList[i][1]
  46321. });
  46322. sector.setStyle(lineStyleModel.getLineStyle(
  46323. // Because we use sector to simulate arc
  46324. // so the properties for stroking are useless
  46325. ['color', 'borderWidth', 'borderColor']
  46326. ));
  46327. group.add(sector);
  46328. prevEndAngle = endAngle;
  46329. }
  46330. var getColor = function (percent) {
  46331. // Less than 0
  46332. if (percent <= 0) {
  46333. return colorList[0][1];
  46334. }
  46335. for (var i = 0; i < colorList.length; i++) {
  46336. if (colorList[i][0] >= percent
  46337. && (i === 0 ? 0 : colorList[i - 1][0]) < percent
  46338. ) {
  46339. return colorList[i][1];
  46340. }
  46341. }
  46342. // More than 1
  46343. return colorList[i - 1][1];
  46344. };
  46345. if (!clockwise) {
  46346. var tmp = startAngle;
  46347. startAngle = endAngle;
  46348. endAngle = tmp;
  46349. }
  46350. this._renderTicks(
  46351. seriesModel, ecModel, api, getColor, posInfo,
  46352. startAngle, endAngle, clockwise
  46353. );
  46354. this._renderPointer(
  46355. seriesModel, ecModel, api, getColor, posInfo,
  46356. startAngle, endAngle, clockwise
  46357. );
  46358. this._renderTitle(
  46359. seriesModel, ecModel, api, getColor, posInfo
  46360. );
  46361. this._renderDetail(
  46362. seriesModel, ecModel, api, getColor, posInfo
  46363. );
  46364. },
  46365. _renderTicks: function (
  46366. seriesModel, ecModel, api, getColor, posInfo,
  46367. startAngle, endAngle, clockwise
  46368. ) {
  46369. var group = this.group;
  46370. var cx = posInfo.cx;
  46371. var cy = posInfo.cy;
  46372. var r = posInfo.r;
  46373. var minVal = +seriesModel.get('min');
  46374. var maxVal = +seriesModel.get('max');
  46375. var splitLineModel = seriesModel.getModel('splitLine');
  46376. var tickModel = seriesModel.getModel('axisTick');
  46377. var labelModel = seriesModel.getModel('axisLabel');
  46378. var splitNumber = seriesModel.get('splitNumber');
  46379. var subSplitNumber = tickModel.get('splitNumber');
  46380. var splitLineLen = parsePercent$1(
  46381. splitLineModel.get('length'), r
  46382. );
  46383. var tickLen = parsePercent$1(
  46384. tickModel.get('length'), r
  46385. );
  46386. var angle = startAngle;
  46387. var step = (endAngle - startAngle) / splitNumber;
  46388. var subStep = step / subSplitNumber;
  46389. var splitLineStyle = splitLineModel.getModel('lineStyle').getLineStyle();
  46390. var tickLineStyle = tickModel.getModel('lineStyle').getLineStyle();
  46391. for (var i = 0; i <= splitNumber; i++) {
  46392. var unitX = Math.cos(angle);
  46393. var unitY = Math.sin(angle);
  46394. // Split line
  46395. if (splitLineModel.get('show')) {
  46396. var splitLine = new Line({
  46397. shape: {
  46398. x1: unitX * r + cx,
  46399. y1: unitY * r + cy,
  46400. x2: unitX * (r - splitLineLen) + cx,
  46401. y2: unitY * (r - splitLineLen) + cy
  46402. },
  46403. style: splitLineStyle,
  46404. silent: true
  46405. });
  46406. if (splitLineStyle.stroke === 'auto') {
  46407. splitLine.setStyle({
  46408. stroke: getColor(i / splitNumber)
  46409. });
  46410. }
  46411. group.add(splitLine);
  46412. }
  46413. // Label
  46414. if (labelModel.get('show')) {
  46415. var label = formatLabel(
  46416. round$1(i / splitNumber * (maxVal - minVal) + minVal),
  46417. labelModel.get('formatter')
  46418. );
  46419. var distance = labelModel.get('distance');
  46420. var autoColor = getColor(i / splitNumber);
  46421. group.add(new Text({
  46422. style: setTextStyle({}, labelModel, {
  46423. text: label,
  46424. x: unitX * (r - splitLineLen - distance) + cx,
  46425. y: unitY * (r - splitLineLen - distance) + cy,
  46426. textVerticalAlign: unitY < -0.4 ? 'top' : (unitY > 0.4 ? 'bottom' : 'middle'),
  46427. textAlign: unitX < -0.4 ? 'left' : (unitX > 0.4 ? 'right' : 'center')
  46428. }, {autoColor: autoColor}),
  46429. silent: true
  46430. }));
  46431. }
  46432. // Axis tick
  46433. if (tickModel.get('show') && i !== splitNumber) {
  46434. for (var j = 0; j <= subSplitNumber; j++) {
  46435. var unitX = Math.cos(angle);
  46436. var unitY = Math.sin(angle);
  46437. var tickLine = new Line({
  46438. shape: {
  46439. x1: unitX * r + cx,
  46440. y1: unitY * r + cy,
  46441. x2: unitX * (r - tickLen) + cx,
  46442. y2: unitY * (r - tickLen) + cy
  46443. },
  46444. silent: true,
  46445. style: tickLineStyle
  46446. });
  46447. if (tickLineStyle.stroke === 'auto') {
  46448. tickLine.setStyle({
  46449. stroke: getColor((i + j / subSplitNumber) / splitNumber)
  46450. });
  46451. }
  46452. group.add(tickLine);
  46453. angle += subStep;
  46454. }
  46455. angle -= subStep;
  46456. }
  46457. else {
  46458. angle += step;
  46459. }
  46460. }
  46461. },
  46462. _renderPointer: function (
  46463. seriesModel, ecModel, api, getColor, posInfo,
  46464. startAngle, endAngle, clockwise
  46465. ) {
  46466. var group = this.group;
  46467. var oldData = this._data;
  46468. if (!seriesModel.get('pointer.show')) {
  46469. // Remove old element
  46470. oldData && oldData.eachItemGraphicEl(function (el) {
  46471. group.remove(el);
  46472. });
  46473. return;
  46474. }
  46475. var valueExtent = [+seriesModel.get('min'), +seriesModel.get('max')];
  46476. var angleExtent = [startAngle, endAngle];
  46477. var data = seriesModel.getData();
  46478. var valueDim = data.mapDimension('value');
  46479. data.diff(oldData)
  46480. .add(function (idx) {
  46481. var pointer = new PointerPath({
  46482. shape: {
  46483. angle: startAngle
  46484. }
  46485. });
  46486. initProps(pointer, {
  46487. shape: {
  46488. angle: linearMap(data.get(valueDim, idx), valueExtent, angleExtent, true)
  46489. }
  46490. }, seriesModel);
  46491. group.add(pointer);
  46492. data.setItemGraphicEl(idx, pointer);
  46493. })
  46494. .update(function (newIdx, oldIdx) {
  46495. var pointer = oldData.getItemGraphicEl(oldIdx);
  46496. updateProps(pointer, {
  46497. shape: {
  46498. angle: linearMap(data.get(valueDim, newIdx), valueExtent, angleExtent, true)
  46499. }
  46500. }, seriesModel);
  46501. group.add(pointer);
  46502. data.setItemGraphicEl(newIdx, pointer);
  46503. })
  46504. .remove(function (idx) {
  46505. var pointer = oldData.getItemGraphicEl(idx);
  46506. group.remove(pointer);
  46507. })
  46508. .execute();
  46509. data.eachItemGraphicEl(function (pointer, idx) {
  46510. var itemModel = data.getItemModel(idx);
  46511. var pointerModel = itemModel.getModel('pointer');
  46512. pointer.setShape({
  46513. x: posInfo.cx,
  46514. y: posInfo.cy,
  46515. width: parsePercent$1(
  46516. pointerModel.get('width'), posInfo.r
  46517. ),
  46518. r: parsePercent$1(pointerModel.get('length'), posInfo.r)
  46519. });
  46520. pointer.useStyle(itemModel.getModel('itemStyle').getItemStyle());
  46521. if (pointer.style.fill === 'auto') {
  46522. pointer.setStyle('fill', getColor(
  46523. linearMap(data.get(valueDim, idx), valueExtent, [0, 1], true)
  46524. ));
  46525. }
  46526. setHoverStyle(
  46527. pointer, itemModel.getModel('emphasis.itemStyle').getItemStyle()
  46528. );
  46529. });
  46530. this._data = data;
  46531. },
  46532. _renderTitle: function (
  46533. seriesModel, ecModel, api, getColor, posInfo
  46534. ) {
  46535. var data = seriesModel.getData();
  46536. var valueDim = data.mapDimension('value');
  46537. var titleModel = seriesModel.getModel('title');
  46538. if (titleModel.get('show')) {
  46539. var offsetCenter = titleModel.get('offsetCenter');
  46540. var x = posInfo.cx + parsePercent$1(offsetCenter[0], posInfo.r);
  46541. var y = posInfo.cy + parsePercent$1(offsetCenter[1], posInfo.r);
  46542. var minVal = +seriesModel.get('min');
  46543. var maxVal = +seriesModel.get('max');
  46544. var value = seriesModel.getData().get(valueDim, 0);
  46545. var autoColor = getColor(
  46546. linearMap(value, [minVal, maxVal], [0, 1], true)
  46547. );
  46548. this.group.add(new Text({
  46549. silent: true,
  46550. style: setTextStyle({}, titleModel, {
  46551. x: x,
  46552. y: y,
  46553. // FIXME First data name ?
  46554. text: data.getName(0),
  46555. textAlign: 'center',
  46556. textVerticalAlign: 'middle'
  46557. }, {autoColor: autoColor, forceRich: true})
  46558. }));
  46559. }
  46560. },
  46561. _renderDetail: function (
  46562. seriesModel, ecModel, api, getColor, posInfo
  46563. ) {
  46564. var detailModel = seriesModel.getModel('detail');
  46565. var minVal = +seriesModel.get('min');
  46566. var maxVal = +seriesModel.get('max');
  46567. if (detailModel.get('show')) {
  46568. var offsetCenter = detailModel.get('offsetCenter');
  46569. var x = posInfo.cx + parsePercent$1(offsetCenter[0], posInfo.r);
  46570. var y = posInfo.cy + parsePercent$1(offsetCenter[1], posInfo.r);
  46571. var width = parsePercent$1(detailModel.get('width'), posInfo.r);
  46572. var height = parsePercent$1(detailModel.get('height'), posInfo.r);
  46573. var data = seriesModel.getData();
  46574. var value = data.get(data.mapDimension('value'), 0);
  46575. var autoColor = getColor(
  46576. linearMap(value, [minVal, maxVal], [0, 1], true)
  46577. );
  46578. this.group.add(new Text({
  46579. silent: true,
  46580. style: setTextStyle({}, detailModel, {
  46581. x: x,
  46582. y: y,
  46583. text: formatLabel(
  46584. // FIXME First data name ?
  46585. value, detailModel.get('formatter')
  46586. ),
  46587. textWidth: isNaN(width) ? null : width,
  46588. textHeight: isNaN(height) ? null : height,
  46589. textAlign: 'center',
  46590. textVerticalAlign: 'middle'
  46591. }, {autoColor: autoColor, forceRich: true})
  46592. }));
  46593. }
  46594. }
  46595. });
  46596. /*
  46597. * Licensed to the Apache Software Foundation (ASF) under one
  46598. * or more contributor license agreements. See the NOTICE file
  46599. * distributed with this work for additional information
  46600. * regarding copyright ownership. The ASF licenses this file
  46601. * to you under the Apache License, Version 2.0 (the
  46602. * "License"); you may not use this file except in compliance
  46603. * with the License. You may obtain a copy of the License at
  46604. *
  46605. * http://www.apache.org/licenses/LICENSE-2.0
  46606. *
  46607. * Unless required by applicable law or agreed to in writing,
  46608. * software distributed under the License is distributed on an
  46609. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46610. * KIND, either express or implied. See the License for the
  46611. * specific language governing permissions and limitations
  46612. * under the License.
  46613. */
  46614. /*
  46615. * Licensed to the Apache Software Foundation (ASF) under one
  46616. * or more contributor license agreements. See the NOTICE file
  46617. * distributed with this work for additional information
  46618. * regarding copyright ownership. The ASF licenses this file
  46619. * to you under the Apache License, Version 2.0 (the
  46620. * "License"); you may not use this file except in compliance
  46621. * with the License. You may obtain a copy of the License at
  46622. *
  46623. * http://www.apache.org/licenses/LICENSE-2.0
  46624. *
  46625. * Unless required by applicable law or agreed to in writing,
  46626. * software distributed under the License is distributed on an
  46627. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46628. * KIND, either express or implied. See the License for the
  46629. * specific language governing permissions and limitations
  46630. * under the License.
  46631. */
  46632. var FunnelSeries = extendSeriesModel({
  46633. type: 'series.funnel',
  46634. init: function (option) {
  46635. FunnelSeries.superApply(this, 'init', arguments);
  46636. // Enable legend selection for each data item
  46637. // Use a function instead of direct access because data reference may changed
  46638. this.legendDataProvider = function () {
  46639. return this.getRawData();
  46640. };
  46641. // Extend labelLine emphasis
  46642. this._defaultLabelLine(option);
  46643. },
  46644. getInitialData: function (option, ecModel) {
  46645. return createListSimply(this, ['value']);
  46646. },
  46647. _defaultLabelLine: function (option) {
  46648. // Extend labelLine emphasis
  46649. defaultEmphasis(option, 'labelLine', ['show']);
  46650. var labelLineNormalOpt = option.labelLine;
  46651. var labelLineEmphasisOpt = option.emphasis.labelLine;
  46652. // Not show label line if `label.normal.show = false`
  46653. labelLineNormalOpt.show = labelLineNormalOpt.show
  46654. && option.label.show;
  46655. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show
  46656. && option.emphasis.label.show;
  46657. },
  46658. // Overwrite
  46659. getDataParams: function (dataIndex) {
  46660. var data = this.getData();
  46661. var params = FunnelSeries.superCall(this, 'getDataParams', dataIndex);
  46662. var valueDim = data.mapDimension('value');
  46663. var sum = data.getSum(valueDim);
  46664. // Percent is 0 if sum is 0
  46665. params.percent = !sum ? 0 : +(data.get(valueDim, dataIndex) / sum * 100).toFixed(2);
  46666. params.$vars.push('percent');
  46667. return params;
  46668. },
  46669. defaultOption: {
  46670. zlevel: 0, // 一级层叠
  46671. z: 2, // 二级层叠
  46672. legendHoverLink: true,
  46673. left: 80,
  46674. top: 60,
  46675. right: 80,
  46676. bottom: 60,
  46677. // width: {totalWidth} - left - right,
  46678. // height: {totalHeight} - top - bottom,
  46679. // 默认取数据最小最大值
  46680. // min: 0,
  46681. // max: 100,
  46682. minSize: '0%',
  46683. maxSize: '100%',
  46684. sort: 'descending', // 'ascending', 'descending'
  46685. gap: 0,
  46686. funnelAlign: 'center',
  46687. label: {
  46688. show: true,
  46689. position: 'outer'
  46690. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  46691. },
  46692. labelLine: {
  46693. show: true,
  46694. length: 20,
  46695. lineStyle: {
  46696. // color: 各异,
  46697. width: 1,
  46698. type: 'solid'
  46699. }
  46700. },
  46701. itemStyle: {
  46702. // color: 各异,
  46703. borderColor: '#fff',
  46704. borderWidth: 1
  46705. },
  46706. emphasis: {
  46707. label: {
  46708. show: true
  46709. }
  46710. }
  46711. }
  46712. });
  46713. /*
  46714. * Licensed to the Apache Software Foundation (ASF) under one
  46715. * or more contributor license agreements. See the NOTICE file
  46716. * distributed with this work for additional information
  46717. * regarding copyright ownership. The ASF licenses this file
  46718. * to you under the Apache License, Version 2.0 (the
  46719. * "License"); you may not use this file except in compliance
  46720. * with the License. You may obtain a copy of the License at
  46721. *
  46722. * http://www.apache.org/licenses/LICENSE-2.0
  46723. *
  46724. * Unless required by applicable law or agreed to in writing,
  46725. * software distributed under the License is distributed on an
  46726. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46727. * KIND, either express or implied. See the License for the
  46728. * specific language governing permissions and limitations
  46729. * under the License.
  46730. */
  46731. /**
  46732. * Piece of pie including Sector, Label, LabelLine
  46733. * @constructor
  46734. * @extends {module:zrender/graphic/Group}
  46735. */
  46736. function FunnelPiece(data, idx) {
  46737. Group.call(this);
  46738. var polygon = new Polygon();
  46739. var labelLine = new Polyline();
  46740. var text = new Text();
  46741. this.add(polygon);
  46742. this.add(labelLine);
  46743. this.add(text);
  46744. this.updateData(data, idx, true);
  46745. // Hover to change label and labelLine
  46746. function onEmphasis() {
  46747. labelLine.ignore = labelLine.hoverIgnore;
  46748. text.ignore = text.hoverIgnore;
  46749. }
  46750. function onNormal() {
  46751. labelLine.ignore = labelLine.normalIgnore;
  46752. text.ignore = text.normalIgnore;
  46753. }
  46754. this.on('emphasis', onEmphasis)
  46755. .on('normal', onNormal)
  46756. .on('mouseover', onEmphasis)
  46757. .on('mouseout', onNormal);
  46758. }
  46759. var funnelPieceProto = FunnelPiece.prototype;
  46760. var opacityAccessPath = ['itemStyle', 'opacity'];
  46761. funnelPieceProto.updateData = function (data, idx, firstCreate) {
  46762. var polygon = this.childAt(0);
  46763. var seriesModel = data.hostModel;
  46764. var itemModel = data.getItemModel(idx);
  46765. var layout = data.getItemLayout(idx);
  46766. var opacity = data.getItemModel(idx).get(opacityAccessPath);
  46767. opacity = opacity == null ? 1 : opacity;
  46768. // Reset style
  46769. polygon.useStyle({});
  46770. if (firstCreate) {
  46771. polygon.setShape({
  46772. points: layout.points
  46773. });
  46774. polygon.setStyle({ opacity : 0 });
  46775. initProps(polygon, {
  46776. style: {
  46777. opacity: opacity
  46778. }
  46779. }, seriesModel, idx);
  46780. }
  46781. else {
  46782. updateProps(polygon, {
  46783. style: {
  46784. opacity: opacity
  46785. },
  46786. shape: {
  46787. points: layout.points
  46788. }
  46789. }, seriesModel, idx);
  46790. }
  46791. // Update common style
  46792. var itemStyleModel = itemModel.getModel('itemStyle');
  46793. var visualColor = data.getItemVisual(idx, 'color');
  46794. polygon.setStyle(
  46795. defaults(
  46796. {
  46797. lineJoin: 'round',
  46798. fill: visualColor
  46799. },
  46800. itemStyleModel.getItemStyle(['opacity'])
  46801. )
  46802. );
  46803. polygon.hoverStyle = itemStyleModel.getModel('emphasis').getItemStyle();
  46804. this._updateLabel(data, idx);
  46805. setHoverStyle(this);
  46806. };
  46807. funnelPieceProto._updateLabel = function (data, idx) {
  46808. var labelLine = this.childAt(1);
  46809. var labelText = this.childAt(2);
  46810. var seriesModel = data.hostModel;
  46811. var itemModel = data.getItemModel(idx);
  46812. var layout = data.getItemLayout(idx);
  46813. var labelLayout = layout.label;
  46814. var visualColor = data.getItemVisual(idx, 'color');
  46815. updateProps(labelLine, {
  46816. shape: {
  46817. points: labelLayout.linePoints || labelLayout.linePoints
  46818. }
  46819. }, seriesModel, idx);
  46820. updateProps(labelText, {
  46821. style: {
  46822. x: labelLayout.x,
  46823. y: labelLayout.y
  46824. }
  46825. }, seriesModel, idx);
  46826. labelText.attr({
  46827. rotation: labelLayout.rotation,
  46828. origin: [labelLayout.x, labelLayout.y],
  46829. z2: 10
  46830. });
  46831. var labelModel = itemModel.getModel('label');
  46832. var labelHoverModel = itemModel.getModel('emphasis.label');
  46833. var labelLineModel = itemModel.getModel('labelLine');
  46834. var labelLineHoverModel = itemModel.getModel('emphasis.labelLine');
  46835. var visualColor = data.getItemVisual(idx, 'color');
  46836. setLabelStyle(
  46837. labelText.style, labelText.hoverStyle = {}, labelModel, labelHoverModel,
  46838. {
  46839. labelFetcher: data.hostModel,
  46840. labelDataIndex: idx,
  46841. defaultText: data.getName(idx),
  46842. autoColor: visualColor,
  46843. useInsideStyle: !!labelLayout.inside
  46844. },
  46845. {
  46846. textAlign: labelLayout.textAlign,
  46847. textVerticalAlign: labelLayout.verticalAlign
  46848. }
  46849. );
  46850. labelText.ignore = labelText.normalIgnore = !labelModel.get('show');
  46851. labelText.hoverIgnore = !labelHoverModel.get('show');
  46852. labelLine.ignore = labelLine.normalIgnore = !labelLineModel.get('show');
  46853. labelLine.hoverIgnore = !labelLineHoverModel.get('show');
  46854. // Default use item visual color
  46855. labelLine.setStyle({
  46856. stroke: visualColor
  46857. });
  46858. labelLine.setStyle(labelLineModel.getModel('lineStyle').getLineStyle());
  46859. labelLine.hoverStyle = labelLineHoverModel.getModel('lineStyle').getLineStyle();
  46860. };
  46861. inherits(FunnelPiece, Group);
  46862. var FunnelView = Chart.extend({
  46863. type: 'funnel',
  46864. render: function (seriesModel, ecModel, api) {
  46865. var data = seriesModel.getData();
  46866. var oldData = this._data;
  46867. var group = this.group;
  46868. data.diff(oldData)
  46869. .add(function (idx) {
  46870. var funnelPiece = new FunnelPiece(data, idx);
  46871. data.setItemGraphicEl(idx, funnelPiece);
  46872. group.add(funnelPiece);
  46873. })
  46874. .update(function (newIdx, oldIdx) {
  46875. var piePiece = oldData.getItemGraphicEl(oldIdx);
  46876. piePiece.updateData(data, newIdx);
  46877. group.add(piePiece);
  46878. data.setItemGraphicEl(newIdx, piePiece);
  46879. })
  46880. .remove(function (idx) {
  46881. var piePiece = oldData.getItemGraphicEl(idx);
  46882. group.remove(piePiece);
  46883. })
  46884. .execute();
  46885. this._data = data;
  46886. },
  46887. remove: function () {
  46888. this.group.removeAll();
  46889. this._data = null;
  46890. },
  46891. dispose: function () {}
  46892. });
  46893. /*
  46894. * Licensed to the Apache Software Foundation (ASF) under one
  46895. * or more contributor license agreements. See the NOTICE file
  46896. * distributed with this work for additional information
  46897. * regarding copyright ownership. The ASF licenses this file
  46898. * to you under the Apache License, Version 2.0 (the
  46899. * "License"); you may not use this file except in compliance
  46900. * with the License. You may obtain a copy of the License at
  46901. *
  46902. * http://www.apache.org/licenses/LICENSE-2.0
  46903. *
  46904. * Unless required by applicable law or agreed to in writing,
  46905. * software distributed under the License is distributed on an
  46906. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46907. * KIND, either express or implied. See the License for the
  46908. * specific language governing permissions and limitations
  46909. * under the License.
  46910. */
  46911. function getViewRect$2(seriesModel, api) {
  46912. return getLayoutRect(
  46913. seriesModel.getBoxLayoutParams(), {
  46914. width: api.getWidth(),
  46915. height: api.getHeight()
  46916. }
  46917. );
  46918. }
  46919. function getSortedIndices(data, sort) {
  46920. var valueDim = data.mapDimension('value');
  46921. var valueArr = data.mapArray(valueDim, function (val) {
  46922. return val;
  46923. });
  46924. var indices = [];
  46925. var isAscending = sort === 'ascending';
  46926. for (var i = 0, len = data.count(); i < len; i++) {
  46927. indices[i] = i;
  46928. }
  46929. // Add custom sortable function & none sortable opetion by "options.sort"
  46930. if (typeof sort === 'function') {
  46931. indices.sort(sort);
  46932. } else if (sort !== 'none') {
  46933. indices.sort(function (a, b) {
  46934. return isAscending ? valueArr[a] - valueArr[b] : valueArr[b] - valueArr[a];
  46935. });
  46936. }
  46937. return indices;
  46938. }
  46939. function labelLayout$1(data) {
  46940. data.each(function (idx) {
  46941. var itemModel = data.getItemModel(idx);
  46942. var labelModel = itemModel.getModel('label');
  46943. var labelPosition = labelModel.get('position');
  46944. var labelLineModel = itemModel.getModel('labelLine');
  46945. var layout = data.getItemLayout(idx);
  46946. var points = layout.points;
  46947. var isLabelInside = labelPosition === 'inner'
  46948. || labelPosition === 'inside' || labelPosition === 'center';
  46949. var textAlign;
  46950. var textX;
  46951. var textY;
  46952. var linePoints;
  46953. if (isLabelInside) {
  46954. textX = (points[0][0] + points[1][0] + points[2][0] + points[3][0]) / 4;
  46955. textY = (points[0][1] + points[1][1] + points[2][1] + points[3][1]) / 4;
  46956. textAlign = 'center';
  46957. linePoints = [
  46958. [textX, textY], [textX, textY]
  46959. ];
  46960. }
  46961. else {
  46962. var x1;
  46963. var y1;
  46964. var x2;
  46965. var labelLineLen = labelLineModel.get('length');
  46966. if (labelPosition === 'left') {
  46967. // Left side
  46968. x1 = (points[3][0] + points[0][0]) / 2;
  46969. y1 = (points[3][1] + points[0][1]) / 2;
  46970. x2 = x1 - labelLineLen;
  46971. textX = x2 - 5;
  46972. textAlign = 'right';
  46973. }
  46974. else {
  46975. // Right side
  46976. x1 = (points[1][0] + points[2][0]) / 2;
  46977. y1 = (points[1][1] + points[2][1]) / 2;
  46978. x2 = x1 + labelLineLen;
  46979. textX = x2 + 5;
  46980. textAlign = 'left';
  46981. }
  46982. var y2 = y1;
  46983. linePoints = [[x1, y1], [x2, y2]];
  46984. textY = y2;
  46985. }
  46986. layout.label = {
  46987. linePoints: linePoints,
  46988. x: textX,
  46989. y: textY,
  46990. verticalAlign: 'middle',
  46991. textAlign: textAlign,
  46992. inside: isLabelInside
  46993. };
  46994. });
  46995. }
  46996. var funnelLayout = function (ecModel, api, payload) {
  46997. ecModel.eachSeriesByType('funnel', function (seriesModel) {
  46998. var data = seriesModel.getData();
  46999. var valueDim = data.mapDimension('value');
  47000. var sort = seriesModel.get('sort');
  47001. var viewRect = getViewRect$2(seriesModel, api);
  47002. var indices = getSortedIndices(data, sort);
  47003. var sizeExtent = [
  47004. parsePercent$1(seriesModel.get('minSize'), viewRect.width),
  47005. parsePercent$1(seriesModel.get('maxSize'), viewRect.width)
  47006. ];
  47007. var dataExtent = data.getDataExtent(valueDim);
  47008. var min = seriesModel.get('min');
  47009. var max = seriesModel.get('max');
  47010. if (min == null) {
  47011. min = Math.min(dataExtent[0], 0);
  47012. }
  47013. if (max == null) {
  47014. max = dataExtent[1];
  47015. }
  47016. var funnelAlign = seriesModel.get('funnelAlign');
  47017. var gap = seriesModel.get('gap');
  47018. var itemHeight = (viewRect.height - gap * (data.count() - 1)) / data.count();
  47019. var y = viewRect.y;
  47020. var getLinePoints = function (idx, offY) {
  47021. // End point index is data.count() and we assign it 0
  47022. var val = data.get(valueDim, idx) || 0;
  47023. var itemWidth = linearMap(val, [min, max], sizeExtent, true);
  47024. var x0;
  47025. switch (funnelAlign) {
  47026. case 'left':
  47027. x0 = viewRect.x;
  47028. break;
  47029. case 'center':
  47030. x0 = viewRect.x + (viewRect.width - itemWidth) / 2;
  47031. break;
  47032. case 'right':
  47033. x0 = viewRect.x + viewRect.width - itemWidth;
  47034. break;
  47035. }
  47036. return [
  47037. [x0, offY],
  47038. [x0 + itemWidth, offY]
  47039. ];
  47040. };
  47041. if (sort === 'ascending') {
  47042. // From bottom to top
  47043. itemHeight = -itemHeight;
  47044. gap = -gap;
  47045. y += viewRect.height;
  47046. indices = indices.reverse();
  47047. }
  47048. for (var i = 0; i < indices.length; i++) {
  47049. var idx = indices[i];
  47050. var nextIdx = indices[i + 1];
  47051. var itemModel = data.getItemModel(idx);
  47052. var height = itemModel.get('itemStyle.height');
  47053. if (height == null) {
  47054. height = itemHeight;
  47055. }
  47056. else {
  47057. height = parsePercent$1(height, viewRect.height);
  47058. if (sort === 'ascending') {
  47059. height = -height;
  47060. }
  47061. }
  47062. var start = getLinePoints(idx, y);
  47063. var end = getLinePoints(nextIdx, y + height);
  47064. y += height + gap;
  47065. data.setItemLayout(idx, {
  47066. points: start.concat(end.slice().reverse())
  47067. });
  47068. }
  47069. labelLayout$1(data);
  47070. });
  47071. };
  47072. /*
  47073. * Licensed to the Apache Software Foundation (ASF) under one
  47074. * or more contributor license agreements. See the NOTICE file
  47075. * distributed with this work for additional information
  47076. * regarding copyright ownership. The ASF licenses this file
  47077. * to you under the Apache License, Version 2.0 (the
  47078. * "License"); you may not use this file except in compliance
  47079. * with the License. You may obtain a copy of the License at
  47080. *
  47081. * http://www.apache.org/licenses/LICENSE-2.0
  47082. *
  47083. * Unless required by applicable law or agreed to in writing,
  47084. * software distributed under the License is distributed on an
  47085. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47086. * KIND, either express or implied. See the License for the
  47087. * specific language governing permissions and limitations
  47088. * under the License.
  47089. */
  47090. registerVisual(dataColor('funnel'));
  47091. registerLayout(funnelLayout);
  47092. registerProcessor(dataFilter('funnel'));
  47093. /*
  47094. * Licensed to the Apache Software Foundation (ASF) under one
  47095. * or more contributor license agreements. See the NOTICE file
  47096. * distributed with this work for additional information
  47097. * regarding copyright ownership. The ASF licenses this file
  47098. * to you under the Apache License, Version 2.0 (the
  47099. * "License"); you may not use this file except in compliance
  47100. * with the License. You may obtain a copy of the License at
  47101. *
  47102. * http://www.apache.org/licenses/LICENSE-2.0
  47103. *
  47104. * Unless required by applicable law or agreed to in writing,
  47105. * software distributed under the License is distributed on an
  47106. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47107. * KIND, either express or implied. See the License for the
  47108. * specific language governing permissions and limitations
  47109. * under the License.
  47110. */
  47111. var parallelPreprocessor = function (option) {
  47112. createParallelIfNeeded(option);
  47113. mergeAxisOptionFromParallel(option);
  47114. };
  47115. /**
  47116. * Create a parallel coordinate if not exists.
  47117. * @inner
  47118. */
  47119. function createParallelIfNeeded(option) {
  47120. if (option.parallel) {
  47121. return;
  47122. }
  47123. var hasParallelSeries = false;
  47124. each$1(option.series, function (seriesOpt) {
  47125. if (seriesOpt && seriesOpt.type === 'parallel') {
  47126. hasParallelSeries = true;
  47127. }
  47128. });
  47129. if (hasParallelSeries) {
  47130. option.parallel = [{}];
  47131. }
  47132. }
  47133. /**
  47134. * Merge aixs definition from parallel option (if exists) to axis option.
  47135. * @inner
  47136. */
  47137. function mergeAxisOptionFromParallel(option) {
  47138. var axes = normalizeToArray(option.parallelAxis);
  47139. each$1(axes, function (axisOption) {
  47140. if (!isObject$1(axisOption)) {
  47141. return;
  47142. }
  47143. var parallelIndex = axisOption.parallelIndex || 0;
  47144. var parallelOption = normalizeToArray(option.parallel)[parallelIndex];
  47145. if (parallelOption && parallelOption.parallelAxisDefault) {
  47146. merge(axisOption, parallelOption.parallelAxisDefault, false);
  47147. }
  47148. });
  47149. }
  47150. /*
  47151. * Licensed to the Apache Software Foundation (ASF) under one
  47152. * or more contributor license agreements. See the NOTICE file
  47153. * distributed with this work for additional information
  47154. * regarding copyright ownership. The ASF licenses this file
  47155. * to you under the Apache License, Version 2.0 (the
  47156. * "License"); you may not use this file except in compliance
  47157. * with the License. You may obtain a copy of the License at
  47158. *
  47159. * http://www.apache.org/licenses/LICENSE-2.0
  47160. *
  47161. * Unless required by applicable law or agreed to in writing,
  47162. * software distributed under the License is distributed on an
  47163. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47164. * KIND, either express or implied. See the License for the
  47165. * specific language governing permissions and limitations
  47166. * under the License.
  47167. */
  47168. /**
  47169. * @constructor module:echarts/coord/parallel/ParallelAxis
  47170. * @extends {module:echarts/coord/Axis}
  47171. * @param {string} dim
  47172. * @param {*} scale
  47173. * @param {Array.<number>} coordExtent
  47174. * @param {string} axisType
  47175. */
  47176. var ParallelAxis = function (dim, scale, coordExtent, axisType, axisIndex) {
  47177. Axis.call(this, dim, scale, coordExtent);
  47178. /**
  47179. * Axis type
  47180. * - 'category'
  47181. * - 'value'
  47182. * - 'time'
  47183. * - 'log'
  47184. * @type {string}
  47185. */
  47186. this.type = axisType || 'value';
  47187. /**
  47188. * @type {number}
  47189. * @readOnly
  47190. */
  47191. this.axisIndex = axisIndex;
  47192. };
  47193. ParallelAxis.prototype = {
  47194. constructor: ParallelAxis,
  47195. /**
  47196. * Axis model
  47197. * @param {module:echarts/coord/parallel/AxisModel}
  47198. */
  47199. model: null,
  47200. /**
  47201. * @override
  47202. */
  47203. isHorizontal: function () {
  47204. return this.coordinateSystem.getModel().get('layout') !== 'horizontal';
  47205. }
  47206. };
  47207. inherits(ParallelAxis, Axis);
  47208. /*
  47209. * Licensed to the Apache Software Foundation (ASF) under one
  47210. * or more contributor license agreements. See the NOTICE file
  47211. * distributed with this work for additional information
  47212. * regarding copyright ownership. The ASF licenses this file
  47213. * to you under the Apache License, Version 2.0 (the
  47214. * "License"); you may not use this file except in compliance
  47215. * with the License. You may obtain a copy of the License at
  47216. *
  47217. * http://www.apache.org/licenses/LICENSE-2.0
  47218. *
  47219. * Unless required by applicable law or agreed to in writing,
  47220. * software distributed under the License is distributed on an
  47221. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47222. * KIND, either express or implied. See the License for the
  47223. * specific language governing permissions and limitations
  47224. * under the License.
  47225. */
  47226. /**
  47227. * Calculate slider move result.
  47228. * Usage:
  47229. * (1) If both handle0 and handle1 are needed to be moved, set minSpan the same as
  47230. * maxSpan and the same as `Math.abs(handleEnd[1] - handleEnds[0])`.
  47231. * (2) If handle0 is forbidden to cross handle1, set minSpan as `0`.
  47232. *
  47233. * @param {number} delta Move length.
  47234. * @param {Array.<number>} handleEnds handleEnds[0] can be bigger then handleEnds[1].
  47235. * handleEnds will be modified in this method.
  47236. * @param {Array.<number>} extent handleEnds is restricted by extent.
  47237. * extent[0] should less or equals than extent[1].
  47238. * @param {number|string} handleIndex Can be 'all', means that both move the two handleEnds,
  47239. * where the input minSpan and maxSpan will not work.
  47240. * @param {number} [minSpan] The range of dataZoom can not be smaller than that.
  47241. * If not set, handle0 and cross handle1. If set as a non-negative
  47242. * number (including `0`), handles will push each other when reaching
  47243. * the minSpan.
  47244. * @param {number} [maxSpan] The range of dataZoom can not be larger than that.
  47245. * @return {Array.<number>} The input handleEnds.
  47246. */
  47247. var sliderMove = function (delta, handleEnds, extent, handleIndex, minSpan, maxSpan) {
  47248. // Normalize firstly.
  47249. handleEnds[0] = restrict$1(handleEnds[0], extent);
  47250. handleEnds[1] = restrict$1(handleEnds[1], extent);
  47251. delta = delta || 0;
  47252. var extentSpan = extent[1] - extent[0];
  47253. // Notice maxSpan and minSpan can be null/undefined.
  47254. if (minSpan != null) {
  47255. minSpan = restrict$1(minSpan, [0, extentSpan]);
  47256. }
  47257. if (maxSpan != null) {
  47258. maxSpan = Math.max(maxSpan, minSpan != null ? minSpan : 0);
  47259. }
  47260. if (handleIndex === 'all') {
  47261. minSpan = maxSpan = Math.abs(handleEnds[1] - handleEnds[0]);
  47262. handleIndex = 0;
  47263. }
  47264. var originalDistSign = getSpanSign(handleEnds, handleIndex);
  47265. handleEnds[handleIndex] += delta;
  47266. // Restrict in extent.
  47267. var extentMinSpan = minSpan || 0;
  47268. var realExtent = extent.slice();
  47269. originalDistSign.sign < 0 ? (realExtent[0] += extentMinSpan) : (realExtent[1] -= extentMinSpan);
  47270. handleEnds[handleIndex] = restrict$1(handleEnds[handleIndex], realExtent);
  47271. // Expand span.
  47272. var currDistSign = getSpanSign(handleEnds, handleIndex);
  47273. if (minSpan != null && (
  47274. currDistSign.sign !== originalDistSign.sign || currDistSign.span < minSpan
  47275. )) {
  47276. // If minSpan exists, 'cross' is forbinden.
  47277. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + originalDistSign.sign * minSpan;
  47278. }
  47279. // Shrink span.
  47280. var currDistSign = getSpanSign(handleEnds, handleIndex);
  47281. if (maxSpan != null && currDistSign.span > maxSpan) {
  47282. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + currDistSign.sign * maxSpan;
  47283. }
  47284. return handleEnds;
  47285. };
  47286. function getSpanSign(handleEnds, handleIndex) {
  47287. var dist = handleEnds[handleIndex] - handleEnds[1 - handleIndex];
  47288. // If `handleEnds[0] === handleEnds[1]`, always believe that handleEnd[0]
  47289. // is at left of handleEnds[1] for non-cross case.
  47290. return {span: Math.abs(dist), sign: dist > 0 ? -1 : dist < 0 ? 1 : handleIndex ? -1 : 1};
  47291. }
  47292. function restrict$1(value, extend) {
  47293. return Math.min(extend[1], Math.max(extend[0], value));
  47294. }
  47295. /*
  47296. * Licensed to the Apache Software Foundation (ASF) under one
  47297. * or more contributor license agreements. See the NOTICE file
  47298. * distributed with this work for additional information
  47299. * regarding copyright ownership. The ASF licenses this file
  47300. * to you under the Apache License, Version 2.0 (the
  47301. * "License"); you may not use this file except in compliance
  47302. * with the License. You may obtain a copy of the License at
  47303. *
  47304. * http://www.apache.org/licenses/LICENSE-2.0
  47305. *
  47306. * Unless required by applicable law or agreed to in writing,
  47307. * software distributed under the License is distributed on an
  47308. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47309. * KIND, either express or implied. See the License for the
  47310. * specific language governing permissions and limitations
  47311. * under the License.
  47312. */
  47313. /**
  47314. * Parallel Coordinates
  47315. * <https://en.wikipedia.org/wiki/Parallel_coordinates>
  47316. */
  47317. var each$11 = each$1;
  47318. var mathMin$5 = Math.min;
  47319. var mathMax$5 = Math.max;
  47320. var mathFloor$2 = Math.floor;
  47321. var mathCeil$2 = Math.ceil;
  47322. var round$2 = round$1;
  47323. var PI$3 = Math.PI;
  47324. function Parallel(parallelModel, ecModel, api) {
  47325. /**
  47326. * key: dimension
  47327. * @type {Object.<string, module:echarts/coord/parallel/Axis>}
  47328. * @private
  47329. */
  47330. this._axesMap = createHashMap();
  47331. /**
  47332. * key: dimension
  47333. * value: {position: [], rotation, }
  47334. * @type {Object.<string, Object>}
  47335. * @private
  47336. */
  47337. this._axesLayout = {};
  47338. /**
  47339. * Always follow axis order.
  47340. * @type {Array.<string>}
  47341. * @readOnly
  47342. */
  47343. this.dimensions = parallelModel.dimensions;
  47344. /**
  47345. * @type {module:zrender/core/BoundingRect}
  47346. */
  47347. this._rect;
  47348. /**
  47349. * @type {module:echarts/coord/parallel/ParallelModel}
  47350. */
  47351. this._model = parallelModel;
  47352. this._init(parallelModel, ecModel, api);
  47353. }
  47354. Parallel.prototype = {
  47355. type: 'parallel',
  47356. constructor: Parallel,
  47357. /**
  47358. * Initialize cartesian coordinate systems
  47359. * @private
  47360. */
  47361. _init: function (parallelModel, ecModel, api) {
  47362. var dimensions = parallelModel.dimensions;
  47363. var parallelAxisIndex = parallelModel.parallelAxisIndex;
  47364. each$11(dimensions, function (dim, idx) {
  47365. var axisIndex = parallelAxisIndex[idx];
  47366. var axisModel = ecModel.getComponent('parallelAxis', axisIndex);
  47367. var axis = this._axesMap.set(dim, new ParallelAxis(
  47368. dim,
  47369. createScaleByModel(axisModel),
  47370. [0, 0],
  47371. axisModel.get('type'),
  47372. axisIndex
  47373. ));
  47374. var isCategory = axis.type === 'category';
  47375. axis.onBand = isCategory && axisModel.get('boundaryGap');
  47376. axis.inverse = axisModel.get('inverse');
  47377. // Injection
  47378. axisModel.axis = axis;
  47379. axis.model = axisModel;
  47380. axis.coordinateSystem = axisModel.coordinateSystem = this;
  47381. }, this);
  47382. },
  47383. /**
  47384. * Update axis scale after data processed
  47385. * @param {module:echarts/model/Global} ecModel
  47386. * @param {module:echarts/ExtensionAPI} api
  47387. */
  47388. update: function (ecModel, api) {
  47389. this._updateAxesFromSeries(this._model, ecModel);
  47390. },
  47391. /**
  47392. * @override
  47393. */
  47394. containPoint: function (point) {
  47395. var layoutInfo = this._makeLayoutInfo();
  47396. var axisBase = layoutInfo.axisBase;
  47397. var layoutBase = layoutInfo.layoutBase;
  47398. var pixelDimIndex = layoutInfo.pixelDimIndex;
  47399. var pAxis = point[1 - pixelDimIndex];
  47400. var pLayout = point[pixelDimIndex];
  47401. return pAxis >= axisBase
  47402. && pAxis <= axisBase + layoutInfo.axisLength
  47403. && pLayout >= layoutBase
  47404. && pLayout <= layoutBase + layoutInfo.layoutLength;
  47405. },
  47406. getModel: function () {
  47407. return this._model;
  47408. },
  47409. /**
  47410. * Update properties from series
  47411. * @private
  47412. */
  47413. _updateAxesFromSeries: function (parallelModel, ecModel) {
  47414. ecModel.eachSeries(function (seriesModel) {
  47415. if (!parallelModel.contains(seriesModel, ecModel)) {
  47416. return;
  47417. }
  47418. var data = seriesModel.getData();
  47419. each$11(this.dimensions, function (dim) {
  47420. var axis = this._axesMap.get(dim);
  47421. axis.scale.unionExtentFromData(data, data.mapDimension(dim));
  47422. niceScaleExtent(axis.scale, axis.model);
  47423. }, this);
  47424. }, this);
  47425. },
  47426. /**
  47427. * Resize the parallel coordinate system.
  47428. * @param {module:echarts/coord/parallel/ParallelModel} parallelModel
  47429. * @param {module:echarts/ExtensionAPI} api
  47430. */
  47431. resize: function (parallelModel, api) {
  47432. this._rect = getLayoutRect(
  47433. parallelModel.getBoxLayoutParams(),
  47434. {
  47435. width: api.getWidth(),
  47436. height: api.getHeight()
  47437. }
  47438. );
  47439. this._layoutAxes();
  47440. },
  47441. /**
  47442. * @return {module:zrender/core/BoundingRect}
  47443. */
  47444. getRect: function () {
  47445. return this._rect;
  47446. },
  47447. /**
  47448. * @private
  47449. */
  47450. _makeLayoutInfo: function () {
  47451. var parallelModel = this._model;
  47452. var rect = this._rect;
  47453. var xy = ['x', 'y'];
  47454. var wh = ['width', 'height'];
  47455. var layout = parallelModel.get('layout');
  47456. var pixelDimIndex = layout === 'horizontal' ? 0 : 1;
  47457. var layoutLength = rect[wh[pixelDimIndex]];
  47458. var layoutExtent = [0, layoutLength];
  47459. var axisCount = this.dimensions.length;
  47460. var axisExpandWidth = restrict(parallelModel.get('axisExpandWidth'), layoutExtent);
  47461. var axisExpandCount = restrict(parallelModel.get('axisExpandCount') || 0, [0, axisCount]);
  47462. var axisExpandable = parallelModel.get('axisExpandable')
  47463. && axisCount > 3
  47464. && axisCount > axisExpandCount
  47465. && axisExpandCount > 1
  47466. && axisExpandWidth > 0
  47467. && layoutLength > 0;
  47468. // `axisExpandWindow` is According to the coordinates of [0, axisExpandLength],
  47469. // for sake of consider the case that axisCollapseWidth is 0 (when screen is narrow),
  47470. // where collapsed axes should be overlapped.
  47471. var axisExpandWindow = parallelModel.get('axisExpandWindow');
  47472. var winSize;
  47473. if (!axisExpandWindow) {
  47474. winSize = restrict(axisExpandWidth * (axisExpandCount - 1), layoutExtent);
  47475. var axisExpandCenter = parallelModel.get('axisExpandCenter') || mathFloor$2(axisCount / 2);
  47476. axisExpandWindow = [axisExpandWidth * axisExpandCenter - winSize / 2];
  47477. axisExpandWindow[1] = axisExpandWindow[0] + winSize;
  47478. }
  47479. else {
  47480. winSize = restrict(axisExpandWindow[1] - axisExpandWindow[0], layoutExtent);
  47481. axisExpandWindow[1] = axisExpandWindow[0] + winSize;
  47482. }
  47483. var axisCollapseWidth = (layoutLength - winSize) / (axisCount - axisExpandCount);
  47484. // Avoid axisCollapseWidth is too small.
  47485. axisCollapseWidth < 3 && (axisCollapseWidth = 0);
  47486. // Find the first and last indices > ewin[0] and < ewin[1].
  47487. var winInnerIndices = [
  47488. mathFloor$2(round$2(axisExpandWindow[0] / axisExpandWidth, 1)) + 1,
  47489. mathCeil$2(round$2(axisExpandWindow[1] / axisExpandWidth, 1)) - 1
  47490. ];
  47491. // Pos in ec coordinates.
  47492. var axisExpandWindow0Pos = axisCollapseWidth / axisExpandWidth * axisExpandWindow[0];
  47493. return {
  47494. layout: layout,
  47495. pixelDimIndex: pixelDimIndex,
  47496. layoutBase: rect[xy[pixelDimIndex]],
  47497. layoutLength: layoutLength,
  47498. axisBase: rect[xy[1 - pixelDimIndex]],
  47499. axisLength: rect[wh[1 - pixelDimIndex]],
  47500. axisExpandable: axisExpandable,
  47501. axisExpandWidth: axisExpandWidth,
  47502. axisCollapseWidth: axisCollapseWidth,
  47503. axisExpandWindow: axisExpandWindow,
  47504. axisCount: axisCount,
  47505. winInnerIndices: winInnerIndices,
  47506. axisExpandWindow0Pos: axisExpandWindow0Pos
  47507. };
  47508. },
  47509. /**
  47510. * @private
  47511. */
  47512. _layoutAxes: function () {
  47513. var rect = this._rect;
  47514. var axes = this._axesMap;
  47515. var dimensions = this.dimensions;
  47516. var layoutInfo = this._makeLayoutInfo();
  47517. var layout = layoutInfo.layout;
  47518. axes.each(function (axis) {
  47519. var axisExtent = [0, layoutInfo.axisLength];
  47520. var idx = axis.inverse ? 1 : 0;
  47521. axis.setExtent(axisExtent[idx], axisExtent[1 - idx]);
  47522. });
  47523. each$11(dimensions, function (dim, idx) {
  47524. var posInfo = (layoutInfo.axisExpandable
  47525. ? layoutAxisWithExpand : layoutAxisWithoutExpand
  47526. )(idx, layoutInfo);
  47527. var positionTable = {
  47528. horizontal: {
  47529. x: posInfo.position,
  47530. y: layoutInfo.axisLength
  47531. },
  47532. vertical: {
  47533. x: 0,
  47534. y: posInfo.position
  47535. }
  47536. };
  47537. var rotationTable = {
  47538. horizontal: PI$3 / 2,
  47539. vertical: 0
  47540. };
  47541. var position = [
  47542. positionTable[layout].x + rect.x,
  47543. positionTable[layout].y + rect.y
  47544. ];
  47545. var rotation = rotationTable[layout];
  47546. var transform = create$1();
  47547. rotate(transform, transform, rotation);
  47548. translate(transform, transform, position);
  47549. // TODO
  47550. // tick等排布信息。
  47551. // TODO
  47552. // 根据axis order 更新 dimensions顺序。
  47553. this._axesLayout[dim] = {
  47554. position: position,
  47555. rotation: rotation,
  47556. transform: transform,
  47557. axisNameAvailableWidth: posInfo.axisNameAvailableWidth,
  47558. axisLabelShow: posInfo.axisLabelShow,
  47559. nameTruncateMaxWidth: posInfo.nameTruncateMaxWidth,
  47560. tickDirection: 1,
  47561. labelDirection: 1
  47562. };
  47563. }, this);
  47564. },
  47565. /**
  47566. * Get axis by dim.
  47567. * @param {string} dim
  47568. * @return {module:echarts/coord/parallel/ParallelAxis} [description]
  47569. */
  47570. getAxis: function (dim) {
  47571. return this._axesMap.get(dim);
  47572. },
  47573. /**
  47574. * Convert a dim value of a single item of series data to Point.
  47575. * @param {*} value
  47576. * @param {string} dim
  47577. * @return {Array}
  47578. */
  47579. dataToPoint: function (value, dim) {
  47580. return this.axisCoordToPoint(
  47581. this._axesMap.get(dim).dataToCoord(value),
  47582. dim
  47583. );
  47584. },
  47585. /**
  47586. * Travel data for one time, get activeState of each data item.
  47587. * @param {module:echarts/data/List} data
  47588. * @param {Functio} cb param: {string} activeState 'active' or 'inactive' or 'normal'
  47589. * {number} dataIndex
  47590. * @param {number} [start=0] the start dataIndex that travel from.
  47591. * @param {number} [end=data.count()] the next dataIndex of the last dataIndex will be travel.
  47592. */
  47593. eachActiveState: function (data, callback, start, end) {
  47594. start == null && (start = 0);
  47595. end == null && (end = data.count());
  47596. var axesMap = this._axesMap;
  47597. var dimensions = this.dimensions;
  47598. var dataDimensions = [];
  47599. var axisModels = [];
  47600. each$1(dimensions, function (axisDim) {
  47601. dataDimensions.push(data.mapDimension(axisDim));
  47602. axisModels.push(axesMap.get(axisDim).model);
  47603. });
  47604. var hasActiveSet = this.hasAxisBrushed();
  47605. for (var dataIndex = start; dataIndex < end; dataIndex++) {
  47606. var activeState;
  47607. if (!hasActiveSet) {
  47608. activeState = 'normal';
  47609. }
  47610. else {
  47611. activeState = 'active';
  47612. var values = data.getValues(dataDimensions, dataIndex);
  47613. for (var j = 0, lenj = dimensions.length; j < lenj; j++) {
  47614. var state = axisModels[j].getActiveState(values[j]);
  47615. if (state === 'inactive') {
  47616. activeState = 'inactive';
  47617. break;
  47618. }
  47619. }
  47620. }
  47621. callback(activeState, dataIndex);
  47622. }
  47623. },
  47624. /**
  47625. * Whether has any activeSet.
  47626. * @return {boolean}
  47627. */
  47628. hasAxisBrushed: function () {
  47629. var dimensions = this.dimensions;
  47630. var axesMap = this._axesMap;
  47631. var hasActiveSet = false;
  47632. for (var j = 0, lenj = dimensions.length; j < lenj; j++) {
  47633. if (axesMap.get(dimensions[j]).model.getActiveState() !== 'normal') {
  47634. hasActiveSet = true;
  47635. }
  47636. }
  47637. return hasActiveSet;
  47638. },
  47639. /**
  47640. * Convert coords of each axis to Point.
  47641. * Return point. For example: [10, 20]
  47642. * @param {Array.<number>} coords
  47643. * @param {string} dim
  47644. * @return {Array.<number>}
  47645. */
  47646. axisCoordToPoint: function (coord, dim) {
  47647. var axisLayout = this._axesLayout[dim];
  47648. return applyTransform$1([coord, 0], axisLayout.transform);
  47649. },
  47650. /**
  47651. * Get axis layout.
  47652. */
  47653. getAxisLayout: function (dim) {
  47654. return clone(this._axesLayout[dim]);
  47655. },
  47656. /**
  47657. * @param {Array.<number>} point
  47658. * @return {Object} {axisExpandWindow, delta, behavior: 'jump' | 'slide' | 'none'}.
  47659. */
  47660. getSlidedAxisExpandWindow: function (point) {
  47661. var layoutInfo = this._makeLayoutInfo();
  47662. var pixelDimIndex = layoutInfo.pixelDimIndex;
  47663. var axisExpandWindow = layoutInfo.axisExpandWindow.slice();
  47664. var winSize = axisExpandWindow[1] - axisExpandWindow[0];
  47665. var extent = [0, layoutInfo.axisExpandWidth * (layoutInfo.axisCount - 1)];
  47666. // Out of the area of coordinate system.
  47667. if (!this.containPoint(point)) {
  47668. return {behavior: 'none', axisExpandWindow: axisExpandWindow};
  47669. }
  47670. // Conver the point from global to expand coordinates.
  47671. var pointCoord = point[pixelDimIndex] - layoutInfo.layoutBase - layoutInfo.axisExpandWindow0Pos;
  47672. // For dragging operation convenience, the window should not be
  47673. // slided when mouse is the center area of the window.
  47674. var delta;
  47675. var behavior = 'slide';
  47676. var axisCollapseWidth = layoutInfo.axisCollapseWidth;
  47677. var triggerArea = this._model.get('axisExpandSlideTriggerArea');
  47678. // But consider touch device, jump is necessary.
  47679. var useJump = triggerArea[0] != null;
  47680. if (axisCollapseWidth) {
  47681. if (useJump && axisCollapseWidth && pointCoord < winSize * triggerArea[0]) {
  47682. behavior = 'jump';
  47683. delta = pointCoord - winSize * triggerArea[2];
  47684. }
  47685. else if (useJump && axisCollapseWidth && pointCoord > winSize * (1 - triggerArea[0])) {
  47686. behavior = 'jump';
  47687. delta = pointCoord - winSize * (1 - triggerArea[2]);
  47688. }
  47689. else {
  47690. (delta = pointCoord - winSize * triggerArea[1]) >= 0
  47691. && (delta = pointCoord - winSize * (1 - triggerArea[1])) <= 0
  47692. && (delta = 0);
  47693. }
  47694. delta *= layoutInfo.axisExpandWidth / axisCollapseWidth;
  47695. delta
  47696. ? sliderMove(delta, axisExpandWindow, extent, 'all')
  47697. // Avoid nonsense triger on mousemove.
  47698. : (behavior = 'none');
  47699. }
  47700. // When screen is too narrow, make it visible and slidable, although it is hard to interact.
  47701. else {
  47702. var winSize = axisExpandWindow[1] - axisExpandWindow[0];
  47703. var pos = extent[1] * pointCoord / winSize;
  47704. axisExpandWindow = [mathMax$5(0, pos - winSize / 2)];
  47705. axisExpandWindow[1] = mathMin$5(extent[1], axisExpandWindow[0] + winSize);
  47706. axisExpandWindow[0] = axisExpandWindow[1] - winSize;
  47707. }
  47708. return {
  47709. axisExpandWindow: axisExpandWindow,
  47710. behavior: behavior
  47711. };
  47712. }
  47713. };
  47714. function restrict(len, extent) {
  47715. return mathMin$5(mathMax$5(len, extent[0]), extent[1]);
  47716. }
  47717. function layoutAxisWithoutExpand(axisIndex, layoutInfo) {
  47718. var step = layoutInfo.layoutLength / (layoutInfo.axisCount - 1);
  47719. return {
  47720. position: step * axisIndex,
  47721. axisNameAvailableWidth: step,
  47722. axisLabelShow: true
  47723. };
  47724. }
  47725. function layoutAxisWithExpand(axisIndex, layoutInfo) {
  47726. var layoutLength = layoutInfo.layoutLength;
  47727. var axisExpandWidth = layoutInfo.axisExpandWidth;
  47728. var axisCount = layoutInfo.axisCount;
  47729. var axisCollapseWidth = layoutInfo.axisCollapseWidth;
  47730. var winInnerIndices = layoutInfo.winInnerIndices;
  47731. var position;
  47732. var axisNameAvailableWidth = axisCollapseWidth;
  47733. var axisLabelShow = false;
  47734. var nameTruncateMaxWidth;
  47735. if (axisIndex < winInnerIndices[0]) {
  47736. position = axisIndex * axisCollapseWidth;
  47737. nameTruncateMaxWidth = axisCollapseWidth;
  47738. }
  47739. else if (axisIndex <= winInnerIndices[1]) {
  47740. position = layoutInfo.axisExpandWindow0Pos
  47741. + axisIndex * axisExpandWidth - layoutInfo.axisExpandWindow[0];
  47742. axisNameAvailableWidth = axisExpandWidth;
  47743. axisLabelShow = true;
  47744. }
  47745. else {
  47746. position = layoutLength - (axisCount - 1 - axisIndex) * axisCollapseWidth;
  47747. nameTruncateMaxWidth = axisCollapseWidth;
  47748. }
  47749. return {
  47750. position: position,
  47751. axisNameAvailableWidth: axisNameAvailableWidth,
  47752. axisLabelShow: axisLabelShow,
  47753. nameTruncateMaxWidth: nameTruncateMaxWidth
  47754. };
  47755. }
  47756. /*
  47757. * Licensed to the Apache Software Foundation (ASF) under one
  47758. * or more contributor license agreements. See the NOTICE file
  47759. * distributed with this work for additional information
  47760. * regarding copyright ownership. The ASF licenses this file
  47761. * to you under the Apache License, Version 2.0 (the
  47762. * "License"); you may not use this file except in compliance
  47763. * with the License. You may obtain a copy of the License at
  47764. *
  47765. * http://www.apache.org/licenses/LICENSE-2.0
  47766. *
  47767. * Unless required by applicable law or agreed to in writing,
  47768. * software distributed under the License is distributed on an
  47769. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47770. * KIND, either express or implied. See the License for the
  47771. * specific language governing permissions and limitations
  47772. * under the License.
  47773. */
  47774. /**
  47775. * Parallel coordinate system creater.
  47776. */
  47777. function create$2(ecModel, api) {
  47778. var coordSysList = [];
  47779. ecModel.eachComponent('parallel', function (parallelModel, idx) {
  47780. var coordSys = new Parallel(parallelModel, ecModel, api);
  47781. coordSys.name = 'parallel_' + idx;
  47782. coordSys.resize(parallelModel, api);
  47783. parallelModel.coordinateSystem = coordSys;
  47784. coordSys.model = parallelModel;
  47785. coordSysList.push(coordSys);
  47786. });
  47787. // Inject the coordinateSystems into seriesModel
  47788. ecModel.eachSeries(function (seriesModel) {
  47789. if (seriesModel.get('coordinateSystem') === 'parallel') {
  47790. var parallelModel = ecModel.queryComponents({
  47791. mainType: 'parallel',
  47792. index: seriesModel.get('parallelIndex'),
  47793. id: seriesModel.get('parallelId')
  47794. })[0];
  47795. seriesModel.coordinateSystem = parallelModel.coordinateSystem;
  47796. }
  47797. });
  47798. return coordSysList;
  47799. }
  47800. CoordinateSystemManager.register('parallel', {create: create$2});
  47801. /*
  47802. * Licensed to the Apache Software Foundation (ASF) under one
  47803. * or more contributor license agreements. See the NOTICE file
  47804. * distributed with this work for additional information
  47805. * regarding copyright ownership. The ASF licenses this file
  47806. * to you under the Apache License, Version 2.0 (the
  47807. * "License"); you may not use this file except in compliance
  47808. * with the License. You may obtain a copy of the License at
  47809. *
  47810. * http://www.apache.org/licenses/LICENSE-2.0
  47811. *
  47812. * Unless required by applicable law or agreed to in writing,
  47813. * software distributed under the License is distributed on an
  47814. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47815. * KIND, either express or implied. See the License for the
  47816. * specific language governing permissions and limitations
  47817. * under the License.
  47818. */
  47819. var AxisModel$2 = ComponentModel.extend({
  47820. type: 'baseParallelAxis',
  47821. /**
  47822. * @type {module:echarts/coord/parallel/Axis}
  47823. */
  47824. axis: null,
  47825. /**
  47826. * @type {Array.<Array.<number>}
  47827. * @readOnly
  47828. */
  47829. activeIntervals: [],
  47830. /**
  47831. * @return {Object}
  47832. */
  47833. getAreaSelectStyle: function () {
  47834. return makeStyleMapper(
  47835. [
  47836. ['fill', 'color'],
  47837. ['lineWidth', 'borderWidth'],
  47838. ['stroke', 'borderColor'],
  47839. ['width', 'width'],
  47840. ['opacity', 'opacity']
  47841. ]
  47842. )(this.getModel('areaSelectStyle'));
  47843. },
  47844. /**
  47845. * The code of this feature is put on AxisModel but not ParallelAxis,
  47846. * because axisModel can be alive after echarts updating but instance of
  47847. * ParallelAxis having been disposed. this._activeInterval should be kept
  47848. * when action dispatched (i.e. legend click).
  47849. *
  47850. * @param {Array.<Array<number>>} intervals interval.length === 0
  47851. * means set all active.
  47852. * @public
  47853. */
  47854. setActiveIntervals: function (intervals) {
  47855. var activeIntervals = this.activeIntervals = clone(intervals);
  47856. // Normalize
  47857. if (activeIntervals) {
  47858. for (var i = activeIntervals.length - 1; i >= 0; i--) {
  47859. asc(activeIntervals[i]);
  47860. }
  47861. }
  47862. },
  47863. /**
  47864. * @param {number|string} [value] When attempting to detect 'no activeIntervals set',
  47865. * value can not be input.
  47866. * @return {string} 'normal': no activeIntervals set,
  47867. * 'active',
  47868. * 'inactive'.
  47869. * @public
  47870. */
  47871. getActiveState: function (value) {
  47872. var activeIntervals = this.activeIntervals;
  47873. if (!activeIntervals.length) {
  47874. return 'normal';
  47875. }
  47876. if (value == null || isNaN(value)) {
  47877. return 'inactive';
  47878. }
  47879. // Simple optimization
  47880. if (activeIntervals.length === 1) {
  47881. var interval = activeIntervals[0];
  47882. if (interval[0] <= value && value <= interval[1]) {
  47883. return 'active';
  47884. }
  47885. }
  47886. else {
  47887. for (var i = 0, len = activeIntervals.length; i < len; i++) {
  47888. if (activeIntervals[i][0] <= value && value <= activeIntervals[i][1]) {
  47889. return 'active';
  47890. }
  47891. }
  47892. }
  47893. return 'inactive';
  47894. }
  47895. });
  47896. var defaultOption$1 = {
  47897. type: 'value',
  47898. /**
  47899. * @type {Array.<number>}
  47900. */
  47901. dim: null, // 0, 1, 2, ...
  47902. // parallelIndex: null,
  47903. areaSelectStyle: {
  47904. width: 20,
  47905. borderWidth: 1,
  47906. borderColor: 'rgba(160,197,232)',
  47907. color: 'rgba(160,197,232)',
  47908. opacity: 0.3
  47909. },
  47910. realtime: true, // Whether realtime update view when select.
  47911. z: 10
  47912. };
  47913. merge(AxisModel$2.prototype, axisModelCommonMixin);
  47914. function getAxisType$1(axisName, option) {
  47915. return option.type || (option.data ? 'category' : 'value');
  47916. }
  47917. axisModelCreator('parallel', AxisModel$2, getAxisType$1, defaultOption$1);
  47918. /*
  47919. * Licensed to the Apache Software Foundation (ASF) under one
  47920. * or more contributor license agreements. See the NOTICE file
  47921. * distributed with this work for additional information
  47922. * regarding copyright ownership. The ASF licenses this file
  47923. * to you under the Apache License, Version 2.0 (the
  47924. * "License"); you may not use this file except in compliance
  47925. * with the License. You may obtain a copy of the License at
  47926. *
  47927. * http://www.apache.org/licenses/LICENSE-2.0
  47928. *
  47929. * Unless required by applicable law or agreed to in writing,
  47930. * software distributed under the License is distributed on an
  47931. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47932. * KIND, either express or implied. See the License for the
  47933. * specific language governing permissions and limitations
  47934. * under the License.
  47935. */
  47936. ComponentModel.extend({
  47937. type: 'parallel',
  47938. dependencies: ['parallelAxis'],
  47939. /**
  47940. * @type {module:echarts/coord/parallel/Parallel}
  47941. */
  47942. coordinateSystem: null,
  47943. /**
  47944. * Each item like: 'dim0', 'dim1', 'dim2', ...
  47945. * @type {Array.<string>}
  47946. * @readOnly
  47947. */
  47948. dimensions: null,
  47949. /**
  47950. * Coresponding to dimensions.
  47951. * @type {Array.<number>}
  47952. * @readOnly
  47953. */
  47954. parallelAxisIndex: null,
  47955. layoutMode: 'box',
  47956. defaultOption: {
  47957. zlevel: 0,
  47958. z: 0,
  47959. left: 80,
  47960. top: 60,
  47961. right: 80,
  47962. bottom: 60,
  47963. // width: {totalWidth} - left - right,
  47964. // height: {totalHeight} - top - bottom,
  47965. layout: 'horizontal', // 'horizontal' or 'vertical'
  47966. // FIXME
  47967. // naming?
  47968. axisExpandable: false,
  47969. axisExpandCenter: null,
  47970. axisExpandCount: 0,
  47971. axisExpandWidth: 50, // FIXME '10%' ?
  47972. axisExpandRate: 17,
  47973. axisExpandDebounce: 50,
  47974. // [out, in, jumpTarget]. In percentage. If use [null, 0.05], null means full.
  47975. // Do not doc to user until necessary.
  47976. axisExpandSlideTriggerArea: [-0.15, 0.05, 0.4],
  47977. axisExpandTriggerOn: 'click', // 'mousemove' or 'click'
  47978. parallelAxisDefault: null
  47979. },
  47980. /**
  47981. * @override
  47982. */
  47983. init: function () {
  47984. ComponentModel.prototype.init.apply(this, arguments);
  47985. this.mergeOption({});
  47986. },
  47987. /**
  47988. * @override
  47989. */
  47990. mergeOption: function (newOption) {
  47991. var thisOption = this.option;
  47992. newOption && merge(thisOption, newOption, true);
  47993. this._initDimensions();
  47994. },
  47995. /**
  47996. * Whether series or axis is in this coordinate system.
  47997. * @param {module:echarts/model/Series|module:echarts/coord/parallel/AxisModel} model
  47998. * @param {module:echarts/model/Global} ecModel
  47999. */
  48000. contains: function (model, ecModel) {
  48001. var parallelIndex = model.get('parallelIndex');
  48002. return parallelIndex != null
  48003. && ecModel.getComponent('parallel', parallelIndex) === this;
  48004. },
  48005. setAxisExpand: function (opt) {
  48006. each$1(
  48007. ['axisExpandable', 'axisExpandCenter', 'axisExpandCount', 'axisExpandWidth', 'axisExpandWindow'],
  48008. function (name) {
  48009. if (opt.hasOwnProperty(name)) {
  48010. this.option[name] = opt[name];
  48011. }
  48012. },
  48013. this
  48014. );
  48015. },
  48016. /**
  48017. * @private
  48018. */
  48019. _initDimensions: function () {
  48020. var dimensions = this.dimensions = [];
  48021. var parallelAxisIndex = this.parallelAxisIndex = [];
  48022. var axisModels = filter(this.dependentModels.parallelAxis, function (axisModel) {
  48023. // Can not use this.contains here, because
  48024. // initialization has not been completed yet.
  48025. return (axisModel.get('parallelIndex') || 0) === this.componentIndex;
  48026. }, this);
  48027. each$1(axisModels, function (axisModel) {
  48028. dimensions.push('dim' + axisModel.get('dim'));
  48029. parallelAxisIndex.push(axisModel.componentIndex);
  48030. });
  48031. }
  48032. });
  48033. /*
  48034. * Licensed to the Apache Software Foundation (ASF) under one
  48035. * or more contributor license agreements. See the NOTICE file
  48036. * distributed with this work for additional information
  48037. * regarding copyright ownership. The ASF licenses this file
  48038. * to you under the Apache License, Version 2.0 (the
  48039. * "License"); you may not use this file except in compliance
  48040. * with the License. You may obtain a copy of the License at
  48041. *
  48042. * http://www.apache.org/licenses/LICENSE-2.0
  48043. *
  48044. * Unless required by applicable law or agreed to in writing,
  48045. * software distributed under the License is distributed on an
  48046. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48047. * KIND, either express or implied. See the License for the
  48048. * specific language governing permissions and limitations
  48049. * under the License.
  48050. */
  48051. /**
  48052. * @payload
  48053. * @property {string} parallelAxisId
  48054. * @property {Array.<Array.<number>>} intervals
  48055. */
  48056. var actionInfo$1 = {
  48057. type: 'axisAreaSelect',
  48058. event: 'axisAreaSelected'
  48059. // update: 'updateVisual'
  48060. };
  48061. registerAction(actionInfo$1, function (payload, ecModel) {
  48062. ecModel.eachComponent(
  48063. {mainType: 'parallelAxis', query: payload},
  48064. function (parallelAxisModel) {
  48065. parallelAxisModel.axis.model.setActiveIntervals(payload.intervals);
  48066. }
  48067. );
  48068. });
  48069. /**
  48070. * @payload
  48071. */
  48072. registerAction('parallelAxisExpand', function (payload, ecModel) {
  48073. ecModel.eachComponent(
  48074. {mainType: 'parallel', query: payload},
  48075. function (parallelModel) {
  48076. parallelModel.setAxisExpand(payload);
  48077. }
  48078. );
  48079. });
  48080. /*
  48081. * Licensed to the Apache Software Foundation (ASF) under one
  48082. * or more contributor license agreements. See the NOTICE file
  48083. * distributed with this work for additional information
  48084. * regarding copyright ownership. The ASF licenses this file
  48085. * to you under the Apache License, Version 2.0 (the
  48086. * "License"); you may not use this file except in compliance
  48087. * with the License. You may obtain a copy of the License at
  48088. *
  48089. * http://www.apache.org/licenses/LICENSE-2.0
  48090. *
  48091. * Unless required by applicable law or agreed to in writing,
  48092. * software distributed under the License is distributed on an
  48093. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48094. * KIND, either express or implied. See the License for the
  48095. * specific language governing permissions and limitations
  48096. * under the License.
  48097. */
  48098. var curry$2 = curry;
  48099. var each$12 = each$1;
  48100. var map$2 = map;
  48101. var mathMin$6 = Math.min;
  48102. var mathMax$6 = Math.max;
  48103. var mathPow$2 = Math.pow;
  48104. var COVER_Z = 10000;
  48105. var UNSELECT_THRESHOLD = 6;
  48106. var MIN_RESIZE_LINE_WIDTH = 6;
  48107. var MUTEX_RESOURCE_KEY = 'globalPan';
  48108. var DIRECTION_MAP = {
  48109. w: [0, 0],
  48110. e: [0, 1],
  48111. n: [1, 0],
  48112. s: [1, 1]
  48113. };
  48114. var CURSOR_MAP = {
  48115. w: 'ew',
  48116. e: 'ew',
  48117. n: 'ns',
  48118. s: 'ns',
  48119. ne: 'nesw',
  48120. sw: 'nesw',
  48121. nw: 'nwse',
  48122. se: 'nwse'
  48123. };
  48124. var DEFAULT_BRUSH_OPT = {
  48125. brushStyle: {
  48126. lineWidth: 2,
  48127. stroke: 'rgba(0,0,0,0.3)',
  48128. fill: 'rgba(0,0,0,0.1)'
  48129. },
  48130. transformable: true,
  48131. brushMode: 'single',
  48132. removeOnClick: false
  48133. };
  48134. var baseUID = 0;
  48135. /**
  48136. * @alias module:echarts/component/helper/BrushController
  48137. * @constructor
  48138. * @mixin {module:zrender/mixin/Eventful}
  48139. * @event module:echarts/component/helper/BrushController#brush
  48140. * params:
  48141. * areas: Array.<Array>, coord relates to container group,
  48142. * If no container specified, to global.
  48143. * opt {
  48144. * isEnd: boolean,
  48145. * removeOnClick: boolean
  48146. * }
  48147. *
  48148. * @param {module:zrender/zrender~ZRender} zr
  48149. */
  48150. function BrushController(zr) {
  48151. if (__DEV__) {
  48152. assert$1(zr);
  48153. }
  48154. Eventful.call(this);
  48155. /**
  48156. * @type {module:zrender/zrender~ZRender}
  48157. * @private
  48158. */
  48159. this._zr = zr;
  48160. /**
  48161. * @type {module:zrender/container/Group}
  48162. * @readOnly
  48163. */
  48164. this.group = new Group();
  48165. /**
  48166. * Only for drawing (after enabledBrush).
  48167. * 'line', 'rect', 'polygon' or false
  48168. * If passing false/null/undefined, disable brush.
  48169. * If passing 'auto', determined by panel.defaultBrushType
  48170. * @private
  48171. * @type {string}
  48172. */
  48173. this._brushType;
  48174. /**
  48175. * Only for drawing (after enabledBrush).
  48176. *
  48177. * @private
  48178. * @type {Object}
  48179. */
  48180. this._brushOption;
  48181. /**
  48182. * @private
  48183. * @type {Object}
  48184. */
  48185. this._panels;
  48186. /**
  48187. * @private
  48188. * @type {Array.<nubmer>}
  48189. */
  48190. this._track = [];
  48191. /**
  48192. * @private
  48193. * @type {boolean}
  48194. */
  48195. this._dragging;
  48196. /**
  48197. * @private
  48198. * @type {Array}
  48199. */
  48200. this._covers = [];
  48201. /**
  48202. * @private
  48203. * @type {moudule:zrender/container/Group}
  48204. */
  48205. this._creatingCover;
  48206. /**
  48207. * `true` means global panel
  48208. * @private
  48209. * @type {module:zrender/container/Group|boolean}
  48210. */
  48211. this._creatingPanel;
  48212. /**
  48213. * @private
  48214. * @type {boolean}
  48215. */
  48216. this._enableGlobalPan;
  48217. /**
  48218. * @private
  48219. * @type {boolean}
  48220. */
  48221. if (__DEV__) {
  48222. this._mounted;
  48223. }
  48224. /**
  48225. * @private
  48226. * @type {string}
  48227. */
  48228. this._uid = 'brushController_' + baseUID++;
  48229. /**
  48230. * @private
  48231. * @type {Object}
  48232. */
  48233. this._handlers = {};
  48234. each$12(mouseHandlers, function (handler, eventName) {
  48235. this._handlers[eventName] = bind(handler, this);
  48236. }, this);
  48237. }
  48238. BrushController.prototype = {
  48239. constructor: BrushController,
  48240. /**
  48241. * If set to null/undefined/false, select disabled.
  48242. * @param {Object} brushOption
  48243. * @param {string|boolean} brushOption.brushType 'line', 'rect', 'polygon' or false
  48244. * If passing false/null/undefined, disable brush.
  48245. * If passing 'auto', determined by panel.defaultBrushType.
  48246. * ('auto' can not be used in global panel)
  48247. * @param {number} [brushOption.brushMode='single'] 'single' or 'multiple'
  48248. * @param {boolean} [brushOption.transformable=true]
  48249. * @param {boolean} [brushOption.removeOnClick=false]
  48250. * @param {Object} [brushOption.brushStyle]
  48251. * @param {number} [brushOption.brushStyle.width]
  48252. * @param {number} [brushOption.brushStyle.lineWidth]
  48253. * @param {string} [brushOption.brushStyle.stroke]
  48254. * @param {string} [brushOption.brushStyle.fill]
  48255. * @param {number} [brushOption.z]
  48256. */
  48257. enableBrush: function (brushOption) {
  48258. if (__DEV__) {
  48259. assert$1(this._mounted);
  48260. }
  48261. this._brushType && doDisableBrush(this);
  48262. brushOption.brushType && doEnableBrush(this, brushOption);
  48263. return this;
  48264. },
  48265. /**
  48266. * @param {Array.<Object>} panelOpts If not pass, it is global brush.
  48267. * Each items: {
  48268. * panelId, // mandatory.
  48269. * clipPath, // mandatory. function.
  48270. * isTargetByCursor, // mandatory. function.
  48271. * defaultBrushType, // optional, only used when brushType is 'auto'.
  48272. * getLinearBrushOtherExtent, // optional. function.
  48273. * }
  48274. */
  48275. setPanels: function (panelOpts) {
  48276. if (panelOpts && panelOpts.length) {
  48277. var panels = this._panels = {};
  48278. each$1(panelOpts, function (panelOpts) {
  48279. panels[panelOpts.panelId] = clone(panelOpts);
  48280. });
  48281. }
  48282. else {
  48283. this._panels = null;
  48284. }
  48285. return this;
  48286. },
  48287. /**
  48288. * @param {Object} [opt]
  48289. * @return {boolean} [opt.enableGlobalPan=false]
  48290. */
  48291. mount: function (opt) {
  48292. opt = opt || {};
  48293. if (__DEV__) {
  48294. this._mounted = true; // should be at first.
  48295. }
  48296. this._enableGlobalPan = opt.enableGlobalPan;
  48297. var thisGroup = this.group;
  48298. this._zr.add(thisGroup);
  48299. thisGroup.attr({
  48300. position: opt.position || [0, 0],
  48301. rotation: opt.rotation || 0,
  48302. scale: opt.scale || [1, 1]
  48303. });
  48304. this._transform = thisGroup.getLocalTransform();
  48305. return this;
  48306. },
  48307. eachCover: function (cb, context) {
  48308. each$12(this._covers, cb, context);
  48309. },
  48310. /**
  48311. * Update covers.
  48312. * @param {Array.<Object>} brushOptionList Like:
  48313. * [
  48314. * {id: 'xx', brushType: 'line', range: [23, 44], brushStyle, transformable},
  48315. * {id: 'yy', brushType: 'rect', range: [[23, 44], [23, 54]]},
  48316. * ...
  48317. * ]
  48318. * `brushType` is required in each cover info. (can not be 'auto')
  48319. * `id` is not mandatory.
  48320. * `brushStyle`, `transformable` is not mandatory, use DEFAULT_BRUSH_OPT by default.
  48321. * If brushOptionList is null/undefined, all covers removed.
  48322. */
  48323. updateCovers: function (brushOptionList) {
  48324. if (__DEV__) {
  48325. assert$1(this._mounted);
  48326. }
  48327. brushOptionList = map(brushOptionList, function (brushOption) {
  48328. return merge(clone(DEFAULT_BRUSH_OPT), brushOption, true);
  48329. });
  48330. var tmpIdPrefix = '\0-brush-index-';
  48331. var oldCovers = this._covers;
  48332. var newCovers = this._covers = [];
  48333. var controller = this;
  48334. var creatingCover = this._creatingCover;
  48335. (new DataDiffer(oldCovers, brushOptionList, oldGetKey, getKey))
  48336. .add(addOrUpdate)
  48337. .update(addOrUpdate)
  48338. .remove(remove)
  48339. .execute();
  48340. return this;
  48341. function getKey(brushOption, index) {
  48342. return (brushOption.id != null ? brushOption.id : tmpIdPrefix + index)
  48343. + '-' + brushOption.brushType;
  48344. }
  48345. function oldGetKey(cover, index) {
  48346. return getKey(cover.__brushOption, index);
  48347. }
  48348. function addOrUpdate(newIndex, oldIndex) {
  48349. var newBrushOption = brushOptionList[newIndex];
  48350. // Consider setOption in event listener of brushSelect,
  48351. // where updating cover when creating should be forbiden.
  48352. if (oldIndex != null && oldCovers[oldIndex] === creatingCover) {
  48353. newCovers[newIndex] = oldCovers[oldIndex];
  48354. }
  48355. else {
  48356. var cover = newCovers[newIndex] = oldIndex != null
  48357. ? (
  48358. oldCovers[oldIndex].__brushOption = newBrushOption,
  48359. oldCovers[oldIndex]
  48360. )
  48361. : endCreating(controller, createCover(controller, newBrushOption));
  48362. updateCoverAfterCreation(controller, cover);
  48363. }
  48364. }
  48365. function remove(oldIndex) {
  48366. if (oldCovers[oldIndex] !== creatingCover) {
  48367. controller.group.remove(oldCovers[oldIndex]);
  48368. }
  48369. }
  48370. },
  48371. unmount: function () {
  48372. if (__DEV__) {
  48373. if (!this._mounted) {
  48374. return;
  48375. }
  48376. }
  48377. this.enableBrush(false);
  48378. // container may 'removeAll' outside.
  48379. clearCovers(this);
  48380. this._zr.remove(this.group);
  48381. if (__DEV__) {
  48382. this._mounted = false; // should be at last.
  48383. }
  48384. return this;
  48385. },
  48386. dispose: function () {
  48387. this.unmount();
  48388. this.off();
  48389. }
  48390. };
  48391. mixin(BrushController, Eventful);
  48392. function doEnableBrush(controller, brushOption) {
  48393. var zr = controller._zr;
  48394. // Consider roam, which takes globalPan too.
  48395. if (!controller._enableGlobalPan) {
  48396. take(zr, MUTEX_RESOURCE_KEY, controller._uid);
  48397. }
  48398. each$12(controller._handlers, function (handler, eventName) {
  48399. zr.on(eventName, handler);
  48400. });
  48401. controller._brushType = brushOption.brushType;
  48402. controller._brushOption = merge(clone(DEFAULT_BRUSH_OPT), brushOption, true);
  48403. }
  48404. function doDisableBrush(controller) {
  48405. var zr = controller._zr;
  48406. release(zr, MUTEX_RESOURCE_KEY, controller._uid);
  48407. each$12(controller._handlers, function (handler, eventName) {
  48408. zr.off(eventName, handler);
  48409. });
  48410. controller._brushType = controller._brushOption = null;
  48411. }
  48412. function createCover(controller, brushOption) {
  48413. var cover = coverRenderers[brushOption.brushType].createCover(controller, brushOption);
  48414. cover.__brushOption = brushOption;
  48415. updateZ$1(cover, brushOption);
  48416. controller.group.add(cover);
  48417. return cover;
  48418. }
  48419. function endCreating(controller, creatingCover) {
  48420. var coverRenderer = getCoverRenderer(creatingCover);
  48421. if (coverRenderer.endCreating) {
  48422. coverRenderer.endCreating(controller, creatingCover);
  48423. updateZ$1(creatingCover, creatingCover.__brushOption);
  48424. }
  48425. return creatingCover;
  48426. }
  48427. function updateCoverShape(controller, cover) {
  48428. var brushOption = cover.__brushOption;
  48429. getCoverRenderer(cover).updateCoverShape(
  48430. controller, cover, brushOption.range, brushOption
  48431. );
  48432. }
  48433. function updateZ$1(cover, brushOption) {
  48434. var z = brushOption.z;
  48435. z == null && (z = COVER_Z);
  48436. cover.traverse(function (el) {
  48437. el.z = z;
  48438. el.z2 = z; // Consider in given container.
  48439. });
  48440. }
  48441. function updateCoverAfterCreation(controller, cover) {
  48442. getCoverRenderer(cover).updateCommon(controller, cover);
  48443. updateCoverShape(controller, cover);
  48444. }
  48445. function getCoverRenderer(cover) {
  48446. return coverRenderers[cover.__brushOption.brushType];
  48447. }
  48448. // return target panel or `true` (means global panel)
  48449. function getPanelByPoint(controller, e, localCursorPoint) {
  48450. var panels = controller._panels;
  48451. if (!panels) {
  48452. return true; // Global panel
  48453. }
  48454. var panel;
  48455. var transform = controller._transform;
  48456. each$12(panels, function (pn) {
  48457. pn.isTargetByCursor(e, localCursorPoint, transform) && (panel = pn);
  48458. });
  48459. return panel;
  48460. }
  48461. // Return a panel or true
  48462. function getPanelByCover(controller, cover) {
  48463. var panels = controller._panels;
  48464. if (!panels) {
  48465. return true; // Global panel
  48466. }
  48467. var panelId = cover.__brushOption.panelId;
  48468. // User may give cover without coord sys info,
  48469. // which is then treated as global panel.
  48470. return panelId != null ? panels[panelId] : true;
  48471. }
  48472. function clearCovers(controller) {
  48473. var covers = controller._covers;
  48474. var originalLength = covers.length;
  48475. each$12(covers, function (cover) {
  48476. controller.group.remove(cover);
  48477. }, controller);
  48478. covers.length = 0;
  48479. return !!originalLength;
  48480. }
  48481. function trigger(controller, opt) {
  48482. var areas = map$2(controller._covers, function (cover) {
  48483. var brushOption = cover.__brushOption;
  48484. var range = clone(brushOption.range);
  48485. return {
  48486. brushType: brushOption.brushType,
  48487. panelId: brushOption.panelId,
  48488. range: range
  48489. };
  48490. });
  48491. controller.trigger('brush', areas, {
  48492. isEnd: !!opt.isEnd,
  48493. removeOnClick: !!opt.removeOnClick
  48494. });
  48495. }
  48496. function shouldShowCover(controller) {
  48497. var track = controller._track;
  48498. if (!track.length) {
  48499. return false;
  48500. }
  48501. var p2 = track[track.length - 1];
  48502. var p1 = track[0];
  48503. var dx = p2[0] - p1[0];
  48504. var dy = p2[1] - p1[1];
  48505. var dist = mathPow$2(dx * dx + dy * dy, 0.5);
  48506. return dist > UNSELECT_THRESHOLD;
  48507. }
  48508. function getTrackEnds(track) {
  48509. var tail = track.length - 1;
  48510. tail < 0 && (tail = 0);
  48511. return [track[0], track[tail]];
  48512. }
  48513. function createBaseRectCover(doDrift, controller, brushOption, edgeNames) {
  48514. var cover = new Group();
  48515. cover.add(new Rect({
  48516. name: 'main',
  48517. style: makeStyle(brushOption),
  48518. silent: true,
  48519. draggable: true,
  48520. cursor: 'move',
  48521. drift: curry$2(doDrift, controller, cover, 'nswe'),
  48522. ondragend: curry$2(trigger, controller, {isEnd: true})
  48523. }));
  48524. each$12(
  48525. edgeNames,
  48526. function (name) {
  48527. cover.add(new Rect({
  48528. name: name,
  48529. style: {opacity: 0},
  48530. draggable: true,
  48531. silent: true,
  48532. invisible: true,
  48533. drift: curry$2(doDrift, controller, cover, name),
  48534. ondragend: curry$2(trigger, controller, {isEnd: true})
  48535. }));
  48536. }
  48537. );
  48538. return cover;
  48539. }
  48540. function updateBaseRect(controller, cover, localRange, brushOption) {
  48541. var lineWidth = brushOption.brushStyle.lineWidth || 0;
  48542. var handleSize = mathMax$6(lineWidth, MIN_RESIZE_LINE_WIDTH);
  48543. var x = localRange[0][0];
  48544. var y = localRange[1][0];
  48545. var xa = x - lineWidth / 2;
  48546. var ya = y - lineWidth / 2;
  48547. var x2 = localRange[0][1];
  48548. var y2 = localRange[1][1];
  48549. var x2a = x2 - handleSize + lineWidth / 2;
  48550. var y2a = y2 - handleSize + lineWidth / 2;
  48551. var width = x2 - x;
  48552. var height = y2 - y;
  48553. var widtha = width + lineWidth;
  48554. var heighta = height + lineWidth;
  48555. updateRectShape(controller, cover, 'main', x, y, width, height);
  48556. if (brushOption.transformable) {
  48557. updateRectShape(controller, cover, 'w', xa, ya, handleSize, heighta);
  48558. updateRectShape(controller, cover, 'e', x2a, ya, handleSize, heighta);
  48559. updateRectShape(controller, cover, 'n', xa, ya, widtha, handleSize);
  48560. updateRectShape(controller, cover, 's', xa, y2a, widtha, handleSize);
  48561. updateRectShape(controller, cover, 'nw', xa, ya, handleSize, handleSize);
  48562. updateRectShape(controller, cover, 'ne', x2a, ya, handleSize, handleSize);
  48563. updateRectShape(controller, cover, 'sw', xa, y2a, handleSize, handleSize);
  48564. updateRectShape(controller, cover, 'se', x2a, y2a, handleSize, handleSize);
  48565. }
  48566. }
  48567. function updateCommon(controller, cover) {
  48568. var brushOption = cover.__brushOption;
  48569. var transformable = brushOption.transformable;
  48570. var mainEl = cover.childAt(0);
  48571. mainEl.useStyle(makeStyle(brushOption));
  48572. mainEl.attr({
  48573. silent: !transformable,
  48574. cursor: transformable ? 'move' : 'default'
  48575. });
  48576. each$12(
  48577. ['w', 'e', 'n', 's', 'se', 'sw', 'ne', 'nw'],
  48578. function (name) {
  48579. var el = cover.childOfName(name);
  48580. var globalDir = getGlobalDirection(controller, name);
  48581. el && el.attr({
  48582. silent: !transformable,
  48583. invisible: !transformable,
  48584. cursor: transformable ? CURSOR_MAP[globalDir] + '-resize' : null
  48585. });
  48586. }
  48587. );
  48588. }
  48589. function updateRectShape(controller, cover, name, x, y, w, h) {
  48590. var el = cover.childOfName(name);
  48591. el && el.setShape(pointsToRect(
  48592. clipByPanel(controller, cover, [[x, y], [x + w, y + h]])
  48593. ));
  48594. }
  48595. function makeStyle(brushOption) {
  48596. return defaults({strokeNoScale: true}, brushOption.brushStyle);
  48597. }
  48598. function formatRectRange(x, y, x2, y2) {
  48599. var min = [mathMin$6(x, x2), mathMin$6(y, y2)];
  48600. var max = [mathMax$6(x, x2), mathMax$6(y, y2)];
  48601. return [
  48602. [min[0], max[0]], // x range
  48603. [min[1], max[1]] // y range
  48604. ];
  48605. }
  48606. function getTransform$1(controller) {
  48607. return getTransform(controller.group);
  48608. }
  48609. function getGlobalDirection(controller, localDirection) {
  48610. if (localDirection.length > 1) {
  48611. localDirection = localDirection.split('');
  48612. var globalDir = [
  48613. getGlobalDirection(controller, localDirection[0]),
  48614. getGlobalDirection(controller, localDirection[1])
  48615. ];
  48616. (globalDir[0] === 'e' || globalDir[0] === 'w') && globalDir.reverse();
  48617. return globalDir.join('');
  48618. }
  48619. else {
  48620. var map$$1 = {w: 'left', e: 'right', n: 'top', s: 'bottom'};
  48621. var inverseMap = {left: 'w', right: 'e', top: 'n', bottom: 's'};
  48622. var globalDir = transformDirection(
  48623. map$$1[localDirection], getTransform$1(controller)
  48624. );
  48625. return inverseMap[globalDir];
  48626. }
  48627. }
  48628. function driftRect(toRectRange, fromRectRange, controller, cover, name, dx, dy, e) {
  48629. var brushOption = cover.__brushOption;
  48630. var rectRange = toRectRange(brushOption.range);
  48631. var localDelta = toLocalDelta(controller, dx, dy);
  48632. each$12(name.split(''), function (namePart) {
  48633. var ind = DIRECTION_MAP[namePart];
  48634. rectRange[ind[0]][ind[1]] += localDelta[ind[0]];
  48635. });
  48636. brushOption.range = fromRectRange(formatRectRange(
  48637. rectRange[0][0], rectRange[1][0], rectRange[0][1], rectRange[1][1]
  48638. ));
  48639. updateCoverAfterCreation(controller, cover);
  48640. trigger(controller, {isEnd: false});
  48641. }
  48642. function driftPolygon(controller, cover, dx, dy, e) {
  48643. var range = cover.__brushOption.range;
  48644. var localDelta = toLocalDelta(controller, dx, dy);
  48645. each$12(range, function (point) {
  48646. point[0] += localDelta[0];
  48647. point[1] += localDelta[1];
  48648. });
  48649. updateCoverAfterCreation(controller, cover);
  48650. trigger(controller, {isEnd: false});
  48651. }
  48652. function toLocalDelta(controller, dx, dy) {
  48653. var thisGroup = controller.group;
  48654. var localD = thisGroup.transformCoordToLocal(dx, dy);
  48655. var localZero = thisGroup.transformCoordToLocal(0, 0);
  48656. return [localD[0] - localZero[0], localD[1] - localZero[1]];
  48657. }
  48658. function clipByPanel(controller, cover, data) {
  48659. var panel = getPanelByCover(controller, cover);
  48660. return (panel && panel !== true)
  48661. ? panel.clipPath(data, controller._transform)
  48662. : clone(data);
  48663. }
  48664. function pointsToRect(points) {
  48665. var xmin = mathMin$6(points[0][0], points[1][0]);
  48666. var ymin = mathMin$6(points[0][1], points[1][1]);
  48667. var xmax = mathMax$6(points[0][0], points[1][0]);
  48668. var ymax = mathMax$6(points[0][1], points[1][1]);
  48669. return {
  48670. x: xmin,
  48671. y: ymin,
  48672. width: xmax - xmin,
  48673. height: ymax - ymin
  48674. };
  48675. }
  48676. function resetCursor(controller, e, localCursorPoint) {
  48677. // Check active
  48678. if (!controller._brushType) {
  48679. return;
  48680. }
  48681. var zr = controller._zr;
  48682. var covers = controller._covers;
  48683. var currPanel = getPanelByPoint(controller, e, localCursorPoint);
  48684. // Check whether in covers.
  48685. if (!controller._dragging) {
  48686. for (var i = 0; i < covers.length; i++) {
  48687. var brushOption = covers[i].__brushOption;
  48688. if (currPanel
  48689. && (currPanel === true || brushOption.panelId === currPanel.panelId)
  48690. && coverRenderers[brushOption.brushType].contain(
  48691. covers[i], localCursorPoint[0], localCursorPoint[1]
  48692. )
  48693. ) {
  48694. // Use cursor style set on cover.
  48695. return;
  48696. }
  48697. }
  48698. }
  48699. currPanel && zr.setCursorStyle('crosshair');
  48700. }
  48701. function preventDefault(e) {
  48702. var rawE = e.event;
  48703. rawE.preventDefault && rawE.preventDefault();
  48704. }
  48705. function mainShapeContain(cover, x, y) {
  48706. return cover.childOfName('main').contain(x, y);
  48707. }
  48708. function updateCoverByMouse(controller, e, localCursorPoint, isEnd) {
  48709. var creatingCover = controller._creatingCover;
  48710. var panel = controller._creatingPanel;
  48711. var thisBrushOption = controller._brushOption;
  48712. var eventParams;
  48713. controller._track.push(localCursorPoint.slice());
  48714. if (shouldShowCover(controller) || creatingCover) {
  48715. if (panel && !creatingCover) {
  48716. thisBrushOption.brushMode === 'single' && clearCovers(controller);
  48717. var brushOption = clone(thisBrushOption);
  48718. brushOption.brushType = determineBrushType(brushOption.brushType, panel);
  48719. brushOption.panelId = panel === true ? null : panel.panelId;
  48720. creatingCover = controller._creatingCover = createCover(controller, brushOption);
  48721. controller._covers.push(creatingCover);
  48722. }
  48723. if (creatingCover) {
  48724. var coverRenderer = coverRenderers[determineBrushType(controller._brushType, panel)];
  48725. var coverBrushOption = creatingCover.__brushOption;
  48726. coverBrushOption.range = coverRenderer.getCreatingRange(
  48727. clipByPanel(controller, creatingCover, controller._track)
  48728. );
  48729. if (isEnd) {
  48730. endCreating(controller, creatingCover);
  48731. coverRenderer.updateCommon(controller, creatingCover);
  48732. }
  48733. updateCoverShape(controller, creatingCover);
  48734. eventParams = {isEnd: isEnd};
  48735. }
  48736. }
  48737. else if (
  48738. isEnd
  48739. && thisBrushOption.brushMode === 'single'
  48740. && thisBrushOption.removeOnClick
  48741. ) {
  48742. // Help user to remove covers easily, only by a tiny drag, in 'single' mode.
  48743. // But a single click do not clear covers, because user may have casual
  48744. // clicks (for example, click on other component and do not expect covers
  48745. // disappear).
  48746. // Only some cover removed, trigger action, but not every click trigger action.
  48747. if (getPanelByPoint(controller, e, localCursorPoint) && clearCovers(controller)) {
  48748. eventParams = {isEnd: isEnd, removeOnClick: true};
  48749. }
  48750. }
  48751. return eventParams;
  48752. }
  48753. function determineBrushType(brushType, panel) {
  48754. if (brushType === 'auto') {
  48755. if (__DEV__) {
  48756. assert$1(
  48757. panel && panel.defaultBrushType,
  48758. 'MUST have defaultBrushType when brushType is "atuo"'
  48759. );
  48760. }
  48761. return panel.defaultBrushType;
  48762. }
  48763. return brushType;
  48764. }
  48765. var mouseHandlers = {
  48766. mousedown: function (e) {
  48767. if (this._dragging) {
  48768. // In case some browser do not support globalOut,
  48769. // and release mose out side the browser.
  48770. handleDragEnd.call(this, e);
  48771. }
  48772. else if (!e.target || !e.target.draggable) {
  48773. preventDefault(e);
  48774. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  48775. this._creatingCover = null;
  48776. var panel = this._creatingPanel = getPanelByPoint(this, e, localCursorPoint);
  48777. if (panel) {
  48778. this._dragging = true;
  48779. this._track = [localCursorPoint.slice()];
  48780. }
  48781. }
  48782. },
  48783. mousemove: function (e) {
  48784. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  48785. resetCursor(this, e, localCursorPoint);
  48786. if (this._dragging) {
  48787. preventDefault(e);
  48788. var eventParams = updateCoverByMouse(this, e, localCursorPoint, false);
  48789. eventParams && trigger(this, eventParams);
  48790. }
  48791. },
  48792. mouseup: handleDragEnd //,
  48793. // FIXME
  48794. // in tooltip, globalout should not be triggered.
  48795. // globalout: handleDragEnd
  48796. };
  48797. function handleDragEnd(e) {
  48798. if (this._dragging) {
  48799. preventDefault(e);
  48800. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  48801. var eventParams = updateCoverByMouse(this, e, localCursorPoint, true);
  48802. this._dragging = false;
  48803. this._track = [];
  48804. this._creatingCover = null;
  48805. // trigger event shoule be at final, after procedure will be nested.
  48806. eventParams && trigger(this, eventParams);
  48807. }
  48808. }
  48809. /**
  48810. * key: brushType
  48811. * @type {Object}
  48812. */
  48813. var coverRenderers = {
  48814. lineX: getLineRenderer(0),
  48815. lineY: getLineRenderer(1),
  48816. rect: {
  48817. createCover: function (controller, brushOption) {
  48818. return createBaseRectCover(
  48819. curry$2(
  48820. driftRect,
  48821. function (range) {
  48822. return range;
  48823. },
  48824. function (range) {
  48825. return range;
  48826. }
  48827. ),
  48828. controller,
  48829. brushOption,
  48830. ['w', 'e', 'n', 's', 'se', 'sw', 'ne', 'nw']
  48831. );
  48832. },
  48833. getCreatingRange: function (localTrack) {
  48834. var ends = getTrackEnds(localTrack);
  48835. return formatRectRange(ends[1][0], ends[1][1], ends[0][0], ends[0][1]);
  48836. },
  48837. updateCoverShape: function (controller, cover, localRange, brushOption) {
  48838. updateBaseRect(controller, cover, localRange, brushOption);
  48839. },
  48840. updateCommon: updateCommon,
  48841. contain: mainShapeContain
  48842. },
  48843. polygon: {
  48844. createCover: function (controller, brushOption) {
  48845. var cover = new Group();
  48846. // Do not use graphic.Polygon because graphic.Polyline do not close the
  48847. // border of the shape when drawing, which is a better experience for user.
  48848. cover.add(new Polyline({
  48849. name: 'main',
  48850. style: makeStyle(brushOption),
  48851. silent: true
  48852. }));
  48853. return cover;
  48854. },
  48855. getCreatingRange: function (localTrack) {
  48856. return localTrack;
  48857. },
  48858. endCreating: function (controller, cover) {
  48859. cover.remove(cover.childAt(0));
  48860. // Use graphic.Polygon close the shape.
  48861. cover.add(new Polygon({
  48862. name: 'main',
  48863. draggable: true,
  48864. drift: curry$2(driftPolygon, controller, cover),
  48865. ondragend: curry$2(trigger, controller, {isEnd: true})
  48866. }));
  48867. },
  48868. updateCoverShape: function (controller, cover, localRange, brushOption) {
  48869. cover.childAt(0).setShape({
  48870. points: clipByPanel(controller, cover, localRange)
  48871. });
  48872. },
  48873. updateCommon: updateCommon,
  48874. contain: mainShapeContain
  48875. }
  48876. };
  48877. function getLineRenderer(xyIndex) {
  48878. return {
  48879. createCover: function (controller, brushOption) {
  48880. return createBaseRectCover(
  48881. curry$2(
  48882. driftRect,
  48883. function (range) {
  48884. var rectRange = [range, [0, 100]];
  48885. xyIndex && rectRange.reverse();
  48886. return rectRange;
  48887. },
  48888. function (rectRange) {
  48889. return rectRange[xyIndex];
  48890. }
  48891. ),
  48892. controller,
  48893. brushOption,
  48894. [['w', 'e'], ['n', 's']][xyIndex]
  48895. );
  48896. },
  48897. getCreatingRange: function (localTrack) {
  48898. var ends = getTrackEnds(localTrack);
  48899. var min = mathMin$6(ends[0][xyIndex], ends[1][xyIndex]);
  48900. var max = mathMax$6(ends[0][xyIndex], ends[1][xyIndex]);
  48901. return [min, max];
  48902. },
  48903. updateCoverShape: function (controller, cover, localRange, brushOption) {
  48904. var otherExtent;
  48905. // If brushWidth not specified, fit the panel.
  48906. var panel = getPanelByCover(controller, cover);
  48907. if (panel !== true && panel.getLinearBrushOtherExtent) {
  48908. otherExtent = panel.getLinearBrushOtherExtent(
  48909. xyIndex, controller._transform
  48910. );
  48911. }
  48912. else {
  48913. var zr = controller._zr;
  48914. otherExtent = [0, [zr.getWidth(), zr.getHeight()][1 - xyIndex]];
  48915. }
  48916. var rectRange = [localRange, otherExtent];
  48917. xyIndex && rectRange.reverse();
  48918. updateBaseRect(controller, cover, rectRange, brushOption);
  48919. },
  48920. updateCommon: updateCommon,
  48921. contain: mainShapeContain
  48922. };
  48923. }
  48924. /*
  48925. * Licensed to the Apache Software Foundation (ASF) under one
  48926. * or more contributor license agreements. See the NOTICE file
  48927. * distributed with this work for additional information
  48928. * regarding copyright ownership. The ASF licenses this file
  48929. * to you under the Apache License, Version 2.0 (the
  48930. * "License"); you may not use this file except in compliance
  48931. * with the License. You may obtain a copy of the License at
  48932. *
  48933. * http://www.apache.org/licenses/LICENSE-2.0
  48934. *
  48935. * Unless required by applicable law or agreed to in writing,
  48936. * software distributed under the License is distributed on an
  48937. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48938. * KIND, either express or implied. See the License for the
  48939. * specific language governing permissions and limitations
  48940. * under the License.
  48941. */
  48942. function makeRectPanelClipPath(rect) {
  48943. rect = normalizeRect(rect);
  48944. return function (localPoints, transform) {
  48945. return clipPointsByRect(localPoints, rect);
  48946. };
  48947. }
  48948. function makeLinearBrushOtherExtent(rect, specifiedXYIndex) {
  48949. rect = normalizeRect(rect);
  48950. return function (xyIndex) {
  48951. var idx = specifiedXYIndex != null ? specifiedXYIndex : xyIndex;
  48952. var brushWidth = idx ? rect.width : rect.height;
  48953. var base = idx ? rect.x : rect.y;
  48954. return [base, base + (brushWidth || 0)];
  48955. };
  48956. }
  48957. function makeRectIsTargetByCursor(rect, api, targetModel) {
  48958. rect = normalizeRect(rect);
  48959. return function (e, localCursorPoint, transform) {
  48960. return rect.contain(localCursorPoint[0], localCursorPoint[1])
  48961. && !onIrrelevantElement(e, api, targetModel);
  48962. };
  48963. }
  48964. // Consider width/height is negative.
  48965. function normalizeRect(rect) {
  48966. return BoundingRect.create(rect);
  48967. }
  48968. /*
  48969. * Licensed to the Apache Software Foundation (ASF) under one
  48970. * or more contributor license agreements. See the NOTICE file
  48971. * distributed with this work for additional information
  48972. * regarding copyright ownership. The ASF licenses this file
  48973. * to you under the Apache License, Version 2.0 (the
  48974. * "License"); you may not use this file except in compliance
  48975. * with the License. You may obtain a copy of the License at
  48976. *
  48977. * http://www.apache.org/licenses/LICENSE-2.0
  48978. *
  48979. * Unless required by applicable law or agreed to in writing,
  48980. * software distributed under the License is distributed on an
  48981. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48982. * KIND, either express or implied. See the License for the
  48983. * specific language governing permissions and limitations
  48984. * under the License.
  48985. */
  48986. var elementList = ['axisLine', 'axisTickLabel', 'axisName'];
  48987. var AxisView$2 = extendComponentView({
  48988. type: 'parallelAxis',
  48989. /**
  48990. * @override
  48991. */
  48992. init: function (ecModel, api) {
  48993. AxisView$2.superApply(this, 'init', arguments);
  48994. /**
  48995. * @type {module:echarts/component/helper/BrushController}
  48996. */
  48997. (this._brushController = new BrushController(api.getZr()))
  48998. .on('brush', bind(this._onBrush, this));
  48999. },
  49000. /**
  49001. * @override
  49002. */
  49003. render: function (axisModel, ecModel, api, payload) {
  49004. if (fromAxisAreaSelect(axisModel, ecModel, payload)) {
  49005. return;
  49006. }
  49007. this.axisModel = axisModel;
  49008. this.api = api;
  49009. this.group.removeAll();
  49010. var oldAxisGroup = this._axisGroup;
  49011. this._axisGroup = new Group();
  49012. this.group.add(this._axisGroup);
  49013. if (!axisModel.get('show')) {
  49014. return;
  49015. }
  49016. var coordSysModel = getCoordSysModel(axisModel, ecModel);
  49017. var coordSys = coordSysModel.coordinateSystem;
  49018. var areaSelectStyle = axisModel.getAreaSelectStyle();
  49019. var areaWidth = areaSelectStyle.width;
  49020. var dim = axisModel.axis.dim;
  49021. var axisLayout = coordSys.getAxisLayout(dim);
  49022. var builderOpt = extend(
  49023. {strokeContainThreshold: areaWidth},
  49024. axisLayout
  49025. );
  49026. var axisBuilder = new AxisBuilder(axisModel, builderOpt);
  49027. each$1(elementList, axisBuilder.add, axisBuilder);
  49028. this._axisGroup.add(axisBuilder.getGroup());
  49029. this._refreshBrushController(
  49030. builderOpt, areaSelectStyle, axisModel, coordSysModel, areaWidth, api
  49031. );
  49032. var animationModel = (payload && payload.animation === false) ? null : axisModel;
  49033. groupTransition(oldAxisGroup, this._axisGroup, animationModel);
  49034. },
  49035. // /**
  49036. // * @override
  49037. // */
  49038. // updateVisual: function (axisModel, ecModel, api, payload) {
  49039. // this._brushController && this._brushController
  49040. // .updateCovers(getCoverInfoList(axisModel));
  49041. // },
  49042. _refreshBrushController: function (
  49043. builderOpt, areaSelectStyle, axisModel, coordSysModel, areaWidth, api
  49044. ) {
  49045. // After filtering, axis may change, select area needs to be update.
  49046. var extent = axisModel.axis.getExtent();
  49047. var extentLen = extent[1] - extent[0];
  49048. var extra = Math.min(30, Math.abs(extentLen) * 0.1); // Arbitrary value.
  49049. // width/height might be negative, which will be
  49050. // normalized in BoundingRect.
  49051. var rect = BoundingRect.create({
  49052. x: extent[0],
  49053. y: -areaWidth / 2,
  49054. width: extentLen,
  49055. height: areaWidth
  49056. });
  49057. rect.x -= extra;
  49058. rect.width += 2 * extra;
  49059. this._brushController
  49060. .mount({
  49061. enableGlobalPan: true,
  49062. rotation: builderOpt.rotation,
  49063. position: builderOpt.position
  49064. })
  49065. .setPanels([{
  49066. panelId: 'pl',
  49067. clipPath: makeRectPanelClipPath(rect),
  49068. isTargetByCursor: makeRectIsTargetByCursor(rect, api, coordSysModel),
  49069. getLinearBrushOtherExtent: makeLinearBrushOtherExtent(rect, 0)
  49070. }])
  49071. .enableBrush({
  49072. brushType: 'lineX',
  49073. brushStyle: areaSelectStyle,
  49074. removeOnClick: true
  49075. })
  49076. .updateCovers(getCoverInfoList(axisModel));
  49077. },
  49078. _onBrush: function (coverInfoList, opt) {
  49079. // Do not cache these object, because the mey be changed.
  49080. var axisModel = this.axisModel;
  49081. var axis = axisModel.axis;
  49082. var intervals = map(coverInfoList, function (coverInfo) {
  49083. return [
  49084. axis.coordToData(coverInfo.range[0], true),
  49085. axis.coordToData(coverInfo.range[1], true)
  49086. ];
  49087. });
  49088. // If realtime is true, action is not dispatched on drag end, because
  49089. // the drag end emits the same params with the last drag move event,
  49090. // and may have some delay when using touch pad.
  49091. if (!axisModel.option.realtime === opt.isEnd || opt.removeOnClick) { // jshint ignore:line
  49092. this.api.dispatchAction({
  49093. type: 'axisAreaSelect',
  49094. parallelAxisId: axisModel.id,
  49095. intervals: intervals
  49096. });
  49097. }
  49098. },
  49099. /**
  49100. * @override
  49101. */
  49102. dispose: function () {
  49103. this._brushController.dispose();
  49104. }
  49105. });
  49106. function fromAxisAreaSelect(axisModel, ecModel, payload) {
  49107. return payload
  49108. && payload.type === 'axisAreaSelect'
  49109. && ecModel.findComponents(
  49110. {mainType: 'parallelAxis', query: payload}
  49111. )[0] === axisModel;
  49112. }
  49113. function getCoverInfoList(axisModel) {
  49114. var axis = axisModel.axis;
  49115. return map(axisModel.activeIntervals, function (interval) {
  49116. return {
  49117. brushType: 'lineX',
  49118. panelId: 'pl',
  49119. range: [
  49120. axis.dataToCoord(interval[0], true),
  49121. axis.dataToCoord(interval[1], true)
  49122. ]
  49123. };
  49124. });
  49125. }
  49126. function getCoordSysModel(axisModel, ecModel) {
  49127. return ecModel.getComponent(
  49128. 'parallel', axisModel.get('parallelIndex')
  49129. );
  49130. }
  49131. /*
  49132. * Licensed to the Apache Software Foundation (ASF) under one
  49133. * or more contributor license agreements. See the NOTICE file
  49134. * distributed with this work for additional information
  49135. * regarding copyright ownership. The ASF licenses this file
  49136. * to you under the Apache License, Version 2.0 (the
  49137. * "License"); you may not use this file except in compliance
  49138. * with the License. You may obtain a copy of the License at
  49139. *
  49140. * http://www.apache.org/licenses/LICENSE-2.0
  49141. *
  49142. * Unless required by applicable law or agreed to in writing,
  49143. * software distributed under the License is distributed on an
  49144. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49145. * KIND, either express or implied. See the License for the
  49146. * specific language governing permissions and limitations
  49147. * under the License.
  49148. */
  49149. /*
  49150. * Licensed to the Apache Software Foundation (ASF) under one
  49151. * or more contributor license agreements. See the NOTICE file
  49152. * distributed with this work for additional information
  49153. * regarding copyright ownership. The ASF licenses this file
  49154. * to you under the Apache License, Version 2.0 (the
  49155. * "License"); you may not use this file except in compliance
  49156. * with the License. You may obtain a copy of the License at
  49157. *
  49158. * http://www.apache.org/licenses/LICENSE-2.0
  49159. *
  49160. * Unless required by applicable law or agreed to in writing,
  49161. * software distributed under the License is distributed on an
  49162. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49163. * KIND, either express or implied. See the License for the
  49164. * specific language governing permissions and limitations
  49165. * under the License.
  49166. */
  49167. var CLICK_THRESHOLD = 5; // > 4
  49168. // Parallel view
  49169. extendComponentView({
  49170. type: 'parallel',
  49171. render: function (parallelModel, ecModel, api) {
  49172. this._model = parallelModel;
  49173. this._api = api;
  49174. if (!this._handlers) {
  49175. this._handlers = {};
  49176. each$1(handlers, function (handler, eventName) {
  49177. api.getZr().on(eventName, this._handlers[eventName] = bind(handler, this));
  49178. }, this);
  49179. }
  49180. createOrUpdate(
  49181. this,
  49182. '_throttledDispatchExpand',
  49183. parallelModel.get('axisExpandRate'),
  49184. 'fixRate'
  49185. );
  49186. },
  49187. dispose: function (ecModel, api) {
  49188. each$1(this._handlers, function (handler, eventName) {
  49189. api.getZr().off(eventName, handler);
  49190. });
  49191. this._handlers = null;
  49192. },
  49193. /**
  49194. * @param {Object} [opt] If null, cancle the last action triggering for debounce.
  49195. */
  49196. _throttledDispatchExpand: function (opt) {
  49197. this._dispatchExpand(opt);
  49198. },
  49199. _dispatchExpand: function (opt) {
  49200. opt && this._api.dispatchAction(
  49201. extend({type: 'parallelAxisExpand'}, opt)
  49202. );
  49203. }
  49204. });
  49205. var handlers = {
  49206. mousedown: function (e) {
  49207. if (checkTrigger(this, 'click')) {
  49208. this._mouseDownPoint = [e.offsetX, e.offsetY];
  49209. }
  49210. },
  49211. mouseup: function (e) {
  49212. var mouseDownPoint = this._mouseDownPoint;
  49213. if (checkTrigger(this, 'click') && mouseDownPoint) {
  49214. var point = [e.offsetX, e.offsetY];
  49215. var dist = Math.pow(mouseDownPoint[0] - point[0], 2)
  49216. + Math.pow(mouseDownPoint[1] - point[1], 2);
  49217. if (dist > CLICK_THRESHOLD) {
  49218. return;
  49219. }
  49220. var result = this._model.coordinateSystem.getSlidedAxisExpandWindow(
  49221. [e.offsetX, e.offsetY]
  49222. );
  49223. result.behavior !== 'none' && this._dispatchExpand({
  49224. axisExpandWindow: result.axisExpandWindow
  49225. });
  49226. }
  49227. this._mouseDownPoint = null;
  49228. },
  49229. mousemove: function (e) {
  49230. // Should do nothing when brushing.
  49231. if (this._mouseDownPoint || !checkTrigger(this, 'mousemove')) {
  49232. return;
  49233. }
  49234. var model = this._model;
  49235. var result = model.coordinateSystem.getSlidedAxisExpandWindow(
  49236. [e.offsetX, e.offsetY]
  49237. );
  49238. var behavior = result.behavior;
  49239. behavior === 'jump' && this._throttledDispatchExpand.debounceNextCall(model.get('axisExpandDebounce'));
  49240. this._throttledDispatchExpand(
  49241. behavior === 'none'
  49242. ? null // Cancle the last trigger, in case that mouse slide out of the area quickly.
  49243. : {
  49244. axisExpandWindow: result.axisExpandWindow,
  49245. // Jumping uses animation, and sliding suppresses animation.
  49246. animation: behavior === 'jump' ? null : false
  49247. }
  49248. );
  49249. }
  49250. };
  49251. function checkTrigger(view, triggerOn) {
  49252. var model = view._model;
  49253. return model.get('axisExpandable') && model.get('axisExpandTriggerOn') === triggerOn;
  49254. }
  49255. registerPreprocessor(parallelPreprocessor);
  49256. /*
  49257. * Licensed to the Apache Software Foundation (ASF) under one
  49258. * or more contributor license agreements. See the NOTICE file
  49259. * distributed with this work for additional information
  49260. * regarding copyright ownership. The ASF licenses this file
  49261. * to you under the Apache License, Version 2.0 (the
  49262. * "License"); you may not use this file except in compliance
  49263. * with the License. You may obtain a copy of the License at
  49264. *
  49265. * http://www.apache.org/licenses/LICENSE-2.0
  49266. *
  49267. * Unless required by applicable law or agreed to in writing,
  49268. * software distributed under the License is distributed on an
  49269. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49270. * KIND, either express or implied. See the License for the
  49271. * specific language governing permissions and limitations
  49272. * under the License.
  49273. */
  49274. SeriesModel.extend({
  49275. type: 'series.parallel',
  49276. dependencies: ['parallel'],
  49277. visualColorAccessPath: 'lineStyle.color',
  49278. getInitialData: function (option, ecModel) {
  49279. var source = this.getSource();
  49280. setEncodeAndDimensions(source, this);
  49281. return createListFromArray(source, this);
  49282. },
  49283. /**
  49284. * User can get data raw indices on 'axisAreaSelected' event received.
  49285. *
  49286. * @public
  49287. * @param {string} activeState 'active' or 'inactive' or 'normal'
  49288. * @return {Array.<number>} Raw indices
  49289. */
  49290. getRawIndicesByActiveState: function (activeState) {
  49291. var coordSys = this.coordinateSystem;
  49292. var data = this.getData();
  49293. var indices = [];
  49294. coordSys.eachActiveState(data, function (theActiveState, dataIndex) {
  49295. if (activeState === theActiveState) {
  49296. indices.push(data.getRawIndex(dataIndex));
  49297. }
  49298. });
  49299. return indices;
  49300. },
  49301. defaultOption: {
  49302. zlevel: 0, // 一级层叠
  49303. z: 2, // 二级层叠
  49304. coordinateSystem: 'parallel',
  49305. parallelIndex: 0,
  49306. label: {
  49307. show: false
  49308. },
  49309. inactiveOpacity: 0.05,
  49310. activeOpacity: 1,
  49311. lineStyle: {
  49312. width: 1,
  49313. opacity: 0.45,
  49314. type: 'solid'
  49315. },
  49316. emphasis: {
  49317. label: {
  49318. show: false
  49319. }
  49320. },
  49321. progressive: 500,
  49322. smooth: false, // true | false | number
  49323. animationEasing: 'linear'
  49324. }
  49325. });
  49326. function setEncodeAndDimensions(source, seriesModel) {
  49327. // The mapping of parallelAxis dimension to data dimension can
  49328. // be specified in parallelAxis.option.dim. For example, if
  49329. // parallelAxis.option.dim is 'dim3', it mapping to the third
  49330. // dimension of data. But `data.encode` has higher priority.
  49331. // Moreover, parallelModel.dimension should not be regarded as data
  49332. // dimensions. Consider dimensions = ['dim4', 'dim2', 'dim6'];
  49333. if (source.encodeDefine) {
  49334. return;
  49335. }
  49336. var parallelModel = seriesModel.ecModel.getComponent(
  49337. 'parallel', seriesModel.get('parallelIndex')
  49338. );
  49339. if (!parallelModel) {
  49340. return;
  49341. }
  49342. var encodeDefine = source.encodeDefine = createHashMap();
  49343. each$1(parallelModel.dimensions, function (axisDim) {
  49344. var dataDimIndex = convertDimNameToNumber(axisDim);
  49345. encodeDefine.set(axisDim, dataDimIndex);
  49346. });
  49347. }
  49348. function convertDimNameToNumber(dimName) {
  49349. return +dimName.replace('dim', '');
  49350. }
  49351. /*
  49352. * Licensed to the Apache Software Foundation (ASF) under one
  49353. * or more contributor license agreements. See the NOTICE file
  49354. * distributed with this work for additional information
  49355. * regarding copyright ownership. The ASF licenses this file
  49356. * to you under the Apache License, Version 2.0 (the
  49357. * "License"); you may not use this file except in compliance
  49358. * with the License. You may obtain a copy of the License at
  49359. *
  49360. * http://www.apache.org/licenses/LICENSE-2.0
  49361. *
  49362. * Unless required by applicable law or agreed to in writing,
  49363. * software distributed under the License is distributed on an
  49364. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49365. * KIND, either express or implied. See the License for the
  49366. * specific language governing permissions and limitations
  49367. * under the License.
  49368. */
  49369. var DEFAULT_SMOOTH = 0.3;
  49370. var ParallelView = Chart.extend({
  49371. type: 'parallel',
  49372. init: function () {
  49373. /**
  49374. * @type {module:zrender/container/Group}
  49375. * @private
  49376. */
  49377. this._dataGroup = new Group();
  49378. this.group.add(this._dataGroup);
  49379. /**
  49380. * @type {module:echarts/data/List}
  49381. */
  49382. this._data;
  49383. /**
  49384. * @type {boolean}
  49385. */
  49386. this._initialized;
  49387. },
  49388. /**
  49389. * @override
  49390. */
  49391. render: function (seriesModel, ecModel, api, payload) {
  49392. var dataGroup = this._dataGroup;
  49393. var data = seriesModel.getData();
  49394. var oldData = this._data;
  49395. var coordSys = seriesModel.coordinateSystem;
  49396. var dimensions = coordSys.dimensions;
  49397. var seriesScope = makeSeriesScope$2(seriesModel);
  49398. data.diff(oldData)
  49399. .add(add)
  49400. .update(update)
  49401. .remove(remove)
  49402. .execute();
  49403. function add(newDataIndex) {
  49404. var line = addEl(data, dataGroup, newDataIndex, dimensions, coordSys);
  49405. updateElCommon(line, data, newDataIndex, seriesScope);
  49406. }
  49407. function update(newDataIndex, oldDataIndex) {
  49408. var line = oldData.getItemGraphicEl(oldDataIndex);
  49409. var points = createLinePoints(data, newDataIndex, dimensions, coordSys);
  49410. data.setItemGraphicEl(newDataIndex, line);
  49411. var animationModel = (payload && payload.animation === false) ? null : seriesModel;
  49412. updateProps(line, {shape: {points: points}}, animationModel, newDataIndex);
  49413. updateElCommon(line, data, newDataIndex, seriesScope);
  49414. }
  49415. function remove(oldDataIndex) {
  49416. var line = oldData.getItemGraphicEl(oldDataIndex);
  49417. dataGroup.remove(line);
  49418. }
  49419. // First create
  49420. if (!this._initialized) {
  49421. this._initialized = true;
  49422. var clipPath = createGridClipShape$1(
  49423. coordSys, seriesModel, function () {
  49424. // Callback will be invoked immediately if there is no animation
  49425. setTimeout(function () {
  49426. dataGroup.removeClipPath();
  49427. });
  49428. }
  49429. );
  49430. dataGroup.setClipPath(clipPath);
  49431. }
  49432. this._data = data;
  49433. },
  49434. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  49435. this._initialized = true;
  49436. this._data = null;
  49437. this._dataGroup.removeAll();
  49438. },
  49439. incrementalRender: function (taskParams, seriesModel, ecModel) {
  49440. var data = seriesModel.getData();
  49441. var coordSys = seriesModel.coordinateSystem;
  49442. var dimensions = coordSys.dimensions;
  49443. var seriesScope = makeSeriesScope$2(seriesModel);
  49444. for (var dataIndex = taskParams.start; dataIndex < taskParams.end; dataIndex++) {
  49445. var line = addEl(data, this._dataGroup, dataIndex, dimensions, coordSys);
  49446. line.incremental = true;
  49447. updateElCommon(line, data, dataIndex, seriesScope);
  49448. }
  49449. },
  49450. dispose: function () {},
  49451. // _renderForProgressive: function (seriesModel) {
  49452. // var dataGroup = this._dataGroup;
  49453. // var data = seriesModel.getData();
  49454. // var oldData = this._data;
  49455. // var coordSys = seriesModel.coordinateSystem;
  49456. // var dimensions = coordSys.dimensions;
  49457. // var option = seriesModel.option;
  49458. // var progressive = option.progressive;
  49459. // var smooth = option.smooth ? SMOOTH : null;
  49460. // // In progressive animation is disabled, so use simple data diff,
  49461. // // which effects performance less.
  49462. // // (Typically performance for data with length 7000+ like:
  49463. // // simpleDiff: 60ms, addEl: 184ms,
  49464. // // in RMBP 2.4GHz intel i7, OSX 10.9 chrome 50.0.2661.102 (64-bit))
  49465. // if (simpleDiff(oldData, data, dimensions)) {
  49466. // dataGroup.removeAll();
  49467. // data.each(function (dataIndex) {
  49468. // addEl(data, dataGroup, dataIndex, dimensions, coordSys);
  49469. // });
  49470. // }
  49471. // updateElCommon(data, progressive, smooth);
  49472. // // Consider switch between progressive and not.
  49473. // data.__plProgressive = true;
  49474. // this._data = data;
  49475. // },
  49476. /**
  49477. * @override
  49478. */
  49479. remove: function () {
  49480. this._dataGroup && this._dataGroup.removeAll();
  49481. this._data = null;
  49482. }
  49483. });
  49484. function createGridClipShape$1(coordSys, seriesModel, cb) {
  49485. var parallelModel = coordSys.model;
  49486. var rect = coordSys.getRect();
  49487. var rectEl = new Rect({
  49488. shape: {
  49489. x: rect.x,
  49490. y: rect.y,
  49491. width: rect.width,
  49492. height: rect.height
  49493. }
  49494. });
  49495. var dim = parallelModel.get('layout') === 'horizontal' ? 'width' : 'height';
  49496. rectEl.setShape(dim, 0);
  49497. initProps(rectEl, {
  49498. shape: {
  49499. width: rect.width,
  49500. height: rect.height
  49501. }
  49502. }, seriesModel, cb);
  49503. return rectEl;
  49504. }
  49505. function createLinePoints(data, dataIndex, dimensions, coordSys) {
  49506. var points = [];
  49507. for (var i = 0; i < dimensions.length; i++) {
  49508. var dimName = dimensions[i];
  49509. var value = data.get(data.mapDimension(dimName), dataIndex);
  49510. if (!isEmptyValue(value, coordSys.getAxis(dimName).type)) {
  49511. points.push(coordSys.dataToPoint(value, dimName));
  49512. }
  49513. }
  49514. return points;
  49515. }
  49516. function addEl(data, dataGroup, dataIndex, dimensions, coordSys) {
  49517. var points = createLinePoints(data, dataIndex, dimensions, coordSys);
  49518. var line = new Polyline({
  49519. shape: {points: points},
  49520. silent: true,
  49521. z2: 10
  49522. });
  49523. dataGroup.add(line);
  49524. data.setItemGraphicEl(dataIndex, line);
  49525. return line;
  49526. }
  49527. function makeSeriesScope$2(seriesModel) {
  49528. var smooth = seriesModel.get('smooth', true);
  49529. smooth === true && (smooth = DEFAULT_SMOOTH);
  49530. return {
  49531. lineStyle: seriesModel.getModel('lineStyle').getLineStyle(),
  49532. smooth: smooth != null ? smooth : DEFAULT_SMOOTH
  49533. };
  49534. }
  49535. function updateElCommon(el, data, dataIndex, seriesScope) {
  49536. var lineStyle = seriesScope.lineStyle;
  49537. if (data.hasItemOption) {
  49538. var lineStyleModel = data.getItemModel(dataIndex).getModel('lineStyle');
  49539. lineStyle = lineStyleModel.getLineStyle();
  49540. }
  49541. el.useStyle(lineStyle);
  49542. var elStyle = el.style;
  49543. elStyle.fill = null;
  49544. // lineStyle.color have been set to itemVisual in module:echarts/visual/seriesColor.
  49545. elStyle.stroke = data.getItemVisual(dataIndex, 'color');
  49546. // lineStyle.opacity have been set to itemVisual in parallelVisual.
  49547. elStyle.opacity = data.getItemVisual(dataIndex, 'opacity');
  49548. seriesScope.smooth && (el.shape.smooth = seriesScope.smooth);
  49549. }
  49550. // function simpleDiff(oldData, newData, dimensions) {
  49551. // var oldLen;
  49552. // if (!oldData
  49553. // || !oldData.__plProgressive
  49554. // || (oldLen = oldData.count()) !== newData.count()
  49555. // ) {
  49556. // return true;
  49557. // }
  49558. // var dimLen = dimensions.length;
  49559. // for (var i = 0; i < oldLen; i++) {
  49560. // for (var j = 0; j < dimLen; j++) {
  49561. // if (oldData.get(dimensions[j], i) !== newData.get(dimensions[j], i)) {
  49562. // return true;
  49563. // }
  49564. // }
  49565. // }
  49566. // return false;
  49567. // }
  49568. // FIXME
  49569. // 公用方法?
  49570. function isEmptyValue(val, axisType) {
  49571. return axisType === 'category'
  49572. ? val == null
  49573. : (val == null || isNaN(val)); // axisType === 'value'
  49574. }
  49575. /*
  49576. * Licensed to the Apache Software Foundation (ASF) under one
  49577. * or more contributor license agreements. See the NOTICE file
  49578. * distributed with this work for additional information
  49579. * regarding copyright ownership. The ASF licenses this file
  49580. * to you under the Apache License, Version 2.0 (the
  49581. * "License"); you may not use this file except in compliance
  49582. * with the License. You may obtain a copy of the License at
  49583. *
  49584. * http://www.apache.org/licenses/LICENSE-2.0
  49585. *
  49586. * Unless required by applicable law or agreed to in writing,
  49587. * software distributed under the License is distributed on an
  49588. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49589. * KIND, either express or implied. See the License for the
  49590. * specific language governing permissions and limitations
  49591. * under the License.
  49592. */
  49593. var opacityAccessPath$1 = ['lineStyle', 'normal', 'opacity'];
  49594. var parallelVisual = {
  49595. seriesType: 'parallel',
  49596. reset: function (seriesModel, ecModel, api) {
  49597. var itemStyleModel = seriesModel.getModel('itemStyle');
  49598. var lineStyleModel = seriesModel.getModel('lineStyle');
  49599. var globalColors = ecModel.get('color');
  49600. var color = lineStyleModel.get('color')
  49601. || itemStyleModel.get('color')
  49602. || globalColors[seriesModel.seriesIndex % globalColors.length];
  49603. var inactiveOpacity = seriesModel.get('inactiveOpacity');
  49604. var activeOpacity = seriesModel.get('activeOpacity');
  49605. var lineStyle = seriesModel.getModel('lineStyle').getLineStyle();
  49606. var coordSys = seriesModel.coordinateSystem;
  49607. var data = seriesModel.getData();
  49608. var opacityMap = {
  49609. normal: lineStyle.opacity,
  49610. active: activeOpacity,
  49611. inactive: inactiveOpacity
  49612. };
  49613. data.setVisual('color', color);
  49614. function progress(params, data) {
  49615. coordSys.eachActiveState(data, function (activeState, dataIndex) {
  49616. var opacity = opacityMap[activeState];
  49617. if (activeState === 'normal' && data.hasItemOption) {
  49618. var itemOpacity = data.getItemModel(dataIndex).get(opacityAccessPath$1, true);
  49619. itemOpacity != null && (opacity = itemOpacity);
  49620. }
  49621. data.setItemVisual(dataIndex, 'opacity', opacity);
  49622. }, params.start, params.end);
  49623. }
  49624. return {progress: progress};
  49625. }
  49626. };
  49627. /*
  49628. * Licensed to the Apache Software Foundation (ASF) under one
  49629. * or more contributor license agreements. See the NOTICE file
  49630. * distributed with this work for additional information
  49631. * regarding copyright ownership. The ASF licenses this file
  49632. * to you under the Apache License, Version 2.0 (the
  49633. * "License"); you may not use this file except in compliance
  49634. * with the License. You may obtain a copy of the License at
  49635. *
  49636. * http://www.apache.org/licenses/LICENSE-2.0
  49637. *
  49638. * Unless required by applicable law or agreed to in writing,
  49639. * software distributed under the License is distributed on an
  49640. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49641. * KIND, either express or implied. See the License for the
  49642. * specific language governing permissions and limitations
  49643. * under the License.
  49644. */
  49645. registerVisual(parallelVisual);
  49646. /*
  49647. * Licensed to the Apache Software Foundation (ASF) under one
  49648. * or more contributor license agreements. See the NOTICE file
  49649. * distributed with this work for additional information
  49650. * regarding copyright ownership. The ASF licenses this file
  49651. * to you under the Apache License, Version 2.0 (the
  49652. * "License"); you may not use this file except in compliance
  49653. * with the License. You may obtain a copy of the License at
  49654. *
  49655. * http://www.apache.org/licenses/LICENSE-2.0
  49656. *
  49657. * Unless required by applicable law or agreed to in writing,
  49658. * software distributed under the License is distributed on an
  49659. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49660. * KIND, either express or implied. See the License for the
  49661. * specific language governing permissions and limitations
  49662. * under the License.
  49663. */
  49664. /**
  49665. * @file Get initial data and define sankey view's series model
  49666. * @author Deqing Li(annong035@gmail.com)
  49667. */
  49668. var SankeySeries = SeriesModel.extend({
  49669. type: 'series.sankey',
  49670. layoutInfo: null,
  49671. /**
  49672. * Init a graph data structure from data in option series
  49673. *
  49674. * @param {Object} option the object used to config echarts view
  49675. * @return {module:echarts/data/List} storage initial data
  49676. */
  49677. getInitialData: function (option) {
  49678. var links = option.edges || option.links;
  49679. var nodes = option.data || option.nodes;
  49680. if (nodes && links) {
  49681. var graph = createGraphFromNodeEdge(nodes, links, this, true);
  49682. return graph.data;
  49683. }
  49684. },
  49685. setNodePosition: function (dataIndex, localPosition) {
  49686. var dataItem = this.option.data[dataIndex];
  49687. dataItem.localX = localPosition[0];
  49688. dataItem.localY = localPosition[1];
  49689. },
  49690. /**
  49691. * Return the graphic data structure
  49692. *
  49693. * @return {module:echarts/data/Graph} graphic data structure
  49694. */
  49695. getGraph: function () {
  49696. return this.getData().graph;
  49697. },
  49698. /**
  49699. * Get edge data of graphic data structure
  49700. *
  49701. * @return {module:echarts/data/List} data structure of list
  49702. */
  49703. getEdgeData: function () {
  49704. return this.getGraph().edgeData;
  49705. },
  49706. /**
  49707. * @override
  49708. */
  49709. formatTooltip: function (dataIndex, multipleSeries, dataType) {
  49710. // dataType === 'node' or empty do not show tooltip by default
  49711. if (dataType === 'edge') {
  49712. var params = this.getDataParams(dataIndex, dataType);
  49713. var rawDataOpt = params.data;
  49714. var html = rawDataOpt.source + ' -- ' + rawDataOpt.target;
  49715. if (params.value) {
  49716. html += ' : ' + params.value;
  49717. }
  49718. return encodeHTML(html);
  49719. }
  49720. return SankeySeries.superCall(this, 'formatTooltip', dataIndex, multipleSeries);
  49721. },
  49722. defaultOption: {
  49723. zlevel: 0,
  49724. z: 2,
  49725. coordinateSystem: 'view',
  49726. layout: null,
  49727. // the position of the whole view
  49728. left: '5%',
  49729. top: '5%',
  49730. right: '20%',
  49731. bottom: '5%',
  49732. // the dx of the node
  49733. nodeWidth: 20,
  49734. // the vertical distance between two nodes
  49735. nodeGap: 8,
  49736. // control if the node can move or not
  49737. draggable: true,
  49738. // the number of iterations to change the position of the node
  49739. layoutIterations: 32,
  49740. label: {
  49741. show: true,
  49742. position: 'right',
  49743. color: '#000',
  49744. fontSize: 12
  49745. },
  49746. itemStyle: {
  49747. borderWidth: 1,
  49748. borderColor: '#333'
  49749. },
  49750. lineStyle: {
  49751. color: '#314656',
  49752. opacity: 0.2,
  49753. curveness: 0.5
  49754. },
  49755. emphasis: {
  49756. label: {
  49757. show: true
  49758. },
  49759. lineStyle: {
  49760. opacity: 0.6
  49761. }
  49762. },
  49763. animationEasing: 'linear',
  49764. animationDuration: 1000
  49765. }
  49766. });
  49767. /*
  49768. * Licensed to the Apache Software Foundation (ASF) under one
  49769. * or more contributor license agreements. See the NOTICE file
  49770. * distributed with this work for additional information
  49771. * regarding copyright ownership. The ASF licenses this file
  49772. * to you under the Apache License, Version 2.0 (the
  49773. * "License"); you may not use this file except in compliance
  49774. * with the License. You may obtain a copy of the License at
  49775. *
  49776. * http://www.apache.org/licenses/LICENSE-2.0
  49777. *
  49778. * Unless required by applicable law or agreed to in writing,
  49779. * software distributed under the License is distributed on an
  49780. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49781. * KIND, either express or implied. See the License for the
  49782. * specific language governing permissions and limitations
  49783. * under the License.
  49784. */
  49785. /**
  49786. * @file The file used to draw sankey view
  49787. * @author Deqing Li(annong035@gmail.com)
  49788. */
  49789. var SankeyShape = extendShape({
  49790. shape: {
  49791. x1: 0, y1: 0,
  49792. x2: 0, y2: 0,
  49793. cpx1: 0, cpy1: 0,
  49794. cpx2: 0, cpy2: 0,
  49795. extent: 0
  49796. },
  49797. buildPath: function (ctx, shape) {
  49798. var halfExtent = shape.extent / 2;
  49799. ctx.moveTo(shape.x1, shape.y1 - halfExtent);
  49800. ctx.bezierCurveTo(
  49801. shape.cpx1, shape.cpy1 - halfExtent,
  49802. shape.cpx2, shape.cpy2 - halfExtent,
  49803. shape.x2, shape.y2 - halfExtent
  49804. );
  49805. ctx.lineTo(shape.x2, shape.y2 + halfExtent);
  49806. ctx.bezierCurveTo(
  49807. shape.cpx2, shape.cpy2 + halfExtent,
  49808. shape.cpx1, shape.cpy1 + halfExtent,
  49809. shape.x1, shape.y1 + halfExtent
  49810. );
  49811. ctx.closePath();
  49812. }
  49813. });
  49814. extendChartView({
  49815. type: 'sankey',
  49816. /**
  49817. * @private
  49818. * @type {module:echarts/chart/sankey/SankeySeries}
  49819. */
  49820. _model: null,
  49821. render: function (seriesModel, ecModel, api) {
  49822. var graph = seriesModel.getGraph();
  49823. var group = this.group;
  49824. var layoutInfo = seriesModel.layoutInfo;
  49825. // view width
  49826. var width = layoutInfo.width;
  49827. // view height
  49828. var height = layoutInfo.height;
  49829. var nodeData = seriesModel.getData();
  49830. var edgeData = seriesModel.getData('edge');
  49831. this._model = seriesModel;
  49832. group.removeAll();
  49833. group.attr('position', [layoutInfo.x, layoutInfo.y]);
  49834. // generate a bezire Curve for each edge
  49835. graph.eachEdge(function (edge) {
  49836. var curve = new SankeyShape();
  49837. curve.dataIndex = edge.dataIndex;
  49838. curve.seriesIndex = seriesModel.seriesIndex;
  49839. curve.dataType = 'edge';
  49840. var lineStyleModel = edge.getModel('lineStyle');
  49841. var curvature = lineStyleModel.get('curveness');
  49842. var n1Layout = edge.node1.getLayout();
  49843. var node1Model =edge.node1.getModel();
  49844. var dragX1 = node1Model.get('localX');
  49845. var dragY1 = node1Model.get('localY');
  49846. var n2Layout = edge.node2.getLayout();
  49847. var node2Model = edge.node2.getModel();
  49848. var dragX2 = node2Model.get('localX');
  49849. var dragY2 = node2Model.get('localY');
  49850. var edgeLayout = edge.getLayout();
  49851. curve.shape.extent = Math.max(1, edgeLayout.dy);
  49852. var x1 = (dragX1 != null ? dragX1 * width : n1Layout.x) + n1Layout.dx;
  49853. var y1 = (dragY1 != null ? dragY1 * height : n1Layout.y) + edgeLayout.sy + edgeLayout.dy / 2;
  49854. var x2 = dragX2 != null ? dragX2 * width : n2Layout.x;
  49855. var y2 = (dragY2 != null ? dragY2 * height : n2Layout.y) + edgeLayout.ty + edgeLayout.dy / 2;
  49856. var cpx1 = x1 * (1 - curvature) + x2 * curvature;
  49857. var cpy1 = y1;
  49858. var cpx2 = x1 * curvature + x2 * (1 - curvature);
  49859. var cpy2 = y2;
  49860. curve.setShape({
  49861. x1: x1,
  49862. y1: y1,
  49863. x2: x2,
  49864. y2: y2,
  49865. cpx1: cpx1,
  49866. cpy1: cpy1,
  49867. cpx2: cpx2,
  49868. cpy2: cpy2
  49869. });
  49870. curve.setStyle(lineStyleModel.getItemStyle());
  49871. // Special color, use source node color or target node color
  49872. switch (curve.style.fill) {
  49873. case 'source':
  49874. curve.style.fill = edge.node1.getVisual('color');
  49875. break;
  49876. case 'target':
  49877. curve.style.fill = edge.node2.getVisual('color');
  49878. break;
  49879. }
  49880. setHoverStyle(curve, edge.getModel('emphasis.lineStyle').getItemStyle());
  49881. group.add(curve);
  49882. edgeData.setItemGraphicEl(edge.dataIndex, curve);
  49883. });
  49884. // generate a rect for each node
  49885. graph.eachNode(function (node) {
  49886. var layout = node.getLayout();
  49887. var itemModel = node.getModel();
  49888. var dragX = itemModel.get('localX');
  49889. var dragY = itemModel.get('localY');
  49890. var labelModel = itemModel.getModel('label');
  49891. var labelHoverModel = itemModel.getModel('emphasis.label');
  49892. var rect = new Rect({
  49893. shape: {
  49894. x: dragX != null ? dragX * width : layout.x,
  49895. y: dragY != null ? dragY * height : layout.y,
  49896. width: layout.dx,
  49897. height: layout.dy
  49898. },
  49899. style: itemModel.getModel('itemStyle').getItemStyle()
  49900. });
  49901. var hoverStyle = node.getModel('emphasis.itemStyle').getItemStyle();
  49902. setLabelStyle(
  49903. rect.style, hoverStyle, labelModel, labelHoverModel,
  49904. {
  49905. labelFetcher: seriesModel,
  49906. labelDataIndex: node.dataIndex,
  49907. defaultText: node.id,
  49908. isRectText: true
  49909. }
  49910. );
  49911. rect.setStyle('fill', node.getVisual('color'));
  49912. setHoverStyle(rect, hoverStyle);
  49913. group.add(rect);
  49914. nodeData.setItemGraphicEl(node.dataIndex, rect);
  49915. rect.dataType = 'node';
  49916. });
  49917. var draggable = seriesModel.get('draggable');
  49918. if (draggable) {
  49919. nodeData.eachItemGraphicEl(function (el, dataIndex) {
  49920. el.drift = function (dx, dy) {
  49921. this.shape.x += dx;
  49922. this.shape.y += dy;
  49923. this.dirty();
  49924. api.dispatchAction({
  49925. type: 'dragNode',
  49926. seriesId: seriesModel.id,
  49927. dataIndex: nodeData.getRawIndex(dataIndex),
  49928. localX: this.shape.x / width,
  49929. localY: this.shape.y / height
  49930. });
  49931. };
  49932. el.draggable = true;
  49933. el.cursor = 'move';
  49934. });
  49935. }
  49936. if (!this._data && seriesModel.get('animation')) {
  49937. group.setClipPath(createGridClipShape$2(group.getBoundingRect(), seriesModel, function () {
  49938. group.removeClipPath();
  49939. }));
  49940. }
  49941. this._data = seriesModel.getData();
  49942. },
  49943. dispose: function () {}
  49944. });
  49945. // add animation to the view
  49946. function createGridClipShape$2(rect, seriesModel, cb) {
  49947. var rectEl = new Rect({
  49948. shape: {
  49949. x: rect.x - 10,
  49950. y: rect.y - 10,
  49951. width: 0,
  49952. height: rect.height + 20
  49953. }
  49954. });
  49955. initProps(rectEl, {
  49956. shape: {
  49957. width: rect.width + 20,
  49958. height: rect.height + 20
  49959. }
  49960. }, seriesModel, cb);
  49961. return rectEl;
  49962. }
  49963. /*
  49964. * Licensed to the Apache Software Foundation (ASF) under one
  49965. * or more contributor license agreements. See the NOTICE file
  49966. * distributed with this work for additional information
  49967. * regarding copyright ownership. The ASF licenses this file
  49968. * to you under the Apache License, Version 2.0 (the
  49969. * "License"); you may not use this file except in compliance
  49970. * with the License. You may obtain a copy of the License at
  49971. *
  49972. * http://www.apache.org/licenses/LICENSE-2.0
  49973. *
  49974. * Unless required by applicable law or agreed to in writing,
  49975. * software distributed under the License is distributed on an
  49976. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49977. * KIND, either express or implied. See the License for the
  49978. * specific language governing permissions and limitations
  49979. * under the License.
  49980. */
  49981. registerAction({
  49982. type: 'dragNode',
  49983. event: 'dragNode',
  49984. // here can only use 'update' now, other value is not support in echarts.
  49985. update: 'update'
  49986. }, function (payload, ecModel) {
  49987. ecModel.eachComponent({mainType: 'series', subType: 'sankey', query: payload}, function (seriesModel) {
  49988. seriesModel.setNodePosition(payload.dataIndex, [payload.localX, payload.localY]);
  49989. });
  49990. });
  49991. /*
  49992. * Licensed to the Apache Software Foundation (ASF) under one
  49993. * or more contributor license agreements. See the NOTICE file
  49994. * distributed with this work for additional information
  49995. * regarding copyright ownership. The ASF licenses this file
  49996. * to you under the Apache License, Version 2.0 (the
  49997. * "License"); you may not use this file except in compliance
  49998. * with the License. You may obtain a copy of the License at
  49999. *
  50000. * http://www.apache.org/licenses/LICENSE-2.0
  50001. *
  50002. * Unless required by applicable law or agreed to in writing,
  50003. * software distributed under the License is distributed on an
  50004. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50005. * KIND, either express or implied. See the License for the
  50006. * specific language governing permissions and limitations
  50007. * under the License.
  50008. */
  50009. /**
  50010. * nest helper used to group by the array.
  50011. * can specified the keys and sort the keys.
  50012. */
  50013. function nest() {
  50014. var keysFunction = [];
  50015. var sortKeysFunction = [];
  50016. /**
  50017. * map an Array into the mapObject.
  50018. * @param {Array} array
  50019. * @param {number} depth
  50020. */
  50021. function map$$1(array, depth) {
  50022. if (depth >= keysFunction.length) {
  50023. return array;
  50024. }
  50025. var i = -1;
  50026. var n = array.length;
  50027. var keyFunction = keysFunction[depth++];
  50028. var mapObject = {};
  50029. var valuesByKey = {};
  50030. while (++i < n) {
  50031. var keyValue = keyFunction(array[i]);
  50032. var values = valuesByKey[keyValue];
  50033. if (values) {
  50034. values.push(array[i]);
  50035. }
  50036. else {
  50037. valuesByKey[keyValue] = [array[i]];
  50038. }
  50039. }
  50040. each$1(valuesByKey, function (value, key) {
  50041. mapObject[key] = map$$1(value, depth);
  50042. });
  50043. return mapObject;
  50044. }
  50045. /**
  50046. * transform the Map Object to multidimensional Array
  50047. * @param {Object} map
  50048. * @param {number} depth
  50049. */
  50050. function entriesMap(mapObject, depth) {
  50051. if (depth >= keysFunction.length) {
  50052. return mapObject;
  50053. }
  50054. var array = [];
  50055. var sortKeyFunction = sortKeysFunction[depth++];
  50056. each$1(mapObject, function (value, key) {
  50057. array.push({
  50058. key: key, values: entriesMap(value, depth)
  50059. });
  50060. });
  50061. if (sortKeyFunction) {
  50062. return array.sort(function (a, b) {
  50063. return sortKeyFunction(a.key, b.key);
  50064. });
  50065. }
  50066. else {
  50067. return array;
  50068. }
  50069. }
  50070. return {
  50071. /**
  50072. * specified the key to groupby the arrays.
  50073. * users can specified one more keys.
  50074. * @param {Function} d
  50075. */
  50076. key: function (d) {
  50077. keysFunction.push(d);
  50078. return this;
  50079. },
  50080. /**
  50081. * specified the comparator to sort the keys
  50082. * @param {Function} order
  50083. */
  50084. sortKeys: function (order) {
  50085. sortKeysFunction[keysFunction.length - 1] = order;
  50086. return this;
  50087. },
  50088. /**
  50089. * the array to be grouped by.
  50090. * @param {Array} array
  50091. */
  50092. entries: function (array) {
  50093. return entriesMap(map$$1(array, 0), 0);
  50094. }
  50095. };
  50096. }
  50097. /*
  50098. * Licensed to the Apache Software Foundation (ASF) under one
  50099. * or more contributor license agreements. See the NOTICE file
  50100. * distributed with this work for additional information
  50101. * regarding copyright ownership. The ASF licenses this file
  50102. * to you under the Apache License, Version 2.0 (the
  50103. * "License"); you may not use this file except in compliance
  50104. * with the License. You may obtain a copy of the License at
  50105. *
  50106. * http://www.apache.org/licenses/LICENSE-2.0
  50107. *
  50108. * Unless required by applicable law or agreed to in writing,
  50109. * software distributed under the License is distributed on an
  50110. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50111. * KIND, either express or implied. See the License for the
  50112. * specific language governing permissions and limitations
  50113. * under the License.
  50114. */
  50115. /**
  50116. * @file The layout algorithm of sankey view
  50117. * @author Deqing Li(annong035@gmail.com)
  50118. */
  50119. var sankeyLayout = function (ecModel, api, payload) {
  50120. ecModel.eachSeriesByType('sankey', function (seriesModel) {
  50121. var nodeWidth = seriesModel.get('nodeWidth');
  50122. var nodeGap = seriesModel.get('nodeGap');
  50123. var layoutInfo = getViewRect$3(seriesModel, api);
  50124. seriesModel.layoutInfo = layoutInfo;
  50125. var width = layoutInfo.width;
  50126. var height = layoutInfo.height;
  50127. var graph = seriesModel.getGraph();
  50128. var nodes = graph.nodes;
  50129. var edges = graph.edges;
  50130. computeNodeValues(nodes);
  50131. var filteredNodes = filter(nodes, function (node) {
  50132. return node.getLayout().value === 0;
  50133. });
  50134. var iterations = filteredNodes.length !== 0
  50135. ? 0 : seriesModel.get('layoutIterations');
  50136. layoutSankey(nodes, edges, nodeWidth, nodeGap, width, height, iterations);
  50137. });
  50138. };
  50139. /**
  50140. * Get the layout position of the whole view
  50141. *
  50142. * @param {module:echarts/model/Series} seriesModel the model object of sankey series
  50143. * @param {module:echarts/ExtensionAPI} api provide the API list that the developer can call
  50144. * @return {module:zrender/core/BoundingRect} size of rect to draw the sankey view
  50145. */
  50146. function getViewRect$3(seriesModel, api) {
  50147. return getLayoutRect(
  50148. seriesModel.getBoxLayoutParams(), {
  50149. width: api.getWidth(),
  50150. height: api.getHeight()
  50151. }
  50152. );
  50153. }
  50154. function layoutSankey(nodes, edges, nodeWidth, nodeGap, width, height, iterations) {
  50155. computeNodeBreadths(nodes, edges, nodeWidth, width);
  50156. computeNodeDepths(nodes, edges, height, nodeGap, iterations);
  50157. computeEdgeDepths(nodes);
  50158. }
  50159. /**
  50160. * Compute the value of each node by summing the associated edge's value
  50161. *
  50162. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  50163. */
  50164. function computeNodeValues(nodes) {
  50165. each$1(nodes, function (node) {
  50166. var value1 = sum(node.outEdges, getEdgeValue);
  50167. var value2 = sum(node.inEdges, getEdgeValue);
  50168. var value = Math.max(value1, value2);
  50169. node.setLayout({value: value}, true);
  50170. });
  50171. }
  50172. /**
  50173. * Compute the x-position for each node.
  50174. *
  50175. * Here we use Kahn algorithm to detect cycle when we traverse
  50176. * the node to computer the initial x position.
  50177. *
  50178. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  50179. * @param {number} nodeWidth the dx of the node
  50180. * @param {number} width the whole width of the area to draw the view
  50181. */
  50182. function computeNodeBreadths(nodes, edges, nodeWidth, width) {
  50183. // Used to mark whether the edge is deleted. if it is deleted,
  50184. // the value is 0, otherwise it is 1.
  50185. var remainEdges = [];
  50186. // Storage each node's indegree.
  50187. var indegreeArr = [];
  50188. //Used to storage the node with indegree is equal to 0.
  50189. var zeroIndegrees = [];
  50190. var nextNode = [];
  50191. var x = 0;
  50192. var kx = 0;
  50193. for (var i = 0; i < edges.length; i++) {
  50194. remainEdges[i] = 1;
  50195. }
  50196. for (var i = 0; i < nodes.length; i++) {
  50197. indegreeArr[i] = nodes[i].inEdges.length;
  50198. if (indegreeArr[i] === 0) {
  50199. zeroIndegrees.push(nodes[i]);
  50200. }
  50201. }
  50202. while (zeroIndegrees.length) {
  50203. each$1(zeroIndegrees, function (node) {
  50204. node.setLayout({x: x}, true);
  50205. node.setLayout({dx: nodeWidth}, true);
  50206. each$1(node.outEdges, function (edge) {
  50207. var indexEdge = edges.indexOf(edge);
  50208. remainEdges[indexEdge] = 0;
  50209. var targetNode = edge.node2;
  50210. var nodeIndex = nodes.indexOf(targetNode);
  50211. if (--indegreeArr[nodeIndex] === 0) {
  50212. nextNode.push(targetNode);
  50213. }
  50214. });
  50215. });
  50216. ++x;
  50217. zeroIndegrees = nextNode;
  50218. nextNode = [];
  50219. }
  50220. for (var i = 0; i < remainEdges.length; i++) {
  50221. if (__DEV__) {
  50222. if (remainEdges[i] === 1) {
  50223. throw new Error('Sankey is a DAG, the original data has cycle!');
  50224. }
  50225. }
  50226. }
  50227. moveSinksRight(nodes, x);
  50228. kx = (width - nodeWidth) / (x - 1);
  50229. scaleNodeBreadths(nodes, kx);
  50230. }
  50231. /**
  50232. * All the node without outEgdes are assigned maximum x-position and
  50233. * be aligned in the last column.
  50234. *
  50235. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  50236. * @param {number} x value (x-1) use to assign to node without outEdges
  50237. * as x-position
  50238. */
  50239. function moveSinksRight(nodes, x) {
  50240. each$1(nodes, function (node) {
  50241. if (!node.outEdges.length) {
  50242. node.setLayout({x: x - 1}, true);
  50243. }
  50244. });
  50245. }
  50246. /**
  50247. * Scale node x-position to the width
  50248. *
  50249. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  50250. * @param {number} kx multiple used to scale nodes
  50251. */
  50252. function scaleNodeBreadths(nodes, kx) {
  50253. each$1(nodes, function (node) {
  50254. var nodeX = node.getLayout().x * kx;
  50255. node.setLayout({x: nodeX}, true);
  50256. });
  50257. }
  50258. /**
  50259. * Using Gauss-Seidel iterations method to compute the node depth(y-position)
  50260. *
  50261. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  50262. * @param {module:echarts/data/Graph~Edge} edges edge of sankey view
  50263. * @param {number} height the whole height of the area to draw the view
  50264. * @param {number} nodeGap the vertical distance between two nodes
  50265. * in the same column.
  50266. * @param {number} iterations the number of iterations for the algorithm
  50267. */
  50268. function computeNodeDepths(nodes, edges, height, nodeGap, iterations) {
  50269. var nodesByBreadth = nest()
  50270. .key(function (d) {
  50271. return d.getLayout().x;
  50272. })
  50273. .sortKeys(ascending)
  50274. .entries(nodes)
  50275. .map(function (d) {
  50276. return d.values;
  50277. });
  50278. initializeNodeDepth(nodes, nodesByBreadth, edges, height, nodeGap);
  50279. resolveCollisions(nodesByBreadth, nodeGap, height);
  50280. for (var alpha = 1; iterations > 0; iterations--) {
  50281. // 0.99 is a experience parameter, ensure that each iterations of
  50282. // changes as small as possible.
  50283. alpha *= 0.99;
  50284. relaxRightToLeft(nodesByBreadth, alpha);
  50285. resolveCollisions(nodesByBreadth, nodeGap, height);
  50286. relaxLeftToRight(nodesByBreadth, alpha);
  50287. resolveCollisions(nodesByBreadth, nodeGap, height);
  50288. }
  50289. }
  50290. /**
  50291. * Compute the original y-position for each node
  50292. *
  50293. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  50294. * @param {Array.<Array.<module:echarts/data/Graph~Node>>} nodesByBreadth
  50295. * group by the array of all sankey nodes based on the nodes x-position.
  50296. * @param {module:echarts/data/Graph~Edge} edges edge of sankey view
  50297. * @param {number} height the whole height of the area to draw the view
  50298. * @param {number} nodeGap the vertical distance between two nodes
  50299. */
  50300. function initializeNodeDepth(nodes, nodesByBreadth, edges, height, nodeGap) {
  50301. var kyArray = [];
  50302. each$1(nodesByBreadth, function (nodes) {
  50303. var n = nodes.length;
  50304. var sum = 0;
  50305. each$1(nodes, function (node) {
  50306. sum += node.getLayout().value;
  50307. });
  50308. var ky = (height - (n - 1) * nodeGap) / sum;
  50309. kyArray.push(ky);
  50310. });
  50311. kyArray.sort(function (a, b) {
  50312. return a - b;
  50313. });
  50314. var ky0 = kyArray[0];
  50315. each$1(nodesByBreadth, function (nodes) {
  50316. each$1(nodes, function (node, i) {
  50317. node.setLayout({y: i}, true);
  50318. var nodeDy = node.getLayout().value * ky0;
  50319. node.setLayout({dy: nodeDy}, true);
  50320. });
  50321. });
  50322. each$1(edges, function (edge) {
  50323. var edgeDy = +edge.getValue() * ky0;
  50324. edge.setLayout({dy: edgeDy}, true);
  50325. });
  50326. }
  50327. /**
  50328. * Resolve the collision of initialized depth (y-position)
  50329. *
  50330. * @param {Array.<Array.<module:echarts/data/Graph~Node>>} nodesByBreadth
  50331. * group by the array of all sankey nodes based on the nodes x-position.
  50332. * @param {number} nodeGap the vertical distance between two nodes
  50333. * @param {number} height the whole height of the area to draw the view
  50334. */
  50335. function resolveCollisions(nodesByBreadth, nodeGap, height) {
  50336. each$1(nodesByBreadth, function (nodes) {
  50337. var node;
  50338. var dy;
  50339. var y0 = 0;
  50340. var n = nodes.length;
  50341. var i;
  50342. nodes.sort(ascendingDepth);
  50343. for (i = 0; i < n; i++) {
  50344. node = nodes[i];
  50345. dy = y0 - node.getLayout().y;
  50346. if (dy > 0) {
  50347. var nodeY = node.getLayout().y + dy;
  50348. node.setLayout({y: nodeY}, true);
  50349. }
  50350. y0 = node.getLayout().y + node.getLayout().dy + nodeGap;
  50351. }
  50352. // If the bottommost node goes outside the bounds, push it back up
  50353. dy = y0 - nodeGap - height;
  50354. if (dy > 0) {
  50355. var nodeY = node.getLayout().y - dy;
  50356. node.setLayout({y: nodeY}, true);
  50357. y0 = node.getLayout().y;
  50358. for (i = n - 2; i >= 0; --i) {
  50359. node = nodes[i];
  50360. dy = node.getLayout().y + node.getLayout().dy + nodeGap - y0;
  50361. if (dy > 0) {
  50362. nodeY = node.getLayout().y - dy;
  50363. node.setLayout({y: nodeY}, true);
  50364. }
  50365. y0 = node.getLayout().y;
  50366. }
  50367. }
  50368. });
  50369. }
  50370. /**
  50371. * Change the y-position of the nodes, except most the right side nodes
  50372. *
  50373. * @param {Array.<Array.<module:echarts/data/Graph~Node>>} nodesByBreadth
  50374. * group by the array of all sankey nodes based on the node x-position.
  50375. * @param {number} alpha parameter used to adjust the nodes y-position
  50376. */
  50377. function relaxRightToLeft(nodesByBreadth, alpha) {
  50378. each$1(nodesByBreadth.slice().reverse(), function (nodes) {
  50379. each$1(nodes, function (node) {
  50380. if (node.outEdges.length) {
  50381. var y = sum(node.outEdges, weightedTarget) / sum(node.outEdges, getEdgeValue);
  50382. var nodeY = node.getLayout().y + (y - center$1(node)) * alpha;
  50383. node.setLayout({y: nodeY}, true);
  50384. }
  50385. });
  50386. });
  50387. }
  50388. function weightedTarget(edge) {
  50389. return center$1(edge.node2) * edge.getValue();
  50390. }
  50391. /**
  50392. * Change the y-position of the nodes, except most the left side nodes
  50393. *
  50394. * @param {Array.<Array.<module:echarts/data/Graph~Node>>} nodesByBreadth
  50395. * group by the array of all sankey nodes based on the node x-position.
  50396. * @param {number} alpha parameter used to adjust the nodes y-position
  50397. */
  50398. function relaxLeftToRight(nodesByBreadth, alpha) {
  50399. each$1(nodesByBreadth, function (nodes) {
  50400. each$1(nodes, function (node) {
  50401. if (node.inEdges.length) {
  50402. var y = sum(node.inEdges, weightedSource) / sum(node.inEdges, getEdgeValue);
  50403. var nodeY = node.getLayout().y + (y - center$1(node)) * alpha;
  50404. node.setLayout({y: nodeY}, true);
  50405. }
  50406. });
  50407. });
  50408. }
  50409. function weightedSource(edge) {
  50410. return center$1(edge.node1) * edge.getValue();
  50411. }
  50412. /**
  50413. * Compute the depth(y-position) of each edge
  50414. *
  50415. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  50416. */
  50417. function computeEdgeDepths(nodes) {
  50418. each$1(nodes, function (node) {
  50419. node.outEdges.sort(ascendingTargetDepth);
  50420. node.inEdges.sort(ascendingSourceDepth);
  50421. });
  50422. each$1(nodes, function (node) {
  50423. var sy = 0;
  50424. var ty = 0;
  50425. each$1(node.outEdges, function (edge) {
  50426. edge.setLayout({sy: sy}, true);
  50427. sy += edge.getLayout().dy;
  50428. });
  50429. each$1(node.inEdges, function (edge) {
  50430. edge.setLayout({ty: ty}, true);
  50431. ty += edge.getLayout().dy;
  50432. });
  50433. });
  50434. }
  50435. function ascendingTargetDepth(a, b) {
  50436. return a.node2.getLayout().y - b.node2.getLayout().y;
  50437. }
  50438. function ascendingSourceDepth(a, b) {
  50439. return a.node1.getLayout().y - b.node1.getLayout().y;
  50440. }
  50441. function sum(array, f) {
  50442. var sum = 0;
  50443. var len = array.length;
  50444. var i = -1;
  50445. while (++i < len) {
  50446. var value = +f.call(array, array[i], i);
  50447. if (!isNaN(value)) {
  50448. sum += value;
  50449. }
  50450. }
  50451. return sum;
  50452. }
  50453. function center$1(node) {
  50454. return node.getLayout().y + node.getLayout().dy / 2;
  50455. }
  50456. function ascendingDepth(a, b) {
  50457. return a.getLayout().y - b.getLayout().y;
  50458. }
  50459. function ascending(a, b) {
  50460. return a - b;
  50461. }
  50462. function getEdgeValue(edge) {
  50463. return edge.getValue();
  50464. }
  50465. /*
  50466. * Licensed to the Apache Software Foundation (ASF) under one
  50467. * or more contributor license agreements. See the NOTICE file
  50468. * distributed with this work for additional information
  50469. * regarding copyright ownership. The ASF licenses this file
  50470. * to you under the Apache License, Version 2.0 (the
  50471. * "License"); you may not use this file except in compliance
  50472. * with the License. You may obtain a copy of the License at
  50473. *
  50474. * http://www.apache.org/licenses/LICENSE-2.0
  50475. *
  50476. * Unless required by applicable law or agreed to in writing,
  50477. * software distributed under the License is distributed on an
  50478. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50479. * KIND, either express or implied. See the License for the
  50480. * specific language governing permissions and limitations
  50481. * under the License.
  50482. */
  50483. /**
  50484. * @file Visual encoding for sankey view
  50485. * @author Deqing Li(annong035@gmail.com)
  50486. */
  50487. var sankeyVisual = function (ecModel, payload) {
  50488. ecModel.eachSeriesByType('sankey', function (seriesModel) {
  50489. var graph = seriesModel.getGraph();
  50490. var nodes = graph.nodes;
  50491. if (nodes.length) {
  50492. var minValue = Infinity;
  50493. var maxValue = -Infinity;
  50494. each$1(nodes, function (node) {
  50495. var nodeValue = node.getLayout().value;
  50496. if (nodeValue < minValue) {
  50497. minValue = nodeValue;
  50498. }
  50499. if (nodeValue > maxValue) {
  50500. maxValue = nodeValue;
  50501. }
  50502. });
  50503. each$1(nodes, function (node) {
  50504. var mapping = new VisualMapping({
  50505. type: 'color',
  50506. mappingMethod: 'linear',
  50507. dataExtent: [minValue, maxValue],
  50508. visual: seriesModel.get('color')
  50509. });
  50510. var mapValueToColor = mapping.mapValueToVisual(node.getLayout().value);
  50511. node.setVisual('color', mapValueToColor);
  50512. // If set itemStyle.normal.color
  50513. var itemModel = node.getModel();
  50514. var customColor = itemModel.get('itemStyle.color');
  50515. if (customColor != null) {
  50516. node.setVisual('color', customColor);
  50517. }
  50518. });
  50519. }
  50520. });
  50521. };
  50522. /*
  50523. * Licensed to the Apache Software Foundation (ASF) under one
  50524. * or more contributor license agreements. See the NOTICE file
  50525. * distributed with this work for additional information
  50526. * regarding copyright ownership. The ASF licenses this file
  50527. * to you under the Apache License, Version 2.0 (the
  50528. * "License"); you may not use this file except in compliance
  50529. * with the License. You may obtain a copy of the License at
  50530. *
  50531. * http://www.apache.org/licenses/LICENSE-2.0
  50532. *
  50533. * Unless required by applicable law or agreed to in writing,
  50534. * software distributed under the License is distributed on an
  50535. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50536. * KIND, either express or implied. See the License for the
  50537. * specific language governing permissions and limitations
  50538. * under the License.
  50539. */
  50540. registerLayout(sankeyLayout);
  50541. registerVisual(sankeyVisual);
  50542. /*
  50543. * Licensed to the Apache Software Foundation (ASF) under one
  50544. * or more contributor license agreements. See the NOTICE file
  50545. * distributed with this work for additional information
  50546. * regarding copyright ownership. The ASF licenses this file
  50547. * to you under the Apache License, Version 2.0 (the
  50548. * "License"); you may not use this file except in compliance
  50549. * with the License. You may obtain a copy of the License at
  50550. *
  50551. * http://www.apache.org/licenses/LICENSE-2.0
  50552. *
  50553. * Unless required by applicable law or agreed to in writing,
  50554. * software distributed under the License is distributed on an
  50555. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50556. * KIND, either express or implied. See the License for the
  50557. * specific language governing permissions and limitations
  50558. * under the License.
  50559. */
  50560. var seriesModelMixin = {
  50561. /**
  50562. * @private
  50563. * @type {string}
  50564. */
  50565. _baseAxisDim: null,
  50566. /**
  50567. * @override
  50568. */
  50569. getInitialData: function (option, ecModel) {
  50570. // When both types of xAxis and yAxis are 'value', layout is
  50571. // needed to be specified by user. Otherwise, layout can be
  50572. // judged by which axis is category.
  50573. var ordinalMeta;
  50574. var xAxisModel = ecModel.getComponent('xAxis', this.get('xAxisIndex'));
  50575. var yAxisModel = ecModel.getComponent('yAxis', this.get('yAxisIndex'));
  50576. var xAxisType = xAxisModel.get('type');
  50577. var yAxisType = yAxisModel.get('type');
  50578. var addOrdinal;
  50579. // FIXME
  50580. // 考虑时间轴
  50581. if (xAxisType === 'category') {
  50582. option.layout = 'horizontal';
  50583. ordinalMeta = xAxisModel.getOrdinalMeta();
  50584. addOrdinal = true;
  50585. }
  50586. else if (yAxisType === 'category') {
  50587. option.layout = 'vertical';
  50588. ordinalMeta = yAxisModel.getOrdinalMeta();
  50589. addOrdinal = true;
  50590. }
  50591. else {
  50592. option.layout = option.layout || 'horizontal';
  50593. }
  50594. var coordDims = ['x', 'y'];
  50595. var baseAxisDimIndex = option.layout === 'horizontal' ? 0 : 1;
  50596. var baseAxisDim = this._baseAxisDim = coordDims[baseAxisDimIndex];
  50597. var otherAxisDim = coordDims[1 - baseAxisDimIndex];
  50598. var axisModels = [xAxisModel, yAxisModel];
  50599. var baseAxisType = axisModels[baseAxisDimIndex].get('type');
  50600. var otherAxisType = axisModels[1 - baseAxisDimIndex].get('type');
  50601. var data = option.data;
  50602. // ??? FIXME make a stage to perform data transfrom.
  50603. // MUST create a new data, consider setOption({}) again.
  50604. if (data && addOrdinal) {
  50605. var newOptionData = [];
  50606. each$1(data, function (item, index) {
  50607. var newItem;
  50608. if (item.value && isArray(item.value)) {
  50609. newItem = item.value.slice();
  50610. item.value.unshift(index);
  50611. }
  50612. else if (isArray(item)) {
  50613. newItem = item.slice();
  50614. item.unshift(index);
  50615. }
  50616. else {
  50617. newItem = item;
  50618. }
  50619. newOptionData.push(newItem);
  50620. });
  50621. option.data = newOptionData;
  50622. }
  50623. var defaultValueDimensions = this.defaultValueDimensions;
  50624. return createListSimply(
  50625. this,
  50626. {
  50627. coordDimensions: [{
  50628. name: baseAxisDim,
  50629. type: getDimensionTypeByAxis(baseAxisType),
  50630. ordinalMeta: ordinalMeta,
  50631. otherDims: {
  50632. tooltip: false,
  50633. itemName: 0
  50634. },
  50635. dimsDef: ['base']
  50636. }, {
  50637. name: otherAxisDim,
  50638. type: getDimensionTypeByAxis(otherAxisType),
  50639. dimsDef: defaultValueDimensions.slice()
  50640. }],
  50641. dimensionsCount: defaultValueDimensions.length + 1
  50642. }
  50643. );
  50644. },
  50645. /**
  50646. * If horizontal, base axis is x, otherwise y.
  50647. * @override
  50648. */
  50649. getBaseAxis: function () {
  50650. var dim = this._baseAxisDim;
  50651. return this.ecModel.getComponent(dim + 'Axis', this.get(dim + 'AxisIndex')).axis;
  50652. }
  50653. };
  50654. /*
  50655. * Licensed to the Apache Software Foundation (ASF) under one
  50656. * or more contributor license agreements. See the NOTICE file
  50657. * distributed with this work for additional information
  50658. * regarding copyright ownership. The ASF licenses this file
  50659. * to you under the Apache License, Version 2.0 (the
  50660. * "License"); you may not use this file except in compliance
  50661. * with the License. You may obtain a copy of the License at
  50662. *
  50663. * http://www.apache.org/licenses/LICENSE-2.0
  50664. *
  50665. * Unless required by applicable law or agreed to in writing,
  50666. * software distributed under the License is distributed on an
  50667. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50668. * KIND, either express or implied. See the License for the
  50669. * specific language governing permissions and limitations
  50670. * under the License.
  50671. */
  50672. var BoxplotSeries = SeriesModel.extend({
  50673. type: 'series.boxplot',
  50674. dependencies: ['xAxis', 'yAxis', 'grid'],
  50675. // TODO
  50676. // box width represents group size, so dimension should have 'size'.
  50677. /**
  50678. * @see <https://en.wikipedia.org/wiki/Box_plot>
  50679. * The meanings of 'min' and 'max' depend on user,
  50680. * and echarts do not need to know it.
  50681. * @readOnly
  50682. */
  50683. defaultValueDimensions: [
  50684. {name: 'min', defaultTooltip: true},
  50685. {name: 'Q1', defaultTooltip: true},
  50686. {name: 'median', defaultTooltip: true},
  50687. {name: 'Q3', defaultTooltip: true},
  50688. {name: 'max', defaultTooltip: true}
  50689. ],
  50690. /**
  50691. * @type {Array.<string>}
  50692. * @readOnly
  50693. */
  50694. dimensions: null,
  50695. /**
  50696. * @override
  50697. */
  50698. defaultOption: {
  50699. zlevel: 0, // 一级层叠
  50700. z: 2, // 二级层叠
  50701. coordinateSystem: 'cartesian2d',
  50702. legendHoverLink: true,
  50703. hoverAnimation: true,
  50704. // xAxisIndex: 0,
  50705. // yAxisIndex: 0,
  50706. layout: null, // 'horizontal' or 'vertical'
  50707. boxWidth: [7, 50], // [min, max] can be percent of band width.
  50708. itemStyle: {
  50709. color: '#fff',
  50710. borderWidth: 1
  50711. },
  50712. emphasis: {
  50713. itemStyle: {
  50714. borderWidth: 2,
  50715. shadowBlur: 5,
  50716. shadowOffsetX: 2,
  50717. shadowOffsetY: 2,
  50718. shadowColor: 'rgba(0,0,0,0.4)'
  50719. }
  50720. },
  50721. animationEasing: 'elasticOut',
  50722. animationDuration: 800
  50723. }
  50724. });
  50725. mixin(BoxplotSeries, seriesModelMixin, true);
  50726. /*
  50727. * Licensed to the Apache Software Foundation (ASF) under one
  50728. * or more contributor license agreements. See the NOTICE file
  50729. * distributed with this work for additional information
  50730. * regarding copyright ownership. The ASF licenses this file
  50731. * to you under the Apache License, Version 2.0 (the
  50732. * "License"); you may not use this file except in compliance
  50733. * with the License. You may obtain a copy of the License at
  50734. *
  50735. * http://www.apache.org/licenses/LICENSE-2.0
  50736. *
  50737. * Unless required by applicable law or agreed to in writing,
  50738. * software distributed under the License is distributed on an
  50739. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50740. * KIND, either express or implied. See the License for the
  50741. * specific language governing permissions and limitations
  50742. * under the License.
  50743. */
  50744. // Update common properties
  50745. var NORMAL_ITEM_STYLE_PATH = ['itemStyle'];
  50746. var EMPHASIS_ITEM_STYLE_PATH = ['emphasis', 'itemStyle'];
  50747. var BoxplotView = Chart.extend({
  50748. type: 'boxplot',
  50749. render: function (seriesModel, ecModel, api) {
  50750. var data = seriesModel.getData();
  50751. var group = this.group;
  50752. var oldData = this._data;
  50753. // There is no old data only when first rendering or switching from
  50754. // stream mode to normal mode, where previous elements should be removed.
  50755. if (!this._data) {
  50756. group.removeAll();
  50757. }
  50758. var constDim = seriesModel.get('layout') === 'horizontal' ? 1 : 0;
  50759. data.diff(oldData)
  50760. .add(function (newIdx) {
  50761. if (data.hasValue(newIdx)) {
  50762. var itemLayout = data.getItemLayout(newIdx);
  50763. var symbolEl = createNormalBox(itemLayout, data, newIdx, constDim, true);
  50764. data.setItemGraphicEl(newIdx, symbolEl);
  50765. group.add(symbolEl);
  50766. }
  50767. })
  50768. .update(function (newIdx, oldIdx) {
  50769. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  50770. // Empty data
  50771. if (!data.hasValue(newIdx)) {
  50772. group.remove(symbolEl);
  50773. return;
  50774. }
  50775. var itemLayout = data.getItemLayout(newIdx);
  50776. if (!symbolEl) {
  50777. symbolEl = createNormalBox(itemLayout, data, newIdx, constDim);
  50778. }
  50779. else {
  50780. updateNormalBoxData(itemLayout, symbolEl, data, newIdx);
  50781. }
  50782. group.add(symbolEl);
  50783. data.setItemGraphicEl(newIdx, symbolEl);
  50784. })
  50785. .remove(function (oldIdx) {
  50786. var el = oldData.getItemGraphicEl(oldIdx);
  50787. el && group.remove(el);
  50788. })
  50789. .execute();
  50790. this._data = data;
  50791. },
  50792. remove: function (ecModel) {
  50793. var group = this.group;
  50794. var data = this._data;
  50795. this._data = null;
  50796. data && data.eachItemGraphicEl(function (el) {
  50797. el && group.remove(el);
  50798. });
  50799. },
  50800. dispose: noop
  50801. });
  50802. var BoxPath = Path.extend({
  50803. type: 'boxplotBoxPath',
  50804. shape: {},
  50805. buildPath: function (ctx, shape) {
  50806. var ends = shape.points;
  50807. var i = 0;
  50808. ctx.moveTo(ends[i][0], ends[i][1]);
  50809. i++;
  50810. for (; i < 4; i++) {
  50811. ctx.lineTo(ends[i][0], ends[i][1]);
  50812. }
  50813. ctx.closePath();
  50814. for (; i < ends.length; i++) {
  50815. ctx.moveTo(ends[i][0], ends[i][1]);
  50816. i++;
  50817. ctx.lineTo(ends[i][0], ends[i][1]);
  50818. }
  50819. }
  50820. });
  50821. function createNormalBox(itemLayout, data, dataIndex, constDim, isInit) {
  50822. var ends = itemLayout.ends;
  50823. var el = new BoxPath({
  50824. shape: {
  50825. points: isInit
  50826. ? transInit(ends, constDim, itemLayout)
  50827. : ends
  50828. }
  50829. });
  50830. updateNormalBoxData(itemLayout, el, data, dataIndex, isInit);
  50831. return el;
  50832. }
  50833. function updateNormalBoxData(itemLayout, el, data, dataIndex, isInit) {
  50834. var seriesModel = data.hostModel;
  50835. var updateMethod = graphic[isInit ? 'initProps' : 'updateProps'];
  50836. updateMethod(
  50837. el,
  50838. {shape: {points: itemLayout.ends}},
  50839. seriesModel,
  50840. dataIndex
  50841. );
  50842. var itemModel = data.getItemModel(dataIndex);
  50843. var normalItemStyleModel = itemModel.getModel(NORMAL_ITEM_STYLE_PATH);
  50844. var borderColor = data.getItemVisual(dataIndex, 'color');
  50845. // Exclude borderColor.
  50846. var itemStyle = normalItemStyleModel.getItemStyle(['borderColor']);
  50847. itemStyle.stroke = borderColor;
  50848. itemStyle.strokeNoScale = true;
  50849. el.useStyle(itemStyle);
  50850. el.z2 = 100;
  50851. var hoverStyle = itemModel.getModel(EMPHASIS_ITEM_STYLE_PATH).getItemStyle();
  50852. setHoverStyle(el, hoverStyle);
  50853. }
  50854. function transInit(points, dim, itemLayout) {
  50855. return map(points, function (point) {
  50856. point = point.slice();
  50857. point[dim] = itemLayout.initBaseline;
  50858. return point;
  50859. });
  50860. }
  50861. /*
  50862. * Licensed to the Apache Software Foundation (ASF) under one
  50863. * or more contributor license agreements. See the NOTICE file
  50864. * distributed with this work for additional information
  50865. * regarding copyright ownership. The ASF licenses this file
  50866. * to you under the Apache License, Version 2.0 (the
  50867. * "License"); you may not use this file except in compliance
  50868. * with the License. You may obtain a copy of the License at
  50869. *
  50870. * http://www.apache.org/licenses/LICENSE-2.0
  50871. *
  50872. * Unless required by applicable law or agreed to in writing,
  50873. * software distributed under the License is distributed on an
  50874. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50875. * KIND, either express or implied. See the License for the
  50876. * specific language governing permissions and limitations
  50877. * under the License.
  50878. */
  50879. var borderColorQuery = ['itemStyle', 'borderColor'];
  50880. var boxplotVisual = function (ecModel, api) {
  50881. var globalColors = ecModel.get('color');
  50882. ecModel.eachRawSeriesByType('boxplot', function (seriesModel) {
  50883. var defaulColor = globalColors[seriesModel.seriesIndex % globalColors.length];
  50884. var data = seriesModel.getData();
  50885. data.setVisual({
  50886. legendSymbol: 'roundRect',
  50887. // Use name 'color' but not 'borderColor' for legend usage and
  50888. // visual coding from other component like dataRange.
  50889. color: seriesModel.get(borderColorQuery) || defaulColor
  50890. });
  50891. // Only visible series has each data be visual encoded
  50892. if (!ecModel.isSeriesFiltered(seriesModel)) {
  50893. data.each(function (idx) {
  50894. var itemModel = data.getItemModel(idx);
  50895. data.setItemVisual(
  50896. idx,
  50897. {color: itemModel.get(borderColorQuery, true)}
  50898. );
  50899. });
  50900. }
  50901. });
  50902. };
  50903. /*
  50904. * Licensed to the Apache Software Foundation (ASF) under one
  50905. * or more contributor license agreements. See the NOTICE file
  50906. * distributed with this work for additional information
  50907. * regarding copyright ownership. The ASF licenses this file
  50908. * to you under the Apache License, Version 2.0 (the
  50909. * "License"); you may not use this file except in compliance
  50910. * with the License. You may obtain a copy of the License at
  50911. *
  50912. * http://www.apache.org/licenses/LICENSE-2.0
  50913. *
  50914. * Unless required by applicable law or agreed to in writing,
  50915. * software distributed under the License is distributed on an
  50916. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50917. * KIND, either express or implied. See the License for the
  50918. * specific language governing permissions and limitations
  50919. * under the License.
  50920. */
  50921. var each$13 = each$1;
  50922. var boxplotLayout = function (ecModel) {
  50923. var groupResult = groupSeriesByAxis(ecModel);
  50924. each$13(groupResult, function (groupItem) {
  50925. var seriesModels = groupItem.seriesModels;
  50926. if (!seriesModels.length) {
  50927. return;
  50928. }
  50929. calculateBase(groupItem);
  50930. each$13(seriesModels, function (seriesModel, idx) {
  50931. layoutSingleSeries(
  50932. seriesModel,
  50933. groupItem.boxOffsetList[idx],
  50934. groupItem.boxWidthList[idx]
  50935. );
  50936. });
  50937. });
  50938. };
  50939. /**
  50940. * Group series by axis.
  50941. */
  50942. function groupSeriesByAxis(ecModel) {
  50943. var result = [];
  50944. var axisList = [];
  50945. ecModel.eachSeriesByType('boxplot', function (seriesModel) {
  50946. var baseAxis = seriesModel.getBaseAxis();
  50947. var idx = indexOf(axisList, baseAxis);
  50948. if (idx < 0) {
  50949. idx = axisList.length;
  50950. axisList[idx] = baseAxis;
  50951. result[idx] = {axis: baseAxis, seriesModels: []};
  50952. }
  50953. result[idx].seriesModels.push(seriesModel);
  50954. });
  50955. return result;
  50956. }
  50957. /**
  50958. * Calculate offset and box width for each series.
  50959. */
  50960. function calculateBase(groupItem) {
  50961. var extent;
  50962. var baseAxis = groupItem.axis;
  50963. var seriesModels = groupItem.seriesModels;
  50964. var seriesCount = seriesModels.length;
  50965. var boxWidthList = groupItem.boxWidthList = [];
  50966. var boxOffsetList = groupItem.boxOffsetList = [];
  50967. var boundList = [];
  50968. var bandWidth;
  50969. if (baseAxis.type === 'category') {
  50970. bandWidth = baseAxis.getBandWidth();
  50971. }
  50972. else {
  50973. var maxDataCount = 0;
  50974. each$13(seriesModels, function (seriesModel) {
  50975. maxDataCount = Math.max(maxDataCount, seriesModel.getData().count());
  50976. });
  50977. extent = baseAxis.getExtent(),
  50978. Math.abs(extent[1] - extent[0]) / maxDataCount;
  50979. }
  50980. each$13(seriesModels, function (seriesModel) {
  50981. var boxWidthBound = seriesModel.get('boxWidth');
  50982. if (!isArray(boxWidthBound)) {
  50983. boxWidthBound = [boxWidthBound, boxWidthBound];
  50984. }
  50985. boundList.push([
  50986. parsePercent$1(boxWidthBound[0], bandWidth) || 0,
  50987. parsePercent$1(boxWidthBound[1], bandWidth) || 0
  50988. ]);
  50989. });
  50990. var availableWidth = bandWidth * 0.8 - 2;
  50991. var boxGap = availableWidth / seriesCount * 0.3;
  50992. var boxWidth = (availableWidth - boxGap * (seriesCount - 1)) / seriesCount;
  50993. var base = boxWidth / 2 - availableWidth / 2;
  50994. each$13(seriesModels, function (seriesModel, idx) {
  50995. boxOffsetList.push(base);
  50996. base += boxGap + boxWidth;
  50997. boxWidthList.push(
  50998. Math.min(Math.max(boxWidth, boundList[idx][0]), boundList[idx][1])
  50999. );
  51000. });
  51001. }
  51002. /**
  51003. * Calculate points location for each series.
  51004. */
  51005. function layoutSingleSeries(seriesModel, offset, boxWidth) {
  51006. var coordSys = seriesModel.coordinateSystem;
  51007. var data = seriesModel.getData();
  51008. var halfWidth = boxWidth / 2;
  51009. var cDimIdx = seriesModel.get('layout') === 'horizontal' ? 0 : 1;
  51010. var vDimIdx = 1 - cDimIdx;
  51011. var coordDims = ['x', 'y'];
  51012. var cDim = data.mapDimension(coordDims[cDimIdx]);
  51013. var vDims = data.mapDimension(coordDims[vDimIdx], true);
  51014. if (cDim == null || vDims.length < 5) {
  51015. return;
  51016. }
  51017. for (var dataIndex = 0; dataIndex < data.count(); dataIndex++) {
  51018. var axisDimVal = data.get(cDim, dataIndex);
  51019. var median = getPoint(axisDimVal, vDims[2], dataIndex);
  51020. var end1 = getPoint(axisDimVal, vDims[0], dataIndex);
  51021. var end2 = getPoint(axisDimVal, vDims[1], dataIndex);
  51022. var end4 = getPoint(axisDimVal, vDims[3], dataIndex);
  51023. var end5 = getPoint(axisDimVal, vDims[4], dataIndex);
  51024. var ends = [];
  51025. addBodyEnd(ends, end2, 0);
  51026. addBodyEnd(ends, end4, 1);
  51027. ends.push(end1, end2, end5, end4);
  51028. layEndLine(ends, end1);
  51029. layEndLine(ends, end5);
  51030. layEndLine(ends, median);
  51031. data.setItemLayout(dataIndex, {
  51032. initBaseline: median[vDimIdx],
  51033. ends: ends
  51034. });
  51035. }
  51036. function getPoint(axisDimVal, dimIdx, dataIndex) {
  51037. var val = data.get(dimIdx, dataIndex);
  51038. var p = [];
  51039. p[cDimIdx] = axisDimVal;
  51040. p[vDimIdx] = val;
  51041. var point;
  51042. if (isNaN(axisDimVal) || isNaN(val)) {
  51043. point = [NaN, NaN];
  51044. }
  51045. else {
  51046. point = coordSys.dataToPoint(p);
  51047. point[cDimIdx] += offset;
  51048. }
  51049. return point;
  51050. }
  51051. function addBodyEnd(ends, point, start) {
  51052. var point1 = point.slice();
  51053. var point2 = point.slice();
  51054. point1[cDimIdx] += halfWidth;
  51055. point2[cDimIdx] -= halfWidth;
  51056. start
  51057. ? ends.push(point1, point2)
  51058. : ends.push(point2, point1);
  51059. }
  51060. function layEndLine(ends, endCenter) {
  51061. var from = endCenter.slice();
  51062. var to = endCenter.slice();
  51063. from[cDimIdx] -= halfWidth;
  51064. to[cDimIdx] += halfWidth;
  51065. ends.push(from, to);
  51066. }
  51067. }
  51068. /*
  51069. * Licensed to the Apache Software Foundation (ASF) under one
  51070. * or more contributor license agreements. See the NOTICE file
  51071. * distributed with this work for additional information
  51072. * regarding copyright ownership. The ASF licenses this file
  51073. * to you under the Apache License, Version 2.0 (the
  51074. * "License"); you may not use this file except in compliance
  51075. * with the License. You may obtain a copy of the License at
  51076. *
  51077. * http://www.apache.org/licenses/LICENSE-2.0
  51078. *
  51079. * Unless required by applicable law or agreed to in writing,
  51080. * software distributed under the License is distributed on an
  51081. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51082. * KIND, either express or implied. See the License for the
  51083. * specific language governing permissions and limitations
  51084. * under the License.
  51085. */
  51086. registerVisual(boxplotVisual);
  51087. registerLayout(boxplotLayout);
  51088. /*
  51089. * Licensed to the Apache Software Foundation (ASF) under one
  51090. * or more contributor license agreements. See the NOTICE file
  51091. * distributed with this work for additional information
  51092. * regarding copyright ownership. The ASF licenses this file
  51093. * to you under the Apache License, Version 2.0 (the
  51094. * "License"); you may not use this file except in compliance
  51095. * with the License. You may obtain a copy of the License at
  51096. *
  51097. * http://www.apache.org/licenses/LICENSE-2.0
  51098. *
  51099. * Unless required by applicable law or agreed to in writing,
  51100. * software distributed under the License is distributed on an
  51101. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51102. * KIND, either express or implied. See the License for the
  51103. * specific language governing permissions and limitations
  51104. * under the License.
  51105. */
  51106. var CandlestickSeries = SeriesModel.extend({
  51107. type: 'series.candlestick',
  51108. dependencies: ['xAxis', 'yAxis', 'grid'],
  51109. /**
  51110. * @readOnly
  51111. */
  51112. defaultValueDimensions: [
  51113. {name: 'open', defaultTooltip: true},
  51114. {name: 'close', defaultTooltip: true},
  51115. {name: 'lowest', defaultTooltip: true},
  51116. {name: 'highest', defaultTooltip: true}
  51117. ],
  51118. /**
  51119. * @type {Array.<string>}
  51120. * @readOnly
  51121. */
  51122. dimensions: null,
  51123. /**
  51124. * @override
  51125. */
  51126. defaultOption: {
  51127. zlevel: 0,
  51128. z: 2,
  51129. coordinateSystem: 'cartesian2d',
  51130. legendHoverLink: true,
  51131. hoverAnimation: true,
  51132. // xAxisIndex: 0,
  51133. // yAxisIndex: 0,
  51134. layout: null, // 'horizontal' or 'vertical'
  51135. itemStyle: {
  51136. color: '#c23531', // 阳线 positive
  51137. color0: '#314656', // 阴线 negative '#c23531', '#314656'
  51138. borderWidth: 1,
  51139. // FIXME
  51140. // ec2中使用的是lineStyle.color 和 lineStyle.color0
  51141. borderColor: '#c23531',
  51142. borderColor0: '#314656'
  51143. },
  51144. emphasis: {
  51145. itemStyle: {
  51146. borderWidth: 2
  51147. }
  51148. },
  51149. barMaxWidth: null,
  51150. barMinWidth: null,
  51151. barWidth: null,
  51152. large: true,
  51153. largeThreshold: 600,
  51154. progressive: 5e3,
  51155. progressiveThreshold: 1e4,
  51156. progressiveChunkMode: 'mod',
  51157. animationUpdate: false,
  51158. animationEasing: 'linear',
  51159. animationDuration: 300
  51160. },
  51161. /**
  51162. * Get dimension for shadow in dataZoom
  51163. * @return {string} dimension name
  51164. */
  51165. getShadowDim: function () {
  51166. return 'open';
  51167. },
  51168. brushSelector: function (dataIndex, data, selectors) {
  51169. var itemLayout = data.getItemLayout(dataIndex);
  51170. return itemLayout && selectors.rect(itemLayout.brushRect);
  51171. }
  51172. });
  51173. mixin(CandlestickSeries, seriesModelMixin, true);
  51174. /*
  51175. * Licensed to the Apache Software Foundation (ASF) under one
  51176. * or more contributor license agreements. See the NOTICE file
  51177. * distributed with this work for additional information
  51178. * regarding copyright ownership. The ASF licenses this file
  51179. * to you under the Apache License, Version 2.0 (the
  51180. * "License"); you may not use this file except in compliance
  51181. * with the License. You may obtain a copy of the License at
  51182. *
  51183. * http://www.apache.org/licenses/LICENSE-2.0
  51184. *
  51185. * Unless required by applicable law or agreed to in writing,
  51186. * software distributed under the License is distributed on an
  51187. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51188. * KIND, either express or implied. See the License for the
  51189. * specific language governing permissions and limitations
  51190. * under the License.
  51191. */
  51192. var NORMAL_ITEM_STYLE_PATH$1 = ['itemStyle'];
  51193. var EMPHASIS_ITEM_STYLE_PATH$1 = ['emphasis', 'itemStyle'];
  51194. var SKIP_PROPS = ['color', 'color0', 'borderColor', 'borderColor0'];
  51195. var CandlestickView = Chart.extend({
  51196. type: 'candlestick',
  51197. render: function (seriesModel, ecModel, api) {
  51198. this._updateDrawMode(seriesModel);
  51199. this._isLargeDraw
  51200. ? this._renderLarge(seriesModel)
  51201. : this._renderNormal(seriesModel);
  51202. },
  51203. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  51204. this._clear();
  51205. this._updateDrawMode(seriesModel);
  51206. },
  51207. incrementalRender: function (params, seriesModel, ecModel, api) {
  51208. this._isLargeDraw
  51209. ? this._incrementalRenderLarge(params, seriesModel)
  51210. : this._incrementalRenderNormal(params, seriesModel);
  51211. },
  51212. _updateDrawMode: function (seriesModel) {
  51213. var isLargeDraw = seriesModel.pipelineContext.large;
  51214. if (this._isLargeDraw == null || isLargeDraw ^ this._isLargeDraw) {
  51215. this._isLargeDraw = isLargeDraw;
  51216. this._clear();
  51217. }
  51218. },
  51219. _renderNormal: function (seriesModel) {
  51220. var data = seriesModel.getData();
  51221. var oldData = this._data;
  51222. var group = this.group;
  51223. var isSimpleBox = data.getLayout('isSimpleBox');
  51224. // There is no old data only when first rendering or switching from
  51225. // stream mode to normal mode, where previous elements should be removed.
  51226. if (!this._data) {
  51227. group.removeAll();
  51228. }
  51229. data.diff(oldData)
  51230. .add(function (newIdx) {
  51231. if (data.hasValue(newIdx)) {
  51232. var el;
  51233. var itemLayout = data.getItemLayout(newIdx);
  51234. el = createNormalBox$1(itemLayout, newIdx, true);
  51235. initProps(el, {shape: {points: itemLayout.ends}}, seriesModel, newIdx);
  51236. setBoxCommon(el, data, newIdx, isSimpleBox);
  51237. group.add(el);
  51238. data.setItemGraphicEl(newIdx, el);
  51239. }
  51240. })
  51241. .update(function (newIdx, oldIdx) {
  51242. var el = oldData.getItemGraphicEl(oldIdx);
  51243. // Empty data
  51244. if (!data.hasValue(newIdx)) {
  51245. group.remove(el);
  51246. return;
  51247. }
  51248. var itemLayout = data.getItemLayout(newIdx);
  51249. if (!el) {
  51250. el = createNormalBox$1(itemLayout, newIdx);
  51251. }
  51252. else {
  51253. updateProps(el, {shape: {points: itemLayout.ends}}, seriesModel, newIdx);
  51254. }
  51255. setBoxCommon(el, data, newIdx, isSimpleBox);
  51256. group.add(el);
  51257. data.setItemGraphicEl(newIdx, el);
  51258. })
  51259. .remove(function (oldIdx) {
  51260. var el = oldData.getItemGraphicEl(oldIdx);
  51261. el && group.remove(el);
  51262. })
  51263. .execute();
  51264. this._data = data;
  51265. },
  51266. _renderLarge: function (seriesModel) {
  51267. this._clear();
  51268. createLarge$1(seriesModel, this.group);
  51269. },
  51270. _incrementalRenderNormal: function (params, seriesModel) {
  51271. var data = seriesModel.getData();
  51272. var isSimpleBox = data.getLayout('isSimpleBox');
  51273. var dataIndex;
  51274. while ((dataIndex = params.next()) != null) {
  51275. var el;
  51276. var itemLayout = data.getItemLayout(dataIndex);
  51277. el = createNormalBox$1(itemLayout, dataIndex);
  51278. setBoxCommon(el, data, dataIndex, isSimpleBox);
  51279. el.incremental = true;
  51280. this.group.add(el);
  51281. }
  51282. },
  51283. _incrementalRenderLarge: function (params, seriesModel) {
  51284. createLarge$1(seriesModel, this.group, true);
  51285. },
  51286. remove: function (ecModel) {
  51287. this._clear();
  51288. },
  51289. _clear: function () {
  51290. this.group.removeAll();
  51291. this._data = null;
  51292. },
  51293. dispose: noop
  51294. });
  51295. var NormalBoxPath = Path.extend({
  51296. type: 'normalCandlestickBox',
  51297. shape: {},
  51298. buildPath: function (ctx, shape) {
  51299. var ends = shape.points;
  51300. if (this.__simpleBox) {
  51301. ctx.moveTo(ends[4][0], ends[4][1]);
  51302. ctx.lineTo(ends[6][0], ends[6][1]);
  51303. }
  51304. else {
  51305. ctx.moveTo(ends[0][0], ends[0][1]);
  51306. ctx.lineTo(ends[1][0], ends[1][1]);
  51307. ctx.lineTo(ends[2][0], ends[2][1]);
  51308. ctx.lineTo(ends[3][0], ends[3][1]);
  51309. ctx.closePath();
  51310. ctx.moveTo(ends[4][0], ends[4][1]);
  51311. ctx.lineTo(ends[5][0], ends[5][1]);
  51312. ctx.moveTo(ends[6][0], ends[6][1]);
  51313. ctx.lineTo(ends[7][0], ends[7][1]);
  51314. }
  51315. }
  51316. });
  51317. function createNormalBox$1(itemLayout, dataIndex, isInit) {
  51318. var ends = itemLayout.ends;
  51319. return new NormalBoxPath({
  51320. shape: {
  51321. points: isInit
  51322. ? transInit$1(ends, itemLayout)
  51323. : ends
  51324. },
  51325. z2: 100
  51326. });
  51327. }
  51328. function setBoxCommon(el, data, dataIndex, isSimpleBox) {
  51329. var itemModel = data.getItemModel(dataIndex);
  51330. var normalItemStyleModel = itemModel.getModel(NORMAL_ITEM_STYLE_PATH$1);
  51331. var color = data.getItemVisual(dataIndex, 'color');
  51332. var borderColor = data.getItemVisual(dataIndex, 'borderColor') || color;
  51333. // Color must be excluded.
  51334. // Because symbol provide setColor individually to set fill and stroke
  51335. var itemStyle = normalItemStyleModel.getItemStyle(SKIP_PROPS);
  51336. el.useStyle(itemStyle);
  51337. el.style.strokeNoScale = true;
  51338. el.style.fill = color;
  51339. el.style.stroke = borderColor;
  51340. el.__simpleBox = isSimpleBox;
  51341. var hoverStyle = itemModel.getModel(EMPHASIS_ITEM_STYLE_PATH$1).getItemStyle();
  51342. setHoverStyle(el, hoverStyle);
  51343. }
  51344. function transInit$1(points, itemLayout) {
  51345. return map(points, function (point) {
  51346. point = point.slice();
  51347. point[1] = itemLayout.initBaseline;
  51348. return point;
  51349. });
  51350. }
  51351. var LargeBoxPath = Path.extend({
  51352. type: 'largeCandlestickBox',
  51353. shape: {},
  51354. buildPath: function (ctx, shape) {
  51355. // Drawing lines is more efficient than drawing
  51356. // a whole line or drawing rects.
  51357. var points = shape.points;
  51358. for (var i = 0; i < points.length;) {
  51359. if (this.__sign === points[i++]) {
  51360. var x = points[i++];
  51361. ctx.moveTo(x, points[i++]);
  51362. ctx.lineTo(x, points[i++]);
  51363. }
  51364. else {
  51365. i += 3;
  51366. }
  51367. }
  51368. }
  51369. });
  51370. function createLarge$1(seriesModel, group, incremental) {
  51371. var data = seriesModel.getData();
  51372. var largePoints = data.getLayout('largePoints');
  51373. var elP = new LargeBoxPath({
  51374. shape: {points: largePoints},
  51375. __sign: 1
  51376. });
  51377. group.add(elP);
  51378. var elN = new LargeBoxPath({
  51379. shape: {points: largePoints},
  51380. __sign: -1
  51381. });
  51382. group.add(elN);
  51383. setLargeStyle$1(1, elP, seriesModel, data);
  51384. setLargeStyle$1(-1, elN, seriesModel, data);
  51385. if (incremental) {
  51386. elP.incremental = true;
  51387. elN.incremental = true;
  51388. }
  51389. }
  51390. function setLargeStyle$1(sign, el, seriesModel, data) {
  51391. var suffix = sign > 0 ? 'P' : 'N';
  51392. var borderColor = data.getVisual('borderColor' + suffix)
  51393. || data.getVisual('color' + suffix);
  51394. // Color must be excluded.
  51395. // Because symbol provide setColor individually to set fill and stroke
  51396. var itemStyle = seriesModel.getModel(NORMAL_ITEM_STYLE_PATH$1).getItemStyle(SKIP_PROPS);
  51397. el.useStyle(itemStyle);
  51398. el.style.fill = null;
  51399. el.style.stroke = borderColor;
  51400. // No different
  51401. // el.style.lineWidth = .5;
  51402. }
  51403. /*
  51404. * Licensed to the Apache Software Foundation (ASF) under one
  51405. * or more contributor license agreements. See the NOTICE file
  51406. * distributed with this work for additional information
  51407. * regarding copyright ownership. The ASF licenses this file
  51408. * to you under the Apache License, Version 2.0 (the
  51409. * "License"); you may not use this file except in compliance
  51410. * with the License. You may obtain a copy of the License at
  51411. *
  51412. * http://www.apache.org/licenses/LICENSE-2.0
  51413. *
  51414. * Unless required by applicable law or agreed to in writing,
  51415. * software distributed under the License is distributed on an
  51416. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51417. * KIND, either express or implied. See the License for the
  51418. * specific language governing permissions and limitations
  51419. * under the License.
  51420. */
  51421. var preprocessor = function (option) {
  51422. if (!option || !isArray(option.series)) {
  51423. return;
  51424. }
  51425. // Translate 'k' to 'candlestick'.
  51426. each$1(option.series, function (seriesItem) {
  51427. if (isObject$1(seriesItem) && seriesItem.type === 'k') {
  51428. seriesItem.type = 'candlestick';
  51429. }
  51430. });
  51431. };
  51432. /*
  51433. * Licensed to the Apache Software Foundation (ASF) under one
  51434. * or more contributor license agreements. See the NOTICE file
  51435. * distributed with this work for additional information
  51436. * regarding copyright ownership. The ASF licenses this file
  51437. * to you under the Apache License, Version 2.0 (the
  51438. * "License"); you may not use this file except in compliance
  51439. * with the License. You may obtain a copy of the License at
  51440. *
  51441. * http://www.apache.org/licenses/LICENSE-2.0
  51442. *
  51443. * Unless required by applicable law or agreed to in writing,
  51444. * software distributed under the License is distributed on an
  51445. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51446. * KIND, either express or implied. See the License for the
  51447. * specific language governing permissions and limitations
  51448. * under the License.
  51449. */
  51450. var positiveBorderColorQuery = ['itemStyle', 'borderColor'];
  51451. var negativeBorderColorQuery = ['itemStyle', 'borderColor0'];
  51452. var positiveColorQuery = ['itemStyle', 'color'];
  51453. var negativeColorQuery = ['itemStyle', 'color0'];
  51454. var candlestickVisual = {
  51455. seriesType: 'candlestick',
  51456. plan: createRenderPlanner(),
  51457. // For legend.
  51458. performRawSeries: true,
  51459. reset: function (seriesModel, ecModel) {
  51460. var data = seriesModel.getData();
  51461. var isLargeRender = seriesModel.pipelineContext.large;
  51462. data.setVisual({
  51463. legendSymbol: 'roundRect',
  51464. colorP: getColor(1, seriesModel),
  51465. colorN: getColor(-1, seriesModel),
  51466. borderColorP: getBorderColor(1, seriesModel),
  51467. borderColorN: getBorderColor(-1, seriesModel)
  51468. });
  51469. // Only visible series has each data be visual encoded
  51470. if (ecModel.isSeriesFiltered(seriesModel)) {
  51471. return;
  51472. }
  51473. return !isLargeRender && {progress: progress};
  51474. function progress(params, data) {
  51475. var dataIndex;
  51476. while ((dataIndex = params.next()) != null) {
  51477. var itemModel = data.getItemModel(dataIndex);
  51478. var sign = data.getItemLayout(dataIndex).sign;
  51479. data.setItemVisual(
  51480. dataIndex,
  51481. {
  51482. color: getColor(sign, itemModel),
  51483. borderColor: getBorderColor(sign, itemModel)
  51484. }
  51485. );
  51486. }
  51487. }
  51488. function getColor(sign, model) {
  51489. return model.get(
  51490. sign > 0 ? positiveColorQuery : negativeColorQuery
  51491. );
  51492. }
  51493. function getBorderColor(sign, model) {
  51494. return model.get(
  51495. sign > 0 ? positiveBorderColorQuery : negativeBorderColorQuery
  51496. );
  51497. }
  51498. }
  51499. };
  51500. /*
  51501. * Licensed to the Apache Software Foundation (ASF) under one
  51502. * or more contributor license agreements. See the NOTICE file
  51503. * distributed with this work for additional information
  51504. * regarding copyright ownership. The ASF licenses this file
  51505. * to you under the Apache License, Version 2.0 (the
  51506. * "License"); you may not use this file except in compliance
  51507. * with the License. You may obtain a copy of the License at
  51508. *
  51509. * http://www.apache.org/licenses/LICENSE-2.0
  51510. *
  51511. * Unless required by applicable law or agreed to in writing,
  51512. * software distributed under the License is distributed on an
  51513. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51514. * KIND, either express or implied. See the License for the
  51515. * specific language governing permissions and limitations
  51516. * under the License.
  51517. */
  51518. var LargeArr$1 = typeof Float32Array !== 'undefined' ? Float32Array : Array;
  51519. var candlestickLayout = {
  51520. seriesType: 'candlestick',
  51521. plan: createRenderPlanner(),
  51522. reset: function (seriesModel) {
  51523. var coordSys = seriesModel.coordinateSystem;
  51524. var data = seriesModel.getData();
  51525. var candleWidth = calculateCandleWidth(seriesModel, data);
  51526. var cDimIdx = 0;
  51527. var vDimIdx = 1;
  51528. var coordDims = ['x', 'y'];
  51529. var cDim = data.mapDimension(coordDims[cDimIdx]);
  51530. var vDims = data.mapDimension(coordDims[vDimIdx], true);
  51531. var openDim = vDims[0];
  51532. var closeDim = vDims[1];
  51533. var lowestDim = vDims[2];
  51534. var highestDim = vDims[3];
  51535. data.setLayout({
  51536. candleWidth: candleWidth,
  51537. // The value is experimented visually.
  51538. isSimpleBox: candleWidth <= 1.3
  51539. });
  51540. if (cDim == null || vDims.length < 4) {
  51541. return;
  51542. }
  51543. return {
  51544. progress: seriesModel.pipelineContext.large
  51545. ? largeProgress : normalProgress
  51546. };
  51547. function normalProgress(params, data) {
  51548. var dataIndex;
  51549. while ((dataIndex = params.next()) != null) {
  51550. var axisDimVal = data.get(cDim, dataIndex);
  51551. var openVal = data.get(openDim, dataIndex);
  51552. var closeVal = data.get(closeDim, dataIndex);
  51553. var lowestVal = data.get(lowestDim, dataIndex);
  51554. var highestVal = data.get(highestDim, dataIndex);
  51555. var ocLow = Math.min(openVal, closeVal);
  51556. var ocHigh = Math.max(openVal, closeVal);
  51557. var ocLowPoint = getPoint(ocLow, axisDimVal);
  51558. var ocHighPoint = getPoint(ocHigh, axisDimVal);
  51559. var lowestPoint = getPoint(lowestVal, axisDimVal);
  51560. var highestPoint = getPoint(highestVal, axisDimVal);
  51561. var ends = [];
  51562. addBodyEnd(ends, ocHighPoint, 0);
  51563. addBodyEnd(ends, ocLowPoint, 1);
  51564. ends.push(
  51565. subPixelOptimizePoint(highestPoint),
  51566. subPixelOptimizePoint(ocHighPoint),
  51567. subPixelOptimizePoint(lowestPoint),
  51568. subPixelOptimizePoint(ocLowPoint)
  51569. );
  51570. data.setItemLayout(dataIndex, {
  51571. sign: getSign(data, dataIndex, openVal, closeVal, closeDim),
  51572. initBaseline: openVal > closeVal
  51573. ? ocHighPoint[vDimIdx] : ocLowPoint[vDimIdx], // open point.
  51574. ends: ends,
  51575. brushRect: makeBrushRect(lowestVal, highestVal, axisDimVal)
  51576. });
  51577. }
  51578. function getPoint(val, axisDimVal) {
  51579. var p = [];
  51580. p[cDimIdx] = axisDimVal;
  51581. p[vDimIdx] = val;
  51582. return (isNaN(axisDimVal) || isNaN(val))
  51583. ? [NaN, NaN]
  51584. : coordSys.dataToPoint(p);
  51585. }
  51586. function addBodyEnd(ends, point, start) {
  51587. var point1 = point.slice();
  51588. var point2 = point.slice();
  51589. point1[cDimIdx] = subPixelOptimize(
  51590. point1[cDimIdx] + candleWidth / 2, 1, false
  51591. );
  51592. point2[cDimIdx] = subPixelOptimize(
  51593. point2[cDimIdx] - candleWidth / 2, 1, true
  51594. );
  51595. start
  51596. ? ends.push(point1, point2)
  51597. : ends.push(point2, point1);
  51598. }
  51599. function makeBrushRect(lowestVal, highestVal, axisDimVal) {
  51600. var pmin = getPoint(lowestVal, axisDimVal);
  51601. var pmax = getPoint(highestVal, axisDimVal);
  51602. pmin[cDimIdx] -= candleWidth / 2;
  51603. pmax[cDimIdx] -= candleWidth / 2;
  51604. return {
  51605. x: pmin[0],
  51606. y: pmin[1],
  51607. width: vDimIdx ? candleWidth : pmax[0] - pmin[0],
  51608. height: vDimIdx ? pmax[1] - pmin[1] : candleWidth
  51609. };
  51610. }
  51611. function subPixelOptimizePoint(point) {
  51612. point[cDimIdx] = subPixelOptimize(point[cDimIdx], 1);
  51613. return point;
  51614. }
  51615. }
  51616. function largeProgress(params, data) {
  51617. // Structure: [sign, x, yhigh, ylow, sign, x, yhigh, ylow, ...]
  51618. var points = new LargeArr$1(params.count * 5);
  51619. var offset = 0;
  51620. var point;
  51621. var tmpIn = [];
  51622. var tmpOut = [];
  51623. var dataIndex;
  51624. while ((dataIndex = params.next()) != null) {
  51625. var axisDimVal = data.get(cDim, dataIndex);
  51626. var openVal = data.get(openDim, dataIndex);
  51627. var closeVal = data.get(closeDim, dataIndex);
  51628. var lowestVal = data.get(lowestDim, dataIndex);
  51629. var highestVal = data.get(highestDim, dataIndex);
  51630. if (isNaN(axisDimVal) || isNaN(lowestVal) || isNaN(highestVal)) {
  51631. points[offset++] = NaN;
  51632. offset += 4;
  51633. continue;
  51634. }
  51635. points[offset++] = getSign(data, dataIndex, openVal, closeVal, closeDim);
  51636. tmpIn[cDimIdx] = axisDimVal;
  51637. tmpIn[vDimIdx] = lowestVal;
  51638. point = coordSys.dataToPoint(tmpIn, null, tmpOut);
  51639. points[offset++] = point ? point[0] : NaN;
  51640. points[offset++] = point ? point[1] : NaN;
  51641. tmpIn[vDimIdx] = highestVal;
  51642. point = coordSys.dataToPoint(tmpIn, null, tmpOut);
  51643. points[offset++] = point ? point[1] : NaN;
  51644. }
  51645. data.setLayout('largePoints', points);
  51646. }
  51647. }
  51648. };
  51649. function getSign(data, dataIndex, openVal, closeVal, closeDim) {
  51650. var sign;
  51651. if (openVal > closeVal) {
  51652. sign = -1;
  51653. }
  51654. else if (openVal < closeVal) {
  51655. sign = 1;
  51656. }
  51657. else {
  51658. sign = dataIndex > 0
  51659. // If close === open, compare with close of last record
  51660. ? (data.get(closeDim, dataIndex - 1) <= closeVal ? 1 : -1)
  51661. // No record of previous, set to be positive
  51662. : 1;
  51663. }
  51664. return sign;
  51665. }
  51666. function calculateCandleWidth(seriesModel, data) {
  51667. var baseAxis = seriesModel.getBaseAxis();
  51668. var extent;
  51669. var bandWidth = baseAxis.type === 'category'
  51670. ? baseAxis.getBandWidth()
  51671. : (
  51672. extent = baseAxis.getExtent(),
  51673. Math.abs(extent[1] - extent[0]) / data.count()
  51674. );
  51675. var barMaxWidth = parsePercent$1(
  51676. retrieve2(seriesModel.get('barMaxWidth'), bandWidth),
  51677. bandWidth
  51678. );
  51679. var barMinWidth = parsePercent$1(
  51680. retrieve2(seriesModel.get('barMinWidth'), 1),
  51681. bandWidth
  51682. );
  51683. var barWidth = seriesModel.get('barWidth');
  51684. return barWidth != null
  51685. ? parsePercent$1(barWidth, bandWidth)
  51686. // Put max outer to ensure bar visible in spite of overlap.
  51687. : Math.max(Math.min(bandWidth / 2, barMaxWidth), barMinWidth);
  51688. }
  51689. /*
  51690. * Licensed to the Apache Software Foundation (ASF) under one
  51691. * or more contributor license agreements. See the NOTICE file
  51692. * distributed with this work for additional information
  51693. * regarding copyright ownership. The ASF licenses this file
  51694. * to you under the Apache License, Version 2.0 (the
  51695. * "License"); you may not use this file except in compliance
  51696. * with the License. You may obtain a copy of the License at
  51697. *
  51698. * http://www.apache.org/licenses/LICENSE-2.0
  51699. *
  51700. * Unless required by applicable law or agreed to in writing,
  51701. * software distributed under the License is distributed on an
  51702. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51703. * KIND, either express or implied. See the License for the
  51704. * specific language governing permissions and limitations
  51705. * under the License.
  51706. */
  51707. registerPreprocessor(preprocessor);
  51708. registerVisual(candlestickVisual);
  51709. registerLayout(candlestickLayout);
  51710. /*
  51711. * Licensed to the Apache Software Foundation (ASF) under one
  51712. * or more contributor license agreements. See the NOTICE file
  51713. * distributed with this work for additional information
  51714. * regarding copyright ownership. The ASF licenses this file
  51715. * to you under the Apache License, Version 2.0 (the
  51716. * "License"); you may not use this file except in compliance
  51717. * with the License. You may obtain a copy of the License at
  51718. *
  51719. * http://www.apache.org/licenses/LICENSE-2.0
  51720. *
  51721. * Unless required by applicable law or agreed to in writing,
  51722. * software distributed under the License is distributed on an
  51723. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51724. * KIND, either express or implied. See the License for the
  51725. * specific language governing permissions and limitations
  51726. * under the License.
  51727. */
  51728. SeriesModel.extend({
  51729. type: 'series.effectScatter',
  51730. dependencies: ['grid', 'polar'],
  51731. getInitialData: function (option, ecModel) {
  51732. return createListFromArray(this.getSource(), this);
  51733. },
  51734. brushSelector: 'point',
  51735. defaultOption: {
  51736. coordinateSystem: 'cartesian2d',
  51737. zlevel: 0,
  51738. z: 2,
  51739. legendHoverLink: true,
  51740. effectType: 'ripple',
  51741. progressive: 0,
  51742. // When to show the effect, option: 'render'|'emphasis'
  51743. showEffectOn: 'render',
  51744. // Ripple effect config
  51745. rippleEffect: {
  51746. period: 4,
  51747. // Scale of ripple
  51748. scale: 2.5,
  51749. // Brush type can be fill or stroke
  51750. brushType: 'fill'
  51751. },
  51752. // Cartesian coordinate system
  51753. // xAxisIndex: 0,
  51754. // yAxisIndex: 0,
  51755. // Polar coordinate system
  51756. // polarIndex: 0,
  51757. // Geo coordinate system
  51758. // geoIndex: 0,
  51759. // symbol: null, // 图形类型
  51760. symbolSize: 10 // 图形大小,半宽(半径)参数,当图形为方向或菱形则总宽度为symbolSize * 2
  51761. // symbolRotate: null, // 图形旋转控制
  51762. // large: false,
  51763. // Available when large is true
  51764. // largeThreshold: 2000,
  51765. // itemStyle: {
  51766. // opacity: 1
  51767. // }
  51768. }
  51769. });
  51770. /*
  51771. * Licensed to the Apache Software Foundation (ASF) under one
  51772. * or more contributor license agreements. See the NOTICE file
  51773. * distributed with this work for additional information
  51774. * regarding copyright ownership. The ASF licenses this file
  51775. * to you under the Apache License, Version 2.0 (the
  51776. * "License"); you may not use this file except in compliance
  51777. * with the License. You may obtain a copy of the License at
  51778. *
  51779. * http://www.apache.org/licenses/LICENSE-2.0
  51780. *
  51781. * Unless required by applicable law or agreed to in writing,
  51782. * software distributed under the License is distributed on an
  51783. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51784. * KIND, either express or implied. See the License for the
  51785. * specific language governing permissions and limitations
  51786. * under the License.
  51787. */
  51788. /**
  51789. * Symbol with ripple effect
  51790. * @module echarts/chart/helper/EffectSymbol
  51791. */
  51792. var EFFECT_RIPPLE_NUMBER = 3;
  51793. function normalizeSymbolSize$1(symbolSize) {
  51794. if (!isArray(symbolSize)) {
  51795. symbolSize = [+symbolSize, +symbolSize];
  51796. }
  51797. return symbolSize;
  51798. }
  51799. function updateRipplePath(rippleGroup, effectCfg) {
  51800. rippleGroup.eachChild(function (ripplePath) {
  51801. ripplePath.attr({
  51802. z: effectCfg.z,
  51803. zlevel: effectCfg.zlevel,
  51804. style: {
  51805. stroke: effectCfg.brushType === 'stroke' ? effectCfg.color : null,
  51806. fill: effectCfg.brushType === 'fill' ? effectCfg.color : null
  51807. }
  51808. });
  51809. });
  51810. }
  51811. /**
  51812. * @constructor
  51813. * @param {module:echarts/data/List} data
  51814. * @param {number} idx
  51815. * @extends {module:zrender/graphic/Group}
  51816. */
  51817. function EffectSymbol(data, idx) {
  51818. Group.call(this);
  51819. var symbol = new SymbolClz$1(data, idx);
  51820. var rippleGroup = new Group();
  51821. this.add(symbol);
  51822. this.add(rippleGroup);
  51823. rippleGroup.beforeUpdate = function () {
  51824. this.attr(symbol.getScale());
  51825. };
  51826. this.updateData(data, idx);
  51827. }
  51828. var effectSymbolProto = EffectSymbol.prototype;
  51829. effectSymbolProto.stopEffectAnimation = function () {
  51830. this.childAt(1).removeAll();
  51831. };
  51832. effectSymbolProto.startEffectAnimation = function (effectCfg) {
  51833. var symbolType = effectCfg.symbolType;
  51834. var color = effectCfg.color;
  51835. var rippleGroup = this.childAt(1);
  51836. for (var i = 0; i < EFFECT_RIPPLE_NUMBER; i++) {
  51837. // var ripplePath = createSymbol(
  51838. // symbolType, -0.5, -0.5, 1, 1, color
  51839. // );
  51840. // If width/height are set too small (e.g., set to 1) on ios10
  51841. // and macOS Sierra, a circle stroke become a rect, no matter what
  51842. // the scale is set. So we set width/height as 2. See #4136.
  51843. var ripplePath = createSymbol(
  51844. symbolType, -1, -1, 2, 2, color
  51845. );
  51846. ripplePath.attr({
  51847. style: {
  51848. strokeNoScale: true
  51849. },
  51850. z2: 99,
  51851. silent: true,
  51852. scale: [0.5, 0.5]
  51853. });
  51854. var delay = -i / EFFECT_RIPPLE_NUMBER * effectCfg.period + effectCfg.effectOffset;
  51855. // TODO Configurable effectCfg.period
  51856. ripplePath.animate('', true)
  51857. .when(effectCfg.period, {
  51858. scale: [effectCfg.rippleScale / 2, effectCfg.rippleScale / 2]
  51859. })
  51860. .delay(delay)
  51861. .start();
  51862. ripplePath.animateStyle(true)
  51863. .when(effectCfg.period, {
  51864. opacity: 0
  51865. })
  51866. .delay(delay)
  51867. .start();
  51868. rippleGroup.add(ripplePath);
  51869. }
  51870. updateRipplePath(rippleGroup, effectCfg);
  51871. };
  51872. /**
  51873. * Update effect symbol
  51874. */
  51875. effectSymbolProto.updateEffectAnimation = function (effectCfg) {
  51876. var oldEffectCfg = this._effectCfg;
  51877. var rippleGroup = this.childAt(1);
  51878. // Must reinitialize effect if following configuration changed
  51879. var DIFFICULT_PROPS = ['symbolType', 'period', 'rippleScale'];
  51880. for (var i = 0; i < DIFFICULT_PROPS.length; i++) {
  51881. var propName = DIFFICULT_PROPS[i];
  51882. if (oldEffectCfg[propName] !== effectCfg[propName]) {
  51883. this.stopEffectAnimation();
  51884. this.startEffectAnimation(effectCfg);
  51885. return;
  51886. }
  51887. }
  51888. updateRipplePath(rippleGroup, effectCfg);
  51889. };
  51890. /**
  51891. * Highlight symbol
  51892. */
  51893. effectSymbolProto.highlight = function () {
  51894. this.trigger('emphasis');
  51895. };
  51896. /**
  51897. * Downplay symbol
  51898. */
  51899. effectSymbolProto.downplay = function () {
  51900. this.trigger('normal');
  51901. };
  51902. /**
  51903. * Update symbol properties
  51904. * @param {module:echarts/data/List} data
  51905. * @param {number} idx
  51906. */
  51907. effectSymbolProto.updateData = function (data, idx) {
  51908. var seriesModel = data.hostModel;
  51909. this.childAt(0).updateData(data, idx);
  51910. var rippleGroup = this.childAt(1);
  51911. var itemModel = data.getItemModel(idx);
  51912. var symbolType = data.getItemVisual(idx, 'symbol');
  51913. var symbolSize = normalizeSymbolSize$1(data.getItemVisual(idx, 'symbolSize'));
  51914. var color = data.getItemVisual(idx, 'color');
  51915. rippleGroup.attr('scale', symbolSize);
  51916. rippleGroup.traverse(function (ripplePath) {
  51917. ripplePath.attr({
  51918. fill: color
  51919. });
  51920. });
  51921. var symbolOffset = itemModel.getShallow('symbolOffset');
  51922. if (symbolOffset) {
  51923. var pos = rippleGroup.position;
  51924. pos[0] = parsePercent$1(symbolOffset[0], symbolSize[0]);
  51925. pos[1] = parsePercent$1(symbolOffset[1], symbolSize[1]);
  51926. }
  51927. rippleGroup.rotation = (itemModel.getShallow('symbolRotate') || 0) * Math.PI / 180 || 0;
  51928. var effectCfg = {};
  51929. effectCfg.showEffectOn = seriesModel.get('showEffectOn');
  51930. effectCfg.rippleScale = itemModel.get('rippleEffect.scale');
  51931. effectCfg.brushType = itemModel.get('rippleEffect.brushType');
  51932. effectCfg.period = itemModel.get('rippleEffect.period') * 1000;
  51933. effectCfg.effectOffset = idx / data.count();
  51934. effectCfg.z = itemModel.getShallow('z') || 0;
  51935. effectCfg.zlevel = itemModel.getShallow('zlevel') || 0;
  51936. effectCfg.symbolType = symbolType;
  51937. effectCfg.color = color;
  51938. this.off('mouseover').off('mouseout').off('emphasis').off('normal');
  51939. if (effectCfg.showEffectOn === 'render') {
  51940. this._effectCfg
  51941. ? this.updateEffectAnimation(effectCfg)
  51942. : this.startEffectAnimation(effectCfg);
  51943. this._effectCfg = effectCfg;
  51944. }
  51945. else {
  51946. // Not keep old effect config
  51947. this._effectCfg = null;
  51948. this.stopEffectAnimation();
  51949. var symbol = this.childAt(0);
  51950. var onEmphasis = function () {
  51951. symbol.highlight();
  51952. if (effectCfg.showEffectOn !== 'render') {
  51953. this.startEffectAnimation(effectCfg);
  51954. }
  51955. };
  51956. var onNormal = function () {
  51957. symbol.downplay();
  51958. if (effectCfg.showEffectOn !== 'render') {
  51959. this.stopEffectAnimation();
  51960. }
  51961. };
  51962. this.on('mouseover', onEmphasis, this)
  51963. .on('mouseout', onNormal, this)
  51964. .on('emphasis', onEmphasis, this)
  51965. .on('normal', onNormal, this);
  51966. }
  51967. this._effectCfg = effectCfg;
  51968. };
  51969. effectSymbolProto.fadeOut = function (cb) {
  51970. this.off('mouseover').off('mouseout').off('emphasis').off('normal');
  51971. cb && cb();
  51972. };
  51973. inherits(EffectSymbol, Group);
  51974. /*
  51975. * Licensed to the Apache Software Foundation (ASF) under one
  51976. * or more contributor license agreements. See the NOTICE file
  51977. * distributed with this work for additional information
  51978. * regarding copyright ownership. The ASF licenses this file
  51979. * to you under the Apache License, Version 2.0 (the
  51980. * "License"); you may not use this file except in compliance
  51981. * with the License. You may obtain a copy of the License at
  51982. *
  51983. * http://www.apache.org/licenses/LICENSE-2.0
  51984. *
  51985. * Unless required by applicable law or agreed to in writing,
  51986. * software distributed under the License is distributed on an
  51987. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51988. * KIND, either express or implied. See the License for the
  51989. * specific language governing permissions and limitations
  51990. * under the License.
  51991. */
  51992. extendChartView({
  51993. type: 'effectScatter',
  51994. init: function () {
  51995. this._symbolDraw = new SymbolDraw(EffectSymbol);
  51996. },
  51997. render: function (seriesModel, ecModel, api) {
  51998. var data = seriesModel.getData();
  51999. var effectSymbolDraw = this._symbolDraw;
  52000. effectSymbolDraw.updateData(data);
  52001. this.group.add(effectSymbolDraw.group);
  52002. },
  52003. updateTransform: function (seriesModel, ecModel, api) {
  52004. var data = seriesModel.getData();
  52005. this.group.dirty();
  52006. var res = pointsLayout().reset(seriesModel);
  52007. if (res.progress) {
  52008. res.progress({ start: 0, end: data.count() }, data);
  52009. }
  52010. this._symbolDraw.updateLayout(data);
  52011. },
  52012. _updateGroupTransform: function (seriesModel) {
  52013. var coordSys = seriesModel.coordinateSystem;
  52014. if (coordSys && coordSys.getRoamTransform) {
  52015. this.group.transform = clone$2(coordSys.getRoamTransform());
  52016. this.group.decomposeTransform();
  52017. }
  52018. },
  52019. remove: function (ecModel, api) {
  52020. this._symbolDraw && this._symbolDraw.remove(api);
  52021. },
  52022. dispose: function () {}
  52023. });
  52024. /*
  52025. * Licensed to the Apache Software Foundation (ASF) under one
  52026. * or more contributor license agreements. See the NOTICE file
  52027. * distributed with this work for additional information
  52028. * regarding copyright ownership. The ASF licenses this file
  52029. * to you under the Apache License, Version 2.0 (the
  52030. * "License"); you may not use this file except in compliance
  52031. * with the License. You may obtain a copy of the License at
  52032. *
  52033. * http://www.apache.org/licenses/LICENSE-2.0
  52034. *
  52035. * Unless required by applicable law or agreed to in writing,
  52036. * software distributed under the License is distributed on an
  52037. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52038. * KIND, either express or implied. See the License for the
  52039. * specific language governing permissions and limitations
  52040. * under the License.
  52041. */
  52042. registerVisual(visualSymbol('effectScatter', 'circle'));
  52043. registerLayout(pointsLayout('effectScatter'));
  52044. /*
  52045. * Licensed to the Apache Software Foundation (ASF) under one
  52046. * or more contributor license agreements. See the NOTICE file
  52047. * distributed with this work for additional information
  52048. * regarding copyright ownership. The ASF licenses this file
  52049. * to you under the Apache License, Version 2.0 (the
  52050. * "License"); you may not use this file except in compliance
  52051. * with the License. You may obtain a copy of the License at
  52052. *
  52053. * http://www.apache.org/licenses/LICENSE-2.0
  52054. *
  52055. * Unless required by applicable law or agreed to in writing,
  52056. * software distributed under the License is distributed on an
  52057. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52058. * KIND, either express or implied. See the License for the
  52059. * specific language governing permissions and limitations
  52060. * under the License.
  52061. */
  52062. var Uint32Arr = typeof Uint32Array === 'undefined' ? Array : Uint32Array;
  52063. var Float64Arr = typeof Float64Array === 'undefined' ? Array : Float64Array;
  52064. function compatEc2(seriesOpt) {
  52065. var data = seriesOpt.data;
  52066. if (data && data[0] && data[0][0] && data[0][0].coord) {
  52067. if (__DEV__) {
  52068. console.warn('Lines data configuration has been changed to'
  52069. + ' { coords:[[1,2],[2,3]] }');
  52070. }
  52071. seriesOpt.data = map(data, function (itemOpt) {
  52072. var coords = [
  52073. itemOpt[0].coord, itemOpt[1].coord
  52074. ];
  52075. var target = {
  52076. coords: coords
  52077. };
  52078. if (itemOpt[0].name) {
  52079. target.fromName = itemOpt[0].name;
  52080. }
  52081. if (itemOpt[1].name) {
  52082. target.toName = itemOpt[1].name;
  52083. }
  52084. return mergeAll([target, itemOpt[0], itemOpt[1]]);
  52085. });
  52086. }
  52087. }
  52088. var LinesSeries = SeriesModel.extend({
  52089. type: 'series.lines',
  52090. dependencies: ['grid', 'polar'],
  52091. visualColorAccessPath: 'lineStyle.color',
  52092. init: function (option) {
  52093. // The input data may be null/undefined.
  52094. option.data = option.data || [];
  52095. // Not using preprocessor because mergeOption may not have series.type
  52096. compatEc2(option);
  52097. var result = this._processFlatCoordsArray(option.data);
  52098. this._flatCoords = result.flatCoords;
  52099. this._flatCoordsOffset = result.flatCoordsOffset;
  52100. if (result.flatCoords) {
  52101. option.data = new Float32Array(result.count);
  52102. }
  52103. LinesSeries.superApply(this, 'init', arguments);
  52104. },
  52105. mergeOption: function (option) {
  52106. // The input data may be null/undefined.
  52107. option.data = option.data || [];
  52108. compatEc2(option);
  52109. if (option.data) {
  52110. // Only update when have option data to merge.
  52111. var result = this._processFlatCoordsArray(option.data);
  52112. this._flatCoords = result.flatCoords;
  52113. this._flatCoordsOffset = result.flatCoordsOffset;
  52114. if (result.flatCoords) {
  52115. option.data = new Float32Array(result.count);
  52116. }
  52117. }
  52118. LinesSeries.superApply(this, 'mergeOption', arguments);
  52119. },
  52120. appendData: function (params) {
  52121. var result = this._processFlatCoordsArray(params.data);
  52122. if (result.flatCoords) {
  52123. if (!this._flatCoords) {
  52124. this._flatCoords = result.flatCoords;
  52125. this._flatCoordsOffset = result.flatCoordsOffset;
  52126. }
  52127. else {
  52128. this._flatCoords = concatArray(this._flatCoords, result.flatCoords);
  52129. this._flatCoordsOffset = concatArray(this._flatCoordsOffset, result.flatCoordsOffset);
  52130. }
  52131. params.data = new Float32Array(result.count);
  52132. }
  52133. this.getRawData().appendData(params.data);
  52134. },
  52135. _getCoordsFromItemModel: function (idx) {
  52136. var itemModel = this.getData().getItemModel(idx);
  52137. var coords = (itemModel.option instanceof Array)
  52138. ? itemModel.option : itemModel.getShallow('coords');
  52139. if (__DEV__) {
  52140. if (!(coords instanceof Array && coords.length > 0 && coords[0] instanceof Array)) {
  52141. throw new Error('Invalid coords ' + JSON.stringify(coords) + '. Lines must have 2d coords array in data item.');
  52142. }
  52143. }
  52144. return coords;
  52145. },
  52146. getLineCoordsCount: function (idx) {
  52147. if (this._flatCoordsOffset) {
  52148. return this._flatCoordsOffset[idx * 2 + 1];
  52149. }
  52150. else {
  52151. return this._getCoordsFromItemModel(idx).length;
  52152. }
  52153. },
  52154. getLineCoords: function (idx, out) {
  52155. if (this._flatCoordsOffset) {
  52156. var offset = this._flatCoordsOffset[idx * 2];
  52157. var len = this._flatCoordsOffset[idx * 2 + 1];
  52158. for (var i = 0; i < len; i++) {
  52159. out[i] = out[i] || [];
  52160. out[i][0] = this._flatCoords[offset + i * 2];
  52161. out[i][1] = this._flatCoords[offset + i * 2 + 1];
  52162. }
  52163. return len;
  52164. }
  52165. else {
  52166. var coords = this._getCoordsFromItemModel(idx);
  52167. for (var i = 0; i < coords.length; i++) {
  52168. out[i] = out[i] || [];
  52169. out[i][0] = coords[i][0];
  52170. out[i][1] = coords[i][1];
  52171. }
  52172. return coords.length;
  52173. }
  52174. },
  52175. _processFlatCoordsArray: function (data) {
  52176. var startOffset = 0;
  52177. if (this._flatCoords) {
  52178. startOffset = this._flatCoords.length;
  52179. }
  52180. // Stored as a typed array. In format
  52181. // Points Count(2) | x | y | x | y | Points Count(3) | x | y | x | y | x | y |
  52182. if (typeof data[0] === 'number') {
  52183. var len = data.length;
  52184. // Store offset and len of each segment
  52185. var coordsOffsetAndLenStorage = new Uint32Arr(len);
  52186. var coordsStorage = new Float64Arr(len);
  52187. var coordsCursor = 0;
  52188. var offsetCursor = 0;
  52189. var dataCount = 0;
  52190. for (var i = 0; i < len;) {
  52191. dataCount++;
  52192. var count = data[i++];
  52193. // Offset
  52194. coordsOffsetAndLenStorage[offsetCursor++] = coordsCursor + startOffset;
  52195. // Len
  52196. coordsOffsetAndLenStorage[offsetCursor++] = count;
  52197. for (var k = 0; k < count; k++) {
  52198. var x = data[i++];
  52199. var y = data[i++];
  52200. coordsStorage[coordsCursor++] = x;
  52201. coordsStorage[coordsCursor++] = y;
  52202. if (i > len) {
  52203. if (__DEV__) {
  52204. throw new Error('Invalid data format.');
  52205. }
  52206. }
  52207. }
  52208. }
  52209. return {
  52210. flatCoordsOffset: new Uint32Array(coordsOffsetAndLenStorage.buffer, 0, offsetCursor),
  52211. flatCoords: coordsStorage,
  52212. count: dataCount
  52213. };
  52214. }
  52215. return {
  52216. flatCoordsOffset: null,
  52217. flatCoords: null,
  52218. count: data.length
  52219. };
  52220. },
  52221. getInitialData: function (option, ecModel) {
  52222. if (__DEV__) {
  52223. var CoordSys = CoordinateSystemManager.get(option.coordinateSystem);
  52224. if (!CoordSys) {
  52225. throw new Error('Unkown coordinate system ' + option.coordinateSystem);
  52226. }
  52227. }
  52228. var lineData = new List(['value'], this);
  52229. lineData.hasItemOption = false;
  52230. lineData.initData(option.data, [], function (dataItem, dimName, dataIndex, dimIndex) {
  52231. // dataItem is simply coords
  52232. if (dataItem instanceof Array) {
  52233. return NaN;
  52234. }
  52235. else {
  52236. lineData.hasItemOption = true;
  52237. var value = dataItem.value;
  52238. if (value != null) {
  52239. return value instanceof Array ? value[dimIndex] : value;
  52240. }
  52241. }
  52242. });
  52243. return lineData;
  52244. },
  52245. formatTooltip: function (dataIndex) {
  52246. var data = this.getData();
  52247. var itemModel = data.getItemModel(dataIndex);
  52248. var name = itemModel.get('name');
  52249. if (name) {
  52250. return name;
  52251. }
  52252. var fromName = itemModel.get('fromName');
  52253. var toName = itemModel.get('toName');
  52254. var html = [];
  52255. fromName != null && html.push(fromName);
  52256. toName != null && html.push(toName);
  52257. return encodeHTML(html.join(' > '));
  52258. },
  52259. preventIncremental: function () {
  52260. return !!this.get('effect.show');
  52261. },
  52262. getProgressive: function () {
  52263. var progressive = this.option.progressive;
  52264. if (progressive == null) {
  52265. return this.option.large ? 1e4 : this.get('progressive');
  52266. }
  52267. return progressive;
  52268. },
  52269. getProgressiveThreshold: function () {
  52270. var progressiveThreshold = this.option.progressiveThreshold;
  52271. if (progressiveThreshold == null) {
  52272. return this.option.large ? 2e4 : this.get('progressiveThreshold');
  52273. }
  52274. return progressiveThreshold;
  52275. },
  52276. defaultOption: {
  52277. coordinateSystem: 'geo',
  52278. zlevel: 0,
  52279. z: 2,
  52280. legendHoverLink: true,
  52281. hoverAnimation: true,
  52282. // Cartesian coordinate system
  52283. xAxisIndex: 0,
  52284. yAxisIndex: 0,
  52285. symbol: ['none', 'none'],
  52286. symbolSize: [10, 10],
  52287. // Geo coordinate system
  52288. geoIndex: 0,
  52289. effect: {
  52290. show: false,
  52291. period: 4,
  52292. // Animation delay. support callback
  52293. // delay: 0,
  52294. // If move with constant speed px/sec
  52295. // period will be ignored if this property is > 0,
  52296. constantSpeed: 0,
  52297. symbol: 'circle',
  52298. symbolSize: 3,
  52299. loop: true,
  52300. // Length of trail, 0 - 1
  52301. trailLength: 0.2
  52302. // Same with lineStyle.color
  52303. // color
  52304. },
  52305. large: false,
  52306. // Available when large is true
  52307. largeThreshold: 2000,
  52308. // If lines are polyline
  52309. // polyline not support curveness, label, animation
  52310. polyline: false,
  52311. label: {
  52312. show: false,
  52313. position: 'end'
  52314. // distance: 5,
  52315. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  52316. },
  52317. lineStyle: {
  52318. opacity: 0.5
  52319. }
  52320. }
  52321. });
  52322. /*
  52323. * Licensed to the Apache Software Foundation (ASF) under one
  52324. * or more contributor license agreements. See the NOTICE file
  52325. * distributed with this work for additional information
  52326. * regarding copyright ownership. The ASF licenses this file
  52327. * to you under the Apache License, Version 2.0 (the
  52328. * "License"); you may not use this file except in compliance
  52329. * with the License. You may obtain a copy of the License at
  52330. *
  52331. * http://www.apache.org/licenses/LICENSE-2.0
  52332. *
  52333. * Unless required by applicable law or agreed to in writing,
  52334. * software distributed under the License is distributed on an
  52335. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52336. * KIND, either express or implied. See the License for the
  52337. * specific language governing permissions and limitations
  52338. * under the License.
  52339. */
  52340. /**
  52341. * Provide effect for line
  52342. * @module echarts/chart/helper/EffectLine
  52343. */
  52344. /**
  52345. * @constructor
  52346. * @extends {module:zrender/graphic/Group}
  52347. * @alias {module:echarts/chart/helper/Line}
  52348. */
  52349. function EffectLine(lineData, idx, seriesScope) {
  52350. Group.call(this);
  52351. this.add(this.createLine(lineData, idx, seriesScope));
  52352. this._updateEffectSymbol(lineData, idx);
  52353. }
  52354. var effectLineProto = EffectLine.prototype;
  52355. effectLineProto.createLine = function (lineData, idx, seriesScope) {
  52356. return new Line$1(lineData, idx, seriesScope);
  52357. };
  52358. effectLineProto._updateEffectSymbol = function (lineData, idx) {
  52359. var itemModel = lineData.getItemModel(idx);
  52360. var effectModel = itemModel.getModel('effect');
  52361. var size = effectModel.get('symbolSize');
  52362. var symbolType = effectModel.get('symbol');
  52363. if (!isArray(size)) {
  52364. size = [size, size];
  52365. }
  52366. var color = effectModel.get('color') || lineData.getItemVisual(idx, 'color');
  52367. var symbol = this.childAt(1);
  52368. if (this._symbolType !== symbolType) {
  52369. // Remove previous
  52370. this.remove(symbol);
  52371. symbol = createSymbol(
  52372. symbolType, -0.5, -0.5, 1, 1, color
  52373. );
  52374. symbol.z2 = 100;
  52375. symbol.culling = true;
  52376. this.add(symbol);
  52377. }
  52378. // Symbol may be removed if loop is false
  52379. if (!symbol) {
  52380. return;
  52381. }
  52382. // Shadow color is same with color in default
  52383. symbol.setStyle('shadowColor', color);
  52384. symbol.setStyle(effectModel.getItemStyle(['color']));
  52385. symbol.attr('scale', size);
  52386. symbol.setColor(color);
  52387. symbol.attr('scale', size);
  52388. this._symbolType = symbolType;
  52389. this._updateEffectAnimation(lineData, effectModel, idx);
  52390. };
  52391. effectLineProto._updateEffectAnimation = function (lineData, effectModel, idx) {
  52392. var symbol = this.childAt(1);
  52393. if (!symbol) {
  52394. return;
  52395. }
  52396. var self = this;
  52397. var points = lineData.getItemLayout(idx);
  52398. var period = effectModel.get('period') * 1000;
  52399. var loop = effectModel.get('loop');
  52400. var constantSpeed = effectModel.get('constantSpeed');
  52401. var delayExpr = retrieve(effectModel.get('delay'), function (idx) {
  52402. return idx / lineData.count() * period / 3;
  52403. });
  52404. var isDelayFunc = typeof delayExpr === 'function';
  52405. // Ignore when updating
  52406. symbol.ignore = true;
  52407. this.updateAnimationPoints(symbol, points);
  52408. if (constantSpeed > 0) {
  52409. period = this.getLineLength(symbol) / constantSpeed * 1000;
  52410. }
  52411. if (period !== this._period || loop !== this._loop) {
  52412. symbol.stopAnimation();
  52413. var delay = delayExpr;
  52414. if (isDelayFunc) {
  52415. delay = delayExpr(idx);
  52416. }
  52417. if (symbol.__t > 0) {
  52418. delay = -period * symbol.__t;
  52419. }
  52420. symbol.__t = 0;
  52421. var animator = symbol.animate('', loop)
  52422. .when(period, {
  52423. __t: 1
  52424. })
  52425. .delay(delay)
  52426. .during(function () {
  52427. self.updateSymbolPosition(symbol);
  52428. });
  52429. if (!loop) {
  52430. animator.done(function () {
  52431. self.remove(symbol);
  52432. });
  52433. }
  52434. animator.start();
  52435. }
  52436. this._period = period;
  52437. this._loop = loop;
  52438. };
  52439. effectLineProto.getLineLength = function (symbol) {
  52440. // Not so accurate
  52441. return (dist(symbol.__p1, symbol.__cp1)
  52442. + dist(symbol.__cp1, symbol.__p2));
  52443. };
  52444. effectLineProto.updateAnimationPoints = function (symbol, points) {
  52445. symbol.__p1 = points[0];
  52446. symbol.__p2 = points[1];
  52447. symbol.__cp1 = points[2] || [
  52448. (points[0][0] + points[1][0]) / 2,
  52449. (points[0][1] + points[1][1]) / 2
  52450. ];
  52451. };
  52452. effectLineProto.updateData = function (lineData, idx, seriesScope) {
  52453. this.childAt(0).updateData(lineData, idx, seriesScope);
  52454. this._updateEffectSymbol(lineData, idx);
  52455. };
  52456. effectLineProto.updateSymbolPosition = function (symbol) {
  52457. var p1 = symbol.__p1;
  52458. var p2 = symbol.__p2;
  52459. var cp1 = symbol.__cp1;
  52460. var t = symbol.__t;
  52461. var pos = symbol.position;
  52462. var quadraticAt$$1 = quadraticAt;
  52463. var quadraticDerivativeAt$$1 = quadraticDerivativeAt;
  52464. pos[0] = quadraticAt$$1(p1[0], cp1[0], p2[0], t);
  52465. pos[1] = quadraticAt$$1(p1[1], cp1[1], p2[1], t);
  52466. // Tangent
  52467. var tx = quadraticDerivativeAt$$1(p1[0], cp1[0], p2[0], t);
  52468. var ty = quadraticDerivativeAt$$1(p1[1], cp1[1], p2[1], t);
  52469. symbol.rotation = -Math.atan2(ty, tx) - Math.PI / 2;
  52470. symbol.ignore = false;
  52471. };
  52472. effectLineProto.updateLayout = function (lineData, idx) {
  52473. this.childAt(0).updateLayout(lineData, idx);
  52474. var effectModel = lineData.getItemModel(idx).getModel('effect');
  52475. this._updateEffectAnimation(lineData, effectModel, idx);
  52476. };
  52477. inherits(EffectLine, Group);
  52478. /*
  52479. * Licensed to the Apache Software Foundation (ASF) under one
  52480. * or more contributor license agreements. See the NOTICE file
  52481. * distributed with this work for additional information
  52482. * regarding copyright ownership. The ASF licenses this file
  52483. * to you under the Apache License, Version 2.0 (the
  52484. * "License"); you may not use this file except in compliance
  52485. * with the License. You may obtain a copy of the License at
  52486. *
  52487. * http://www.apache.org/licenses/LICENSE-2.0
  52488. *
  52489. * Unless required by applicable law or agreed to in writing,
  52490. * software distributed under the License is distributed on an
  52491. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52492. * KIND, either express or implied. See the License for the
  52493. * specific language governing permissions and limitations
  52494. * under the License.
  52495. */
  52496. /**
  52497. * @module echarts/chart/helper/Line
  52498. */
  52499. /**
  52500. * @constructor
  52501. * @extends {module:zrender/graphic/Group}
  52502. * @alias {module:echarts/chart/helper/Polyline}
  52503. */
  52504. function Polyline$2(lineData, idx, seriesScope) {
  52505. Group.call(this);
  52506. this._createPolyline(lineData, idx, seriesScope);
  52507. }
  52508. var polylineProto = Polyline$2.prototype;
  52509. polylineProto._createPolyline = function (lineData, idx, seriesScope) {
  52510. // var seriesModel = lineData.hostModel;
  52511. var points = lineData.getItemLayout(idx);
  52512. var line = new Polyline({
  52513. shape: {
  52514. points: points
  52515. }
  52516. });
  52517. this.add(line);
  52518. this._updateCommonStl(lineData, idx, seriesScope);
  52519. };
  52520. polylineProto.updateData = function (lineData, idx, seriesScope) {
  52521. var seriesModel = lineData.hostModel;
  52522. var line = this.childAt(0);
  52523. var target = {
  52524. shape: {
  52525. points: lineData.getItemLayout(idx)
  52526. }
  52527. };
  52528. updateProps(line, target, seriesModel, idx);
  52529. this._updateCommonStl(lineData, idx, seriesScope);
  52530. };
  52531. polylineProto._updateCommonStl = function (lineData, idx, seriesScope) {
  52532. var line = this.childAt(0);
  52533. var itemModel = lineData.getItemModel(idx);
  52534. var visualColor = lineData.getItemVisual(idx, 'color');
  52535. var lineStyle = seriesScope && seriesScope.lineStyle;
  52536. var hoverLineStyle = seriesScope && seriesScope.hoverLineStyle;
  52537. if (!seriesScope || lineData.hasItemOption) {
  52538. lineStyle = itemModel.getModel('lineStyle').getLineStyle();
  52539. hoverLineStyle = itemModel.getModel('emphasis.lineStyle').getLineStyle();
  52540. }
  52541. line.useStyle(defaults(
  52542. {
  52543. strokeNoScale: true,
  52544. fill: 'none',
  52545. stroke: visualColor
  52546. },
  52547. lineStyle
  52548. ));
  52549. line.hoverStyle = hoverLineStyle;
  52550. setHoverStyle(this);
  52551. };
  52552. polylineProto.updateLayout = function (lineData, idx) {
  52553. var polyline = this.childAt(0);
  52554. polyline.setShape('points', lineData.getItemLayout(idx));
  52555. };
  52556. inherits(Polyline$2, Group);
  52557. /*
  52558. * Licensed to the Apache Software Foundation (ASF) under one
  52559. * or more contributor license agreements. See the NOTICE file
  52560. * distributed with this work for additional information
  52561. * regarding copyright ownership. The ASF licenses this file
  52562. * to you under the Apache License, Version 2.0 (the
  52563. * "License"); you may not use this file except in compliance
  52564. * with the License. You may obtain a copy of the License at
  52565. *
  52566. * http://www.apache.org/licenses/LICENSE-2.0
  52567. *
  52568. * Unless required by applicable law or agreed to in writing,
  52569. * software distributed under the License is distributed on an
  52570. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52571. * KIND, either express or implied. See the License for the
  52572. * specific language governing permissions and limitations
  52573. * under the License.
  52574. */
  52575. /**
  52576. * Provide effect for line
  52577. * @module echarts/chart/helper/EffectLine
  52578. */
  52579. /**
  52580. * @constructor
  52581. * @extends {module:echarts/chart/helper/EffectLine}
  52582. * @alias {module:echarts/chart/helper/Polyline}
  52583. */
  52584. function EffectPolyline(lineData, idx, seriesScope) {
  52585. EffectLine.call(this, lineData, idx, seriesScope);
  52586. this._lastFrame = 0;
  52587. this._lastFramePercent = 0;
  52588. }
  52589. var effectPolylineProto = EffectPolyline.prototype;
  52590. // Overwrite
  52591. effectPolylineProto.createLine = function (lineData, idx, seriesScope) {
  52592. return new Polyline$2(lineData, idx, seriesScope);
  52593. };
  52594. // Overwrite
  52595. effectPolylineProto.updateAnimationPoints = function (symbol, points) {
  52596. this._points = points;
  52597. var accLenArr = [0];
  52598. var len$$1 = 0;
  52599. for (var i = 1; i < points.length; i++) {
  52600. var p1 = points[i - 1];
  52601. var p2 = points[i];
  52602. len$$1 += dist(p1, p2);
  52603. accLenArr.push(len$$1);
  52604. }
  52605. if (len$$1 === 0) {
  52606. return;
  52607. }
  52608. for (var i = 0; i < accLenArr.length; i++) {
  52609. accLenArr[i] /= len$$1;
  52610. }
  52611. this._offsets = accLenArr;
  52612. this._length = len$$1;
  52613. };
  52614. // Overwrite
  52615. effectPolylineProto.getLineLength = function (symbol) {
  52616. return this._length;
  52617. };
  52618. // Overwrite
  52619. effectPolylineProto.updateSymbolPosition = function (symbol) {
  52620. var t = symbol.__t;
  52621. var points = this._points;
  52622. var offsets = this._offsets;
  52623. var len$$1 = points.length;
  52624. if (!offsets) {
  52625. // Has length 0
  52626. return;
  52627. }
  52628. var lastFrame = this._lastFrame;
  52629. var frame;
  52630. if (t < this._lastFramePercent) {
  52631. // Start from the next frame
  52632. // PENDING start from lastFrame ?
  52633. var start = Math.min(lastFrame + 1, len$$1 - 1);
  52634. for (frame = start; frame >= 0; frame--) {
  52635. if (offsets[frame] <= t) {
  52636. break;
  52637. }
  52638. }
  52639. // PENDING really need to do this ?
  52640. frame = Math.min(frame, len$$1 - 2);
  52641. }
  52642. else {
  52643. for (var frame = lastFrame; frame < len$$1; frame++) {
  52644. if (offsets[frame] > t) {
  52645. break;
  52646. }
  52647. }
  52648. frame = Math.min(frame - 1, len$$1 - 2);
  52649. }
  52650. lerp(
  52651. symbol.position, points[frame], points[frame + 1],
  52652. (t - offsets[frame]) / (offsets[frame + 1] - offsets[frame])
  52653. );
  52654. var tx = points[frame + 1][0] - points[frame][0];
  52655. var ty = points[frame + 1][1] - points[frame][1];
  52656. symbol.rotation = -Math.atan2(ty, tx) - Math.PI / 2;
  52657. this._lastFrame = frame;
  52658. this._lastFramePercent = t;
  52659. symbol.ignore = false;
  52660. };
  52661. inherits(EffectPolyline, EffectLine);
  52662. /*
  52663. * Licensed to the Apache Software Foundation (ASF) under one
  52664. * or more contributor license agreements. See the NOTICE file
  52665. * distributed with this work for additional information
  52666. * regarding copyright ownership. The ASF licenses this file
  52667. * to you under the Apache License, Version 2.0 (the
  52668. * "License"); you may not use this file except in compliance
  52669. * with the License. You may obtain a copy of the License at
  52670. *
  52671. * http://www.apache.org/licenses/LICENSE-2.0
  52672. *
  52673. * Unless required by applicable law or agreed to in writing,
  52674. * software distributed under the License is distributed on an
  52675. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52676. * KIND, either express or implied. See the License for the
  52677. * specific language governing permissions and limitations
  52678. * under the License.
  52679. */
  52680. // TODO Batch by color
  52681. var LargeLineShape = extendShape({
  52682. shape: {
  52683. polyline: false,
  52684. curveness: 0,
  52685. segs: []
  52686. },
  52687. buildPath: function (path, shape) {
  52688. var segs = shape.segs;
  52689. var curveness = shape.curveness;
  52690. if (shape.polyline) {
  52691. for (var i = 0; i < segs.length;) {
  52692. var count = segs[i++];
  52693. if (count > 0) {
  52694. path.moveTo(segs[i++], segs[i++]);
  52695. for (var k = 1; k < count; k++) {
  52696. path.lineTo(segs[i++], segs[i++]);
  52697. }
  52698. }
  52699. }
  52700. }
  52701. else {
  52702. for (var i = 0; i < segs.length;) {
  52703. var x0 = segs[i++];
  52704. var y0 = segs[i++];
  52705. var x1 = segs[i++];
  52706. var y1 = segs[i++];
  52707. path.moveTo(x0, y0);
  52708. if (curveness > 0) {
  52709. var x2 = (x0 + x1) / 2 - (y0 - y1) * curveness;
  52710. var y2 = (y0 + y1) / 2 - (x1 - x0) * curveness;
  52711. path.quadraticCurveTo(x2, y2, x1, y1);
  52712. }
  52713. else {
  52714. path.lineTo(x1, y1);
  52715. }
  52716. }
  52717. }
  52718. },
  52719. findDataIndex: function (x, y) {
  52720. var shape = this.shape;
  52721. var segs = shape.segs;
  52722. var curveness = shape.curveness;
  52723. if (shape.polyline) {
  52724. var dataIndex = 0;
  52725. for (var i = 0; i < segs.length;) {
  52726. var count = segs[i++];
  52727. if (count > 0) {
  52728. var x0 = segs[i++];
  52729. var y0 = segs[i++];
  52730. for (var k = 1; k < count; k++) {
  52731. var x1 = segs[i++];
  52732. var y1 = segs[i++];
  52733. if (containStroke$1(x0, y0, x1, y1)) {
  52734. return dataIndex;
  52735. }
  52736. }
  52737. }
  52738. dataIndex++;
  52739. }
  52740. }
  52741. else {
  52742. var dataIndex = 0;
  52743. for (var i = 0; i < segs.length;) {
  52744. var x0 = segs[i++];
  52745. var y0 = segs[i++];
  52746. var x1 = segs[i++];
  52747. var y1 = segs[i++];
  52748. if (curveness > 0) {
  52749. var x2 = (x0 + x1) / 2 - (y0 - y1) * curveness;
  52750. var y2 = (y0 + y1) / 2 - (x1 - x0) * curveness;
  52751. if (containStroke$3(x0, y0, x2, y2, x1, y1)) {
  52752. return dataIndex;
  52753. }
  52754. }
  52755. else {
  52756. if (containStroke$1(x0, y0, x1, y1)) {
  52757. return dataIndex;
  52758. }
  52759. }
  52760. dataIndex++;
  52761. }
  52762. }
  52763. return -1;
  52764. }
  52765. });
  52766. function LargeLineDraw() {
  52767. this.group = new Group();
  52768. }
  52769. var largeLineProto = LargeLineDraw.prototype;
  52770. largeLineProto.isPersistent = function () {
  52771. return !this._incremental;
  52772. };
  52773. /**
  52774. * Update symbols draw by new data
  52775. * @param {module:echarts/data/List} data
  52776. */
  52777. largeLineProto.updateData = function (data) {
  52778. this.group.removeAll();
  52779. var lineEl = new LargeLineShape({
  52780. rectHover: true,
  52781. cursor: 'default'
  52782. });
  52783. lineEl.setShape({
  52784. segs: data.getLayout('linesPoints')
  52785. });
  52786. this._setCommon(lineEl, data);
  52787. // Add back
  52788. this.group.add(lineEl);
  52789. this._incremental = null;
  52790. };
  52791. /**
  52792. * @override
  52793. */
  52794. largeLineProto.incrementalPrepareUpdate = function (data) {
  52795. this.group.removeAll();
  52796. this._clearIncremental();
  52797. if (data.count() > 5e5) {
  52798. if (!this._incremental) {
  52799. this._incremental = new IncrementalDisplayble({
  52800. silent: true
  52801. });
  52802. }
  52803. this.group.add(this._incremental);
  52804. }
  52805. else {
  52806. this._incremental = null;
  52807. }
  52808. };
  52809. /**
  52810. * @override
  52811. */
  52812. largeLineProto.incrementalUpdate = function (taskParams, data) {
  52813. var lineEl = new LargeLineShape();
  52814. lineEl.setShape({
  52815. segs: data.getLayout('linesPoints')
  52816. });
  52817. this._setCommon(lineEl, data, !!this._incremental);
  52818. if (!this._incremental) {
  52819. lineEl.rectHover = true;
  52820. lineEl.cursor = 'default';
  52821. lineEl.__startIndex = taskParams.start;
  52822. this.group.add(lineEl);
  52823. }
  52824. else {
  52825. this._incremental.addDisplayable(lineEl, true);
  52826. }
  52827. };
  52828. /**
  52829. * @override
  52830. */
  52831. largeLineProto.remove = function () {
  52832. this._clearIncremental();
  52833. this._incremental = null;
  52834. this.group.removeAll();
  52835. };
  52836. largeLineProto._setCommon = function (lineEl, data, isIncremental) {
  52837. var hostModel = data.hostModel;
  52838. lineEl.setShape({
  52839. polyline: hostModel.get('polyline'),
  52840. curveness: hostModel.get('lineStyle.curveness')
  52841. });
  52842. lineEl.useStyle(
  52843. hostModel.getModel('lineStyle').getLineStyle()
  52844. );
  52845. lineEl.style.strokeNoScale = true;
  52846. var visualColor = data.getVisual('color');
  52847. if (visualColor) {
  52848. lineEl.setStyle('stroke', visualColor);
  52849. }
  52850. lineEl.setStyle('fill');
  52851. if (!isIncremental) {
  52852. // Enable tooltip
  52853. // PENDING May have performance issue when path is extremely large
  52854. lineEl.seriesIndex = hostModel.seriesIndex;
  52855. lineEl.on('mousemove', function (e) {
  52856. lineEl.dataIndex = null;
  52857. var dataIndex = lineEl.findDataIndex(e.offsetX, e.offsetY);
  52858. if (dataIndex > 0) {
  52859. // Provide dataIndex for tooltip
  52860. lineEl.dataIndex = dataIndex + lineEl.__startIndex;
  52861. }
  52862. });
  52863. }
  52864. };
  52865. largeLineProto._clearIncremental = function () {
  52866. var incremental = this._incremental;
  52867. if (incremental) {
  52868. incremental.clearDisplaybles();
  52869. }
  52870. };
  52871. /*
  52872. * Licensed to the Apache Software Foundation (ASF) under one
  52873. * or more contributor license agreements. See the NOTICE file
  52874. * distributed with this work for additional information
  52875. * regarding copyright ownership. The ASF licenses this file
  52876. * to you under the Apache License, Version 2.0 (the
  52877. * "License"); you may not use this file except in compliance
  52878. * with the License. You may obtain a copy of the License at
  52879. *
  52880. * http://www.apache.org/licenses/LICENSE-2.0
  52881. *
  52882. * Unless required by applicable law or agreed to in writing,
  52883. * software distributed under the License is distributed on an
  52884. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52885. * KIND, either express or implied. See the License for the
  52886. * specific language governing permissions and limitations
  52887. * under the License.
  52888. */
  52889. var linesLayout = {
  52890. seriesType: 'lines',
  52891. plan: createRenderPlanner(),
  52892. reset: function (seriesModel) {
  52893. var coordSys = seriesModel.coordinateSystem;
  52894. var isPolyline = seriesModel.get('polyline');
  52895. var isLarge = seriesModel.pipelineContext.large;
  52896. function progress(params, lineData) {
  52897. var lineCoords = [];
  52898. if (isLarge) {
  52899. var points;
  52900. var segCount = params.end - params.start;
  52901. if (isPolyline) {
  52902. var totalCoordsCount = 0;
  52903. for (var i = params.start; i < params.end; i++) {
  52904. totalCoordsCount += seriesModel.getLineCoordsCount(i);
  52905. }
  52906. points = new Float32Array(segCount + totalCoordsCount * 2);
  52907. }
  52908. else {
  52909. points = new Float32Array(segCount * 4);
  52910. }
  52911. var offset = 0;
  52912. var pt = [];
  52913. for (var i = params.start; i < params.end; i++) {
  52914. var len = seriesModel.getLineCoords(i, lineCoords);
  52915. if (isPolyline) {
  52916. points[offset++] = len;
  52917. }
  52918. for (var k = 0; k < len; k++) {
  52919. pt = coordSys.dataToPoint(lineCoords[k], false, pt);
  52920. points[offset++] = pt[0];
  52921. points[offset++] = pt[1];
  52922. }
  52923. }
  52924. lineData.setLayout('linesPoints', points);
  52925. }
  52926. else {
  52927. for (var i = params.start; i < params.end; i++) {
  52928. var itemModel = lineData.getItemModel(i);
  52929. var len = seriesModel.getLineCoords(i, lineCoords);
  52930. var pts = [];
  52931. if (isPolyline) {
  52932. for (var j = 0; j < len; j++) {
  52933. pts.push(coordSys.dataToPoint(lineCoords[j]));
  52934. }
  52935. }
  52936. else {
  52937. pts[0] = coordSys.dataToPoint(lineCoords[0]);
  52938. pts[1] = coordSys.dataToPoint(lineCoords[1]);
  52939. var curveness = itemModel.get('lineStyle.curveness');
  52940. if (+curveness) {
  52941. pts[2] = [
  52942. (pts[0][0] + pts[1][0]) / 2 - (pts[0][1] - pts[1][1]) * curveness,
  52943. (pts[0][1] + pts[1][1]) / 2 - (pts[1][0] - pts[0][0]) * curveness
  52944. ];
  52945. }
  52946. }
  52947. lineData.setItemLayout(i, pts);
  52948. }
  52949. }
  52950. }
  52951. return { progress: progress };
  52952. }
  52953. };
  52954. /*
  52955. * Licensed to the Apache Software Foundation (ASF) under one
  52956. * or more contributor license agreements. See the NOTICE file
  52957. * distributed with this work for additional information
  52958. * regarding copyright ownership. The ASF licenses this file
  52959. * to you under the Apache License, Version 2.0 (the
  52960. * "License"); you may not use this file except in compliance
  52961. * with the License. You may obtain a copy of the License at
  52962. *
  52963. * http://www.apache.org/licenses/LICENSE-2.0
  52964. *
  52965. * Unless required by applicable law or agreed to in writing,
  52966. * software distributed under the License is distributed on an
  52967. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52968. * KIND, either express or implied. See the License for the
  52969. * specific language governing permissions and limitations
  52970. * under the License.
  52971. */
  52972. extendChartView({
  52973. type: 'lines',
  52974. init: function () {},
  52975. render: function (seriesModel, ecModel, api) {
  52976. var data = seriesModel.getData();
  52977. var lineDraw = this._updateLineDraw(data, seriesModel);
  52978. var zlevel = seriesModel.get('zlevel');
  52979. var trailLength = seriesModel.get('effect.trailLength');
  52980. var zr = api.getZr();
  52981. // Avoid the drag cause ghost shadow
  52982. // FIXME Better way ?
  52983. // SVG doesn't support
  52984. var isSvg = zr.painter.getType() === 'svg';
  52985. if (!isSvg) {
  52986. zr.painter.getLayer(zlevel).clear(true);
  52987. }
  52988. // Config layer with motion blur
  52989. if (this._lastZlevel != null && !isSvg) {
  52990. zr.configLayer(this._lastZlevel, {
  52991. motionBlur: false
  52992. });
  52993. }
  52994. if (this._showEffect(seriesModel) && trailLength) {
  52995. if (__DEV__) {
  52996. var notInIndividual = false;
  52997. ecModel.eachSeries(function (otherSeriesModel) {
  52998. if (otherSeriesModel !== seriesModel && otherSeriesModel.get('zlevel') === zlevel) {
  52999. notInIndividual = true;
  53000. }
  53001. });
  53002. notInIndividual && console.warn('Lines with trail effect should have an individual zlevel');
  53003. }
  53004. if (!isSvg) {
  53005. zr.configLayer(zlevel, {
  53006. motionBlur: true,
  53007. lastFrameAlpha: Math.max(Math.min(trailLength / 10 + 0.9, 1), 0)
  53008. });
  53009. }
  53010. }
  53011. lineDraw.updateData(data);
  53012. this._lastZlevel = zlevel;
  53013. this._finished = true;
  53014. },
  53015. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  53016. var data = seriesModel.getData();
  53017. var lineDraw = this._updateLineDraw(data, seriesModel);
  53018. lineDraw.incrementalPrepareUpdate(data);
  53019. this._clearLayer(api);
  53020. this._finished = false;
  53021. },
  53022. incrementalRender: function (taskParams, seriesModel, ecModel) {
  53023. this._lineDraw.incrementalUpdate(taskParams, seriesModel.getData());
  53024. this._finished = taskParams.end === seriesModel.getData().count();
  53025. },
  53026. updateTransform: function (seriesModel, ecModel, api) {
  53027. var data = seriesModel.getData();
  53028. var pipelineContext = seriesModel.pipelineContext;
  53029. if (!this._finished || pipelineContext.large || pipelineContext.progressiveRender) {
  53030. // TODO Don't have to do update in large mode. Only do it when there are millions of data.
  53031. return {
  53032. update: true
  53033. };
  53034. }
  53035. else {
  53036. // TODO Use same logic with ScatterView.
  53037. // Manually update layout
  53038. var res = linesLayout.reset(seriesModel);
  53039. if (res.progress) {
  53040. res.progress({ start: 0, end: data.count() }, data);
  53041. }
  53042. this._lineDraw.updateLayout();
  53043. this._clearLayer(api);
  53044. }
  53045. },
  53046. _updateLineDraw: function (data, seriesModel) {
  53047. var lineDraw = this._lineDraw;
  53048. var hasEffect = this._showEffect(seriesModel);
  53049. var isPolyline = !!seriesModel.get('polyline');
  53050. var pipelineContext = seriesModel.pipelineContext;
  53051. var isLargeDraw = pipelineContext.large;
  53052. if (__DEV__) {
  53053. if (hasEffect && isLargeDraw) {
  53054. console.warn('Large lines not support effect');
  53055. }
  53056. }
  53057. if (!lineDraw
  53058. || hasEffect !== this._hasEffet
  53059. || isPolyline !== this._isPolyline
  53060. || isLargeDraw !== this._isLargeDraw
  53061. ) {
  53062. if (lineDraw) {
  53063. lineDraw.remove();
  53064. }
  53065. lineDraw = this._lineDraw = isLargeDraw
  53066. ? new LargeLineDraw()
  53067. : new LineDraw(
  53068. isPolyline
  53069. ? (hasEffect ? EffectPolyline : Polyline$2)
  53070. : (hasEffect ? EffectLine : Line$1)
  53071. );
  53072. this._hasEffet = hasEffect;
  53073. this._isPolyline = isPolyline;
  53074. this._isLargeDraw = isLargeDraw;
  53075. this.group.removeAll();
  53076. }
  53077. this.group.add(lineDraw.group);
  53078. return lineDraw;
  53079. },
  53080. _showEffect: function (seriesModel) {
  53081. return !!seriesModel.get('effect.show');
  53082. },
  53083. _clearLayer: function (api) {
  53084. // Not use motion when dragging or zooming
  53085. var zr = api.getZr();
  53086. var isSvg = zr.painter.getType() === 'svg';
  53087. if (!isSvg && this._lastZlevel != null) {
  53088. zr.painter.getLayer(this._lastZlevel).clear(true);
  53089. }
  53090. },
  53091. remove: function (ecModel, api) {
  53092. this._lineDraw && this._lineDraw.remove();
  53093. this._lineDraw = null;
  53094. // Clear motion when lineDraw is removed
  53095. this._clearLayer(api);
  53096. },
  53097. dispose: function () {}
  53098. });
  53099. /*
  53100. * Licensed to the Apache Software Foundation (ASF) under one
  53101. * or more contributor license agreements. See the NOTICE file
  53102. * distributed with this work for additional information
  53103. * regarding copyright ownership. The ASF licenses this file
  53104. * to you under the Apache License, Version 2.0 (the
  53105. * "License"); you may not use this file except in compliance
  53106. * with the License. You may obtain a copy of the License at
  53107. *
  53108. * http://www.apache.org/licenses/LICENSE-2.0
  53109. *
  53110. * Unless required by applicable law or agreed to in writing,
  53111. * software distributed under the License is distributed on an
  53112. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53113. * KIND, either express or implied. See the License for the
  53114. * specific language governing permissions and limitations
  53115. * under the License.
  53116. */
  53117. function normalize$2(a) {
  53118. if (!(a instanceof Array)) {
  53119. a = [a, a];
  53120. }
  53121. return a;
  53122. }
  53123. var opacityQuery = 'lineStyle.opacity'.split('.');
  53124. var linesVisual = {
  53125. seriesType: 'lines',
  53126. reset: function (seriesModel, ecModel, api) {
  53127. var symbolType = normalize$2(seriesModel.get('symbol'));
  53128. var symbolSize = normalize$2(seriesModel.get('symbolSize'));
  53129. var data = seriesModel.getData();
  53130. data.setVisual('fromSymbol', symbolType && symbolType[0]);
  53131. data.setVisual('toSymbol', symbolType && symbolType[1]);
  53132. data.setVisual('fromSymbolSize', symbolSize && symbolSize[0]);
  53133. data.setVisual('toSymbolSize', symbolSize && symbolSize[1]);
  53134. data.setVisual('opacity', seriesModel.get(opacityQuery));
  53135. function dataEach(data, idx) {
  53136. var itemModel = data.getItemModel(idx);
  53137. var symbolType = normalize$2(itemModel.getShallow('symbol', true));
  53138. var symbolSize = normalize$2(itemModel.getShallow('symbolSize', true));
  53139. var opacity = itemModel.get(opacityQuery);
  53140. symbolType[0] && data.setItemVisual(idx, 'fromSymbol', symbolType[0]);
  53141. symbolType[1] && data.setItemVisual(idx, 'toSymbol', symbolType[1]);
  53142. symbolSize[0] && data.setItemVisual(idx, 'fromSymbolSize', symbolSize[0]);
  53143. symbolSize[1] && data.setItemVisual(idx, 'toSymbolSize', symbolSize[1]);
  53144. data.setItemVisual(idx, 'opacity', opacity);
  53145. }
  53146. return {dataEach: data.hasItemOption ? dataEach : null};
  53147. }
  53148. };
  53149. /*
  53150. * Licensed to the Apache Software Foundation (ASF) under one
  53151. * or more contributor license agreements. See the NOTICE file
  53152. * distributed with this work for additional information
  53153. * regarding copyright ownership. The ASF licenses this file
  53154. * to you under the Apache License, Version 2.0 (the
  53155. * "License"); you may not use this file except in compliance
  53156. * with the License. You may obtain a copy of the License at
  53157. *
  53158. * http://www.apache.org/licenses/LICENSE-2.0
  53159. *
  53160. * Unless required by applicable law or agreed to in writing,
  53161. * software distributed under the License is distributed on an
  53162. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53163. * KIND, either express or implied. See the License for the
  53164. * specific language governing permissions and limitations
  53165. * under the License.
  53166. */
  53167. registerLayout(linesLayout);
  53168. registerVisual(linesVisual);
  53169. /*
  53170. * Licensed to the Apache Software Foundation (ASF) under one
  53171. * or more contributor license agreements. See the NOTICE file
  53172. * distributed with this work for additional information
  53173. * regarding copyright ownership. The ASF licenses this file
  53174. * to you under the Apache License, Version 2.0 (the
  53175. * "License"); you may not use this file except in compliance
  53176. * with the License. You may obtain a copy of the License at
  53177. *
  53178. * http://www.apache.org/licenses/LICENSE-2.0
  53179. *
  53180. * Unless required by applicable law or agreed to in writing,
  53181. * software distributed under the License is distributed on an
  53182. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53183. * KIND, either express or implied. See the License for the
  53184. * specific language governing permissions and limitations
  53185. * under the License.
  53186. */
  53187. SeriesModel.extend({
  53188. type: 'series.heatmap',
  53189. getInitialData: function (option, ecModel) {
  53190. return createListFromArray(this.getSource(), this, {
  53191. generateCoord: 'value'
  53192. });
  53193. },
  53194. preventIncremental: function () {
  53195. var coordSysCreator = CoordinateSystemManager.get(this.get('coordinateSystem'));
  53196. if (coordSysCreator && coordSysCreator.dimensions) {
  53197. return coordSysCreator.dimensions[0] === 'lng' && coordSysCreator.dimensions[1] === 'lat';
  53198. }
  53199. },
  53200. defaultOption: {
  53201. // Cartesian2D or geo
  53202. coordinateSystem: 'cartesian2d',
  53203. zlevel: 0,
  53204. z: 2,
  53205. // Cartesian coordinate system
  53206. // xAxisIndex: 0,
  53207. // yAxisIndex: 0,
  53208. // Geo coordinate system
  53209. geoIndex: 0,
  53210. blurSize: 30,
  53211. pointSize: 20,
  53212. maxOpacity: 1,
  53213. minOpacity: 0
  53214. }
  53215. });
  53216. /*
  53217. * Licensed to the Apache Software Foundation (ASF) under one
  53218. * or more contributor license agreements. See the NOTICE file
  53219. * distributed with this work for additional information
  53220. * regarding copyright ownership. The ASF licenses this file
  53221. * to you under the Apache License, Version 2.0 (the
  53222. * "License"); you may not use this file except in compliance
  53223. * with the License. You may obtain a copy of the License at
  53224. *
  53225. * http://www.apache.org/licenses/LICENSE-2.0
  53226. *
  53227. * Unless required by applicable law or agreed to in writing,
  53228. * software distributed under the License is distributed on an
  53229. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53230. * KIND, either express or implied. See the License for the
  53231. * specific language governing permissions and limitations
  53232. * under the License.
  53233. */
  53234. /**
  53235. * @file defines echarts Heatmap Chart
  53236. * @author Ovilia (me@zhangwenli.com)
  53237. * Inspired by https://github.com/mourner/simpleheat
  53238. *
  53239. * @module
  53240. */
  53241. var GRADIENT_LEVELS = 256;
  53242. /**
  53243. * Heatmap Chart
  53244. *
  53245. * @class
  53246. */
  53247. function Heatmap() {
  53248. var canvas = createCanvas();
  53249. this.canvas = canvas;
  53250. this.blurSize = 30;
  53251. this.pointSize = 20;
  53252. this.maxOpacity = 1;
  53253. this.minOpacity = 0;
  53254. this._gradientPixels = {};
  53255. }
  53256. Heatmap.prototype = {
  53257. /**
  53258. * Renders Heatmap and returns the rendered canvas
  53259. * @param {Array} data array of data, each has x, y, value
  53260. * @param {number} width canvas width
  53261. * @param {number} height canvas height
  53262. */
  53263. update: function(data, width, height, normalize, colorFunc, isInRange) {
  53264. var brush = this._getBrush();
  53265. var gradientInRange = this._getGradient(data, colorFunc, 'inRange');
  53266. var gradientOutOfRange = this._getGradient(data, colorFunc, 'outOfRange');
  53267. var r = this.pointSize + this.blurSize;
  53268. var canvas = this.canvas;
  53269. var ctx = canvas.getContext('2d');
  53270. var len = data.length;
  53271. canvas.width = width;
  53272. canvas.height = height;
  53273. for (var i = 0; i < len; ++i) {
  53274. var p = data[i];
  53275. var x = p[0];
  53276. var y = p[1];
  53277. var value = p[2];
  53278. // calculate alpha using value
  53279. var alpha = normalize(value);
  53280. // draw with the circle brush with alpha
  53281. ctx.globalAlpha = alpha;
  53282. ctx.drawImage(brush, x - r, y - r);
  53283. }
  53284. if (!canvas.width || !canvas.height) {
  53285. // Avoid "Uncaught DOMException: Failed to execute 'getImageData' on
  53286. // 'CanvasRenderingContext2D': The source height is 0."
  53287. return canvas;
  53288. }
  53289. // colorize the canvas using alpha value and set with gradient
  53290. var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
  53291. var pixels = imageData.data;
  53292. var offset = 0;
  53293. var pixelLen = pixels.length;
  53294. var minOpacity = this.minOpacity;
  53295. var maxOpacity = this.maxOpacity;
  53296. var diffOpacity = maxOpacity - minOpacity;
  53297. while(offset < pixelLen) {
  53298. var alpha = pixels[offset + 3] / 256;
  53299. var gradientOffset = Math.floor(alpha * (GRADIENT_LEVELS - 1)) * 4;
  53300. // Simple optimize to ignore the empty data
  53301. if (alpha > 0) {
  53302. var gradient = isInRange(alpha) ? gradientInRange : gradientOutOfRange;
  53303. // Any alpha > 0 will be mapped to [minOpacity, maxOpacity]
  53304. alpha > 0 && (alpha = alpha * diffOpacity + minOpacity);
  53305. pixels[offset++] = gradient[gradientOffset];
  53306. pixels[offset++] = gradient[gradientOffset + 1];
  53307. pixels[offset++] = gradient[gradientOffset + 2];
  53308. pixels[offset++] = gradient[gradientOffset + 3] * alpha * 256;
  53309. }
  53310. else {
  53311. offset += 4;
  53312. }
  53313. }
  53314. ctx.putImageData(imageData, 0, 0);
  53315. return canvas;
  53316. },
  53317. /**
  53318. * get canvas of a black circle brush used for canvas to draw later
  53319. * @private
  53320. * @returns {Object} circle brush canvas
  53321. */
  53322. _getBrush: function() {
  53323. var brushCanvas = this._brushCanvas || (this._brushCanvas = createCanvas());
  53324. // set brush size
  53325. var r = this.pointSize + this.blurSize;
  53326. var d = r * 2;
  53327. brushCanvas.width = d;
  53328. brushCanvas.height = d;
  53329. var ctx = brushCanvas.getContext('2d');
  53330. ctx.clearRect(0, 0, d, d);
  53331. // in order to render shadow without the distinct circle,
  53332. // draw the distinct circle in an invisible place,
  53333. // and use shadowOffset to draw shadow in the center of the canvas
  53334. ctx.shadowOffsetX = d;
  53335. ctx.shadowBlur = this.blurSize;
  53336. // draw the shadow in black, and use alpha and shadow blur to generate
  53337. // color in color map
  53338. ctx.shadowColor = '#000';
  53339. // draw circle in the left to the canvas
  53340. ctx.beginPath();
  53341. ctx.arc(-r, r, this.pointSize, 0, Math.PI * 2, true);
  53342. ctx.closePath();
  53343. ctx.fill();
  53344. return brushCanvas;
  53345. },
  53346. /**
  53347. * get gradient color map
  53348. * @private
  53349. */
  53350. _getGradient: function (data, colorFunc, state) {
  53351. var gradientPixels = this._gradientPixels;
  53352. var pixelsSingleState = gradientPixels[state] || (gradientPixels[state] = new Uint8ClampedArray(256 * 4));
  53353. var color = [0, 0, 0, 0];
  53354. var off = 0;
  53355. for (var i = 0; i < 256; i++) {
  53356. colorFunc[state](i / 255, true, color);
  53357. pixelsSingleState[off++] = color[0];
  53358. pixelsSingleState[off++] = color[1];
  53359. pixelsSingleState[off++] = color[2];
  53360. pixelsSingleState[off++] = color[3];
  53361. }
  53362. return pixelsSingleState;
  53363. }
  53364. };
  53365. /*
  53366. * Licensed to the Apache Software Foundation (ASF) under one
  53367. * or more contributor license agreements. See the NOTICE file
  53368. * distributed with this work for additional information
  53369. * regarding copyright ownership. The ASF licenses this file
  53370. * to you under the Apache License, Version 2.0 (the
  53371. * "License"); you may not use this file except in compliance
  53372. * with the License. You may obtain a copy of the License at
  53373. *
  53374. * http://www.apache.org/licenses/LICENSE-2.0
  53375. *
  53376. * Unless required by applicable law or agreed to in writing,
  53377. * software distributed under the License is distributed on an
  53378. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53379. * KIND, either express or implied. See the License for the
  53380. * specific language governing permissions and limitations
  53381. * under the License.
  53382. */
  53383. function getIsInPiecewiseRange(dataExtent, pieceList, selected) {
  53384. var dataSpan = dataExtent[1] - dataExtent[0];
  53385. pieceList = map(pieceList, function (piece) {
  53386. return {
  53387. interval: [
  53388. (piece.interval[0] - dataExtent[0]) / dataSpan,
  53389. (piece.interval[1] - dataExtent[0]) / dataSpan
  53390. ]
  53391. };
  53392. });
  53393. var len = pieceList.length;
  53394. var lastIndex = 0;
  53395. return function (val) {
  53396. // Try to find in the location of the last found
  53397. for (var i = lastIndex; i < len; i++) {
  53398. var interval = pieceList[i].interval;
  53399. if (interval[0] <= val && val <= interval[1]) {
  53400. lastIndex = i;
  53401. break;
  53402. }
  53403. }
  53404. if (i === len) { // Not found, back interation
  53405. for (var i = lastIndex - 1; i >= 0; i--) {
  53406. var interval = pieceList[i].interval;
  53407. if (interval[0] <= val && val <= interval[1]) {
  53408. lastIndex = i;
  53409. break;
  53410. }
  53411. }
  53412. }
  53413. return i >= 0 && i < len && selected[i];
  53414. };
  53415. }
  53416. function getIsInContinuousRange(dataExtent, range) {
  53417. var dataSpan = dataExtent[1] - dataExtent[0];
  53418. range = [
  53419. (range[0] - dataExtent[0]) / dataSpan,
  53420. (range[1] - dataExtent[0]) / dataSpan
  53421. ];
  53422. return function (val) {
  53423. return val >= range[0] && val <= range[1];
  53424. };
  53425. }
  53426. function isGeoCoordSys(coordSys) {
  53427. var dimensions = coordSys.dimensions;
  53428. // Not use coorSys.type === 'geo' because coordSys maybe extended
  53429. return dimensions[0] === 'lng' && dimensions[1] === 'lat';
  53430. }
  53431. extendChartView({
  53432. type: 'heatmap',
  53433. render: function (seriesModel, ecModel, api) {
  53434. var visualMapOfThisSeries;
  53435. ecModel.eachComponent('visualMap', function (visualMap) {
  53436. visualMap.eachTargetSeries(function (targetSeries) {
  53437. if (targetSeries === seriesModel) {
  53438. visualMapOfThisSeries = visualMap;
  53439. }
  53440. });
  53441. });
  53442. if (__DEV__) {
  53443. if (!visualMapOfThisSeries) {
  53444. throw new Error('Heatmap must use with visualMap');
  53445. }
  53446. }
  53447. this.group.removeAll();
  53448. this._incrementalDisplayable = null;
  53449. var coordSys = seriesModel.coordinateSystem;
  53450. if (coordSys.type === 'cartesian2d' || coordSys.type === 'calendar') {
  53451. this._renderOnCartesianAndCalendar(seriesModel, api, 0, seriesModel.getData().count());
  53452. }
  53453. else if (isGeoCoordSys(coordSys)) {
  53454. this._renderOnGeo(
  53455. coordSys, seriesModel, visualMapOfThisSeries, api
  53456. );
  53457. }
  53458. },
  53459. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  53460. this.group.removeAll();
  53461. },
  53462. incrementalRender: function (params, seriesModel, ecModel, api) {
  53463. var coordSys = seriesModel.coordinateSystem;
  53464. if (coordSys) {
  53465. this._renderOnCartesianAndCalendar(seriesModel, api, params.start, params.end, true);
  53466. }
  53467. },
  53468. _renderOnCartesianAndCalendar: function (seriesModel, api, start, end, incremental) {
  53469. var coordSys = seriesModel.coordinateSystem;
  53470. var width;
  53471. var height;
  53472. if (coordSys.type === 'cartesian2d') {
  53473. var xAxis = coordSys.getAxis('x');
  53474. var yAxis = coordSys.getAxis('y');
  53475. if (__DEV__) {
  53476. if (!(xAxis.type === 'category' && yAxis.type === 'category')) {
  53477. throw new Error('Heatmap on cartesian must have two category axes');
  53478. }
  53479. if (!(xAxis.onBand && yAxis.onBand)) {
  53480. throw new Error('Heatmap on cartesian must have two axes with boundaryGap true');
  53481. }
  53482. }
  53483. width = xAxis.getBandWidth();
  53484. height = yAxis.getBandWidth();
  53485. }
  53486. var group = this.group;
  53487. var data = seriesModel.getData();
  53488. var itemStyleQuery = 'itemStyle';
  53489. var hoverItemStyleQuery = 'emphasis.itemStyle';
  53490. var labelQuery = 'label';
  53491. var hoverLabelQuery = 'emphasis.label';
  53492. var style = seriesModel.getModel(itemStyleQuery).getItemStyle(['color']);
  53493. var hoverStl = seriesModel.getModel(hoverItemStyleQuery).getItemStyle();
  53494. var labelModel = seriesModel.getModel(labelQuery);
  53495. var hoverLabelModel = seriesModel.getModel(hoverLabelQuery);
  53496. var coordSysType = coordSys.type;
  53497. var dataDims = coordSysType === 'cartesian2d'
  53498. ? [
  53499. data.mapDimension('x'),
  53500. data.mapDimension('y'),
  53501. data.mapDimension('value')
  53502. ]
  53503. : [
  53504. data.mapDimension('time'),
  53505. data.mapDimension('value')
  53506. ];
  53507. for (var idx = start; idx < end; idx++) {
  53508. var rect;
  53509. if (coordSysType === 'cartesian2d') {
  53510. // Ignore empty data
  53511. if (isNaN(data.get(dataDims[2], idx))) {
  53512. continue;
  53513. }
  53514. var point = coordSys.dataToPoint([
  53515. data.get(dataDims[0], idx),
  53516. data.get(dataDims[1], idx)
  53517. ]);
  53518. rect = new Rect({
  53519. shape: {
  53520. x: point[0] - width / 2,
  53521. y: point[1] - height / 2,
  53522. width: width,
  53523. height: height
  53524. },
  53525. style: {
  53526. fill: data.getItemVisual(idx, 'color'),
  53527. opacity: data.getItemVisual(idx, 'opacity')
  53528. }
  53529. });
  53530. }
  53531. else {
  53532. // Ignore empty data
  53533. if (isNaN(data.get(dataDims[1], idx))) {
  53534. continue;
  53535. }
  53536. rect = new Rect({
  53537. z2: 1,
  53538. shape: coordSys.dataToRect([data.get(dataDims[0], idx)]).contentShape,
  53539. style: {
  53540. fill: data.getItemVisual(idx, 'color'),
  53541. opacity: data.getItemVisual(idx, 'opacity')
  53542. }
  53543. });
  53544. }
  53545. var itemModel = data.getItemModel(idx);
  53546. // Optimization for large datset
  53547. if (data.hasItemOption) {
  53548. style = itemModel.getModel(itemStyleQuery).getItemStyle(['color']);
  53549. hoverStl = itemModel.getModel(hoverItemStyleQuery).getItemStyle();
  53550. labelModel = itemModel.getModel(labelQuery);
  53551. hoverLabelModel = itemModel.getModel(hoverLabelQuery);
  53552. }
  53553. var rawValue = seriesModel.getRawValue(idx);
  53554. var defaultText = '-';
  53555. if (rawValue && rawValue[2] != null) {
  53556. defaultText = rawValue[2];
  53557. }
  53558. setLabelStyle(
  53559. style, hoverStl, labelModel, hoverLabelModel,
  53560. {
  53561. labelFetcher: seriesModel,
  53562. labelDataIndex: idx,
  53563. defaultText: defaultText,
  53564. isRectText: true
  53565. }
  53566. );
  53567. rect.setStyle(style);
  53568. setHoverStyle(rect, data.hasItemOption ? hoverStl : extend({}, hoverStl));
  53569. rect.incremental = incremental;
  53570. // PENDING
  53571. if (incremental) {
  53572. // Rect must use hover layer if it's incremental.
  53573. rect.useHoverLayer = true;
  53574. }
  53575. group.add(rect);
  53576. data.setItemGraphicEl(idx, rect);
  53577. }
  53578. },
  53579. _renderOnGeo: function (geo, seriesModel, visualMapModel, api) {
  53580. var inRangeVisuals = visualMapModel.targetVisuals.inRange;
  53581. var outOfRangeVisuals = visualMapModel.targetVisuals.outOfRange;
  53582. // if (!visualMapping) {
  53583. // throw new Error('Data range must have color visuals');
  53584. // }
  53585. var data = seriesModel.getData();
  53586. var hmLayer = this._hmLayer || (this._hmLayer || new Heatmap());
  53587. hmLayer.blurSize = seriesModel.get('blurSize');
  53588. hmLayer.pointSize = seriesModel.get('pointSize');
  53589. hmLayer.minOpacity = seriesModel.get('minOpacity');
  53590. hmLayer.maxOpacity = seriesModel.get('maxOpacity');
  53591. var rect = geo.getViewRect().clone();
  53592. var roamTransform = geo.getRoamTransform();
  53593. rect.applyTransform(roamTransform);
  53594. // Clamp on viewport
  53595. var x = Math.max(rect.x, 0);
  53596. var y = Math.max(rect.y, 0);
  53597. var x2 = Math.min(rect.width + rect.x, api.getWidth());
  53598. var y2 = Math.min(rect.height + rect.y, api.getHeight());
  53599. var width = x2 - x;
  53600. var height = y2 - y;
  53601. var dims = [
  53602. data.mapDimension('lng'),
  53603. data.mapDimension('lat'),
  53604. data.mapDimension('value')
  53605. ];
  53606. var points = data.mapArray(dims, function (lng, lat, value) {
  53607. var pt = geo.dataToPoint([lng, lat]);
  53608. pt[0] -= x;
  53609. pt[1] -= y;
  53610. pt.push(value);
  53611. return pt;
  53612. });
  53613. var dataExtent = visualMapModel.getExtent();
  53614. var isInRange = visualMapModel.type === 'visualMap.continuous'
  53615. ? getIsInContinuousRange(dataExtent, visualMapModel.option.range)
  53616. : getIsInPiecewiseRange(
  53617. dataExtent, visualMapModel.getPieceList(), visualMapModel.option.selected
  53618. );
  53619. hmLayer.update(
  53620. points, width, height,
  53621. inRangeVisuals.color.getNormalizer(),
  53622. {
  53623. inRange: inRangeVisuals.color.getColorMapper(),
  53624. outOfRange: outOfRangeVisuals.color.getColorMapper()
  53625. },
  53626. isInRange
  53627. );
  53628. var img = new ZImage({
  53629. style: {
  53630. width: width,
  53631. height: height,
  53632. x: x,
  53633. y: y,
  53634. image: hmLayer.canvas
  53635. },
  53636. silent: true
  53637. });
  53638. this.group.add(img);
  53639. },
  53640. dispose: function () {}
  53641. });
  53642. /*
  53643. * Licensed to the Apache Software Foundation (ASF) under one
  53644. * or more contributor license agreements. See the NOTICE file
  53645. * distributed with this work for additional information
  53646. * regarding copyright ownership. The ASF licenses this file
  53647. * to you under the Apache License, Version 2.0 (the
  53648. * "License"); you may not use this file except in compliance
  53649. * with the License. You may obtain a copy of the License at
  53650. *
  53651. * http://www.apache.org/licenses/LICENSE-2.0
  53652. *
  53653. * Unless required by applicable law or agreed to in writing,
  53654. * software distributed under the License is distributed on an
  53655. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53656. * KIND, either express or implied. See the License for the
  53657. * specific language governing permissions and limitations
  53658. * under the License.
  53659. */
  53660. /*
  53661. * Licensed to the Apache Software Foundation (ASF) under one
  53662. * or more contributor license agreements. See the NOTICE file
  53663. * distributed with this work for additional information
  53664. * regarding copyright ownership. The ASF licenses this file
  53665. * to you under the Apache License, Version 2.0 (the
  53666. * "License"); you may not use this file except in compliance
  53667. * with the License. You may obtain a copy of the License at
  53668. *
  53669. * http://www.apache.org/licenses/LICENSE-2.0
  53670. *
  53671. * Unless required by applicable law or agreed to in writing,
  53672. * software distributed under the License is distributed on an
  53673. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53674. * KIND, either express or implied. See the License for the
  53675. * specific language governing permissions and limitations
  53676. * under the License.
  53677. */
  53678. var PictorialBarSeries = BaseBarSeries.extend({
  53679. type: 'series.pictorialBar',
  53680. dependencies: ['grid'],
  53681. defaultOption: {
  53682. symbol: 'circle', // Customized bar shape
  53683. symbolSize: null, // Can be ['100%', '100%'], null means auto.
  53684. symbolRotate: null,
  53685. symbolPosition: null, // 'start' or 'end' or 'center', null means auto.
  53686. symbolOffset: null,
  53687. symbolMargin: null, // start margin and end margin. Can be a number or a percent string.
  53688. // Auto margin by defualt.
  53689. symbolRepeat: false, // false/null/undefined, means no repeat.
  53690. // Can be true, means auto calculate repeat times and cut by data.
  53691. // Can be a number, specifies repeat times, and do not cut by data.
  53692. // Can be 'fixed', means auto calculate repeat times but do not cut by data.
  53693. symbolRepeatDirection: 'end', // 'end' means from 'start' to 'end'.
  53694. symbolClip: false,
  53695. symbolBoundingData: null, // Can be 60 or -40 or [-40, 60]
  53696. symbolPatternSize: 400, // 400 * 400 px
  53697. barGap: '-100%', // In most case, overlap is needed.
  53698. // z can be set in data item, which is z2 actually.
  53699. // Disable progressive
  53700. progressive: 0,
  53701. hoverAnimation: false // Open only when needed.
  53702. },
  53703. getInitialData: function (option) {
  53704. // Disable stack.
  53705. option.stack = null;
  53706. return PictorialBarSeries.superApply(this, 'getInitialData', arguments);
  53707. }
  53708. });
  53709. /*
  53710. * Licensed to the Apache Software Foundation (ASF) under one
  53711. * or more contributor license agreements. See the NOTICE file
  53712. * distributed with this work for additional information
  53713. * regarding copyright ownership. The ASF licenses this file
  53714. * to you under the Apache License, Version 2.0 (the
  53715. * "License"); you may not use this file except in compliance
  53716. * with the License. You may obtain a copy of the License at
  53717. *
  53718. * http://www.apache.org/licenses/LICENSE-2.0
  53719. *
  53720. * Unless required by applicable law or agreed to in writing,
  53721. * software distributed under the License is distributed on an
  53722. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53723. * KIND, either express or implied. See the License for the
  53724. * specific language governing permissions and limitations
  53725. * under the License.
  53726. */
  53727. var BAR_BORDER_WIDTH_QUERY$1 = ['itemStyle', 'borderWidth'];
  53728. // index: +isHorizontal
  53729. var LAYOUT_ATTRS = [
  53730. {xy: 'x', wh: 'width', index: 0, posDesc: ['left', 'right']},
  53731. {xy: 'y', wh: 'height', index: 1, posDesc: ['top', 'bottom']}
  53732. ];
  53733. var pathForLineWidth = new Circle();
  53734. var BarView$1 = extendChartView({
  53735. type: 'pictorialBar',
  53736. render: function (seriesModel, ecModel, api) {
  53737. var group = this.group;
  53738. var data = seriesModel.getData();
  53739. var oldData = this._data;
  53740. var cartesian = seriesModel.coordinateSystem;
  53741. var baseAxis = cartesian.getBaseAxis();
  53742. var isHorizontal = !!baseAxis.isHorizontal();
  53743. var coordSysRect = cartesian.grid.getRect();
  53744. var opt = {
  53745. ecSize: {width: api.getWidth(), height: api.getHeight()},
  53746. seriesModel: seriesModel,
  53747. coordSys: cartesian,
  53748. coordSysExtent: [
  53749. [coordSysRect.x, coordSysRect.x + coordSysRect.width],
  53750. [coordSysRect.y, coordSysRect.y + coordSysRect.height]
  53751. ],
  53752. isHorizontal: isHorizontal,
  53753. valueDim: LAYOUT_ATTRS[+isHorizontal],
  53754. categoryDim: LAYOUT_ATTRS[1 - isHorizontal]
  53755. };
  53756. data.diff(oldData)
  53757. .add(function (dataIndex) {
  53758. if (!data.hasValue(dataIndex)) {
  53759. return;
  53760. }
  53761. var itemModel = getItemModel(data, dataIndex);
  53762. var symbolMeta = getSymbolMeta(data, dataIndex, itemModel, opt);
  53763. var bar = createBar(data, opt, symbolMeta);
  53764. data.setItemGraphicEl(dataIndex, bar);
  53765. group.add(bar);
  53766. updateCommon$1(bar, opt, symbolMeta);
  53767. })
  53768. .update(function (newIndex, oldIndex) {
  53769. var bar = oldData.getItemGraphicEl(oldIndex);
  53770. if (!data.hasValue(newIndex)) {
  53771. group.remove(bar);
  53772. return;
  53773. }
  53774. var itemModel = getItemModel(data, newIndex);
  53775. var symbolMeta = getSymbolMeta(data, newIndex, itemModel, opt);
  53776. var pictorialShapeStr = getShapeStr(data, symbolMeta);
  53777. if (bar && pictorialShapeStr !== bar.__pictorialShapeStr) {
  53778. group.remove(bar);
  53779. data.setItemGraphicEl(newIndex, null);
  53780. bar = null;
  53781. }
  53782. if (bar) {
  53783. updateBar(bar, opt, symbolMeta);
  53784. }
  53785. else {
  53786. bar = createBar(data, opt, symbolMeta, true);
  53787. }
  53788. data.setItemGraphicEl(newIndex, bar);
  53789. bar.__pictorialSymbolMeta = symbolMeta;
  53790. // Add back
  53791. group.add(bar);
  53792. updateCommon$1(bar, opt, symbolMeta);
  53793. })
  53794. .remove(function (dataIndex) {
  53795. var bar = oldData.getItemGraphicEl(dataIndex);
  53796. bar && removeBar(oldData, dataIndex, bar.__pictorialSymbolMeta.animationModel, bar);
  53797. })
  53798. .execute();
  53799. this._data = data;
  53800. return this.group;
  53801. },
  53802. dispose: noop,
  53803. remove: function (ecModel, api) {
  53804. var group = this.group;
  53805. var data = this._data;
  53806. if (ecModel.get('animation')) {
  53807. if (data) {
  53808. data.eachItemGraphicEl(function (bar) {
  53809. removeBar(data, bar.dataIndex, ecModel, bar);
  53810. });
  53811. }
  53812. }
  53813. else {
  53814. group.removeAll();
  53815. }
  53816. }
  53817. });
  53818. // Set or calculate default value about symbol, and calculate layout info.
  53819. function getSymbolMeta(data, dataIndex, itemModel, opt) {
  53820. var layout = data.getItemLayout(dataIndex);
  53821. var symbolRepeat = itemModel.get('symbolRepeat');
  53822. var symbolClip = itemModel.get('symbolClip');
  53823. var symbolPosition = itemModel.get('symbolPosition') || 'start';
  53824. var symbolRotate = itemModel.get('symbolRotate');
  53825. var rotation = (symbolRotate || 0) * Math.PI / 180 || 0;
  53826. var symbolPatternSize = itemModel.get('symbolPatternSize') || 2;
  53827. var isAnimationEnabled = itemModel.isAnimationEnabled();
  53828. var symbolMeta = {
  53829. dataIndex: dataIndex,
  53830. layout: layout,
  53831. itemModel: itemModel,
  53832. symbolType: data.getItemVisual(dataIndex, 'symbol') || 'circle',
  53833. color: data.getItemVisual(dataIndex, 'color'),
  53834. symbolClip: symbolClip,
  53835. symbolRepeat: symbolRepeat,
  53836. symbolRepeatDirection: itemModel.get('symbolRepeatDirection'),
  53837. symbolPatternSize: symbolPatternSize,
  53838. rotation: rotation,
  53839. animationModel: isAnimationEnabled ? itemModel : null,
  53840. hoverAnimation: isAnimationEnabled && itemModel.get('hoverAnimation'),
  53841. z2: itemModel.getShallow('z', true) || 0
  53842. };
  53843. prepareBarLength(itemModel, symbolRepeat, layout, opt, symbolMeta);
  53844. prepareSymbolSize(
  53845. data, dataIndex, layout, symbolRepeat, symbolClip, symbolMeta.boundingLength,
  53846. symbolMeta.pxSign, symbolPatternSize, opt, symbolMeta
  53847. );
  53848. prepareLineWidth(itemModel, symbolMeta.symbolScale, rotation, opt, symbolMeta);
  53849. var symbolSize = symbolMeta.symbolSize;
  53850. var symbolOffset = itemModel.get('symbolOffset');
  53851. if (isArray(symbolOffset)) {
  53852. symbolOffset = [
  53853. parsePercent$1(symbolOffset[0], symbolSize[0]),
  53854. parsePercent$1(symbolOffset[1], symbolSize[1])
  53855. ];
  53856. }
  53857. prepareLayoutInfo(
  53858. itemModel, symbolSize, layout, symbolRepeat, symbolClip, symbolOffset,
  53859. symbolPosition, symbolMeta.valueLineWidth, symbolMeta.boundingLength, symbolMeta.repeatCutLength,
  53860. opt, symbolMeta
  53861. );
  53862. return symbolMeta;
  53863. }
  53864. // bar length can be negative.
  53865. function prepareBarLength(itemModel, symbolRepeat, layout, opt, output) {
  53866. var valueDim = opt.valueDim;
  53867. var symbolBoundingData = itemModel.get('symbolBoundingData');
  53868. var valueAxis = opt.coordSys.getOtherAxis(opt.coordSys.getBaseAxis());
  53869. var zeroPx = valueAxis.toGlobalCoord(valueAxis.dataToCoord(0));
  53870. var pxSignIdx = 1 - +(layout[valueDim.wh] <= 0);
  53871. var boundingLength;
  53872. if (isArray(symbolBoundingData)) {
  53873. var symbolBoundingExtent = [
  53874. convertToCoordOnAxis(valueAxis, symbolBoundingData[0]) - zeroPx,
  53875. convertToCoordOnAxis(valueAxis, symbolBoundingData[1]) - zeroPx
  53876. ];
  53877. symbolBoundingExtent[1] < symbolBoundingExtent[0] && (symbolBoundingExtent.reverse());
  53878. boundingLength = symbolBoundingExtent[pxSignIdx];
  53879. }
  53880. else if (symbolBoundingData != null) {
  53881. boundingLength = convertToCoordOnAxis(valueAxis, symbolBoundingData) - zeroPx;
  53882. }
  53883. else if (symbolRepeat) {
  53884. boundingLength = opt.coordSysExtent[valueDim.index][pxSignIdx] - zeroPx;
  53885. }
  53886. else {
  53887. boundingLength = layout[valueDim.wh];
  53888. }
  53889. output.boundingLength = boundingLength;
  53890. if (symbolRepeat) {
  53891. output.repeatCutLength = layout[valueDim.wh];
  53892. }
  53893. output.pxSign = boundingLength > 0 ? 1 : boundingLength < 0 ? -1 : 0;
  53894. }
  53895. function convertToCoordOnAxis(axis, value) {
  53896. return axis.toGlobalCoord(axis.dataToCoord(axis.scale.parse(value)));
  53897. }
  53898. // Support ['100%', '100%']
  53899. function prepareSymbolSize(
  53900. data, dataIndex, layout, symbolRepeat, symbolClip, boundingLength,
  53901. pxSign, symbolPatternSize, opt, output
  53902. ) {
  53903. var valueDim = opt.valueDim;
  53904. var categoryDim = opt.categoryDim;
  53905. var categorySize = Math.abs(layout[categoryDim.wh]);
  53906. var symbolSize = data.getItemVisual(dataIndex, 'symbolSize');
  53907. if (isArray(symbolSize)) {
  53908. symbolSize = symbolSize.slice();
  53909. }
  53910. else {
  53911. if (symbolSize == null) {
  53912. symbolSize = '100%';
  53913. }
  53914. symbolSize = [symbolSize, symbolSize];
  53915. }
  53916. // Note: percentage symbolSize (like '100%') do not consider lineWidth, because it is
  53917. // to complicated to calculate real percent value if considering scaled lineWidth.
  53918. // So the actual size will bigger than layout size if lineWidth is bigger than zero,
  53919. // which can be tolerated in pictorial chart.
  53920. symbolSize[categoryDim.index] = parsePercent$1(
  53921. symbolSize[categoryDim.index],
  53922. categorySize
  53923. );
  53924. symbolSize[valueDim.index] = parsePercent$1(
  53925. symbolSize[valueDim.index],
  53926. symbolRepeat ? categorySize : Math.abs(boundingLength)
  53927. );
  53928. output.symbolSize = symbolSize;
  53929. // If x or y is less than zero, show reversed shape.
  53930. var symbolScale = output.symbolScale = [
  53931. symbolSize[0] / symbolPatternSize,
  53932. symbolSize[1] / symbolPatternSize
  53933. ];
  53934. // Follow convention, 'right' and 'top' is the normal scale.
  53935. symbolScale[valueDim.index] *= (opt.isHorizontal ? -1 : 1) * pxSign;
  53936. }
  53937. function prepareLineWidth(itemModel, symbolScale, rotation, opt, output) {
  53938. // In symbols are drawn with scale, so do not need to care about the case that width
  53939. // or height are too small. But symbol use strokeNoScale, where acture lineWidth should
  53940. // be calculated.
  53941. var valueLineWidth = itemModel.get(BAR_BORDER_WIDTH_QUERY$1) || 0;
  53942. if (valueLineWidth) {
  53943. pathForLineWidth.attr({
  53944. scale: symbolScale.slice(),
  53945. rotation: rotation
  53946. });
  53947. pathForLineWidth.updateTransform();
  53948. valueLineWidth /= pathForLineWidth.getLineScale();
  53949. valueLineWidth *= symbolScale[opt.valueDim.index];
  53950. }
  53951. output.valueLineWidth = valueLineWidth;
  53952. }
  53953. function prepareLayoutInfo(
  53954. itemModel, symbolSize, layout, symbolRepeat, symbolClip, symbolOffset,
  53955. symbolPosition, valueLineWidth, boundingLength, repeatCutLength, opt, output
  53956. ) {
  53957. var categoryDim = opt.categoryDim;
  53958. var valueDim = opt.valueDim;
  53959. var pxSign = output.pxSign;
  53960. var unitLength = Math.max(symbolSize[valueDim.index] + valueLineWidth, 0);
  53961. var pathLen = unitLength;
  53962. // Note: rotation will not effect the layout of symbols, because user may
  53963. // want symbols to rotate on its center, which should not be translated
  53964. // when rotating.
  53965. if (symbolRepeat) {
  53966. var absBoundingLength = Math.abs(boundingLength);
  53967. var symbolMargin = retrieve(itemModel.get('symbolMargin'), '15%') + '';
  53968. var hasEndGap = false;
  53969. if (symbolMargin.lastIndexOf('!') === symbolMargin.length - 1) {
  53970. hasEndGap = true;
  53971. symbolMargin = symbolMargin.slice(0, symbolMargin.length - 1);
  53972. }
  53973. symbolMargin = parsePercent$1(symbolMargin, symbolSize[valueDim.index]);
  53974. var uLenWithMargin = Math.max(unitLength + symbolMargin * 2, 0);
  53975. // When symbol margin is less than 0, margin at both ends will be subtracted
  53976. // to ensure that all of the symbols will not be overflow the given area.
  53977. var endFix = hasEndGap ? 0 : symbolMargin * 2;
  53978. // Both final repeatTimes and final symbolMargin area calculated based on
  53979. // boundingLength.
  53980. var repeatSpecified = isNumeric(symbolRepeat);
  53981. var repeatTimes = repeatSpecified
  53982. ? symbolRepeat
  53983. : toIntTimes((absBoundingLength + endFix) / uLenWithMargin);
  53984. // Adjust calculate margin, to ensure each symbol is displayed
  53985. // entirely in the given layout area.
  53986. var mDiff = absBoundingLength - repeatTimes * unitLength;
  53987. symbolMargin = mDiff / 2 / (hasEndGap ? repeatTimes : repeatTimes - 1);
  53988. uLenWithMargin = unitLength + symbolMargin * 2;
  53989. endFix = hasEndGap ? 0 : symbolMargin * 2;
  53990. // Update repeatTimes when not all symbol will be shown.
  53991. if (!repeatSpecified && symbolRepeat !== 'fixed') {
  53992. repeatTimes = repeatCutLength
  53993. ? toIntTimes((Math.abs(repeatCutLength) + endFix) / uLenWithMargin)
  53994. : 0;
  53995. }
  53996. pathLen = repeatTimes * uLenWithMargin - endFix;
  53997. output.repeatTimes = repeatTimes;
  53998. output.symbolMargin = symbolMargin;
  53999. }
  54000. var sizeFix = pxSign * (pathLen / 2);
  54001. var pathPosition = output.pathPosition = [];
  54002. pathPosition[categoryDim.index] = layout[categoryDim.wh] / 2;
  54003. pathPosition[valueDim.index] = symbolPosition === 'start'
  54004. ? sizeFix
  54005. : symbolPosition === 'end'
  54006. ? boundingLength - sizeFix
  54007. : boundingLength / 2; // 'center'
  54008. if (symbolOffset) {
  54009. pathPosition[0] += symbolOffset[0];
  54010. pathPosition[1] += symbolOffset[1];
  54011. }
  54012. var bundlePosition = output.bundlePosition = [];
  54013. bundlePosition[categoryDim.index] = layout[categoryDim.xy];
  54014. bundlePosition[valueDim.index] = layout[valueDim.xy];
  54015. var barRectShape = output.barRectShape = extend({}, layout);
  54016. barRectShape[valueDim.wh] = pxSign * Math.max(
  54017. Math.abs(layout[valueDim.wh]), Math.abs(pathPosition[valueDim.index] + sizeFix)
  54018. );
  54019. barRectShape[categoryDim.wh] = layout[categoryDim.wh];
  54020. var clipShape = output.clipShape = {};
  54021. // Consider that symbol may be overflow layout rect.
  54022. clipShape[categoryDim.xy] = -layout[categoryDim.xy];
  54023. clipShape[categoryDim.wh] = opt.ecSize[categoryDim.wh];
  54024. clipShape[valueDim.xy] = 0;
  54025. clipShape[valueDim.wh] = layout[valueDim.wh];
  54026. }
  54027. function createPath(symbolMeta) {
  54028. var symbolPatternSize = symbolMeta.symbolPatternSize;
  54029. var path = createSymbol(
  54030. // Consider texture img, make a big size.
  54031. symbolMeta.symbolType,
  54032. -symbolPatternSize / 2,
  54033. -symbolPatternSize / 2,
  54034. symbolPatternSize,
  54035. symbolPatternSize,
  54036. symbolMeta.color
  54037. );
  54038. path.attr({
  54039. culling: true
  54040. });
  54041. path.type !== 'image' && path.setStyle({
  54042. strokeNoScale: true
  54043. });
  54044. return path;
  54045. }
  54046. function createOrUpdateRepeatSymbols(bar, opt, symbolMeta, isUpdate) {
  54047. var bundle = bar.__pictorialBundle;
  54048. var symbolSize = symbolMeta.symbolSize;
  54049. var valueLineWidth = symbolMeta.valueLineWidth;
  54050. var pathPosition = symbolMeta.pathPosition;
  54051. var valueDim = opt.valueDim;
  54052. var repeatTimes = symbolMeta.repeatTimes || 0;
  54053. var index = 0;
  54054. var unit = symbolSize[opt.valueDim.index] + valueLineWidth + symbolMeta.symbolMargin * 2;
  54055. eachPath(bar, function (path) {
  54056. path.__pictorialAnimationIndex = index;
  54057. path.__pictorialRepeatTimes = repeatTimes;
  54058. if (index < repeatTimes) {
  54059. updateAttr(path, null, makeTarget(index), symbolMeta, isUpdate);
  54060. }
  54061. else {
  54062. updateAttr(path, null, {scale: [0, 0]}, symbolMeta, isUpdate, function () {
  54063. bundle.remove(path);
  54064. });
  54065. }
  54066. updateHoverAnimation(path, symbolMeta);
  54067. index++;
  54068. });
  54069. for (; index < repeatTimes; index++) {
  54070. var path = createPath(symbolMeta);
  54071. path.__pictorialAnimationIndex = index;
  54072. path.__pictorialRepeatTimes = repeatTimes;
  54073. bundle.add(path);
  54074. var target = makeTarget(index);
  54075. updateAttr(
  54076. path,
  54077. {
  54078. position: target.position,
  54079. scale: [0, 0]
  54080. },
  54081. {
  54082. scale: target.scale,
  54083. rotation: target.rotation
  54084. },
  54085. symbolMeta,
  54086. isUpdate
  54087. );
  54088. // FIXME
  54089. // If all emphasis/normal through action.
  54090. path
  54091. .on('mouseover', onMouseOver)
  54092. .on('mouseout', onMouseOut);
  54093. updateHoverAnimation(path, symbolMeta);
  54094. }
  54095. function makeTarget(index) {
  54096. var position = pathPosition.slice();
  54097. // (start && pxSign > 0) || (end && pxSign < 0): i = repeatTimes - index
  54098. // Otherwise: i = index;
  54099. var pxSign = symbolMeta.pxSign;
  54100. var i = index;
  54101. if (symbolMeta.symbolRepeatDirection === 'start' ? pxSign > 0 : pxSign < 0) {
  54102. i = repeatTimes - 1 - index;
  54103. }
  54104. position[valueDim.index] = unit * (i - repeatTimes / 2 + 0.5) + pathPosition[valueDim.index];
  54105. return {
  54106. position: position,
  54107. scale: symbolMeta.symbolScale.slice(),
  54108. rotation: symbolMeta.rotation
  54109. };
  54110. }
  54111. function onMouseOver() {
  54112. eachPath(bar, function (path) {
  54113. path.trigger('emphasis');
  54114. });
  54115. }
  54116. function onMouseOut() {
  54117. eachPath(bar, function (path) {
  54118. path.trigger('normal');
  54119. });
  54120. }
  54121. }
  54122. function createOrUpdateSingleSymbol(bar, opt, symbolMeta, isUpdate) {
  54123. var bundle = bar.__pictorialBundle;
  54124. var mainPath = bar.__pictorialMainPath;
  54125. if (!mainPath) {
  54126. mainPath = bar.__pictorialMainPath = createPath(symbolMeta);
  54127. bundle.add(mainPath);
  54128. updateAttr(
  54129. mainPath,
  54130. {
  54131. position: symbolMeta.pathPosition.slice(),
  54132. scale: [0, 0],
  54133. rotation: symbolMeta.rotation
  54134. },
  54135. {
  54136. scale: symbolMeta.symbolScale.slice()
  54137. },
  54138. symbolMeta,
  54139. isUpdate
  54140. );
  54141. mainPath
  54142. .on('mouseover', onMouseOver)
  54143. .on('mouseout', onMouseOut);
  54144. }
  54145. else {
  54146. updateAttr(
  54147. mainPath,
  54148. null,
  54149. {
  54150. position: symbolMeta.pathPosition.slice(),
  54151. scale: symbolMeta.symbolScale.slice(),
  54152. rotation: symbolMeta.rotation
  54153. },
  54154. symbolMeta,
  54155. isUpdate
  54156. );
  54157. }
  54158. updateHoverAnimation(mainPath, symbolMeta);
  54159. function onMouseOver() {
  54160. this.trigger('emphasis');
  54161. }
  54162. function onMouseOut() {
  54163. this.trigger('normal');
  54164. }
  54165. }
  54166. // bar rect is used for label.
  54167. function createOrUpdateBarRect(bar, symbolMeta, isUpdate) {
  54168. var rectShape = extend({}, symbolMeta.barRectShape);
  54169. var barRect = bar.__pictorialBarRect;
  54170. if (!barRect) {
  54171. barRect = bar.__pictorialBarRect = new Rect({
  54172. z2: 2,
  54173. shape: rectShape,
  54174. silent: true,
  54175. style: {
  54176. stroke: 'transparent',
  54177. fill: 'transparent',
  54178. lineWidth: 0
  54179. }
  54180. });
  54181. bar.add(barRect);
  54182. }
  54183. else {
  54184. updateAttr(barRect, null, {shape: rectShape}, symbolMeta, isUpdate);
  54185. }
  54186. }
  54187. function createOrUpdateClip(bar, opt, symbolMeta, isUpdate) {
  54188. // If not clip, symbol will be remove and rebuilt.
  54189. if (symbolMeta.symbolClip) {
  54190. var clipPath = bar.__pictorialClipPath;
  54191. var clipShape = extend({}, symbolMeta.clipShape);
  54192. var valueDim = opt.valueDim;
  54193. var animationModel = symbolMeta.animationModel;
  54194. var dataIndex = symbolMeta.dataIndex;
  54195. if (clipPath) {
  54196. updateProps(
  54197. clipPath, {shape: clipShape}, animationModel, dataIndex
  54198. );
  54199. }
  54200. else {
  54201. clipShape[valueDim.wh] = 0;
  54202. clipPath = new Rect({shape: clipShape});
  54203. bar.__pictorialBundle.setClipPath(clipPath);
  54204. bar.__pictorialClipPath = clipPath;
  54205. var target = {};
  54206. target[valueDim.wh] = symbolMeta.clipShape[valueDim.wh];
  54207. graphic[isUpdate ? 'updateProps' : 'initProps'](
  54208. clipPath, {shape: target}, animationModel, dataIndex
  54209. );
  54210. }
  54211. }
  54212. }
  54213. function getItemModel(data, dataIndex) {
  54214. var itemModel = data.getItemModel(dataIndex);
  54215. itemModel.getAnimationDelayParams = getAnimationDelayParams;
  54216. itemModel.isAnimationEnabled = isAnimationEnabled;
  54217. return itemModel;
  54218. }
  54219. function getAnimationDelayParams(path) {
  54220. // The order is the same as the z-order, see `symbolRepeatDiretion`.
  54221. return {
  54222. index: path.__pictorialAnimationIndex,
  54223. count: path.__pictorialRepeatTimes
  54224. };
  54225. }
  54226. function isAnimationEnabled() {
  54227. // `animation` prop can be set on itemModel in pictorial bar chart.
  54228. return this.parentModel.isAnimationEnabled() && !!this.getShallow('animation');
  54229. }
  54230. function updateHoverAnimation(path, symbolMeta) {
  54231. path.off('emphasis').off('normal');
  54232. var scale = symbolMeta.symbolScale.slice();
  54233. symbolMeta.hoverAnimation && path
  54234. .on('emphasis', function() {
  54235. this.animateTo({
  54236. scale: [scale[0] * 1.1, scale[1] * 1.1]
  54237. }, 400, 'elasticOut');
  54238. })
  54239. .on('normal', function() {
  54240. this.animateTo({
  54241. scale: scale.slice()
  54242. }, 400, 'elasticOut');
  54243. });
  54244. }
  54245. function createBar(data, opt, symbolMeta, isUpdate) {
  54246. // bar is the main element for each data.
  54247. var bar = new Group();
  54248. // bundle is used for location and clip.
  54249. var bundle = new Group();
  54250. bar.add(bundle);
  54251. bar.__pictorialBundle = bundle;
  54252. bundle.attr('position', symbolMeta.bundlePosition.slice());
  54253. if (symbolMeta.symbolRepeat) {
  54254. createOrUpdateRepeatSymbols(bar, opt, symbolMeta);
  54255. }
  54256. else {
  54257. createOrUpdateSingleSymbol(bar, opt, symbolMeta);
  54258. }
  54259. createOrUpdateBarRect(bar, symbolMeta, isUpdate);
  54260. createOrUpdateClip(bar, opt, symbolMeta, isUpdate);
  54261. bar.__pictorialShapeStr = getShapeStr(data, symbolMeta);
  54262. bar.__pictorialSymbolMeta = symbolMeta;
  54263. return bar;
  54264. }
  54265. function updateBar(bar, opt, symbolMeta) {
  54266. var animationModel = symbolMeta.animationModel;
  54267. var dataIndex = symbolMeta.dataIndex;
  54268. var bundle = bar.__pictorialBundle;
  54269. updateProps(
  54270. bundle, {position: symbolMeta.bundlePosition.slice()}, animationModel, dataIndex
  54271. );
  54272. if (symbolMeta.symbolRepeat) {
  54273. createOrUpdateRepeatSymbols(bar, opt, symbolMeta, true);
  54274. }
  54275. else {
  54276. createOrUpdateSingleSymbol(bar, opt, symbolMeta, true);
  54277. }
  54278. createOrUpdateBarRect(bar, symbolMeta, true);
  54279. createOrUpdateClip(bar, opt, symbolMeta, true);
  54280. }
  54281. function removeBar(data, dataIndex, animationModel, bar) {
  54282. // Not show text when animating
  54283. var labelRect = bar.__pictorialBarRect;
  54284. labelRect && (labelRect.style.text = null);
  54285. var pathes = [];
  54286. eachPath(bar, function (path) {
  54287. pathes.push(path);
  54288. });
  54289. bar.__pictorialMainPath && pathes.push(bar.__pictorialMainPath);
  54290. // I do not find proper remove animation for clip yet.
  54291. bar.__pictorialClipPath && (animationModel = null);
  54292. each$1(pathes, function (path) {
  54293. updateProps(
  54294. path, {scale: [0, 0]}, animationModel, dataIndex,
  54295. function () {
  54296. bar.parent && bar.parent.remove(bar);
  54297. }
  54298. );
  54299. });
  54300. data.setItemGraphicEl(dataIndex, null);
  54301. }
  54302. function getShapeStr(data, symbolMeta) {
  54303. return [
  54304. data.getItemVisual(symbolMeta.dataIndex, 'symbol') || 'none',
  54305. !!symbolMeta.symbolRepeat,
  54306. !!symbolMeta.symbolClip
  54307. ].join(':');
  54308. }
  54309. function eachPath(bar, cb, context) {
  54310. // Do not use Group#eachChild, because it do not support remove.
  54311. each$1(bar.__pictorialBundle.children(), function (el) {
  54312. el !== bar.__pictorialBarRect && cb.call(context, el);
  54313. });
  54314. }
  54315. function updateAttr(el, immediateAttrs, animationAttrs, symbolMeta, isUpdate, cb) {
  54316. immediateAttrs && el.attr(immediateAttrs);
  54317. // when symbolCip used, only clip path has init animation, otherwise it would be weird effect.
  54318. if (symbolMeta.symbolClip && !isUpdate) {
  54319. animationAttrs && el.attr(animationAttrs);
  54320. }
  54321. else {
  54322. animationAttrs && graphic[isUpdate ? 'updateProps' : 'initProps'](
  54323. el, animationAttrs, symbolMeta.animationModel, symbolMeta.dataIndex, cb
  54324. );
  54325. }
  54326. }
  54327. function updateCommon$1(bar, opt, symbolMeta) {
  54328. var color = symbolMeta.color;
  54329. var dataIndex = symbolMeta.dataIndex;
  54330. var itemModel = symbolMeta.itemModel;
  54331. // Color must be excluded.
  54332. // Because symbol provide setColor individually to set fill and stroke
  54333. var normalStyle = itemModel.getModel('itemStyle').getItemStyle(['color']);
  54334. var hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  54335. var cursorStyle = itemModel.getShallow('cursor');
  54336. eachPath(bar, function (path) {
  54337. // PENDING setColor should be before setStyle!!!
  54338. path.setColor(color);
  54339. path.setStyle(defaults(
  54340. {
  54341. fill: color,
  54342. opacity: symbolMeta.opacity
  54343. },
  54344. normalStyle
  54345. ));
  54346. setHoverStyle(path, hoverStyle);
  54347. cursorStyle && (path.cursor = cursorStyle);
  54348. path.z2 = symbolMeta.z2;
  54349. });
  54350. var barRectHoverStyle = {};
  54351. var barPositionOutside = opt.valueDim.posDesc[+(symbolMeta.boundingLength > 0)];
  54352. var barRect = bar.__pictorialBarRect;
  54353. setLabel(
  54354. barRect.style, barRectHoverStyle, itemModel,
  54355. color, opt.seriesModel, dataIndex, barPositionOutside
  54356. );
  54357. setHoverStyle(barRect, barRectHoverStyle);
  54358. }
  54359. function toIntTimes(times) {
  54360. var roundedTimes = Math.round(times);
  54361. // Escapse accurate error
  54362. return Math.abs(times - roundedTimes) < 1e-4
  54363. ? roundedTimes
  54364. : Math.ceil(times);
  54365. }
  54366. /*
  54367. * Licensed to the Apache Software Foundation (ASF) under one
  54368. * or more contributor license agreements. See the NOTICE file
  54369. * distributed with this work for additional information
  54370. * regarding copyright ownership. The ASF licenses this file
  54371. * to you under the Apache License, Version 2.0 (the
  54372. * "License"); you may not use this file except in compliance
  54373. * with the License. You may obtain a copy of the License at
  54374. *
  54375. * http://www.apache.org/licenses/LICENSE-2.0
  54376. *
  54377. * Unless required by applicable law or agreed to in writing,
  54378. * software distributed under the License is distributed on an
  54379. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54380. * KIND, either express or implied. See the License for the
  54381. * specific language governing permissions and limitations
  54382. * under the License.
  54383. */
  54384. // In case developer forget to include grid component
  54385. registerLayout(curry(
  54386. layout, 'pictorialBar'
  54387. ));
  54388. registerVisual(visualSymbol('pictorialBar', 'roundRect'));
  54389. /*
  54390. * Licensed to the Apache Software Foundation (ASF) under one
  54391. * or more contributor license agreements. See the NOTICE file
  54392. * distributed with this work for additional information
  54393. * regarding copyright ownership. The ASF licenses this file
  54394. * to you under the Apache License, Version 2.0 (the
  54395. * "License"); you may not use this file except in compliance
  54396. * with the License. You may obtain a copy of the License at
  54397. *
  54398. * http://www.apache.org/licenses/LICENSE-2.0
  54399. *
  54400. * Unless required by applicable law or agreed to in writing,
  54401. * software distributed under the License is distributed on an
  54402. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54403. * KIND, either express or implied. See the License for the
  54404. * specific language governing permissions and limitations
  54405. * under the License.
  54406. */
  54407. /**
  54408. * @constructor module:echarts/coord/single/SingleAxis
  54409. * @extends {module:echarts/coord/Axis}
  54410. * @param {string} dim
  54411. * @param {*} scale
  54412. * @param {Array.<number>} coordExtent
  54413. * @param {string} axisType
  54414. * @param {string} position
  54415. */
  54416. var SingleAxis = function (dim, scale, coordExtent, axisType, position) {
  54417. Axis.call(this, dim, scale, coordExtent);
  54418. /**
  54419. * Axis type
  54420. * - 'category'
  54421. * - 'value'
  54422. * - 'time'
  54423. * - 'log'
  54424. * @type {string}
  54425. */
  54426. this.type = axisType || 'value';
  54427. /**
  54428. * Axis position
  54429. * - 'top'
  54430. * - 'bottom'
  54431. * - 'left'
  54432. * - 'right'
  54433. * @type {string}
  54434. */
  54435. this.position = position || 'bottom';
  54436. /**
  54437. * Axis orient
  54438. * - 'horizontal'
  54439. * - 'vertical'
  54440. * @type {[type]}
  54441. */
  54442. this.orient = null;
  54443. };
  54444. SingleAxis.prototype = {
  54445. constructor: SingleAxis,
  54446. /**
  54447. * Axis model
  54448. * @type {module:echarts/coord/single/AxisModel}
  54449. */
  54450. model: null,
  54451. /**
  54452. * Judge the orient of the axis.
  54453. * @return {boolean}
  54454. */
  54455. isHorizontal: function () {
  54456. var position = this.position;
  54457. return position === 'top' || position === 'bottom';
  54458. },
  54459. /**
  54460. * @override
  54461. */
  54462. pointToData: function (point, clamp) {
  54463. return this.coordinateSystem.pointToData(point, clamp)[0];
  54464. },
  54465. /**
  54466. * Convert the local coord(processed by dataToCoord())
  54467. * to global coord(concrete pixel coord).
  54468. * designated by module:echarts/coord/single/Single.
  54469. * @type {Function}
  54470. */
  54471. toGlobalCoord: null,
  54472. /**
  54473. * Convert the global coord to local coord.
  54474. * designated by module:echarts/coord/single/Single.
  54475. * @type {Function}
  54476. */
  54477. toLocalCoord: null
  54478. };
  54479. inherits(SingleAxis, Axis);
  54480. /*
  54481. * Licensed to the Apache Software Foundation (ASF) under one
  54482. * or more contributor license agreements. See the NOTICE file
  54483. * distributed with this work for additional information
  54484. * regarding copyright ownership. The ASF licenses this file
  54485. * to you under the Apache License, Version 2.0 (the
  54486. * "License"); you may not use this file except in compliance
  54487. * with the License. You may obtain a copy of the License at
  54488. *
  54489. * http://www.apache.org/licenses/LICENSE-2.0
  54490. *
  54491. * Unless required by applicable law or agreed to in writing,
  54492. * software distributed under the License is distributed on an
  54493. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54494. * KIND, either express or implied. See the License for the
  54495. * specific language governing permissions and limitations
  54496. * under the License.
  54497. */
  54498. /**
  54499. * Single coordinates system.
  54500. */
  54501. /**
  54502. * Create a single coordinates system.
  54503. *
  54504. * @param {module:echarts/coord/single/AxisModel} axisModel
  54505. * @param {module:echarts/model/Global} ecModel
  54506. * @param {module:echarts/ExtensionAPI} api
  54507. */
  54508. function Single(axisModel, ecModel, api) {
  54509. /**
  54510. * @type {string}
  54511. * @readOnly
  54512. */
  54513. this.dimension = 'single';
  54514. /**
  54515. * Add it just for draw tooltip.
  54516. *
  54517. * @type {Array.<string>}
  54518. * @readOnly
  54519. */
  54520. this.dimensions = ['single'];
  54521. /**
  54522. * @private
  54523. * @type {module:echarts/coord/single/SingleAxis}.
  54524. */
  54525. this._axis = null;
  54526. /**
  54527. * @private
  54528. * @type {module:zrender/core/BoundingRect}
  54529. */
  54530. this._rect;
  54531. this._init(axisModel, ecModel, api);
  54532. /**
  54533. * @type {module:echarts/coord/single/AxisModel}
  54534. */
  54535. this.model = axisModel;
  54536. }
  54537. Single.prototype = {
  54538. type: 'singleAxis',
  54539. axisPointerEnabled: true,
  54540. constructor: Single,
  54541. /**
  54542. * Initialize single coordinate system.
  54543. *
  54544. * @param {module:echarts/coord/single/AxisModel} axisModel
  54545. * @param {module:echarts/model/Global} ecModel
  54546. * @param {module:echarts/ExtensionAPI} api
  54547. * @private
  54548. */
  54549. _init: function (axisModel, ecModel, api) {
  54550. var dim = this.dimension;
  54551. var axis = new SingleAxis(
  54552. dim,
  54553. createScaleByModel(axisModel),
  54554. [0, 0],
  54555. axisModel.get('type'),
  54556. axisModel.get('position')
  54557. );
  54558. var isCategory = axis.type === 'category';
  54559. axis.onBand = isCategory && axisModel.get('boundaryGap');
  54560. axis.inverse = axisModel.get('inverse');
  54561. axis.orient = axisModel.get('orient');
  54562. axisModel.axis = axis;
  54563. axis.model = axisModel;
  54564. axis.coordinateSystem = this;
  54565. this._axis = axis;
  54566. },
  54567. /**
  54568. * Update axis scale after data processed
  54569. * @param {module:echarts/model/Global} ecModel
  54570. * @param {module:echarts/ExtensionAPI} api
  54571. */
  54572. update: function (ecModel, api) {
  54573. ecModel.eachSeries(function (seriesModel) {
  54574. if (seriesModel.coordinateSystem === this) {
  54575. var data = seriesModel.getData();
  54576. each$1(data.mapDimension(this.dimension, true), function (dim) {
  54577. this._axis.scale.unionExtentFromData(data, dim);
  54578. }, this);
  54579. niceScaleExtent(this._axis.scale, this._axis.model);
  54580. }
  54581. }, this);
  54582. },
  54583. /**
  54584. * Resize the single coordinate system.
  54585. *
  54586. * @param {module:echarts/coord/single/AxisModel} axisModel
  54587. * @param {module:echarts/ExtensionAPI} api
  54588. */
  54589. resize: function (axisModel, api) {
  54590. this._rect = getLayoutRect(
  54591. {
  54592. left: axisModel.get('left'),
  54593. top: axisModel.get('top'),
  54594. right: axisModel.get('right'),
  54595. bottom: axisModel.get('bottom'),
  54596. width: axisModel.get('width'),
  54597. height: axisModel.get('height')
  54598. },
  54599. {
  54600. width: api.getWidth(),
  54601. height: api.getHeight()
  54602. }
  54603. );
  54604. this._adjustAxis();
  54605. },
  54606. /**
  54607. * @return {module:zrender/core/BoundingRect}
  54608. */
  54609. getRect: function () {
  54610. return this._rect;
  54611. },
  54612. /**
  54613. * @private
  54614. */
  54615. _adjustAxis: function () {
  54616. var rect = this._rect;
  54617. var axis = this._axis;
  54618. var isHorizontal = axis.isHorizontal();
  54619. var extent = isHorizontal ? [0, rect.width] : [0, rect.height];
  54620. var idx = axis.reverse ? 1 : 0;
  54621. axis.setExtent(extent[idx], extent[1 - idx]);
  54622. this._updateAxisTransform(axis, isHorizontal ? rect.x : rect.y);
  54623. },
  54624. /**
  54625. * @param {module:echarts/coord/single/SingleAxis} axis
  54626. * @param {number} coordBase
  54627. */
  54628. _updateAxisTransform: function (axis, coordBase) {
  54629. var axisExtent = axis.getExtent();
  54630. var extentSum = axisExtent[0] + axisExtent[1];
  54631. var isHorizontal = axis.isHorizontal();
  54632. axis.toGlobalCoord = isHorizontal
  54633. ? function (coord) {
  54634. return coord + coordBase;
  54635. }
  54636. : function (coord) {
  54637. return extentSum - coord + coordBase;
  54638. };
  54639. axis.toLocalCoord = isHorizontal
  54640. ? function (coord) {
  54641. return coord - coordBase;
  54642. }
  54643. : function (coord) {
  54644. return extentSum - coord + coordBase;
  54645. };
  54646. },
  54647. /**
  54648. * Get axis.
  54649. *
  54650. * @return {module:echarts/coord/single/SingleAxis}
  54651. */
  54652. getAxis: function () {
  54653. return this._axis;
  54654. },
  54655. /**
  54656. * Get axis, add it just for draw tooltip.
  54657. *
  54658. * @return {[type]} [description]
  54659. */
  54660. getBaseAxis: function () {
  54661. return this._axis;
  54662. },
  54663. /**
  54664. * @return {Array.<module:echarts/coord/Axis>}
  54665. */
  54666. getAxes: function () {
  54667. return [this._axis];
  54668. },
  54669. /**
  54670. * @return {Object} {baseAxes: [], otherAxes: []}
  54671. */
  54672. getTooltipAxes: function () {
  54673. return {baseAxes: [this.getAxis()]};
  54674. },
  54675. /**
  54676. * If contain point.
  54677. *
  54678. * @param {Array.<number>} point
  54679. * @return {boolean}
  54680. */
  54681. containPoint: function (point) {
  54682. var rect = this.getRect();
  54683. var axis = this.getAxis();
  54684. var orient = axis.orient;
  54685. if (orient === 'horizontal') {
  54686. return axis.contain(axis.toLocalCoord(point[0]))
  54687. && (point[1] >= rect.y && point[1] <= (rect.y + rect.height));
  54688. }
  54689. else {
  54690. return axis.contain(axis.toLocalCoord(point[1]))
  54691. && (point[0] >= rect.y && point[0] <= (rect.y + rect.height));
  54692. }
  54693. },
  54694. /**
  54695. * @param {Array.<number>} point
  54696. * @return {Array.<number>}
  54697. */
  54698. pointToData: function (point) {
  54699. var axis = this.getAxis();
  54700. return [axis.coordToData(axis.toLocalCoord(
  54701. point[axis.orient === 'horizontal' ? 0 : 1]
  54702. ))];
  54703. },
  54704. /**
  54705. * Convert the series data to concrete point.
  54706. *
  54707. * @param {number|Array.<number>} val
  54708. * @return {Array.<number>}
  54709. */
  54710. dataToPoint: function (val) {
  54711. var axis = this.getAxis();
  54712. var rect = this.getRect();
  54713. var pt = [];
  54714. var idx = axis.orient === 'horizontal' ? 0 : 1;
  54715. if (val instanceof Array) {
  54716. val = val[0];
  54717. }
  54718. pt[idx] = axis.toGlobalCoord(axis.dataToCoord(+val));
  54719. pt[1 - idx] = idx === 0 ? (rect.y + rect.height / 2) : (rect.x + rect.width / 2);
  54720. return pt;
  54721. }
  54722. };
  54723. /*
  54724. * Licensed to the Apache Software Foundation (ASF) under one
  54725. * or more contributor license agreements. See the NOTICE file
  54726. * distributed with this work for additional information
  54727. * regarding copyright ownership. The ASF licenses this file
  54728. * to you under the Apache License, Version 2.0 (the
  54729. * "License"); you may not use this file except in compliance
  54730. * with the License. You may obtain a copy of the License at
  54731. *
  54732. * http://www.apache.org/licenses/LICENSE-2.0
  54733. *
  54734. * Unless required by applicable law or agreed to in writing,
  54735. * software distributed under the License is distributed on an
  54736. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54737. * KIND, either express or implied. See the License for the
  54738. * specific language governing permissions and limitations
  54739. * under the License.
  54740. */
  54741. /**
  54742. * Single coordinate system creator.
  54743. */
  54744. /**
  54745. * Create single coordinate system and inject it into seriesModel.
  54746. *
  54747. * @param {module:echarts/model/Global} ecModel
  54748. * @param {module:echarts/ExtensionAPI} api
  54749. * @return {Array.<module:echarts/coord/single/Single>}
  54750. */
  54751. function create$3(ecModel, api) {
  54752. var singles = [];
  54753. ecModel.eachComponent('singleAxis', function(axisModel, idx) {
  54754. var single = new Single(axisModel, ecModel, api);
  54755. single.name = 'single_' + idx;
  54756. single.resize(axisModel, api);
  54757. axisModel.coordinateSystem = single;
  54758. singles.push(single);
  54759. });
  54760. ecModel.eachSeries(function (seriesModel) {
  54761. if (seriesModel.get('coordinateSystem') === 'singleAxis') {
  54762. var singleAxisModel = ecModel.queryComponents({
  54763. mainType: 'singleAxis',
  54764. index: seriesModel.get('singleAxisIndex'),
  54765. id: seriesModel.get('singleAxisId')
  54766. })[0];
  54767. seriesModel.coordinateSystem = singleAxisModel && singleAxisModel.coordinateSystem;
  54768. }
  54769. });
  54770. return singles;
  54771. }
  54772. CoordinateSystemManager.register('single', {
  54773. create: create$3,
  54774. dimensions: Single.prototype.dimensions
  54775. });
  54776. /*
  54777. * Licensed to the Apache Software Foundation (ASF) under one
  54778. * or more contributor license agreements. See the NOTICE file
  54779. * distributed with this work for additional information
  54780. * regarding copyright ownership. The ASF licenses this file
  54781. * to you under the Apache License, Version 2.0 (the
  54782. * "License"); you may not use this file except in compliance
  54783. * with the License. You may obtain a copy of the License at
  54784. *
  54785. * http://www.apache.org/licenses/LICENSE-2.0
  54786. *
  54787. * Unless required by applicable law or agreed to in writing,
  54788. * software distributed under the License is distributed on an
  54789. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54790. * KIND, either express or implied. See the License for the
  54791. * specific language governing permissions and limitations
  54792. * under the License.
  54793. */
  54794. /**
  54795. * @param {Object} opt {labelInside}
  54796. * @return {Object} {
  54797. * position, rotation, labelDirection, labelOffset,
  54798. * tickDirection, labelRotate, z2
  54799. * }
  54800. */
  54801. function layout$2(axisModel, opt) {
  54802. opt = opt || {};
  54803. var single = axisModel.coordinateSystem;
  54804. var axis = axisModel.axis;
  54805. var layout = {};
  54806. var axisPosition = axis.position;
  54807. var orient = axis.orient;
  54808. var rect = single.getRect();
  54809. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  54810. var positionMap = {
  54811. horizontal: {top: rectBound[2], bottom: rectBound[3]},
  54812. vertical: {left: rectBound[0], right: rectBound[1]}
  54813. };
  54814. layout.position = [
  54815. orient === 'vertical'
  54816. ? positionMap.vertical[axisPosition]
  54817. : rectBound[0],
  54818. orient === 'horizontal'
  54819. ? positionMap.horizontal[axisPosition]
  54820. : rectBound[3]
  54821. ];
  54822. var r = {horizontal: 0, vertical: 1};
  54823. layout.rotation = Math.PI / 2 * r[orient];
  54824. var directionMap = {top: -1, bottom: 1, right: 1, left: -1};
  54825. layout.labelDirection = layout.tickDirection
  54826. = layout.nameDirection
  54827. = directionMap[axisPosition];
  54828. if (axisModel.get('axisTick.inside')) {
  54829. layout.tickDirection = -layout.tickDirection;
  54830. }
  54831. if (retrieve(opt.labelInside, axisModel.get('axisLabel.inside'))) {
  54832. layout.labelDirection = -layout.labelDirection;
  54833. }
  54834. var labelRotation = opt.rotate;
  54835. labelRotation == null && (labelRotation = axisModel.get('axisLabel.rotate'));
  54836. layout.labelRotation = axisPosition === 'top' ? -labelRotation : labelRotation;
  54837. layout.z2 = 1;
  54838. return layout;
  54839. }
  54840. /*
  54841. * Licensed to the Apache Software Foundation (ASF) under one
  54842. * or more contributor license agreements. See the NOTICE file
  54843. * distributed with this work for additional information
  54844. * regarding copyright ownership. The ASF licenses this file
  54845. * to you under the Apache License, Version 2.0 (the
  54846. * "License"); you may not use this file except in compliance
  54847. * with the License. You may obtain a copy of the License at
  54848. *
  54849. * http://www.apache.org/licenses/LICENSE-2.0
  54850. *
  54851. * Unless required by applicable law or agreed to in writing,
  54852. * software distributed under the License is distributed on an
  54853. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54854. * KIND, either express or implied. See the License for the
  54855. * specific language governing permissions and limitations
  54856. * under the License.
  54857. */
  54858. var axisBuilderAttrs$2 = [
  54859. 'axisLine', 'axisTickLabel', 'axisName'
  54860. ];
  54861. var selfBuilderAttr = 'splitLine';
  54862. var SingleAxisView = AxisView.extend({
  54863. type: 'singleAxis',
  54864. axisPointerClass: 'SingleAxisPointer',
  54865. render: function (axisModel, ecModel, api, payload) {
  54866. var group = this.group;
  54867. group.removeAll();
  54868. var layout = layout$2(axisModel);
  54869. var axisBuilder = new AxisBuilder(axisModel, layout);
  54870. each$1(axisBuilderAttrs$2, axisBuilder.add, axisBuilder);
  54871. group.add(axisBuilder.getGroup());
  54872. if (axisModel.get(selfBuilderAttr + '.show')) {
  54873. this['_' + selfBuilderAttr](axisModel);
  54874. }
  54875. SingleAxisView.superCall(this, 'render', axisModel, ecModel, api, payload);
  54876. },
  54877. _splitLine: function(axisModel) {
  54878. var axis = axisModel.axis;
  54879. if (axis.scale.isBlank()) {
  54880. return;
  54881. }
  54882. var splitLineModel = axisModel.getModel('splitLine');
  54883. var lineStyleModel = splitLineModel.getModel('lineStyle');
  54884. var lineWidth = lineStyleModel.get('width');
  54885. var lineColors = lineStyleModel.get('color');
  54886. lineColors = lineColors instanceof Array ? lineColors : [lineColors];
  54887. var gridRect = axisModel.coordinateSystem.getRect();
  54888. var isHorizontal = axis.isHorizontal();
  54889. var splitLines = [];
  54890. var lineCount = 0;
  54891. var ticksCoords = axis.getTicksCoords({
  54892. tickModel: splitLineModel
  54893. });
  54894. var p1 = [];
  54895. var p2 = [];
  54896. for (var i = 0; i < ticksCoords.length; ++i) {
  54897. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  54898. if (isHorizontal) {
  54899. p1[0] = tickCoord;
  54900. p1[1] = gridRect.y;
  54901. p2[0] = tickCoord;
  54902. p2[1] = gridRect.y + gridRect.height;
  54903. }
  54904. else {
  54905. p1[0] = gridRect.x;
  54906. p1[1] = tickCoord;
  54907. p2[0] = gridRect.x + gridRect.width;
  54908. p2[1] = tickCoord;
  54909. }
  54910. var colorIndex = (lineCount++) % lineColors.length;
  54911. splitLines[colorIndex] = splitLines[colorIndex] || [];
  54912. splitLines[colorIndex].push(new Line(
  54913. subPixelOptimizeLine({
  54914. shape: {
  54915. x1: p1[0],
  54916. y1: p1[1],
  54917. x2: p2[0],
  54918. y2: p2[1]
  54919. },
  54920. style: {
  54921. lineWidth: lineWidth
  54922. },
  54923. silent: true
  54924. })));
  54925. }
  54926. for (var i = 0; i < splitLines.length; ++i) {
  54927. this.group.add(mergePath(splitLines[i], {
  54928. style: {
  54929. stroke: lineColors[i % lineColors.length],
  54930. lineDash: lineStyleModel.getLineDash(lineWidth),
  54931. lineWidth: lineWidth
  54932. },
  54933. silent: true
  54934. }));
  54935. }
  54936. }
  54937. });
  54938. /*
  54939. * Licensed to the Apache Software Foundation (ASF) under one
  54940. * or more contributor license agreements. See the NOTICE file
  54941. * distributed with this work for additional information
  54942. * regarding copyright ownership. The ASF licenses this file
  54943. * to you under the Apache License, Version 2.0 (the
  54944. * "License"); you may not use this file except in compliance
  54945. * with the License. You may obtain a copy of the License at
  54946. *
  54947. * http://www.apache.org/licenses/LICENSE-2.0
  54948. *
  54949. * Unless required by applicable law or agreed to in writing,
  54950. * software distributed under the License is distributed on an
  54951. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54952. * KIND, either express or implied. See the License for the
  54953. * specific language governing permissions and limitations
  54954. * under the License.
  54955. */
  54956. var AxisModel$4 = ComponentModel.extend({
  54957. type: 'singleAxis',
  54958. layoutMode: 'box',
  54959. /**
  54960. * @type {module:echarts/coord/single/SingleAxis}
  54961. */
  54962. axis: null,
  54963. /**
  54964. * @type {module:echarts/coord/single/Single}
  54965. */
  54966. coordinateSystem: null,
  54967. /**
  54968. * @override
  54969. */
  54970. getCoordSysModel: function () {
  54971. return this;
  54972. }
  54973. });
  54974. var defaultOption$2 = {
  54975. left: '5%',
  54976. top: '5%',
  54977. right: '5%',
  54978. bottom: '5%',
  54979. type: 'value',
  54980. position: 'bottom',
  54981. orient: 'horizontal',
  54982. axisLine: {
  54983. show: true,
  54984. lineStyle: {
  54985. width: 2,
  54986. type: 'solid'
  54987. }
  54988. },
  54989. // Single coordinate system and single axis is the,
  54990. // which is used as the parent tooltip model.
  54991. // same model, so we set default tooltip show as true.
  54992. tooltip: {
  54993. show: true
  54994. },
  54995. axisTick: {
  54996. show: true,
  54997. length: 6,
  54998. lineStyle: {
  54999. width: 2
  55000. }
  55001. },
  55002. axisLabel: {
  55003. show: true,
  55004. interval: 'auto'
  55005. },
  55006. splitLine: {
  55007. show: true,
  55008. lineStyle: {
  55009. type: 'dashed',
  55010. opacity: 0.2
  55011. }
  55012. }
  55013. };
  55014. function getAxisType$2(axisName, option) {
  55015. return option.type || (option.data ? 'category' : 'value');
  55016. }
  55017. merge(AxisModel$4.prototype, axisModelCommonMixin);
  55018. axisModelCreator('single', AxisModel$4, getAxisType$2, defaultOption$2);
  55019. /*
  55020. * Licensed to the Apache Software Foundation (ASF) under one
  55021. * or more contributor license agreements. See the NOTICE file
  55022. * distributed with this work for additional information
  55023. * regarding copyright ownership. The ASF licenses this file
  55024. * to you under the Apache License, Version 2.0 (the
  55025. * "License"); you may not use this file except in compliance
  55026. * with the License. You may obtain a copy of the License at
  55027. *
  55028. * http://www.apache.org/licenses/LICENSE-2.0
  55029. *
  55030. * Unless required by applicable law or agreed to in writing,
  55031. * software distributed under the License is distributed on an
  55032. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55033. * KIND, either express or implied. See the License for the
  55034. * specific language governing permissions and limitations
  55035. * under the License.
  55036. */
  55037. /**
  55038. * @param {Object} finder contains {seriesIndex, dataIndex, dataIndexInside}
  55039. * @param {module:echarts/model/Global} ecModel
  55040. * @return {Object} {point: [x, y], el: ...} point Will not be null.
  55041. */
  55042. var findPointFromSeries = function (finder, ecModel) {
  55043. var point = [];
  55044. var seriesIndex = finder.seriesIndex;
  55045. var seriesModel;
  55046. if (seriesIndex == null || !(
  55047. seriesModel = ecModel.getSeriesByIndex(seriesIndex)
  55048. )) {
  55049. return {point: []};
  55050. }
  55051. var data = seriesModel.getData();
  55052. var dataIndex = queryDataIndex(data, finder);
  55053. if (dataIndex == null || dataIndex < 0 || isArray(dataIndex)) {
  55054. return {point: []};
  55055. }
  55056. var el = data.getItemGraphicEl(dataIndex);
  55057. var coordSys = seriesModel.coordinateSystem;
  55058. if (seriesModel.getTooltipPosition) {
  55059. point = seriesModel.getTooltipPosition(dataIndex) || [];
  55060. }
  55061. else if (coordSys && coordSys.dataToPoint) {
  55062. point = coordSys.dataToPoint(
  55063. data.getValues(
  55064. map(coordSys.dimensions, function (dim) {
  55065. return data.mapDimension(dim);
  55066. }), dataIndex, true
  55067. )
  55068. ) || [];
  55069. }
  55070. else if (el) {
  55071. // Use graphic bounding rect
  55072. var rect = el.getBoundingRect().clone();
  55073. rect.applyTransform(el.transform);
  55074. point = [
  55075. rect.x + rect.width / 2,
  55076. rect.y + rect.height / 2
  55077. ];
  55078. }
  55079. return {point: point, el: el};
  55080. };
  55081. /*
  55082. * Licensed to the Apache Software Foundation (ASF) under one
  55083. * or more contributor license agreements. See the NOTICE file
  55084. * distributed with this work for additional information
  55085. * regarding copyright ownership. The ASF licenses this file
  55086. * to you under the Apache License, Version 2.0 (the
  55087. * "License"); you may not use this file except in compliance
  55088. * with the License. You may obtain a copy of the License at
  55089. *
  55090. * http://www.apache.org/licenses/LICENSE-2.0
  55091. *
  55092. * Unless required by applicable law or agreed to in writing,
  55093. * software distributed under the License is distributed on an
  55094. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55095. * KIND, either express or implied. See the License for the
  55096. * specific language governing permissions and limitations
  55097. * under the License.
  55098. */
  55099. var each$14 = each$1;
  55100. var curry$3 = curry;
  55101. var inner$7 = makeInner();
  55102. /**
  55103. * Basic logic: check all axis, if they do not demand show/highlight,
  55104. * then hide/downplay them.
  55105. *
  55106. * @param {Object} coordSysAxesInfo
  55107. * @param {Object} payload
  55108. * @param {string} [payload.currTrigger] 'click' | 'mousemove' | 'leave'
  55109. * @param {Array.<number>} [payload.x] x and y, which are mandatory, specify a point to
  55110. * trigger axisPointer and tooltip.
  55111. * @param {Array.<number>} [payload.y] x and y, which are mandatory, specify a point to
  55112. * trigger axisPointer and tooltip.
  55113. * @param {Object} [payload.seriesIndex] finder, optional, restrict target axes.
  55114. * @param {Object} [payload.dataIndex] finder, restrict target axes.
  55115. * @param {Object} [payload.axesInfo] finder, restrict target axes.
  55116. * [{
  55117. * axisDim: 'x'|'y'|'angle'|...,
  55118. * axisIndex: ...,
  55119. * value: ...
  55120. * }, ...]
  55121. * @param {Function} [payload.dispatchAction]
  55122. * @param {Object} [payload.tooltipOption]
  55123. * @param {Object|Array.<number>|Function} [payload.position] Tooltip position,
  55124. * which can be specified in dispatchAction
  55125. * @param {module:echarts/model/Global} ecModel
  55126. * @param {module:echarts/ExtensionAPI} api
  55127. * @return {Object} content of event obj for echarts.connect.
  55128. */
  55129. var axisTrigger = function (payload, ecModel, api) {
  55130. var currTrigger = payload.currTrigger;
  55131. var point = [payload.x, payload.y];
  55132. var finder = payload;
  55133. var dispatchAction = payload.dispatchAction || bind(api.dispatchAction, api);
  55134. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
  55135. // Pending
  55136. // See #6121. But we are not able to reproduce it yet.
  55137. if (!coordSysAxesInfo) {
  55138. return;
  55139. }
  55140. if (illegalPoint(point)) {
  55141. // Used in the default behavior of `connection`: use the sample seriesIndex
  55142. // and dataIndex. And also used in the tooltipView trigger.
  55143. point = findPointFromSeries({
  55144. seriesIndex: finder.seriesIndex,
  55145. // Do not use dataIndexInside from other ec instance.
  55146. // FIXME: auto detect it?
  55147. dataIndex: finder.dataIndex
  55148. }, ecModel).point;
  55149. }
  55150. var isIllegalPoint = illegalPoint(point);
  55151. // Axis and value can be specified when calling dispatchAction({type: 'updateAxisPointer'}).
  55152. // Notice: In this case, it is difficult to get the `point` (which is necessary to show
  55153. // tooltip, so if point is not given, we just use the point found by sample seriesIndex
  55154. // and dataIndex.
  55155. var inputAxesInfo = finder.axesInfo;
  55156. var axesInfo = coordSysAxesInfo.axesInfo;
  55157. var shouldHide = currTrigger === 'leave' || illegalPoint(point);
  55158. var outputFinder = {};
  55159. var showValueMap = {};
  55160. var dataByCoordSys = {list: [], map: {}};
  55161. var updaters = {
  55162. showPointer: curry$3(showPointer, showValueMap),
  55163. showTooltip: curry$3(showTooltip, dataByCoordSys)
  55164. };
  55165. // Process for triggered axes.
  55166. each$14(coordSysAxesInfo.coordSysMap, function (coordSys, coordSysKey) {
  55167. // If a point given, it must be contained by the coordinate system.
  55168. var coordSysContainsPoint = isIllegalPoint || coordSys.containPoint(point);
  55169. each$14(coordSysAxesInfo.coordSysAxesInfo[coordSysKey], function (axisInfo, key) {
  55170. var axis = axisInfo.axis;
  55171. var inputAxisInfo = findInputAxisInfo(inputAxesInfo, axisInfo);
  55172. // If no inputAxesInfo, no axis is restricted.
  55173. if (!shouldHide && coordSysContainsPoint && (!inputAxesInfo || inputAxisInfo)) {
  55174. var val = inputAxisInfo && inputAxisInfo.value;
  55175. if (val == null && !isIllegalPoint) {
  55176. val = axis.pointToData(point);
  55177. }
  55178. val != null && processOnAxis(axisInfo, val, updaters, false, outputFinder);
  55179. }
  55180. });
  55181. });
  55182. // Process for linked axes.
  55183. var linkTriggers = {};
  55184. each$14(axesInfo, function (tarAxisInfo, tarKey) {
  55185. var linkGroup = tarAxisInfo.linkGroup;
  55186. // If axis has been triggered in the previous stage, it should not be triggered by link.
  55187. if (linkGroup && !showValueMap[tarKey]) {
  55188. each$14(linkGroup.axesInfo, function (srcAxisInfo, srcKey) {
  55189. var srcValItem = showValueMap[srcKey];
  55190. // If srcValItem exist, source axis is triggered, so link to target axis.
  55191. if (srcAxisInfo !== tarAxisInfo && srcValItem) {
  55192. var val = srcValItem.value;
  55193. linkGroup.mapper && (val = tarAxisInfo.axis.scale.parse(linkGroup.mapper(
  55194. val, makeMapperParam(srcAxisInfo), makeMapperParam(tarAxisInfo)
  55195. )));
  55196. linkTriggers[tarAxisInfo.key] = val;
  55197. }
  55198. });
  55199. }
  55200. });
  55201. each$14(linkTriggers, function (val, tarKey) {
  55202. processOnAxis(axesInfo[tarKey], val, updaters, true, outputFinder);
  55203. });
  55204. updateModelActually(showValueMap, axesInfo, outputFinder);
  55205. dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction);
  55206. dispatchHighDownActually(axesInfo, dispatchAction, api);
  55207. return outputFinder;
  55208. };
  55209. function processOnAxis(axisInfo, newValue, updaters, dontSnap, outputFinder) {
  55210. var axis = axisInfo.axis;
  55211. if (axis.scale.isBlank() || !axis.containData(newValue)) {
  55212. return;
  55213. }
  55214. if (!axisInfo.involveSeries) {
  55215. updaters.showPointer(axisInfo, newValue);
  55216. return;
  55217. }
  55218. // Heavy calculation. So put it after axis.containData checking.
  55219. var payloadInfo = buildPayloadsBySeries(newValue, axisInfo);
  55220. var payloadBatch = payloadInfo.payloadBatch;
  55221. var snapToValue = payloadInfo.snapToValue;
  55222. // Fill content of event obj for echarts.connect.
  55223. // By defualt use the first involved series data as a sample to connect.
  55224. if (payloadBatch[0] && outputFinder.seriesIndex == null) {
  55225. extend(outputFinder, payloadBatch[0]);
  55226. }
  55227. // If no linkSource input, this process is for collecting link
  55228. // target, where snap should not be accepted.
  55229. if (!dontSnap && axisInfo.snap) {
  55230. if (axis.containData(snapToValue) && snapToValue != null) {
  55231. newValue = snapToValue;
  55232. }
  55233. }
  55234. updaters.showPointer(axisInfo, newValue, payloadBatch, outputFinder);
  55235. // Tooltip should always be snapToValue, otherwise there will be
  55236. // incorrect "axis value ~ series value" mapping displayed in tooltip.
  55237. updaters.showTooltip(axisInfo, payloadInfo, snapToValue);
  55238. }
  55239. function buildPayloadsBySeries(value, axisInfo) {
  55240. var axis = axisInfo.axis;
  55241. var dim = axis.dim;
  55242. var snapToValue = value;
  55243. var payloadBatch = [];
  55244. var minDist = Number.MAX_VALUE;
  55245. var minDiff = -1;
  55246. each$14(axisInfo.seriesModels, function (series, idx) {
  55247. var dataDim = series.getData().mapDimension(dim, true);
  55248. var seriesNestestValue;
  55249. var dataIndices;
  55250. if (series.getAxisTooltipData) {
  55251. var result = series.getAxisTooltipData(dataDim, value, axis);
  55252. dataIndices = result.dataIndices;
  55253. seriesNestestValue = result.nestestValue;
  55254. }
  55255. else {
  55256. dataIndices = series.getData().indicesOfNearest(
  55257. dataDim[0],
  55258. value,
  55259. // Add a threshold to avoid find the wrong dataIndex
  55260. // when data length is not same.
  55261. // false,
  55262. axis.type === 'category' ? 0.5 : null
  55263. );
  55264. if (!dataIndices.length) {
  55265. return;
  55266. }
  55267. seriesNestestValue = series.getData().get(dataDim[0], dataIndices[0]);
  55268. }
  55269. if (seriesNestestValue == null || !isFinite(seriesNestestValue)) {
  55270. return;
  55271. }
  55272. var diff = value - seriesNestestValue;
  55273. var dist = Math.abs(diff);
  55274. // Consider category case
  55275. if (dist <= minDist) {
  55276. if (dist < minDist || (diff >= 0 && minDiff < 0)) {
  55277. minDist = dist;
  55278. minDiff = diff;
  55279. snapToValue = seriesNestestValue;
  55280. payloadBatch.length = 0;
  55281. }
  55282. each$14(dataIndices, function (dataIndex) {
  55283. payloadBatch.push({
  55284. seriesIndex: series.seriesIndex,
  55285. dataIndexInside: dataIndex,
  55286. dataIndex: series.getData().getRawIndex(dataIndex)
  55287. });
  55288. });
  55289. }
  55290. });
  55291. return {
  55292. payloadBatch: payloadBatch,
  55293. snapToValue: snapToValue
  55294. };
  55295. }
  55296. function showPointer(showValueMap, axisInfo, value, payloadBatch) {
  55297. showValueMap[axisInfo.key] = {value: value, payloadBatch: payloadBatch};
  55298. }
  55299. function showTooltip(dataByCoordSys, axisInfo, payloadInfo, value) {
  55300. var payloadBatch = payloadInfo.payloadBatch;
  55301. var axis = axisInfo.axis;
  55302. var axisModel = axis.model;
  55303. var axisPointerModel = axisInfo.axisPointerModel;
  55304. // If no data, do not create anything in dataByCoordSys,
  55305. // whose length will be used to judge whether dispatch action.
  55306. if (!axisInfo.triggerTooltip || !payloadBatch.length) {
  55307. return;
  55308. }
  55309. var coordSysModel = axisInfo.coordSys.model;
  55310. var coordSysKey = makeKey(coordSysModel);
  55311. var coordSysItem = dataByCoordSys.map[coordSysKey];
  55312. if (!coordSysItem) {
  55313. coordSysItem = dataByCoordSys.map[coordSysKey] = {
  55314. coordSysId: coordSysModel.id,
  55315. coordSysIndex: coordSysModel.componentIndex,
  55316. coordSysType: coordSysModel.type,
  55317. coordSysMainType: coordSysModel.mainType,
  55318. dataByAxis: []
  55319. };
  55320. dataByCoordSys.list.push(coordSysItem);
  55321. }
  55322. coordSysItem.dataByAxis.push({
  55323. axisDim: axis.dim,
  55324. axisIndex: axisModel.componentIndex,
  55325. axisType: axisModel.type,
  55326. axisId: axisModel.id,
  55327. value: value,
  55328. // Caustion: viewHelper.getValueLabel is actually on "view stage", which
  55329. // depends that all models have been updated. So it should not be performed
  55330. // here. Considering axisPointerModel used here is volatile, which is hard
  55331. // to be retrieve in TooltipView, we prepare parameters here.
  55332. valueLabelOpt: {
  55333. precision: axisPointerModel.get('label.precision'),
  55334. formatter: axisPointerModel.get('label.formatter')
  55335. },
  55336. seriesDataIndices: payloadBatch.slice()
  55337. });
  55338. }
  55339. function updateModelActually(showValueMap, axesInfo, outputFinder) {
  55340. var outputAxesInfo = outputFinder.axesInfo = [];
  55341. // Basic logic: If no 'show' required, 'hide' this axisPointer.
  55342. each$14(axesInfo, function (axisInfo, key) {
  55343. var option = axisInfo.axisPointerModel.option;
  55344. var valItem = showValueMap[key];
  55345. if (valItem) {
  55346. !axisInfo.useHandle && (option.status = 'show');
  55347. option.value = valItem.value;
  55348. // For label formatter param and highlight.
  55349. option.seriesDataIndices = (valItem.payloadBatch || []).slice();
  55350. }
  55351. // When always show (e.g., handle used), remain
  55352. // original value and status.
  55353. else {
  55354. // If hide, value still need to be set, consider
  55355. // click legend to toggle axis blank.
  55356. !axisInfo.useHandle && (option.status = 'hide');
  55357. }
  55358. // If status is 'hide', should be no info in payload.
  55359. option.status === 'show' && outputAxesInfo.push({
  55360. axisDim: axisInfo.axis.dim,
  55361. axisIndex: axisInfo.axis.model.componentIndex,
  55362. value: option.value
  55363. });
  55364. });
  55365. }
  55366. function dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction) {
  55367. // Basic logic: If no showTip required, hideTip will be dispatched.
  55368. if (illegalPoint(point) || !dataByCoordSys.list.length) {
  55369. dispatchAction({type: 'hideTip'});
  55370. return;
  55371. }
  55372. // In most case only one axis (or event one series is used). It is
  55373. // convinient to fetch payload.seriesIndex and payload.dataIndex
  55374. // dirtectly. So put the first seriesIndex and dataIndex of the first
  55375. // axis on the payload.
  55376. var sampleItem = ((dataByCoordSys.list[0].dataByAxis[0] || {}).seriesDataIndices || [])[0] || {};
  55377. dispatchAction({
  55378. type: 'showTip',
  55379. escapeConnect: true,
  55380. x: point[0],
  55381. y: point[1],
  55382. tooltipOption: payload.tooltipOption,
  55383. position: payload.position,
  55384. dataIndexInside: sampleItem.dataIndexInside,
  55385. dataIndex: sampleItem.dataIndex,
  55386. seriesIndex: sampleItem.seriesIndex,
  55387. dataByCoordSys: dataByCoordSys.list
  55388. });
  55389. }
  55390. function dispatchHighDownActually(axesInfo, dispatchAction, api) {
  55391. // FIXME
  55392. // highlight status modification shoule be a stage of main process?
  55393. // (Consider confilct (e.g., legend and axisPointer) and setOption)
  55394. var zr = api.getZr();
  55395. var highDownKey = 'axisPointerLastHighlights';
  55396. var lastHighlights = inner$7(zr)[highDownKey] || {};
  55397. var newHighlights = inner$7(zr)[highDownKey] = {};
  55398. // Update highlight/downplay status according to axisPointer model.
  55399. // Build hash map and remove duplicate incidentally.
  55400. each$14(axesInfo, function (axisInfo, key) {
  55401. var option = axisInfo.axisPointerModel.option;
  55402. option.status === 'show' && each$14(option.seriesDataIndices, function (batchItem) {
  55403. var key = batchItem.seriesIndex + ' | ' + batchItem.dataIndex;
  55404. newHighlights[key] = batchItem;
  55405. });
  55406. });
  55407. // Diff.
  55408. var toHighlight = [];
  55409. var toDownplay = [];
  55410. each$1(lastHighlights, function (batchItem, key) {
  55411. !newHighlights[key] && toDownplay.push(batchItem);
  55412. });
  55413. each$1(newHighlights, function (batchItem, key) {
  55414. !lastHighlights[key] && toHighlight.push(batchItem);
  55415. });
  55416. toDownplay.length && api.dispatchAction({
  55417. type: 'downplay', escapeConnect: true, batch: toDownplay
  55418. });
  55419. toHighlight.length && api.dispatchAction({
  55420. type: 'highlight', escapeConnect: true, batch: toHighlight
  55421. });
  55422. }
  55423. function findInputAxisInfo(inputAxesInfo, axisInfo) {
  55424. for (var i = 0; i < (inputAxesInfo || []).length; i++) {
  55425. var inputAxisInfo = inputAxesInfo[i];
  55426. if (axisInfo.axis.dim === inputAxisInfo.axisDim
  55427. && axisInfo.axis.model.componentIndex === inputAxisInfo.axisIndex
  55428. ) {
  55429. return inputAxisInfo;
  55430. }
  55431. }
  55432. }
  55433. function makeMapperParam(axisInfo) {
  55434. var axisModel = axisInfo.axis.model;
  55435. var item = {};
  55436. var dim = item.axisDim = axisInfo.axis.dim;
  55437. item.axisIndex = item[dim + 'AxisIndex'] = axisModel.componentIndex;
  55438. item.axisName = item[dim + 'AxisName'] = axisModel.name;
  55439. item.axisId = item[dim + 'AxisId'] = axisModel.id;
  55440. return item;
  55441. }
  55442. function illegalPoint(point) {
  55443. return !point || point[0] == null || isNaN(point[0]) || point[1] == null || isNaN(point[1]);
  55444. }
  55445. /*
  55446. * Licensed to the Apache Software Foundation (ASF) under one
  55447. * or more contributor license agreements. See the NOTICE file
  55448. * distributed with this work for additional information
  55449. * regarding copyright ownership. The ASF licenses this file
  55450. * to you under the Apache License, Version 2.0 (the
  55451. * "License"); you may not use this file except in compliance
  55452. * with the License. You may obtain a copy of the License at
  55453. *
  55454. * http://www.apache.org/licenses/LICENSE-2.0
  55455. *
  55456. * Unless required by applicable law or agreed to in writing,
  55457. * software distributed under the License is distributed on an
  55458. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55459. * KIND, either express or implied. See the License for the
  55460. * specific language governing permissions and limitations
  55461. * under the License.
  55462. */
  55463. var AxisPointerModel = extendComponentModel({
  55464. type: 'axisPointer',
  55465. coordSysAxesInfo: null,
  55466. defaultOption: {
  55467. // 'auto' means that show when triggered by tooltip or handle.
  55468. show: 'auto',
  55469. // 'click' | 'mousemove' | 'none'
  55470. triggerOn: null, // set default in AxisPonterView.js
  55471. zlevel: 0,
  55472. z: 50,
  55473. type: 'line',
  55474. // axispointer triggered by tootip determine snap automatically,
  55475. // see `modelHelper`.
  55476. snap: false,
  55477. triggerTooltip: true,
  55478. value: null,
  55479. status: null, // Init value depends on whether handle is used.
  55480. // [group0, group1, ...]
  55481. // Each group can be: {
  55482. // mapper: function () {},
  55483. // singleTooltip: 'multiple', // 'multiple' or 'single'
  55484. // xAxisId: ...,
  55485. // yAxisName: ...,
  55486. // angleAxisIndex: ...
  55487. // }
  55488. // mapper: can be ignored.
  55489. // input: {axisInfo, value}
  55490. // output: {axisInfo, value}
  55491. link: [],
  55492. // Do not set 'auto' here, otherwise global animation: false
  55493. // will not effect at this axispointer.
  55494. animation: null,
  55495. animationDurationUpdate: 200,
  55496. lineStyle: {
  55497. color: '#aaa',
  55498. width: 1,
  55499. type: 'solid'
  55500. },
  55501. shadowStyle: {
  55502. color: 'rgba(150,150,150,0.3)'
  55503. },
  55504. label: {
  55505. show: true,
  55506. formatter: null, // string | Function
  55507. precision: 'auto', // Or a number like 0, 1, 2 ...
  55508. margin: 3,
  55509. color: '#fff',
  55510. padding: [5, 7, 5, 7],
  55511. backgroundColor: 'auto', // default: axis line color
  55512. borderColor: null,
  55513. borderWidth: 0,
  55514. shadowBlur: 3,
  55515. shadowColor: '#aaa'
  55516. // Considering applicability, common style should
  55517. // better not have shadowOffset.
  55518. // shadowOffsetX: 0,
  55519. // shadowOffsetY: 2
  55520. },
  55521. handle: {
  55522. show: false,
  55523. 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
  55524. size: 45,
  55525. // handle margin is from symbol center to axis, which is stable when circular move.
  55526. margin: 50,
  55527. // color: '#1b8bbd'
  55528. // color: '#2f4554'
  55529. color: '#333',
  55530. shadowBlur: 3,
  55531. shadowColor: '#aaa',
  55532. shadowOffsetX: 0,
  55533. shadowOffsetY: 2,
  55534. // For mobile performance
  55535. throttle: 40
  55536. }
  55537. }
  55538. });
  55539. /*
  55540. * Licensed to the Apache Software Foundation (ASF) under one
  55541. * or more contributor license agreements. See the NOTICE file
  55542. * distributed with this work for additional information
  55543. * regarding copyright ownership. The ASF licenses this file
  55544. * to you under the Apache License, Version 2.0 (the
  55545. * "License"); you may not use this file except in compliance
  55546. * with the License. You may obtain a copy of the License at
  55547. *
  55548. * http://www.apache.org/licenses/LICENSE-2.0
  55549. *
  55550. * Unless required by applicable law or agreed to in writing,
  55551. * software distributed under the License is distributed on an
  55552. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55553. * KIND, either express or implied. See the License for the
  55554. * specific language governing permissions and limitations
  55555. * under the License.
  55556. */
  55557. var inner$8 = makeInner();
  55558. var each$15 = each$1;
  55559. /**
  55560. * @param {string} key
  55561. * @param {module:echarts/ExtensionAPI} api
  55562. * @param {Function} handler
  55563. * param: {string} currTrigger
  55564. * param: {Array.<number>} point
  55565. */
  55566. function register(key, api, handler) {
  55567. if (env$1.node) {
  55568. return;
  55569. }
  55570. var zr = api.getZr();
  55571. inner$8(zr).records || (inner$8(zr).records = {});
  55572. initGlobalListeners(zr, api);
  55573. var record = inner$8(zr).records[key] || (inner$8(zr).records[key] = {});
  55574. record.handler = handler;
  55575. }
  55576. function initGlobalListeners(zr, api) {
  55577. if (inner$8(zr).initialized) {
  55578. return;
  55579. }
  55580. inner$8(zr).initialized = true;
  55581. useHandler('click', curry(doEnter, 'click'));
  55582. useHandler('mousemove', curry(doEnter, 'mousemove'));
  55583. // useHandler('mouseout', onLeave);
  55584. useHandler('globalout', onLeave);
  55585. function useHandler(eventType, cb) {
  55586. zr.on(eventType, function (e) {
  55587. var dis = makeDispatchAction(api);
  55588. each$15(inner$8(zr).records, function (record) {
  55589. record && cb(record, e, dis.dispatchAction);
  55590. });
  55591. dispatchTooltipFinally(dis.pendings, api);
  55592. });
  55593. }
  55594. }
  55595. function dispatchTooltipFinally(pendings, api) {
  55596. var showLen = pendings.showTip.length;
  55597. var hideLen = pendings.hideTip.length;
  55598. var actuallyPayload;
  55599. if (showLen) {
  55600. actuallyPayload = pendings.showTip[showLen - 1];
  55601. }
  55602. else if (hideLen) {
  55603. actuallyPayload = pendings.hideTip[hideLen - 1];
  55604. }
  55605. if (actuallyPayload) {
  55606. actuallyPayload.dispatchAction = null;
  55607. api.dispatchAction(actuallyPayload);
  55608. }
  55609. }
  55610. function onLeave(record, e, dispatchAction) {
  55611. record.handler('leave', null, dispatchAction);
  55612. }
  55613. function doEnter(currTrigger, record, e, dispatchAction) {
  55614. record.handler(currTrigger, e, dispatchAction);
  55615. }
  55616. function makeDispatchAction(api) {
  55617. var pendings = {
  55618. showTip: [],
  55619. hideTip: []
  55620. };
  55621. // FIXME
  55622. // better approach?
  55623. // 'showTip' and 'hideTip' can be triggered by axisPointer and tooltip,
  55624. // which may be conflict, (axisPointer call showTip but tooltip call hideTip);
  55625. // So we have to add "final stage" to merge those dispatched actions.
  55626. var dispatchAction = function (payload) {
  55627. var pendingList = pendings[payload.type];
  55628. if (pendingList) {
  55629. pendingList.push(payload);
  55630. }
  55631. else {
  55632. payload.dispatchAction = dispatchAction;
  55633. api.dispatchAction(payload);
  55634. }
  55635. };
  55636. return {
  55637. dispatchAction: dispatchAction,
  55638. pendings: pendings
  55639. };
  55640. }
  55641. /**
  55642. * @param {string} key
  55643. * @param {module:echarts/ExtensionAPI} api
  55644. */
  55645. function unregister(key, api) {
  55646. if (env$1.node) {
  55647. return;
  55648. }
  55649. var zr = api.getZr();
  55650. var record = (inner$8(zr).records || {})[key];
  55651. if (record) {
  55652. inner$8(zr).records[key] = null;
  55653. }
  55654. }
  55655. /*
  55656. * Licensed to the Apache Software Foundation (ASF) under one
  55657. * or more contributor license agreements. See the NOTICE file
  55658. * distributed with this work for additional information
  55659. * regarding copyright ownership. The ASF licenses this file
  55660. * to you under the Apache License, Version 2.0 (the
  55661. * "License"); you may not use this file except in compliance
  55662. * with the License. You may obtain a copy of the License at
  55663. *
  55664. * http://www.apache.org/licenses/LICENSE-2.0
  55665. *
  55666. * Unless required by applicable law or agreed to in writing,
  55667. * software distributed under the License is distributed on an
  55668. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55669. * KIND, either express or implied. See the License for the
  55670. * specific language governing permissions and limitations
  55671. * under the License.
  55672. */
  55673. var AxisPointerView = extendComponentView({
  55674. type: 'axisPointer',
  55675. render: function (globalAxisPointerModel, ecModel, api) {
  55676. var globalTooltipModel = ecModel.getComponent('tooltip');
  55677. var triggerOn = globalAxisPointerModel.get('triggerOn')
  55678. || (globalTooltipModel && globalTooltipModel.get('triggerOn') || 'mousemove|click');
  55679. // Register global listener in AxisPointerView to enable
  55680. // AxisPointerView to be independent to Tooltip.
  55681. register(
  55682. 'axisPointer',
  55683. api,
  55684. function (currTrigger, e, dispatchAction) {
  55685. // If 'none', it is not controlled by mouse totally.
  55686. if (triggerOn !== 'none'
  55687. && (currTrigger === 'leave' || triggerOn.indexOf(currTrigger) >= 0)
  55688. ) {
  55689. dispatchAction({
  55690. type: 'updateAxisPointer',
  55691. currTrigger: currTrigger,
  55692. x: e && e.offsetX,
  55693. y: e && e.offsetY
  55694. });
  55695. }
  55696. }
  55697. );
  55698. },
  55699. /**
  55700. * @override
  55701. */
  55702. remove: function (ecModel, api) {
  55703. unregister(api.getZr(), 'axisPointer');
  55704. AxisPointerView.superApply(this._model, 'remove', arguments);
  55705. },
  55706. /**
  55707. * @override
  55708. */
  55709. dispose: function (ecModel, api) {
  55710. unregister('axisPointer', api);
  55711. AxisPointerView.superApply(this._model, 'dispose', arguments);
  55712. }
  55713. });
  55714. /*
  55715. * Licensed to the Apache Software Foundation (ASF) under one
  55716. * or more contributor license agreements. See the NOTICE file
  55717. * distributed with this work for additional information
  55718. * regarding copyright ownership. The ASF licenses this file
  55719. * to you under the Apache License, Version 2.0 (the
  55720. * "License"); you may not use this file except in compliance
  55721. * with the License. You may obtain a copy of the License at
  55722. *
  55723. * http://www.apache.org/licenses/LICENSE-2.0
  55724. *
  55725. * Unless required by applicable law or agreed to in writing,
  55726. * software distributed under the License is distributed on an
  55727. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55728. * KIND, either express or implied. See the License for the
  55729. * specific language governing permissions and limitations
  55730. * under the License.
  55731. */
  55732. var inner$9 = makeInner();
  55733. var clone$4 = clone;
  55734. var bind$2 = bind;
  55735. /**
  55736. * Base axis pointer class in 2D.
  55737. * Implemenents {module:echarts/component/axis/IAxisPointer}.
  55738. */
  55739. function BaseAxisPointer () {
  55740. }
  55741. BaseAxisPointer.prototype = {
  55742. /**
  55743. * @private
  55744. */
  55745. _group: null,
  55746. /**
  55747. * @private
  55748. */
  55749. _lastGraphicKey: null,
  55750. /**
  55751. * @private
  55752. */
  55753. _handle: null,
  55754. /**
  55755. * @private
  55756. */
  55757. _dragging: false,
  55758. /**
  55759. * @private
  55760. */
  55761. _lastValue: null,
  55762. /**
  55763. * @private
  55764. */
  55765. _lastStatus: null,
  55766. /**
  55767. * @private
  55768. */
  55769. _payloadInfo: null,
  55770. /**
  55771. * In px, arbitrary value. Do not set too small,
  55772. * no animation is ok for most cases.
  55773. * @protected
  55774. */
  55775. animationThreshold: 15,
  55776. /**
  55777. * @implement
  55778. */
  55779. render: function (axisModel, axisPointerModel, api, forceRender) {
  55780. var value = axisPointerModel.get('value');
  55781. var status = axisPointerModel.get('status');
  55782. // Bind them to `this`, not in closure, otherwise they will not
  55783. // be replaced when user calling setOption in not merge mode.
  55784. this._axisModel = axisModel;
  55785. this._axisPointerModel = axisPointerModel;
  55786. this._api = api;
  55787. // Optimize: `render` will be called repeatly during mouse move.
  55788. // So it is power consuming if performing `render` each time,
  55789. // especially on mobile device.
  55790. if (!forceRender
  55791. && this._lastValue === value
  55792. && this._lastStatus === status
  55793. ) {
  55794. return;
  55795. }
  55796. this._lastValue = value;
  55797. this._lastStatus = status;
  55798. var group = this._group;
  55799. var handle = this._handle;
  55800. if (!status || status === 'hide') {
  55801. // Do not clear here, for animation better.
  55802. group && group.hide();
  55803. handle && handle.hide();
  55804. return;
  55805. }
  55806. group && group.show();
  55807. handle && handle.show();
  55808. // Otherwise status is 'show'
  55809. var elOption = {};
  55810. this.makeElOption(elOption, value, axisModel, axisPointerModel, api);
  55811. // Enable change axis pointer type.
  55812. var graphicKey = elOption.graphicKey;
  55813. if (graphicKey !== this._lastGraphicKey) {
  55814. this.clear(api);
  55815. }
  55816. this._lastGraphicKey = graphicKey;
  55817. var moveAnimation = this._moveAnimation =
  55818. this.determineAnimation(axisModel, axisPointerModel);
  55819. if (!group) {
  55820. group = this._group = new Group();
  55821. this.createPointerEl(group, elOption, axisModel, axisPointerModel);
  55822. this.createLabelEl(group, elOption, axisModel, axisPointerModel);
  55823. api.getZr().add(group);
  55824. }
  55825. else {
  55826. var doUpdateProps = curry(updateProps$1, axisPointerModel, moveAnimation);
  55827. this.updatePointerEl(group, elOption, doUpdateProps, axisPointerModel);
  55828. this.updateLabelEl(group, elOption, doUpdateProps, axisPointerModel);
  55829. }
  55830. updateMandatoryProps(group, axisPointerModel, true);
  55831. this._renderHandle(value);
  55832. },
  55833. /**
  55834. * @implement
  55835. */
  55836. remove: function (api) {
  55837. this.clear(api);
  55838. },
  55839. /**
  55840. * @implement
  55841. */
  55842. dispose: function (api) {
  55843. this.clear(api);
  55844. },
  55845. /**
  55846. * @protected
  55847. */
  55848. determineAnimation: function (axisModel, axisPointerModel) {
  55849. var animation = axisPointerModel.get('animation');
  55850. var axis = axisModel.axis;
  55851. var isCategoryAxis = axis.type === 'category';
  55852. var useSnap = axisPointerModel.get('snap');
  55853. // Value axis without snap always do not snap.
  55854. if (!useSnap && !isCategoryAxis) {
  55855. return false;
  55856. }
  55857. if (animation === 'auto' || animation == null) {
  55858. var animationThreshold = this.animationThreshold;
  55859. if (isCategoryAxis && axis.getBandWidth() > animationThreshold) {
  55860. return true;
  55861. }
  55862. // It is important to auto animation when snap used. Consider if there is
  55863. // a dataZoom, animation will be disabled when too many points exist, while
  55864. // it will be enabled for better visual effect when little points exist.
  55865. if (useSnap) {
  55866. var seriesDataCount = getAxisInfo(axisModel).seriesDataCount;
  55867. var axisExtent = axis.getExtent();
  55868. // Approximate band width
  55869. return Math.abs(axisExtent[0] - axisExtent[1]) / seriesDataCount > animationThreshold;
  55870. }
  55871. return false;
  55872. }
  55873. return animation === true;
  55874. },
  55875. /**
  55876. * add {pointer, label, graphicKey} to elOption
  55877. * @protected
  55878. */
  55879. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  55880. // Shoule be implemenented by sub-class.
  55881. },
  55882. /**
  55883. * @protected
  55884. */
  55885. createPointerEl: function (group, elOption, axisModel, axisPointerModel) {
  55886. var pointerOption = elOption.pointer;
  55887. if (pointerOption) {
  55888. var pointerEl = inner$9(group).pointerEl = new graphic[pointerOption.type](
  55889. clone$4(elOption.pointer)
  55890. );
  55891. group.add(pointerEl);
  55892. }
  55893. },
  55894. /**
  55895. * @protected
  55896. */
  55897. createLabelEl: function (group, elOption, axisModel, axisPointerModel) {
  55898. if (elOption.label) {
  55899. var labelEl = inner$9(group).labelEl = new Rect(
  55900. clone$4(elOption.label)
  55901. );
  55902. group.add(labelEl);
  55903. updateLabelShowHide(labelEl, axisPointerModel);
  55904. }
  55905. },
  55906. /**
  55907. * @protected
  55908. */
  55909. updatePointerEl: function (group, elOption, updateProps$$1) {
  55910. var pointerEl = inner$9(group).pointerEl;
  55911. if (pointerEl) {
  55912. pointerEl.setStyle(elOption.pointer.style);
  55913. updateProps$$1(pointerEl, {shape: elOption.pointer.shape});
  55914. }
  55915. },
  55916. /**
  55917. * @protected
  55918. */
  55919. updateLabelEl: function (group, elOption, updateProps$$1, axisPointerModel) {
  55920. var labelEl = inner$9(group).labelEl;
  55921. if (labelEl) {
  55922. labelEl.setStyle(elOption.label.style);
  55923. updateProps$$1(labelEl, {
  55924. // Consider text length change in vertical axis, animation should
  55925. // be used on shape, otherwise the effect will be weird.
  55926. shape: elOption.label.shape,
  55927. position: elOption.label.position
  55928. });
  55929. updateLabelShowHide(labelEl, axisPointerModel);
  55930. }
  55931. },
  55932. /**
  55933. * @private
  55934. */
  55935. _renderHandle: function (value) {
  55936. if (this._dragging || !this.updateHandleTransform) {
  55937. return;
  55938. }
  55939. var axisPointerModel = this._axisPointerModel;
  55940. var zr = this._api.getZr();
  55941. var handle = this._handle;
  55942. var handleModel = axisPointerModel.getModel('handle');
  55943. var status = axisPointerModel.get('status');
  55944. if (!handleModel.get('show') || !status || status === 'hide') {
  55945. handle && zr.remove(handle);
  55946. this._handle = null;
  55947. return;
  55948. }
  55949. var isInit;
  55950. if (!this._handle) {
  55951. isInit = true;
  55952. handle = this._handle = createIcon(
  55953. handleModel.get('icon'),
  55954. {
  55955. cursor: 'move',
  55956. draggable: true,
  55957. onmousemove: function (e) {
  55958. // Fot mobile devicem, prevent screen slider on the button.
  55959. stop(e.event);
  55960. },
  55961. onmousedown: bind$2(this._onHandleDragMove, this, 0, 0),
  55962. drift: bind$2(this._onHandleDragMove, this),
  55963. ondragend: bind$2(this._onHandleDragEnd, this)
  55964. }
  55965. );
  55966. zr.add(handle);
  55967. }
  55968. updateMandatoryProps(handle, axisPointerModel, false);
  55969. // update style
  55970. var includeStyles = [
  55971. 'color', 'borderColor', 'borderWidth', 'opacity',
  55972. 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY'
  55973. ];
  55974. handle.setStyle(handleModel.getItemStyle(null, includeStyles));
  55975. // update position
  55976. var handleSize = handleModel.get('size');
  55977. if (!isArray(handleSize)) {
  55978. handleSize = [handleSize, handleSize];
  55979. }
  55980. handle.attr('scale', [handleSize[0] / 2, handleSize[1] / 2]);
  55981. createOrUpdate(
  55982. this,
  55983. '_doDispatchAxisPointer',
  55984. handleModel.get('throttle') || 0,
  55985. 'fixRate'
  55986. );
  55987. this._moveHandleToValue(value, isInit);
  55988. },
  55989. /**
  55990. * @private
  55991. */
  55992. _moveHandleToValue: function (value, isInit) {
  55993. updateProps$1(
  55994. this._axisPointerModel,
  55995. !isInit && this._moveAnimation,
  55996. this._handle,
  55997. getHandleTransProps(this.getHandleTransform(
  55998. value, this._axisModel, this._axisPointerModel
  55999. ))
  56000. );
  56001. },
  56002. /**
  56003. * @private
  56004. */
  56005. _onHandleDragMove: function (dx, dy) {
  56006. var handle = this._handle;
  56007. if (!handle) {
  56008. return;
  56009. }
  56010. this._dragging = true;
  56011. // Persistent for throttle.
  56012. var trans = this.updateHandleTransform(
  56013. getHandleTransProps(handle),
  56014. [dx, dy],
  56015. this._axisModel,
  56016. this._axisPointerModel
  56017. );
  56018. this._payloadInfo = trans;
  56019. handle.stopAnimation();
  56020. handle.attr(getHandleTransProps(trans));
  56021. inner$9(handle).lastProp = null;
  56022. this._doDispatchAxisPointer();
  56023. },
  56024. /**
  56025. * Throttled method.
  56026. * @private
  56027. */
  56028. _doDispatchAxisPointer: function () {
  56029. var handle = this._handle;
  56030. if (!handle) {
  56031. return;
  56032. }
  56033. var payloadInfo = this._payloadInfo;
  56034. var axisModel = this._axisModel;
  56035. this._api.dispatchAction({
  56036. type: 'updateAxisPointer',
  56037. x: payloadInfo.cursorPoint[0],
  56038. y: payloadInfo.cursorPoint[1],
  56039. tooltipOption: payloadInfo.tooltipOption,
  56040. axesInfo: [{
  56041. axisDim: axisModel.axis.dim,
  56042. axisIndex: axisModel.componentIndex
  56043. }]
  56044. });
  56045. },
  56046. /**
  56047. * @private
  56048. */
  56049. _onHandleDragEnd: function (moveAnimation) {
  56050. this._dragging = false;
  56051. var handle = this._handle;
  56052. if (!handle) {
  56053. return;
  56054. }
  56055. var value = this._axisPointerModel.get('value');
  56056. // Consider snap or categroy axis, handle may be not consistent with
  56057. // axisPointer. So move handle to align the exact value position when
  56058. // drag ended.
  56059. this._moveHandleToValue(value);
  56060. // For the effect: tooltip will be shown when finger holding on handle
  56061. // button, and will be hidden after finger left handle button.
  56062. this._api.dispatchAction({
  56063. type: 'hideTip'
  56064. });
  56065. },
  56066. /**
  56067. * Should be implemenented by sub-class if support `handle`.
  56068. * @protected
  56069. * @param {number} value
  56070. * @param {module:echarts/model/Model} axisModel
  56071. * @param {module:echarts/model/Model} axisPointerModel
  56072. * @return {Object} {position: [x, y], rotation: 0}
  56073. */
  56074. getHandleTransform: null,
  56075. /**
  56076. * * Should be implemenented by sub-class if support `handle`.
  56077. * @protected
  56078. * @param {Object} transform {position, rotation}
  56079. * @param {Array.<number>} delta [dx, dy]
  56080. * @param {module:echarts/model/Model} axisModel
  56081. * @param {module:echarts/model/Model} axisPointerModel
  56082. * @return {Object} {position: [x, y], rotation: 0, cursorPoint: [x, y]}
  56083. */
  56084. updateHandleTransform: null,
  56085. /**
  56086. * @private
  56087. */
  56088. clear: function (api) {
  56089. this._lastValue = null;
  56090. this._lastStatus = null;
  56091. var zr = api.getZr();
  56092. var group = this._group;
  56093. var handle = this._handle;
  56094. if (zr && group) {
  56095. this._lastGraphicKey = null;
  56096. group && zr.remove(group);
  56097. handle && zr.remove(handle);
  56098. this._group = null;
  56099. this._handle = null;
  56100. this._payloadInfo = null;
  56101. }
  56102. },
  56103. /**
  56104. * @protected
  56105. */
  56106. doClear: function () {
  56107. // Implemented by sub-class if necessary.
  56108. },
  56109. /**
  56110. * @protected
  56111. * @param {Array.<number>} xy
  56112. * @param {Array.<number>} wh
  56113. * @param {number} [xDimIndex=0] or 1
  56114. */
  56115. buildLabel: function (xy, wh, xDimIndex) {
  56116. xDimIndex = xDimIndex || 0;
  56117. return {
  56118. x: xy[xDimIndex],
  56119. y: xy[1 - xDimIndex],
  56120. width: wh[xDimIndex],
  56121. height: wh[1 - xDimIndex]
  56122. };
  56123. }
  56124. };
  56125. BaseAxisPointer.prototype.constructor = BaseAxisPointer;
  56126. function updateProps$1(animationModel, moveAnimation, el, props) {
  56127. // Animation optimize.
  56128. if (!propsEqual(inner$9(el).lastProp, props)) {
  56129. inner$9(el).lastProp = props;
  56130. moveAnimation
  56131. ? updateProps(el, props, animationModel)
  56132. : (el.stopAnimation(), el.attr(props));
  56133. }
  56134. }
  56135. function propsEqual(lastProps, newProps) {
  56136. if (isObject$1(lastProps) && isObject$1(newProps)) {
  56137. var equals = true;
  56138. each$1(newProps, function (item, key) {
  56139. equals = equals && propsEqual(lastProps[key], item);
  56140. });
  56141. return !!equals;
  56142. }
  56143. else {
  56144. return lastProps === newProps;
  56145. }
  56146. }
  56147. function updateLabelShowHide(labelEl, axisPointerModel) {
  56148. labelEl[axisPointerModel.get('label.show') ? 'show' : 'hide']();
  56149. }
  56150. function getHandleTransProps(trans) {
  56151. return {
  56152. position: trans.position.slice(),
  56153. rotation: trans.rotation || 0
  56154. };
  56155. }
  56156. function updateMandatoryProps(group, axisPointerModel, silent) {
  56157. var z = axisPointerModel.get('z');
  56158. var zlevel = axisPointerModel.get('zlevel');
  56159. group && group.traverse(function (el) {
  56160. if (el.type !== 'group') {
  56161. z != null && (el.z = z);
  56162. zlevel != null && (el.zlevel = zlevel);
  56163. el.silent = silent;
  56164. }
  56165. });
  56166. }
  56167. enableClassExtend(BaseAxisPointer);
  56168. /*
  56169. * Licensed to the Apache Software Foundation (ASF) under one
  56170. * or more contributor license agreements. See the NOTICE file
  56171. * distributed with this work for additional information
  56172. * regarding copyright ownership. The ASF licenses this file
  56173. * to you under the Apache License, Version 2.0 (the
  56174. * "License"); you may not use this file except in compliance
  56175. * with the License. You may obtain a copy of the License at
  56176. *
  56177. * http://www.apache.org/licenses/LICENSE-2.0
  56178. *
  56179. * Unless required by applicable law or agreed to in writing,
  56180. * software distributed under the License is distributed on an
  56181. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56182. * KIND, either express or implied. See the License for the
  56183. * specific language governing permissions and limitations
  56184. * under the License.
  56185. */
  56186. /**
  56187. * @param {module:echarts/model/Model} axisPointerModel
  56188. */
  56189. function buildElStyle(axisPointerModel) {
  56190. var axisPointerType = axisPointerModel.get('type');
  56191. var styleModel = axisPointerModel.getModel(axisPointerType + 'Style');
  56192. var style;
  56193. if (axisPointerType === 'line') {
  56194. style = styleModel.getLineStyle();
  56195. style.fill = null;
  56196. }
  56197. else if (axisPointerType === 'shadow') {
  56198. style = styleModel.getAreaStyle();
  56199. style.stroke = null;
  56200. }
  56201. return style;
  56202. }
  56203. /**
  56204. * @param {Function} labelPos {align, verticalAlign, position}
  56205. */
  56206. function buildLabelElOption(
  56207. elOption, axisModel, axisPointerModel, api, labelPos
  56208. ) {
  56209. var value = axisPointerModel.get('value');
  56210. var text = getValueLabel(
  56211. value, axisModel.axis, axisModel.ecModel,
  56212. axisPointerModel.get('seriesDataIndices'),
  56213. {
  56214. precision: axisPointerModel.get('label.precision'),
  56215. formatter: axisPointerModel.get('label.formatter')
  56216. }
  56217. );
  56218. var labelModel = axisPointerModel.getModel('label');
  56219. var paddings = normalizeCssArray$1(labelModel.get('padding') || 0);
  56220. var font = labelModel.getFont();
  56221. var textRect = getBoundingRect(text, font);
  56222. var position = labelPos.position;
  56223. var width = textRect.width + paddings[1] + paddings[3];
  56224. var height = textRect.height + paddings[0] + paddings[2];
  56225. // Adjust by align.
  56226. var align = labelPos.align;
  56227. align === 'right' && (position[0] -= width);
  56228. align === 'center' && (position[0] -= width / 2);
  56229. var verticalAlign = labelPos.verticalAlign;
  56230. verticalAlign === 'bottom' && (position[1] -= height);
  56231. verticalAlign === 'middle' && (position[1] -= height / 2);
  56232. // Not overflow ec container
  56233. confineInContainer(position, width, height, api);
  56234. var bgColor = labelModel.get('backgroundColor');
  56235. if (!bgColor || bgColor === 'auto') {
  56236. bgColor = axisModel.get('axisLine.lineStyle.color');
  56237. }
  56238. elOption.label = {
  56239. shape: {x: 0, y: 0, width: width, height: height, r: labelModel.get('borderRadius')},
  56240. position: position.slice(),
  56241. // TODO: rich
  56242. style: {
  56243. text: text,
  56244. textFont: font,
  56245. textFill: labelModel.getTextColor(),
  56246. textPosition: 'inside',
  56247. fill: bgColor,
  56248. stroke: labelModel.get('borderColor') || 'transparent',
  56249. lineWidth: labelModel.get('borderWidth') || 0,
  56250. shadowBlur: labelModel.get('shadowBlur'),
  56251. shadowColor: labelModel.get('shadowColor'),
  56252. shadowOffsetX: labelModel.get('shadowOffsetX'),
  56253. shadowOffsetY: labelModel.get('shadowOffsetY')
  56254. },
  56255. // Lable should be over axisPointer.
  56256. z2: 10
  56257. };
  56258. }
  56259. // Do not overflow ec container
  56260. function confineInContainer(position, width, height, api) {
  56261. var viewWidth = api.getWidth();
  56262. var viewHeight = api.getHeight();
  56263. position[0] = Math.min(position[0] + width, viewWidth) - width;
  56264. position[1] = Math.min(position[1] + height, viewHeight) - height;
  56265. position[0] = Math.max(position[0], 0);
  56266. position[1] = Math.max(position[1], 0);
  56267. }
  56268. /**
  56269. * @param {number} value
  56270. * @param {module:echarts/coord/Axis} axis
  56271. * @param {module:echarts/model/Global} ecModel
  56272. * @param {Object} opt
  56273. * @param {Array.<Object>} seriesDataIndices
  56274. * @param {number|string} opt.precision 'auto' or a number
  56275. * @param {string|Function} opt.formatter label formatter
  56276. */
  56277. function getValueLabel(value, axis, ecModel, seriesDataIndices, opt) {
  56278. value = axis.scale.parse(value);
  56279. var text = axis.scale.getLabel(
  56280. // If `precision` is set, width can be fixed (like '12.00500'), which
  56281. // helps to debounce when when moving label.
  56282. value, {precision: opt.precision}
  56283. );
  56284. var formatter = opt.formatter;
  56285. if (formatter) {
  56286. var params = {
  56287. value: getAxisRawValue(axis, value),
  56288. seriesData: []
  56289. };
  56290. each$1(seriesDataIndices, function (idxItem) {
  56291. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  56292. var dataIndex = idxItem.dataIndexInside;
  56293. var dataParams = series && series.getDataParams(dataIndex);
  56294. dataParams && params.seriesData.push(dataParams);
  56295. });
  56296. if (isString(formatter)) {
  56297. text = formatter.replace('{value}', text);
  56298. }
  56299. else if (isFunction$1(formatter)) {
  56300. text = formatter(params);
  56301. }
  56302. }
  56303. return text;
  56304. }
  56305. /**
  56306. * @param {module:echarts/coord/Axis} axis
  56307. * @param {number} value
  56308. * @param {Object} layoutInfo {
  56309. * rotation, position, labelOffset, labelDirection, labelMargin
  56310. * }
  56311. */
  56312. function getTransformedPosition (axis, value, layoutInfo) {
  56313. var transform = create$1();
  56314. rotate(transform, transform, layoutInfo.rotation);
  56315. translate(transform, transform, layoutInfo.position);
  56316. return applyTransform$1([
  56317. axis.dataToCoord(value),
  56318. (layoutInfo.labelOffset || 0)
  56319. + (layoutInfo.labelDirection || 1) * (layoutInfo.labelMargin || 0)
  56320. ], transform);
  56321. }
  56322. function buildCartesianSingleLabelElOption(
  56323. value, elOption, layoutInfo, axisModel, axisPointerModel, api
  56324. ) {
  56325. var textLayout = AxisBuilder.innerTextLayout(
  56326. layoutInfo.rotation, 0, layoutInfo.labelDirection
  56327. );
  56328. layoutInfo.labelMargin = axisPointerModel.get('label.margin');
  56329. buildLabelElOption(elOption, axisModel, axisPointerModel, api, {
  56330. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  56331. align: textLayout.textAlign,
  56332. verticalAlign: textLayout.textVerticalAlign
  56333. });
  56334. }
  56335. /**
  56336. * @param {Array.<number>} p1
  56337. * @param {Array.<number>} p2
  56338. * @param {number} [xDimIndex=0] or 1
  56339. */
  56340. function makeLineShape(p1, p2, xDimIndex) {
  56341. xDimIndex = xDimIndex || 0;
  56342. return {
  56343. x1: p1[xDimIndex],
  56344. y1: p1[1 - xDimIndex],
  56345. x2: p2[xDimIndex],
  56346. y2: p2[1 - xDimIndex]
  56347. };
  56348. }
  56349. /**
  56350. * @param {Array.<number>} xy
  56351. * @param {Array.<number>} wh
  56352. * @param {number} [xDimIndex=0] or 1
  56353. */
  56354. function makeRectShape(xy, wh, xDimIndex) {
  56355. xDimIndex = xDimIndex || 0;
  56356. return {
  56357. x: xy[xDimIndex],
  56358. y: xy[1 - xDimIndex],
  56359. width: wh[xDimIndex],
  56360. height: wh[1 - xDimIndex]
  56361. };
  56362. }
  56363. function makeSectorShape(cx, cy, r0, r, startAngle, endAngle) {
  56364. return {
  56365. cx: cx,
  56366. cy: cy,
  56367. r0: r0,
  56368. r: r,
  56369. startAngle: startAngle,
  56370. endAngle: endAngle,
  56371. clockwise: true
  56372. };
  56373. }
  56374. /*
  56375. * Licensed to the Apache Software Foundation (ASF) under one
  56376. * or more contributor license agreements. See the NOTICE file
  56377. * distributed with this work for additional information
  56378. * regarding copyright ownership. The ASF licenses this file
  56379. * to you under the Apache License, Version 2.0 (the
  56380. * "License"); you may not use this file except in compliance
  56381. * with the License. You may obtain a copy of the License at
  56382. *
  56383. * http://www.apache.org/licenses/LICENSE-2.0
  56384. *
  56385. * Unless required by applicable law or agreed to in writing,
  56386. * software distributed under the License is distributed on an
  56387. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56388. * KIND, either express or implied. See the License for the
  56389. * specific language governing permissions and limitations
  56390. * under the License.
  56391. */
  56392. var CartesianAxisPointer = BaseAxisPointer.extend({
  56393. /**
  56394. * @override
  56395. */
  56396. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  56397. var axis = axisModel.axis;
  56398. var grid = axis.grid;
  56399. var axisPointerType = axisPointerModel.get('type');
  56400. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  56401. var pixelValue = axis.toGlobalCoord(axis.dataToCoord(value, true));
  56402. if (axisPointerType && axisPointerType !== 'none') {
  56403. var elStyle = buildElStyle(axisPointerModel);
  56404. var pointerOption = pointerShapeBuilder[axisPointerType](
  56405. axis, pixelValue, otherExtent, elStyle
  56406. );
  56407. pointerOption.style = elStyle;
  56408. elOption.graphicKey = pointerOption.type;
  56409. elOption.pointer = pointerOption;
  56410. }
  56411. var layoutInfo = layout$1(grid.model, axisModel);
  56412. buildCartesianSingleLabelElOption(
  56413. value, elOption, layoutInfo, axisModel, axisPointerModel, api
  56414. );
  56415. },
  56416. /**
  56417. * @override
  56418. */
  56419. getHandleTransform: function (value, axisModel, axisPointerModel) {
  56420. var layoutInfo = layout$1(axisModel.axis.grid.model, axisModel, {
  56421. labelInside: false
  56422. });
  56423. layoutInfo.labelMargin = axisPointerModel.get('handle.margin');
  56424. return {
  56425. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  56426. rotation: layoutInfo.rotation + (layoutInfo.labelDirection < 0 ? Math.PI : 0)
  56427. };
  56428. },
  56429. /**
  56430. * @override
  56431. */
  56432. updateHandleTransform: function (transform, delta, axisModel, axisPointerModel) {
  56433. var axis = axisModel.axis;
  56434. var grid = axis.grid;
  56435. var axisExtent = axis.getGlobalExtent(true);
  56436. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  56437. var dimIndex = axis.dim === 'x' ? 0 : 1;
  56438. var currPosition = transform.position;
  56439. currPosition[dimIndex] += delta[dimIndex];
  56440. currPosition[dimIndex] = Math.min(axisExtent[1], currPosition[dimIndex]);
  56441. currPosition[dimIndex] = Math.max(axisExtent[0], currPosition[dimIndex]);
  56442. var cursorOtherValue = (otherExtent[1] + otherExtent[0]) / 2;
  56443. var cursorPoint = [cursorOtherValue, cursorOtherValue];
  56444. cursorPoint[dimIndex] = currPosition[dimIndex];
  56445. // Make tooltip do not overlap axisPointer and in the middle of the grid.
  56446. var tooltipOptions = [{verticalAlign: 'middle'}, {align: 'center'}];
  56447. return {
  56448. position: currPosition,
  56449. rotation: transform.rotation,
  56450. cursorPoint: cursorPoint,
  56451. tooltipOption: tooltipOptions[dimIndex]
  56452. };
  56453. }
  56454. });
  56455. function getCartesian(grid, axis) {
  56456. var opt = {};
  56457. opt[axis.dim + 'AxisIndex'] = axis.index;
  56458. return grid.getCartesian(opt);
  56459. }
  56460. var pointerShapeBuilder = {
  56461. line: function (axis, pixelValue, otherExtent, elStyle) {
  56462. var targetShape = makeLineShape(
  56463. [pixelValue, otherExtent[0]],
  56464. [pixelValue, otherExtent[1]],
  56465. getAxisDimIndex(axis)
  56466. );
  56467. subPixelOptimizeLine({
  56468. shape: targetShape,
  56469. style: elStyle
  56470. });
  56471. return {
  56472. type: 'Line',
  56473. shape: targetShape
  56474. };
  56475. },
  56476. shadow: function (axis, pixelValue, otherExtent, elStyle) {
  56477. var bandWidth = Math.max(1, axis.getBandWidth());
  56478. var span = otherExtent[1] - otherExtent[0];
  56479. return {
  56480. type: 'Rect',
  56481. shape: makeRectShape(
  56482. [pixelValue - bandWidth / 2, otherExtent[0]],
  56483. [bandWidth, span],
  56484. getAxisDimIndex(axis)
  56485. )
  56486. };
  56487. }
  56488. };
  56489. function getAxisDimIndex(axis) {
  56490. return axis.dim === 'x' ? 0 : 1;
  56491. }
  56492. AxisView.registerAxisPointerClass('CartesianAxisPointer', CartesianAxisPointer);
  56493. /*
  56494. * Licensed to the Apache Software Foundation (ASF) under one
  56495. * or more contributor license agreements. See the NOTICE file
  56496. * distributed with this work for additional information
  56497. * regarding copyright ownership. The ASF licenses this file
  56498. * to you under the Apache License, Version 2.0 (the
  56499. * "License"); you may not use this file except in compliance
  56500. * with the License. You may obtain a copy of the License at
  56501. *
  56502. * http://www.apache.org/licenses/LICENSE-2.0
  56503. *
  56504. * Unless required by applicable law or agreed to in writing,
  56505. * software distributed under the License is distributed on an
  56506. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56507. * KIND, either express or implied. See the License for the
  56508. * specific language governing permissions and limitations
  56509. * under the License.
  56510. */
  56511. // CartesianAxisPointer is not supposed to be required here. But consider
  56512. // echarts.simple.js and online build tooltip, which only require gridSimple,
  56513. // CartesianAxisPointer should be able to required somewhere.
  56514. registerPreprocessor(function (option) {
  56515. // Always has a global axisPointerModel for default setting.
  56516. if (option) {
  56517. (!option.axisPointer || option.axisPointer.length === 0)
  56518. && (option.axisPointer = {});
  56519. var link = option.axisPointer.link;
  56520. // Normalize to array to avoid object mergin. But if link
  56521. // is not set, remain null/undefined, otherwise it will
  56522. // override existent link setting.
  56523. if (link && !isArray(link)) {
  56524. option.axisPointer.link = [link];
  56525. }
  56526. }
  56527. });
  56528. // This process should proformed after coordinate systems created
  56529. // and series data processed. So put it on statistic processing stage.
  56530. registerProcessor(PRIORITY.PROCESSOR.STATISTIC, function (ecModel, api) {
  56531. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  56532. // allAxesInfo should be updated when setOption performed.
  56533. ecModel.getComponent('axisPointer').coordSysAxesInfo
  56534. = collect(ecModel, api);
  56535. });
  56536. // Broadcast to all views.
  56537. registerAction({
  56538. type: 'updateAxisPointer',
  56539. event: 'updateAxisPointer',
  56540. update: ':updateAxisPointer'
  56541. }, axisTrigger);
  56542. /*
  56543. * Licensed to the Apache Software Foundation (ASF) under one
  56544. * or more contributor license agreements. See the NOTICE file
  56545. * distributed with this work for additional information
  56546. * regarding copyright ownership. The ASF licenses this file
  56547. * to you under the Apache License, Version 2.0 (the
  56548. * "License"); you may not use this file except in compliance
  56549. * with the License. You may obtain a copy of the License at
  56550. *
  56551. * http://www.apache.org/licenses/LICENSE-2.0
  56552. *
  56553. * Unless required by applicable law or agreed to in writing,
  56554. * software distributed under the License is distributed on an
  56555. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56556. * KIND, either express or implied. See the License for the
  56557. * specific language governing permissions and limitations
  56558. * under the License.
  56559. */
  56560. var XY = ['x', 'y'];
  56561. var WH = ['width', 'height'];
  56562. var SingleAxisPointer = BaseAxisPointer.extend({
  56563. /**
  56564. * @override
  56565. */
  56566. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  56567. var axis = axisModel.axis;
  56568. var coordSys = axis.coordinateSystem;
  56569. var otherExtent = getGlobalExtent(coordSys, 1 - getPointDimIndex(axis));
  56570. var pixelValue = coordSys.dataToPoint(value)[0];
  56571. var axisPointerType = axisPointerModel.get('type');
  56572. if (axisPointerType && axisPointerType !== 'none') {
  56573. var elStyle = buildElStyle(axisPointerModel);
  56574. var pointerOption = pointerShapeBuilder$1[axisPointerType](
  56575. axis, pixelValue, otherExtent, elStyle
  56576. );
  56577. pointerOption.style = elStyle;
  56578. elOption.graphicKey = pointerOption.type;
  56579. elOption.pointer = pointerOption;
  56580. }
  56581. var layoutInfo = layout$2(axisModel);
  56582. buildCartesianSingleLabelElOption(
  56583. value, elOption, layoutInfo, axisModel, axisPointerModel, api
  56584. );
  56585. },
  56586. /**
  56587. * @override
  56588. */
  56589. getHandleTransform: function (value, axisModel, axisPointerModel) {
  56590. var layoutInfo = layout$2(axisModel, {labelInside: false});
  56591. layoutInfo.labelMargin = axisPointerModel.get('handle.margin');
  56592. return {
  56593. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  56594. rotation: layoutInfo.rotation + (layoutInfo.labelDirection < 0 ? Math.PI : 0)
  56595. };
  56596. },
  56597. /**
  56598. * @override
  56599. */
  56600. updateHandleTransform: function (transform, delta, axisModel, axisPointerModel) {
  56601. var axis = axisModel.axis;
  56602. var coordSys = axis.coordinateSystem;
  56603. var dimIndex = getPointDimIndex(axis);
  56604. var axisExtent = getGlobalExtent(coordSys, dimIndex);
  56605. var currPosition = transform.position;
  56606. currPosition[dimIndex] += delta[dimIndex];
  56607. currPosition[dimIndex] = Math.min(axisExtent[1], currPosition[dimIndex]);
  56608. currPosition[dimIndex] = Math.max(axisExtent[0], currPosition[dimIndex]);
  56609. var otherExtent = getGlobalExtent(coordSys, 1 - dimIndex);
  56610. var cursorOtherValue = (otherExtent[1] + otherExtent[0]) / 2;
  56611. var cursorPoint = [cursorOtherValue, cursorOtherValue];
  56612. cursorPoint[dimIndex] = currPosition[dimIndex];
  56613. return {
  56614. position: currPosition,
  56615. rotation: transform.rotation,
  56616. cursorPoint: cursorPoint,
  56617. tooltipOption: {
  56618. verticalAlign: 'middle'
  56619. }
  56620. };
  56621. }
  56622. });
  56623. var pointerShapeBuilder$1 = {
  56624. line: function (axis, pixelValue, otherExtent, elStyle) {
  56625. var targetShape = makeLineShape(
  56626. [pixelValue, otherExtent[0]],
  56627. [pixelValue, otherExtent[1]],
  56628. getPointDimIndex(axis)
  56629. );
  56630. subPixelOptimizeLine({
  56631. shape: targetShape,
  56632. style: elStyle
  56633. });
  56634. return {
  56635. type: 'Line',
  56636. shape: targetShape
  56637. };
  56638. },
  56639. shadow: function (axis, pixelValue, otherExtent, elStyle) {
  56640. var bandWidth = axis.getBandWidth();
  56641. var span = otherExtent[1] - otherExtent[0];
  56642. return {
  56643. type: 'Rect',
  56644. shape: makeRectShape(
  56645. [pixelValue - bandWidth / 2, otherExtent[0]],
  56646. [bandWidth, span],
  56647. getPointDimIndex(axis)
  56648. )
  56649. };
  56650. }
  56651. };
  56652. function getPointDimIndex(axis) {
  56653. return axis.isHorizontal() ? 0 : 1;
  56654. }
  56655. function getGlobalExtent(coordSys, dimIndex) {
  56656. var rect = coordSys.getRect();
  56657. return [rect[XY[dimIndex]], rect[XY[dimIndex]] + rect[WH[dimIndex]]];
  56658. }
  56659. AxisView.registerAxisPointerClass('SingleAxisPointer', SingleAxisPointer);
  56660. /*
  56661. * Licensed to the Apache Software Foundation (ASF) under one
  56662. * or more contributor license agreements. See the NOTICE file
  56663. * distributed with this work for additional information
  56664. * regarding copyright ownership. The ASF licenses this file
  56665. * to you under the Apache License, Version 2.0 (the
  56666. * "License"); you may not use this file except in compliance
  56667. * with the License. You may obtain a copy of the License at
  56668. *
  56669. * http://www.apache.org/licenses/LICENSE-2.0
  56670. *
  56671. * Unless required by applicable law or agreed to in writing,
  56672. * software distributed under the License is distributed on an
  56673. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56674. * KIND, either express or implied. See the License for the
  56675. * specific language governing permissions and limitations
  56676. * under the License.
  56677. */
  56678. extendComponentView({
  56679. type: 'single'
  56680. });
  56681. /*
  56682. * Licensed to the Apache Software Foundation (ASF) under one
  56683. * or more contributor license agreements. See the NOTICE file
  56684. * distributed with this work for additional information
  56685. * regarding copyright ownership. The ASF licenses this file
  56686. * to you under the Apache License, Version 2.0 (the
  56687. * "License"); you may not use this file except in compliance
  56688. * with the License. You may obtain a copy of the License at
  56689. *
  56690. * http://www.apache.org/licenses/LICENSE-2.0
  56691. *
  56692. * Unless required by applicable law or agreed to in writing,
  56693. * software distributed under the License is distributed on an
  56694. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56695. * KIND, either express or implied. See the License for the
  56696. * specific language governing permissions and limitations
  56697. * under the License.
  56698. */
  56699. /**
  56700. * @file Define the themeRiver view's series model
  56701. * @author Deqing Li(annong035@gmail.com)
  56702. */
  56703. var DATA_NAME_INDEX = 2;
  56704. var ThemeRiverSeries = SeriesModel.extend({
  56705. type: 'series.themeRiver',
  56706. dependencies: ['singleAxis'],
  56707. /**
  56708. * @readOnly
  56709. * @type {module:zrender/core/util#HashMap}
  56710. */
  56711. nameMap: null,
  56712. /**
  56713. * @override
  56714. */
  56715. init: function (option) {
  56716. ThemeRiverSeries.superApply(this, 'init', arguments);
  56717. // Put this function here is for the sake of consistency of code style.
  56718. // Enable legend selection for each data item
  56719. // Use a function instead of direct access because data reference may changed
  56720. this.legendDataProvider = function () {
  56721. return this.getRawData();
  56722. };
  56723. },
  56724. /**
  56725. * If there is no value of a certain point in the time for some event,set it value to 0.
  56726. *
  56727. * @param {Array} data initial data in the option
  56728. * @return {Array}
  56729. */
  56730. fixData: function (data) {
  56731. var rawDataLength = data.length;
  56732. // grouped data by name
  56733. var dataByName = nest()
  56734. .key(function (dataItem) {
  56735. return dataItem[2];
  56736. })
  56737. .entries(data);
  56738. // data group in each layer
  56739. var layData = map(dataByName, function (d) {
  56740. return {
  56741. name: d.key,
  56742. dataList: d.values
  56743. };
  56744. });
  56745. var layerNum = layData.length;
  56746. var largestLayer = -1;
  56747. var index = -1;
  56748. for (var i = 0; i < layerNum; ++i) {
  56749. var len = layData[i].dataList.length;
  56750. if (len > largestLayer) {
  56751. largestLayer = len;
  56752. index = i;
  56753. }
  56754. }
  56755. for (var k = 0; k < layerNum; ++k) {
  56756. if (k === index) {
  56757. continue;
  56758. }
  56759. var name = layData[k].name;
  56760. for (var j = 0; j < largestLayer; ++j) {
  56761. var timeValue = layData[index].dataList[j][0];
  56762. var length = layData[k].dataList.length;
  56763. var keyIndex = -1;
  56764. for (var l = 0; l < length; ++l) {
  56765. var value = layData[k].dataList[l][0];
  56766. if (value === timeValue) {
  56767. keyIndex = l;
  56768. break;
  56769. }
  56770. }
  56771. if (keyIndex === -1) {
  56772. data[rawDataLength] = [];
  56773. data[rawDataLength][0] = timeValue;
  56774. data[rawDataLength][1] = 0;
  56775. data[rawDataLength][2] = name;
  56776. rawDataLength++;
  56777. }
  56778. }
  56779. }
  56780. return data;
  56781. },
  56782. /**
  56783. * @override
  56784. * @param {Object} option the initial option that user gived
  56785. * @param {module:echarts/model/Model} ecModel the model object for themeRiver option
  56786. * @return {module:echarts/data/List}
  56787. */
  56788. getInitialData: function (option, ecModel) {
  56789. var singleAxisModel = ecModel.queryComponents({
  56790. mainType: 'singleAxis',
  56791. index: this.get('singleAxisIndex'),
  56792. id: this.get('singleAxisId')
  56793. })[0];
  56794. var axisType = singleAxisModel.get('type');
  56795. // filter the data item with the value of label is undefined
  56796. var filterData = filter(option.data, function (dataItem) {
  56797. return dataItem[2] !== undefined;
  56798. });
  56799. // ??? TODO design a stage to transfer data for themeRiver and lines?
  56800. var data = this.fixData(filterData || []);
  56801. var nameList = [];
  56802. var nameMap = this.nameMap = createHashMap();
  56803. var count = 0;
  56804. for (var i = 0; i < data.length; ++i) {
  56805. nameList.push(data[i][DATA_NAME_INDEX]);
  56806. if (!nameMap.get(data[i][DATA_NAME_INDEX])) {
  56807. nameMap.set(data[i][DATA_NAME_INDEX], count);
  56808. count++;
  56809. }
  56810. }
  56811. var dimensionsInfo = createDimensions(data, {
  56812. coordDimensions: ['single'],
  56813. dimensionsDefine: [
  56814. {
  56815. name: 'time',
  56816. type: getDimensionTypeByAxis(axisType)
  56817. },
  56818. {
  56819. name: 'value',
  56820. type: 'float'
  56821. },
  56822. {
  56823. name: 'name',
  56824. type: 'ordinal'
  56825. }
  56826. ],
  56827. encodeDefine: {
  56828. single: 0,
  56829. value: 1,
  56830. itemName: 2
  56831. }
  56832. });
  56833. var list = new List(dimensionsInfo, this);
  56834. list.initData(data);
  56835. return list;
  56836. },
  56837. /**
  56838. * The raw data is divided into multiple layers and each layer
  56839. * has same name.
  56840. *
  56841. * @return {Array.<Array.<number>>}
  56842. */
  56843. getLayerSeries: function () {
  56844. var data = this.getData();
  56845. var lenCount = data.count();
  56846. var indexArr = [];
  56847. for (var i = 0; i < lenCount; ++i) {
  56848. indexArr[i] = i;
  56849. }
  56850. // data group by name
  56851. var dataByName = nest()
  56852. .key(function (index) {
  56853. return data.get('name', index);
  56854. })
  56855. .entries(indexArr);
  56856. var layerSeries = map(dataByName, function (d) {
  56857. return {
  56858. name: d.key,
  56859. indices: d.values
  56860. };
  56861. });
  56862. var timeDim = data.mapDimension('single');
  56863. for (var j = 0; j < layerSeries.length; ++j) {
  56864. layerSeries[j].indices.sort(comparer);
  56865. }
  56866. function comparer(index1, index2) {
  56867. return data.get(timeDim, index1) - data.get(timeDim, index2);
  56868. }
  56869. return layerSeries;
  56870. },
  56871. /**
  56872. * Get data indices for show tooltip content
  56873. *
  56874. * @param {Array.<string>|string} dim single coordinate dimension
  56875. * @param {number} value axis value
  56876. * @param {module:echarts/coord/single/SingleAxis} baseAxis single Axis used
  56877. * the themeRiver.
  56878. * @return {Object} {dataIndices, nestestValue}
  56879. */
  56880. getAxisTooltipData: function (dim, value, baseAxis) {
  56881. if (!isArray(dim)) {
  56882. dim = dim ? [dim] : [];
  56883. }
  56884. var data = this.getData();
  56885. var layerSeries = this.getLayerSeries();
  56886. var indices = [];
  56887. var layerNum = layerSeries.length;
  56888. var nestestValue;
  56889. for (var i = 0; i < layerNum; ++i) {
  56890. var minDist = Number.MAX_VALUE;
  56891. var nearestIdx = -1;
  56892. var pointNum = layerSeries[i].indices.length;
  56893. for (var j = 0; j < pointNum; ++j) {
  56894. var theValue = data.get(dim[0], layerSeries[i].indices[j]);
  56895. var dist = Math.abs(theValue - value);
  56896. if (dist <= minDist) {
  56897. nestestValue = theValue;
  56898. minDist = dist;
  56899. nearestIdx = layerSeries[i].indices[j];
  56900. }
  56901. }
  56902. indices.push(nearestIdx);
  56903. }
  56904. return {dataIndices: indices, nestestValue: nestestValue};
  56905. },
  56906. /**
  56907. * @override
  56908. * @param {number} dataIndex index of data
  56909. */
  56910. formatTooltip: function (dataIndex) {
  56911. var data = this.getData();
  56912. var htmlName = data.getName(dataIndex);
  56913. var htmlValue = data.get(data.mapDimension('value'), dataIndex);
  56914. if (isNaN(htmlValue) || htmlValue == null) {
  56915. htmlValue = '-';
  56916. }
  56917. return encodeHTML(htmlName + ' : ' + htmlValue);
  56918. },
  56919. defaultOption: {
  56920. zlevel: 0,
  56921. z: 2,
  56922. coordinateSystem: 'singleAxis',
  56923. // gap in axis's orthogonal orientation
  56924. boundaryGap: ['10%', '10%'],
  56925. // legendHoverLink: true,
  56926. singleAxisIndex: 0,
  56927. animationEasing: 'linear',
  56928. label: {
  56929. margin: 4,
  56930. show: true,
  56931. position: 'left',
  56932. color: '#000',
  56933. fontSize: 11
  56934. },
  56935. emphasis: {
  56936. label: {
  56937. show: true
  56938. }
  56939. }
  56940. }
  56941. });
  56942. /*
  56943. * Licensed to the Apache Software Foundation (ASF) under one
  56944. * or more contributor license agreements. See the NOTICE file
  56945. * distributed with this work for additional information
  56946. * regarding copyright ownership. The ASF licenses this file
  56947. * to you under the Apache License, Version 2.0 (the
  56948. * "License"); you may not use this file except in compliance
  56949. * with the License. You may obtain a copy of the License at
  56950. *
  56951. * http://www.apache.org/licenses/LICENSE-2.0
  56952. *
  56953. * Unless required by applicable law or agreed to in writing,
  56954. * software distributed under the License is distributed on an
  56955. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56956. * KIND, either express or implied. See the License for the
  56957. * specific language governing permissions and limitations
  56958. * under the License.
  56959. */
  56960. /**
  56961. * @file The file used to draw themeRiver view
  56962. * @author Deqing Li(annong035@gmail.com)
  56963. */
  56964. extendChartView({
  56965. type: 'themeRiver',
  56966. init: function () {
  56967. this._layers = [];
  56968. },
  56969. render: function (seriesModel, ecModel, api) {
  56970. var data = seriesModel.getData();
  56971. var group = this.group;
  56972. var layerSeries = seriesModel.getLayerSeries();
  56973. var layoutInfo = data.getLayout('layoutInfo');
  56974. var rect = layoutInfo.rect;
  56975. var boundaryGap = layoutInfo.boundaryGap;
  56976. group.attr('position', [0, rect.y + boundaryGap[0]]);
  56977. function keyGetter(item) {
  56978. return item.name;
  56979. }
  56980. var dataDiffer = new DataDiffer(
  56981. this._layersSeries || [], layerSeries,
  56982. keyGetter, keyGetter
  56983. );
  56984. var newLayersGroups = {};
  56985. dataDiffer
  56986. .add(bind(process, this, 'add'))
  56987. .update(bind(process, this, 'update'))
  56988. .remove(bind(process, this, 'remove'))
  56989. .execute();
  56990. function process(status, idx, oldIdx) {
  56991. var oldLayersGroups = this._layers;
  56992. if (status === 'remove') {
  56993. group.remove(oldLayersGroups[idx]);
  56994. return;
  56995. }
  56996. var points0 = [];
  56997. var points1 = [];
  56998. var color;
  56999. var indices = layerSeries[idx].indices;
  57000. for (var j = 0; j < indices.length; j++) {
  57001. var layout = data.getItemLayout(indices[j]);
  57002. var x = layout.x;
  57003. var y0 = layout.y0;
  57004. var y = layout.y;
  57005. points0.push([x, y0]);
  57006. points1.push([x, y0 + y]);
  57007. color = data.getItemVisual(indices[j], 'color');
  57008. }
  57009. var polygon;
  57010. var text;
  57011. var textLayout = data.getItemLayout(indices[0]);
  57012. var itemModel = data.getItemModel(indices[j - 1]);
  57013. var labelModel = itemModel.getModel('label');
  57014. var margin = labelModel.get('margin');
  57015. if (status === 'add') {
  57016. var layerGroup = newLayersGroups[idx] = new Group();
  57017. polygon = new Polygon$1({
  57018. shape: {
  57019. points: points0,
  57020. stackedOnPoints: points1,
  57021. smooth: 0.4,
  57022. stackedOnSmooth: 0.4,
  57023. smoothConstraint: false
  57024. },
  57025. z2: 0
  57026. });
  57027. text = new Text({
  57028. style: {
  57029. x: textLayout.x - margin,
  57030. y: textLayout.y0 + textLayout.y / 2
  57031. }
  57032. });
  57033. layerGroup.add(polygon);
  57034. layerGroup.add(text);
  57035. group.add(layerGroup);
  57036. polygon.setClipPath(createGridClipShape$3(polygon.getBoundingRect(), seriesModel, function () {
  57037. polygon.removeClipPath();
  57038. }));
  57039. }
  57040. else {
  57041. var layerGroup = oldLayersGroups[oldIdx];
  57042. polygon = layerGroup.childAt(0);
  57043. text = layerGroup.childAt(1);
  57044. group.add(layerGroup);
  57045. newLayersGroups[idx] = layerGroup;
  57046. updateProps(polygon, {
  57047. shape: {
  57048. points: points0,
  57049. stackedOnPoints: points1
  57050. }
  57051. }, seriesModel);
  57052. updateProps(text, {
  57053. style: {
  57054. x: textLayout.x - margin,
  57055. y: textLayout.y0 + textLayout.y / 2
  57056. }
  57057. }, seriesModel);
  57058. }
  57059. var hoverItemStyleModel = itemModel.getModel('emphasis.itemStyle');
  57060. var itemStyleModel = itemModel.getModel('itemStyle');
  57061. setTextStyle(text.style, labelModel, {
  57062. text: labelModel.get('show')
  57063. ? seriesModel.getFormattedLabel(indices[j - 1], 'normal')
  57064. || data.getName(indices[j - 1])
  57065. : null,
  57066. textVerticalAlign: 'middle'
  57067. });
  57068. polygon.setStyle(extend({
  57069. fill: color
  57070. }, itemStyleModel.getItemStyle(['color'])));
  57071. setHoverStyle(polygon, hoverItemStyleModel.getItemStyle());
  57072. }
  57073. this._layersSeries = layerSeries;
  57074. this._layers = newLayersGroups;
  57075. },
  57076. dispose: function () {}
  57077. });
  57078. // add animation to the view
  57079. function createGridClipShape$3(rect, seriesModel, cb) {
  57080. var rectEl = new Rect({
  57081. shape: {
  57082. x: rect.x - 10,
  57083. y: rect.y - 10,
  57084. width: 0,
  57085. height: rect.height + 20
  57086. }
  57087. });
  57088. initProps(rectEl, {
  57089. shape: {
  57090. width: rect.width + 20,
  57091. height: rect.height + 20
  57092. }
  57093. }, seriesModel, cb);
  57094. return rectEl;
  57095. }
  57096. /*
  57097. * Licensed to the Apache Software Foundation (ASF) under one
  57098. * or more contributor license agreements. See the NOTICE file
  57099. * distributed with this work for additional information
  57100. * regarding copyright ownership. The ASF licenses this file
  57101. * to you under the Apache License, Version 2.0 (the
  57102. * "License"); you may not use this file except in compliance
  57103. * with the License. You may obtain a copy of the License at
  57104. *
  57105. * http://www.apache.org/licenses/LICENSE-2.0
  57106. *
  57107. * Unless required by applicable law or agreed to in writing,
  57108. * software distributed under the License is distributed on an
  57109. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57110. * KIND, either express or implied. See the License for the
  57111. * specific language governing permissions and limitations
  57112. * under the License.
  57113. */
  57114. /**
  57115. * @file Using layout algorithm transform the raw data to layout information.
  57116. * @author Deqing Li(annong035@gmail.com)
  57117. */
  57118. var themeRiverLayout = function (ecModel, api) {
  57119. ecModel.eachSeriesByType('themeRiver', function (seriesModel) {
  57120. var data = seriesModel.getData();
  57121. var single = seriesModel.coordinateSystem;
  57122. var layoutInfo = {};
  57123. // use the axis boundingRect for view
  57124. var rect = single.getRect();
  57125. layoutInfo.rect = rect;
  57126. var boundaryGap = seriesModel.get('boundaryGap');
  57127. var axis = single.getAxis();
  57128. layoutInfo.boundaryGap = boundaryGap;
  57129. if (axis.orient === 'horizontal') {
  57130. boundaryGap[0] = parsePercent$1(boundaryGap[0], rect.height);
  57131. boundaryGap[1] = parsePercent$1(boundaryGap[1], rect.height);
  57132. var height = rect.height - boundaryGap[0] - boundaryGap[1];
  57133. themeRiverLayout$1(data, seriesModel, height);
  57134. }
  57135. else {
  57136. boundaryGap[0] = parsePercent$1(boundaryGap[0], rect.width);
  57137. boundaryGap[1] = parsePercent$1(boundaryGap[1], rect.width);
  57138. var width = rect.width - boundaryGap[0] - boundaryGap[1];
  57139. themeRiverLayout$1(data, seriesModel, width);
  57140. }
  57141. data.setLayout('layoutInfo', layoutInfo);
  57142. });
  57143. };
  57144. /**
  57145. * The layout information about themeriver
  57146. *
  57147. * @param {module:echarts/data/List} data data in the series
  57148. * @param {module:echarts/model/Series} seriesModel the model object of themeRiver series
  57149. * @param {number} height value used to compute every series height
  57150. */
  57151. function themeRiverLayout$1(data, seriesModel, height) {
  57152. if (!data.count()) {
  57153. return;
  57154. }
  57155. var coordSys = seriesModel.coordinateSystem;
  57156. // the data in each layer are organized into a series.
  57157. var layerSeries = seriesModel.getLayerSeries();
  57158. // the points in each layer.
  57159. var timeDim = data.mapDimension('single');
  57160. var valueDim = data.mapDimension('value');
  57161. var layerPoints = map(layerSeries, function (singleLayer) {
  57162. return map(singleLayer.indices, function (idx) {
  57163. var pt = coordSys.dataToPoint(data.get(timeDim, idx));
  57164. pt[1] = data.get(valueDim, idx);
  57165. return pt;
  57166. });
  57167. });
  57168. var base = computeBaseline(layerPoints);
  57169. var baseLine = base.y0;
  57170. var ky = height / base.max;
  57171. // set layout information for each item.
  57172. var n = layerSeries.length;
  57173. var m = layerSeries[0].indices.length;
  57174. var baseY0;
  57175. for (var j = 0; j < m; ++j) {
  57176. baseY0 = baseLine[j] * ky;
  57177. data.setItemLayout(layerSeries[0].indices[j], {
  57178. layerIndex: 0,
  57179. x: layerPoints[0][j][0],
  57180. y0: baseY0,
  57181. y: layerPoints[0][j][1] * ky
  57182. });
  57183. for (var i = 1; i < n; ++i) {
  57184. baseY0 += layerPoints[i - 1][j][1] * ky;
  57185. data.setItemLayout(layerSeries[i].indices[j], {
  57186. layerIndex: i,
  57187. x: layerPoints[i][j][0],
  57188. y0: baseY0,
  57189. y: layerPoints[i][j][1] * ky
  57190. });
  57191. }
  57192. }
  57193. }
  57194. /**
  57195. * Compute the baseLine of the rawdata
  57196. * Inspired by Lee Byron's paper Stacked Graphs - Geometry & Aesthetics
  57197. *
  57198. * @param {Array.<Array>} data the points in each layer
  57199. * @return {Object}
  57200. */
  57201. function computeBaseline(data) {
  57202. var layerNum = data.length;
  57203. var pointNum = data[0].length;
  57204. var sums = [];
  57205. var y0 = [];
  57206. var max = 0;
  57207. var temp;
  57208. var base = {};
  57209. for (var i = 0; i < pointNum; ++i) {
  57210. for (var j = 0, temp = 0; j < layerNum; ++j) {
  57211. temp += data[j][i][1];
  57212. }
  57213. if (temp > max) {
  57214. max = temp;
  57215. }
  57216. sums.push(temp);
  57217. }
  57218. for (var k = 0; k < pointNum; ++k) {
  57219. y0[k] = (max - sums[k]) / 2;
  57220. }
  57221. max = 0;
  57222. for (var l = 0; l < pointNum; ++l) {
  57223. var sum = sums[l] + y0[l];
  57224. if (sum > max) {
  57225. max = sum;
  57226. }
  57227. }
  57228. base.y0 = y0;
  57229. base.max = max;
  57230. return base;
  57231. }
  57232. /*
  57233. * Licensed to the Apache Software Foundation (ASF) under one
  57234. * or more contributor license agreements. See the NOTICE file
  57235. * distributed with this work for additional information
  57236. * regarding copyright ownership. The ASF licenses this file
  57237. * to you under the Apache License, Version 2.0 (the
  57238. * "License"); you may not use this file except in compliance
  57239. * with the License. You may obtain a copy of the License at
  57240. *
  57241. * http://www.apache.org/licenses/LICENSE-2.0
  57242. *
  57243. * Unless required by applicable law or agreed to in writing,
  57244. * software distributed under the License is distributed on an
  57245. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57246. * KIND, either express or implied. See the License for the
  57247. * specific language governing permissions and limitations
  57248. * under the License.
  57249. */
  57250. /**
  57251. * @file Visual encoding for themeRiver view
  57252. * @author Deqing Li(annong035@gmail.com)
  57253. */
  57254. var themeRiverVisual = function (ecModel) {
  57255. ecModel.eachSeriesByType('themeRiver', function (seriesModel) {
  57256. var data = seriesModel.getData();
  57257. var rawData = seriesModel.getRawData();
  57258. var colorList = seriesModel.get('color');
  57259. var idxMap = createHashMap();
  57260. data.each(function (idx) {
  57261. idxMap.set(data.getRawIndex(idx), idx);
  57262. });
  57263. rawData.each(function (rawIndex) {
  57264. var name = rawData.getName(rawIndex);
  57265. var color = colorList[(seriesModel.nameMap.get(name) - 1) % colorList.length];
  57266. rawData.setItemVisual(rawIndex, 'color', color);
  57267. var idx = idxMap.get(rawIndex);
  57268. if (idx != null) {
  57269. data.setItemVisual(idx, 'color', color);
  57270. }
  57271. });
  57272. });
  57273. };
  57274. /*
  57275. * Licensed to the Apache Software Foundation (ASF) under one
  57276. * or more contributor license agreements. See the NOTICE file
  57277. * distributed with this work for additional information
  57278. * regarding copyright ownership. The ASF licenses this file
  57279. * to you under the Apache License, Version 2.0 (the
  57280. * "License"); you may not use this file except in compliance
  57281. * with the License. You may obtain a copy of the License at
  57282. *
  57283. * http://www.apache.org/licenses/LICENSE-2.0
  57284. *
  57285. * Unless required by applicable law or agreed to in writing,
  57286. * software distributed under the License is distributed on an
  57287. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57288. * KIND, either express or implied. See the License for the
  57289. * specific language governing permissions and limitations
  57290. * under the License.
  57291. */
  57292. registerLayout(themeRiverLayout);
  57293. registerVisual(themeRiverVisual);
  57294. registerProcessor(dataFilter('themeRiver'));
  57295. /*
  57296. * Licensed to the Apache Software Foundation (ASF) under one
  57297. * or more contributor license agreements. See the NOTICE file
  57298. * distributed with this work for additional information
  57299. * regarding copyright ownership. The ASF licenses this file
  57300. * to you under the Apache License, Version 2.0 (the
  57301. * "License"); you may not use this file except in compliance
  57302. * with the License. You may obtain a copy of the License at
  57303. *
  57304. * http://www.apache.org/licenses/LICENSE-2.0
  57305. *
  57306. * Unless required by applicable law or agreed to in writing,
  57307. * software distributed under the License is distributed on an
  57308. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57309. * KIND, either express or implied. See the License for the
  57310. * specific language governing permissions and limitations
  57311. * under the License.
  57312. */
  57313. SeriesModel.extend({
  57314. type: 'series.sunburst',
  57315. /**
  57316. * @type {module:echarts/data/Tree~Node}
  57317. */
  57318. _viewRoot: null,
  57319. getInitialData: function (option, ecModel) {
  57320. // Create a virtual root.
  57321. var root = { name: option.name, children: option.data };
  57322. completeTreeValue$1(root);
  57323. var levels = option.levels || [];
  57324. // levels = option.levels = setDefault(levels, ecModel);
  57325. var treeOption = {};
  57326. treeOption.levels = levels;
  57327. // Make sure always a new tree is created when setOption,
  57328. // in TreemapView, we check whether oldTree === newTree
  57329. // to choose mappings approach among old shapes and new shapes.
  57330. return Tree.createTree(root, this, treeOption).data;
  57331. },
  57332. optionUpdated: function () {
  57333. this.resetViewRoot();
  57334. },
  57335. /*
  57336. * @override
  57337. */
  57338. getDataParams: function (dataIndex) {
  57339. var params = SeriesModel.prototype.getDataParams.apply(this, arguments);
  57340. var node = this.getData().tree.getNodeByDataIndex(dataIndex);
  57341. params.treePathInfo = wrapTreePathInfo(node, this);
  57342. return params;
  57343. },
  57344. defaultOption: {
  57345. zlevel: 0,
  57346. z: 2,
  57347. // 默认全局居中
  57348. center: ['50%', '50%'],
  57349. radius: [0, '75%'],
  57350. // 默认顺时针
  57351. clockwise: true,
  57352. startAngle: 90,
  57353. // 最小角度改为0
  57354. minAngle: 0,
  57355. percentPrecision: 2,
  57356. // If still show when all data zero.
  57357. stillShowZeroSum: true,
  57358. // Policy of highlighting pieces when hover on one
  57359. // Valid values: 'none' (for not downplay others), 'descendant',
  57360. // 'ancestor', 'self'
  57361. highlightPolicy: 'descendant',
  57362. // 'rootToNode', 'link', or false
  57363. nodeClick: 'rootToNode',
  57364. renderLabelForZeroData: false,
  57365. label: {
  57366. // could be: 'radial', 'tangential', or 'none'
  57367. rotate: 'radial',
  57368. show: true,
  57369. opacity: 1,
  57370. // 'left' is for inner side of inside, and 'right' is for outter
  57371. // side for inside
  57372. align: 'center',
  57373. position: 'inside',
  57374. distance: 5,
  57375. silent: true,
  57376. emphasis: {}
  57377. },
  57378. itemStyle: {
  57379. borderWidth: 1,
  57380. borderColor: 'white',
  57381. opacity: 1,
  57382. emphasis: {},
  57383. highlight: {
  57384. opacity: 1
  57385. },
  57386. downplay: {
  57387. opacity: 0.9
  57388. }
  57389. },
  57390. // Animation type canbe expansion, scale
  57391. animationType: 'expansion',
  57392. animationDuration: 1000,
  57393. animationDurationUpdate: 500,
  57394. animationEasing: 'cubicOut',
  57395. data: [],
  57396. levels: [],
  57397. /**
  57398. * Sort order.
  57399. *
  57400. * Valid values: 'desc', 'asc', null, or callback function.
  57401. * 'desc' and 'asc' for descend and ascendant order;
  57402. * null for not sorting;
  57403. * example of callback function:
  57404. * function(nodeA, nodeB) {
  57405. * return nodeA.getValue() - nodeB.getValue();
  57406. * }
  57407. */
  57408. sort: 'desc'
  57409. },
  57410. getViewRoot: function () {
  57411. return this._viewRoot;
  57412. },
  57413. /**
  57414. * @param {module:echarts/data/Tree~Node} [viewRoot]
  57415. */
  57416. resetViewRoot: function (viewRoot) {
  57417. viewRoot
  57418. ? (this._viewRoot = viewRoot)
  57419. : (viewRoot = this._viewRoot);
  57420. var root = this.getRawData().tree.root;
  57421. if (!viewRoot
  57422. || (viewRoot !== root && !root.contains(viewRoot))
  57423. ) {
  57424. this._viewRoot = root;
  57425. }
  57426. }
  57427. });
  57428. /**
  57429. * @param {Object} dataNode
  57430. */
  57431. function completeTreeValue$1(dataNode) {
  57432. // Postorder travel tree.
  57433. // If value of none-leaf node is not set,
  57434. // calculate it by suming up the value of all children.
  57435. var sum = 0;
  57436. each$1(dataNode.children, function (child) {
  57437. completeTreeValue$1(child);
  57438. var childValue = child.value;
  57439. isArray(childValue) && (childValue = childValue[0]);
  57440. sum += childValue;
  57441. });
  57442. var thisValue = dataNode.value;
  57443. if (isArray(thisValue)) {
  57444. thisValue = thisValue[0];
  57445. }
  57446. if (thisValue == null || isNaN(thisValue)) {
  57447. thisValue = sum;
  57448. }
  57449. // Value should not less than 0.
  57450. if (thisValue < 0) {
  57451. thisValue = 0;
  57452. }
  57453. isArray(dataNode.value)
  57454. ? (dataNode.value[0] = thisValue)
  57455. : (dataNode.value = thisValue);
  57456. }
  57457. /*
  57458. * Licensed to the Apache Software Foundation (ASF) under one
  57459. * or more contributor license agreements. See the NOTICE file
  57460. * distributed with this work for additional information
  57461. * regarding copyright ownership. The ASF licenses this file
  57462. * to you under the Apache License, Version 2.0 (the
  57463. * "License"); you may not use this file except in compliance
  57464. * with the License. You may obtain a copy of the License at
  57465. *
  57466. * http://www.apache.org/licenses/LICENSE-2.0
  57467. *
  57468. * Unless required by applicable law or agreed to in writing,
  57469. * software distributed under the License is distributed on an
  57470. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57471. * KIND, either express or implied. See the License for the
  57472. * specific language governing permissions and limitations
  57473. * under the License.
  57474. */
  57475. var NodeHighlightPolicy = {
  57476. NONE: 'none', // not downplay others
  57477. DESCENDANT: 'descendant',
  57478. ANCESTOR: 'ancestor',
  57479. SELF: 'self'
  57480. };
  57481. var DEFAULT_SECTOR_Z = 2;
  57482. var DEFAULT_TEXT_Z = 4;
  57483. /**
  57484. * Sunburstce of Sunburst including Sector, Label, LabelLine
  57485. * @constructor
  57486. * @extends {module:zrender/graphic/Group}
  57487. */
  57488. function SunburstPiece(node, seriesModel, ecModel) {
  57489. Group.call(this);
  57490. var sector = new Sector({
  57491. z2: DEFAULT_SECTOR_Z
  57492. });
  57493. sector.seriesIndex = seriesModel.seriesIndex;
  57494. var text = new Text({
  57495. z2: DEFAULT_TEXT_Z,
  57496. silent: node.getModel('label').get('silent')
  57497. });
  57498. this.add(sector);
  57499. this.add(text);
  57500. this.updateData(true, node, 'normal', seriesModel, ecModel);
  57501. // Hover to change label and labelLine
  57502. function onEmphasis() {
  57503. text.ignore = text.hoverIgnore;
  57504. }
  57505. function onNormal() {
  57506. text.ignore = text.normalIgnore;
  57507. }
  57508. this.on('emphasis', onEmphasis)
  57509. .on('normal', onNormal)
  57510. .on('mouseover', onEmphasis)
  57511. .on('mouseout', onNormal);
  57512. }
  57513. var SunburstPieceProto = SunburstPiece.prototype;
  57514. SunburstPieceProto.updateData = function (
  57515. firstCreate,
  57516. node,
  57517. state,
  57518. seriesModel,
  57519. ecModel
  57520. ) {
  57521. this.node = node;
  57522. node.piece = this;
  57523. seriesModel = seriesModel || this._seriesModel;
  57524. ecModel = ecModel || this._ecModel;
  57525. var sector = this.childAt(0);
  57526. sector.dataIndex = node.dataIndex;
  57527. var itemModel = node.getModel();
  57528. var layout = node.getLayout();
  57529. if (!layout) {
  57530. console.log(node.getLayout());
  57531. }
  57532. var sectorShape = extend({}, layout);
  57533. sectorShape.label = null;
  57534. var visualColor = getNodeColor(node, seriesModel, ecModel);
  57535. var normalStyle = itemModel.getModel('itemStyle').getItemStyle();
  57536. var style;
  57537. if (state === 'normal') {
  57538. style = normalStyle;
  57539. }
  57540. else {
  57541. var stateStyle = itemModel.getModel(state + '.itemStyle')
  57542. .getItemStyle();
  57543. style = merge(stateStyle, normalStyle);
  57544. }
  57545. style = defaults(
  57546. {
  57547. lineJoin: 'bevel',
  57548. fill: style.fill || visualColor
  57549. },
  57550. style
  57551. );
  57552. if (firstCreate) {
  57553. sector.setShape(sectorShape);
  57554. sector.shape.r = layout.r0;
  57555. updateProps(
  57556. sector,
  57557. {
  57558. shape: {
  57559. r: layout.r
  57560. }
  57561. },
  57562. seriesModel,
  57563. node.dataIndex
  57564. );
  57565. sector.useStyle(style);
  57566. }
  57567. else if (typeof style.fill === 'object' && style.fill.type
  57568. || typeof sector.style.fill === 'object' && sector.style.fill.type
  57569. ) {
  57570. // Disable animation for gradient since no interpolation method
  57571. // is supported for gradient
  57572. updateProps(sector, {
  57573. shape: sectorShape
  57574. }, seriesModel);
  57575. sector.useStyle(style);
  57576. }
  57577. else {
  57578. updateProps(sector, {
  57579. shape: sectorShape,
  57580. style: style
  57581. }, seriesModel);
  57582. }
  57583. this._updateLabel(seriesModel, visualColor, state);
  57584. var cursorStyle = itemModel.getShallow('cursor');
  57585. cursorStyle && sector.attr('cursor', cursorStyle);
  57586. if (firstCreate) {
  57587. var highlightPolicy = seriesModel.getShallow('highlightPolicy');
  57588. this._initEvents(sector, node, seriesModel, highlightPolicy);
  57589. }
  57590. this._seriesModel = seriesModel || this._seriesModel;
  57591. this._ecModel = ecModel || this._ecModel;
  57592. };
  57593. SunburstPieceProto.onEmphasis = function (highlightPolicy) {
  57594. var that = this;
  57595. this.node.hostTree.root.eachNode(function (n) {
  57596. if (n.piece) {
  57597. if (that.node === n) {
  57598. n.piece.updateData(false, n, 'emphasis');
  57599. }
  57600. else if (isNodeHighlighted(n, that.node, highlightPolicy)) {
  57601. n.piece.childAt(0).trigger('highlight');
  57602. }
  57603. else if (highlightPolicy !== NodeHighlightPolicy.NONE) {
  57604. n.piece.childAt(0).trigger('downplay');
  57605. }
  57606. }
  57607. });
  57608. };
  57609. SunburstPieceProto.onNormal = function () {
  57610. this.node.hostTree.root.eachNode(function (n) {
  57611. if (n.piece) {
  57612. n.piece.updateData(false, n, 'normal');
  57613. }
  57614. });
  57615. };
  57616. SunburstPieceProto.onHighlight = function () {
  57617. this.updateData(false, this.node, 'highlight');
  57618. };
  57619. SunburstPieceProto.onDownplay = function () {
  57620. this.updateData(false, this.node, 'downplay');
  57621. };
  57622. SunburstPieceProto._updateLabel = function (seriesModel, visualColor, state) {
  57623. var itemModel = this.node.getModel();
  57624. var normalModel = itemModel.getModel('label');
  57625. var labelModel = state === 'normal' || state === 'emphasis'
  57626. ? normalModel
  57627. : itemModel.getModel(state + '.label');
  57628. var labelHoverModel = itemModel.getModel('emphasis.label');
  57629. var text = retrieve(
  57630. seriesModel.getFormattedLabel(
  57631. this.node.dataIndex, 'normal', null, null, 'label'
  57632. ),
  57633. this.node.name
  57634. );
  57635. if (getLabelAttr('show') === false) {
  57636. text = '';
  57637. }
  57638. var layout = this.node.getLayout();
  57639. var labelMinAngle = labelModel.get('minAngle');
  57640. if (labelMinAngle == null) {
  57641. labelMinAngle = normalModel.get('minAngle');
  57642. }
  57643. labelMinAngle = labelMinAngle / 180 * Math.PI;
  57644. var angle = layout.endAngle - layout.startAngle;
  57645. if (labelMinAngle != null && Math.abs(angle) < labelMinAngle) {
  57646. // Not displaying text when angle is too small
  57647. text = '';
  57648. }
  57649. var label = this.childAt(1);
  57650. setLabelStyle(
  57651. label.style, label.hoverStyle || {}, normalModel, labelHoverModel,
  57652. {
  57653. defaultText: labelModel.getShallow('show') ? text : null,
  57654. autoColor: visualColor,
  57655. useInsideStyle: true
  57656. }
  57657. );
  57658. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  57659. var dx = Math.cos(midAngle);
  57660. var dy = Math.sin(midAngle);
  57661. var r;
  57662. var labelPosition = getLabelAttr('position');
  57663. var labelPadding = getLabelAttr('distance') || 0;
  57664. var textAlign = getLabelAttr('align');
  57665. if (labelPosition === 'outside') {
  57666. r = layout.r + labelPadding;
  57667. textAlign = midAngle > Math.PI / 2 ? 'right' : 'left';
  57668. }
  57669. else {
  57670. if (!textAlign || textAlign === 'center') {
  57671. r = (layout.r + layout.r0) / 2;
  57672. textAlign = 'center';
  57673. }
  57674. else if (textAlign === 'left') {
  57675. r = layout.r0 + labelPadding;
  57676. if (midAngle > Math.PI / 2) {
  57677. textAlign = 'right';
  57678. }
  57679. }
  57680. else if (textAlign === 'right') {
  57681. r = layout.r - labelPadding;
  57682. if (midAngle > Math.PI / 2) {
  57683. textAlign = 'left';
  57684. }
  57685. }
  57686. }
  57687. label.attr('style', {
  57688. text: text,
  57689. textAlign: textAlign,
  57690. textVerticalAlign: getLabelAttr('verticalAlign') || 'middle',
  57691. opacity: getLabelAttr('opacity')
  57692. });
  57693. var textX = r * dx + layout.cx;
  57694. var textY = r * dy + layout.cy;
  57695. label.attr('position', [textX, textY]);
  57696. var rotateType = getLabelAttr('rotate');
  57697. var rotate = 0;
  57698. if (rotateType === 'radial') {
  57699. rotate = -midAngle;
  57700. if (rotate < -Math.PI / 2) {
  57701. rotate += Math.PI;
  57702. }
  57703. }
  57704. else if (rotateType === 'tangential') {
  57705. rotate = Math.PI / 2 - midAngle;
  57706. if (rotate > Math.PI / 2) {
  57707. rotate -= Math.PI;
  57708. }
  57709. else if (rotate < -Math.PI / 2) {
  57710. rotate += Math.PI;
  57711. }
  57712. } else if (typeof rotateType === 'number') {
  57713. rotate = rotateType * Math.PI / 180;
  57714. }
  57715. label.attr('rotation', rotate);
  57716. function getLabelAttr(name) {
  57717. var stateAttr = labelModel.get(name);
  57718. if (stateAttr == null) {
  57719. return normalModel.get(name);
  57720. }
  57721. else {
  57722. return stateAttr;
  57723. }
  57724. }
  57725. };
  57726. SunburstPieceProto._initEvents = function (
  57727. sector,
  57728. node,
  57729. seriesModel,
  57730. highlightPolicy
  57731. ) {
  57732. sector.off('mouseover').off('mouseout').off('emphasis').off('normal');
  57733. var that = this;
  57734. var onEmphasis = function () {
  57735. that.onEmphasis(highlightPolicy);
  57736. };
  57737. var onNormal = function () {
  57738. that.onNormal();
  57739. };
  57740. var onDownplay = function () {
  57741. that.onDownplay();
  57742. };
  57743. var onHighlight = function () {
  57744. that.onHighlight();
  57745. };
  57746. if (seriesModel.isAnimationEnabled()) {
  57747. sector
  57748. .on('mouseover', onEmphasis)
  57749. .on('mouseout', onNormal)
  57750. .on('emphasis', onEmphasis)
  57751. .on('normal', onNormal)
  57752. .on('downplay', onDownplay)
  57753. .on('highlight', onHighlight);
  57754. }
  57755. };
  57756. inherits(SunburstPiece, Group);
  57757. /**
  57758. * Get node color
  57759. *
  57760. * @param {TreeNode} node the node to get color
  57761. * @param {module:echarts/model/Series} seriesModel series
  57762. * @param {module:echarts/model/Global} ecModel echarts defaults
  57763. */
  57764. function getNodeColor(node, seriesModel, ecModel) {
  57765. // Color from visualMap
  57766. var visualColor = node.getVisual('color');
  57767. var visualMetaList = node.getVisual('visualMeta');
  57768. if (!visualMetaList || visualMetaList.length === 0) {
  57769. // Use first-generation color if has no visualMap
  57770. visualColor = null;
  57771. }
  57772. // Self color or level color
  57773. var color = node.getModel('itemStyle').get('color');
  57774. if (color) {
  57775. return color;
  57776. }
  57777. else if (visualColor) {
  57778. // Color mapping
  57779. return visualColor;
  57780. }
  57781. else if (node.depth === 0) {
  57782. // Virtual root node
  57783. return ecModel.option.color[0];
  57784. }
  57785. else {
  57786. // First-generation color
  57787. var length = ecModel.option.color.length;
  57788. color = ecModel.option.color[getRootId(node) % length];
  57789. }
  57790. return color;
  57791. }
  57792. /**
  57793. * Get index of root in sorted order
  57794. *
  57795. * @param {TreeNode} node current node
  57796. * @return {number} index in root
  57797. */
  57798. function getRootId(node) {
  57799. var ancestor = node;
  57800. while (ancestor.depth > 1) {
  57801. ancestor = ancestor.parentNode;
  57802. }
  57803. var virtualRoot = node.getAncestors()[0];
  57804. return indexOf(virtualRoot.children, ancestor);
  57805. }
  57806. function isNodeHighlighted(node, activeNode, policy) {
  57807. if (policy === NodeHighlightPolicy.NONE) {
  57808. return false;
  57809. }
  57810. else if (policy === NodeHighlightPolicy.SELF) {
  57811. return node === activeNode;
  57812. }
  57813. else if (policy === NodeHighlightPolicy.ANCESTOR) {
  57814. return node === activeNode || node.isAncestorOf(activeNode);
  57815. }
  57816. else {
  57817. return node === activeNode || node.isDescendantOf(activeNode);
  57818. }
  57819. }
  57820. /*
  57821. * Licensed to the Apache Software Foundation (ASF) under one
  57822. * or more contributor license agreements. See the NOTICE file
  57823. * distributed with this work for additional information
  57824. * regarding copyright ownership. The ASF licenses this file
  57825. * to you under the Apache License, Version 2.0 (the
  57826. * "License"); you may not use this file except in compliance
  57827. * with the License. You may obtain a copy of the License at
  57828. *
  57829. * http://www.apache.org/licenses/LICENSE-2.0
  57830. *
  57831. * Unless required by applicable law or agreed to in writing,
  57832. * software distributed under the License is distributed on an
  57833. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57834. * KIND, either express or implied. See the License for the
  57835. * specific language governing permissions and limitations
  57836. * under the License.
  57837. */
  57838. var ROOT_TO_NODE_ACTION = 'sunburstRootToNode';
  57839. var SunburstView = Chart.extend({
  57840. type: 'sunburst',
  57841. init: function () {
  57842. },
  57843. render: function (seriesModel, ecModel, api, payload) {
  57844. var that = this;
  57845. this.seriesModel = seriesModel;
  57846. this.api = api;
  57847. this.ecModel = ecModel;
  57848. var data = seriesModel.getData();
  57849. var virtualRoot = data.tree.root;
  57850. var newRoot = seriesModel.getViewRoot();
  57851. var group = this.group;
  57852. var renderLabelForZeroData = seriesModel.get('renderLabelForZeroData');
  57853. var newChildren = [];
  57854. newRoot.eachNode(function (node) {
  57855. newChildren.push(node);
  57856. });
  57857. var oldChildren = this._oldChildren || [];
  57858. dualTravel(newChildren, oldChildren);
  57859. renderRollUp(virtualRoot, newRoot);
  57860. if (payload && payload.highlight && payload.highlight.piece) {
  57861. var highlightPolicy = seriesModel.getShallow('highlightPolicy');
  57862. payload.highlight.piece.onEmphasis(highlightPolicy);
  57863. }
  57864. else if (payload && payload.unhighlight) {
  57865. var piece = this.virtualPiece;
  57866. if (!piece && virtualRoot.children.length) {
  57867. piece = virtualRoot.children[0].piece;
  57868. }
  57869. if (piece) {
  57870. piece.onNormal();
  57871. }
  57872. }
  57873. this._initEvents();
  57874. this._oldChildren = newChildren;
  57875. function dualTravel(newChildren, oldChildren) {
  57876. if (newChildren.length === 0 && oldChildren.length === 0) {
  57877. return;
  57878. }
  57879. new DataDiffer(oldChildren, newChildren, getKey, getKey)
  57880. .add(processNode)
  57881. .update(processNode)
  57882. .remove(curry(processNode, null))
  57883. .execute();
  57884. function getKey(node) {
  57885. return node.getId();
  57886. }
  57887. function processNode(newId, oldId) {
  57888. var newNode = newId == null ? null : newChildren[newId];
  57889. var oldNode = oldId == null ? null : oldChildren[oldId];
  57890. doRenderNode(newNode, oldNode);
  57891. }
  57892. }
  57893. function doRenderNode(newNode, oldNode) {
  57894. if (!renderLabelForZeroData && newNode && !newNode.getValue()) {
  57895. // Not render data with value 0
  57896. newNode = null;
  57897. }
  57898. if (newNode !== virtualRoot && oldNode !== virtualRoot) {
  57899. if (oldNode && oldNode.piece) {
  57900. if (newNode) {
  57901. // Update
  57902. oldNode.piece.updateData(
  57903. false, newNode, 'normal', seriesModel, ecModel);
  57904. // For tooltip
  57905. data.setItemGraphicEl(newNode.dataIndex, oldNode.piece);
  57906. }
  57907. else {
  57908. // Remove
  57909. removeNode(oldNode);
  57910. }
  57911. }
  57912. else if (newNode) {
  57913. // Add
  57914. var piece = new SunburstPiece(
  57915. newNode,
  57916. seriesModel,
  57917. ecModel
  57918. );
  57919. group.add(piece);
  57920. // For tooltip
  57921. data.setItemGraphicEl(newNode.dataIndex, piece);
  57922. }
  57923. }
  57924. }
  57925. function removeNode(node) {
  57926. if (!node) {
  57927. return;
  57928. }
  57929. if (node.piece) {
  57930. group.remove(node.piece);
  57931. node.piece = null;
  57932. }
  57933. }
  57934. function renderRollUp(virtualRoot, viewRoot) {
  57935. if (viewRoot.depth > 0) {
  57936. // Render
  57937. if (that.virtualPiece) {
  57938. // Update
  57939. that.virtualPiece.updateData(
  57940. false, virtualRoot, 'normal', seriesModel, ecModel);
  57941. }
  57942. else {
  57943. // Add
  57944. that.virtualPiece = new SunburstPiece(
  57945. virtualRoot,
  57946. seriesModel,
  57947. ecModel
  57948. );
  57949. group.add(that.virtualPiece);
  57950. }
  57951. if (viewRoot.piece._onclickEvent) {
  57952. viewRoot.piece.off('click', viewRoot.piece._onclickEvent);
  57953. }
  57954. var event = function (e) {
  57955. that._rootToNode(viewRoot.parentNode);
  57956. };
  57957. viewRoot.piece._onclickEvent = event;
  57958. that.virtualPiece.on('click', event);
  57959. }
  57960. else if (that.virtualPiece) {
  57961. // Remove
  57962. group.remove(that.virtualPiece);
  57963. that.virtualPiece = null;
  57964. }
  57965. }
  57966. },
  57967. dispose: function () {
  57968. },
  57969. /**
  57970. * @private
  57971. */
  57972. _initEvents: function () {
  57973. var that = this;
  57974. var event = function (e) {
  57975. var targetFound = false;
  57976. var viewRoot = that.seriesModel.getViewRoot();
  57977. viewRoot.eachNode(function (node) {
  57978. if (!targetFound
  57979. && node.piece && node.piece.childAt(0) === e.target
  57980. ) {
  57981. var nodeClick = node.getModel().get('nodeClick');
  57982. if (nodeClick === 'rootToNode') {
  57983. that._rootToNode(node);
  57984. }
  57985. else if (nodeClick === 'link') {
  57986. var itemModel = node.getModel();
  57987. var link = itemModel.get('link');
  57988. if (link) {
  57989. var linkTarget = itemModel.get('target', true)
  57990. || '_blank';
  57991. window.open(link, linkTarget);
  57992. }
  57993. }
  57994. targetFound = true;
  57995. }
  57996. });
  57997. };
  57998. if (this.group._onclickEvent) {
  57999. this.group.off('click', this.group._onclickEvent);
  58000. }
  58001. this.group.on('click', event);
  58002. this.group._onclickEvent = event;
  58003. },
  58004. /**
  58005. * @private
  58006. */
  58007. _rootToNode: function (node) {
  58008. if (node !== this.seriesModel.getViewRoot()) {
  58009. this.api.dispatchAction({
  58010. type: ROOT_TO_NODE_ACTION,
  58011. from: this.uid,
  58012. seriesId: this.seriesModel.id,
  58013. targetNode: node
  58014. });
  58015. }
  58016. },
  58017. /**
  58018. * @implement
  58019. */
  58020. containPoint: function (point, seriesModel) {
  58021. var treeRoot = seriesModel.getData();
  58022. var itemLayout = treeRoot.getItemLayout(0);
  58023. if (itemLayout) {
  58024. var dx = point[0] - itemLayout.cx;
  58025. var dy = point[1] - itemLayout.cy;
  58026. var radius = Math.sqrt(dx * dx + dy * dy);
  58027. return radius <= itemLayout.r && radius >= itemLayout.r0;
  58028. }
  58029. }
  58030. });
  58031. /*
  58032. * Licensed to the Apache Software Foundation (ASF) under one
  58033. * or more contributor license agreements. See the NOTICE file
  58034. * distributed with this work for additional information
  58035. * regarding copyright ownership. The ASF licenses this file
  58036. * to you under the Apache License, Version 2.0 (the
  58037. * "License"); you may not use this file except in compliance
  58038. * with the License. You may obtain a copy of the License at
  58039. *
  58040. * http://www.apache.org/licenses/LICENSE-2.0
  58041. *
  58042. * Unless required by applicable law or agreed to in writing,
  58043. * software distributed under the License is distributed on an
  58044. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58045. * KIND, either express or implied. See the License for the
  58046. * specific language governing permissions and limitations
  58047. * under the License.
  58048. */
  58049. /**
  58050. * @file Sunburst action
  58051. */
  58052. var ROOT_TO_NODE_ACTION$1 = 'sunburstRootToNode';
  58053. registerAction(
  58054. {type: ROOT_TO_NODE_ACTION$1, update: 'updateView'},
  58055. function (payload, ecModel) {
  58056. ecModel.eachComponent(
  58057. {mainType: 'series', subType: 'sunburst', query: payload},
  58058. handleRootToNode
  58059. );
  58060. function handleRootToNode(model, index) {
  58061. var targetInfo = retrieveTargetInfo(payload, [ROOT_TO_NODE_ACTION$1], model);
  58062. if (targetInfo) {
  58063. var originViewRoot = model.getViewRoot();
  58064. if (originViewRoot) {
  58065. payload.direction = aboveViewRoot(originViewRoot, targetInfo.node)
  58066. ? 'rollUp' : 'drillDown';
  58067. }
  58068. model.resetViewRoot(targetInfo.node);
  58069. }
  58070. }
  58071. }
  58072. );
  58073. var HIGHLIGHT_ACTION = 'sunburstHighlight';
  58074. registerAction(
  58075. {type: HIGHLIGHT_ACTION, update: 'updateView'},
  58076. function (payload, ecModel) {
  58077. ecModel.eachComponent(
  58078. {mainType: 'series', subType: 'sunburst', query: payload},
  58079. handleHighlight
  58080. );
  58081. function handleHighlight(model, index) {
  58082. var targetInfo = retrieveTargetInfo(payload, [HIGHLIGHT_ACTION], model);
  58083. if (targetInfo) {
  58084. payload.highlight = targetInfo.node;
  58085. }
  58086. }
  58087. }
  58088. );
  58089. var UNHIGHLIGHT_ACTION = 'sunburstUnhighlight';
  58090. registerAction(
  58091. {type: UNHIGHLIGHT_ACTION, update: 'updateView'},
  58092. function (payload, ecModel) {
  58093. ecModel.eachComponent(
  58094. {mainType: 'series', subType: 'sunburst', query: payload},
  58095. handleUnhighlight
  58096. );
  58097. function handleUnhighlight(model, index) {
  58098. payload.unhighlight = true;
  58099. }
  58100. }
  58101. );
  58102. /*
  58103. * Licensed to the Apache Software Foundation (ASF) under one
  58104. * or more contributor license agreements. See the NOTICE file
  58105. * distributed with this work for additional information
  58106. * regarding copyright ownership. The ASF licenses this file
  58107. * to you under the Apache License, Version 2.0 (the
  58108. * "License"); you may not use this file except in compliance
  58109. * with the License. You may obtain a copy of the License at
  58110. *
  58111. * http://www.apache.org/licenses/LICENSE-2.0
  58112. *
  58113. * Unless required by applicable law or agreed to in writing,
  58114. * software distributed under the License is distributed on an
  58115. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58116. * KIND, either express or implied. See the License for the
  58117. * specific language governing permissions and limitations
  58118. * under the License.
  58119. */
  58120. var RADIAN$1 = Math.PI / 180;
  58121. var sunburstLayout = function (seriesType, ecModel, api, payload) {
  58122. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  58123. var center = seriesModel.get('center');
  58124. var radius = seriesModel.get('radius');
  58125. if (!isArray(radius)) {
  58126. radius = [0, radius];
  58127. }
  58128. if (!isArray(center)) {
  58129. center = [center, center];
  58130. }
  58131. var width = api.getWidth();
  58132. var height = api.getHeight();
  58133. var size = Math.min(width, height);
  58134. var cx = parsePercent$1(center[0], width);
  58135. var cy = parsePercent$1(center[1], height);
  58136. var r0 = parsePercent$1(radius[0], size / 2);
  58137. var r = parsePercent$1(radius[1], size / 2);
  58138. var startAngle = -seriesModel.get('startAngle') * RADIAN$1;
  58139. var minAngle = seriesModel.get('minAngle') * RADIAN$1;
  58140. var virtualRoot = seriesModel.getData().tree.root;
  58141. var treeRoot = seriesModel.getViewRoot();
  58142. var rootDepth = treeRoot.depth;
  58143. var sort = seriesModel.get('sort');
  58144. if (sort != null) {
  58145. initChildren$1(treeRoot, sort);
  58146. }
  58147. var validDataCount = 0;
  58148. each$1(treeRoot.children, function (child) {
  58149. !isNaN(child.getValue()) && validDataCount++;
  58150. });
  58151. var sum = treeRoot.getValue();
  58152. // Sum may be 0
  58153. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  58154. var renderRollupNode = treeRoot.depth > 0;
  58155. var levels = treeRoot.height - (renderRollupNode ? -1 : 1);
  58156. var rPerLevel = (r - r0) / (levels || 1);
  58157. var clockwise = seriesModel.get('clockwise');
  58158. var stillShowZeroSum = seriesModel.get('stillShowZeroSum');
  58159. // In the case some sector angle is smaller than minAngle
  58160. var dir = clockwise ? 1 : -1;
  58161. /**
  58162. * Render a tree
  58163. * @return increased angle
  58164. */
  58165. var renderNode = function (node, startAngle) {
  58166. if (!node) {
  58167. return;
  58168. }
  58169. var endAngle = startAngle;
  58170. // Render self
  58171. if (node !== virtualRoot) {
  58172. // Tree node is virtual, so it doesn't need to be drawn
  58173. var value = node.getValue();
  58174. var angle = (sum === 0 && stillShowZeroSum)
  58175. ? unitRadian : (value * unitRadian);
  58176. if (angle < minAngle) {
  58177. angle = minAngle;
  58178. }
  58179. else {
  58180. }
  58181. endAngle = startAngle + dir * angle;
  58182. var depth = node.depth - rootDepth
  58183. - (renderRollupNode ? -1 : 1);
  58184. var rStart = r0 + rPerLevel * depth;
  58185. var rEnd = r0 + rPerLevel * (depth + 1);
  58186. var itemModel = node.getModel();
  58187. if (itemModel.get('r0') != null) {
  58188. rStart = parsePercent$1(itemModel.get('r0'), size / 2);
  58189. }
  58190. if (itemModel.get('r') != null) {
  58191. rEnd = parsePercent$1(itemModel.get('r'), size / 2);
  58192. }
  58193. node.setLayout({
  58194. angle: angle,
  58195. startAngle: startAngle,
  58196. endAngle: endAngle,
  58197. clockwise: clockwise,
  58198. cx: cx,
  58199. cy: cy,
  58200. r0: rStart,
  58201. r: rEnd
  58202. });
  58203. }
  58204. // Render children
  58205. if (node.children && node.children.length) {
  58206. // currentAngle = startAngle;
  58207. var siblingAngle = 0;
  58208. each$1(node.children, function (node) {
  58209. siblingAngle += renderNode(node, startAngle + siblingAngle);
  58210. });
  58211. }
  58212. return endAngle - startAngle;
  58213. };
  58214. // Virtual root node for roll up
  58215. if (renderRollupNode) {
  58216. var rStart = r0;
  58217. var rEnd = r0 + rPerLevel;
  58218. var angle = Math.PI * 2;
  58219. virtualRoot.setLayout({
  58220. angle: angle,
  58221. startAngle: startAngle,
  58222. endAngle: startAngle + angle,
  58223. clockwise: clockwise,
  58224. cx: cx,
  58225. cy: cy,
  58226. r0: rStart,
  58227. r: rEnd
  58228. });
  58229. }
  58230. renderNode(treeRoot, startAngle);
  58231. });
  58232. };
  58233. /**
  58234. * Init node children by order and update visual
  58235. *
  58236. * @param {TreeNode} node root node
  58237. * @param {boolean} isAsc if is in ascendant order
  58238. */
  58239. function initChildren$1(node, isAsc) {
  58240. var children = node.children || [];
  58241. node.children = sort$2(children, isAsc);
  58242. // Init children recursively
  58243. if (children.length) {
  58244. each$1(node.children, function (child) {
  58245. initChildren$1(child, isAsc);
  58246. });
  58247. }
  58248. }
  58249. /**
  58250. * Sort children nodes
  58251. *
  58252. * @param {TreeNode[]} children children of node to be sorted
  58253. * @param {string | function | null} sort sort method
  58254. * See SunburstSeries.js for details.
  58255. */
  58256. function sort$2(children, sortOrder) {
  58257. if (typeof sortOrder === 'function') {
  58258. return children.sort(sortOrder);
  58259. }
  58260. else {
  58261. var isAsc = sortOrder === 'asc';
  58262. return children.sort(function (a, b) {
  58263. var diff = (a.getValue() - b.getValue()) * (isAsc ? 1 : -1);
  58264. return diff === 0
  58265. ? (a.dataIndex - b.dataIndex) * (isAsc ? -1 : 1)
  58266. : diff;
  58267. });
  58268. }
  58269. }
  58270. /*
  58271. * Licensed to the Apache Software Foundation (ASF) under one
  58272. * or more contributor license agreements. See the NOTICE file
  58273. * distributed with this work for additional information
  58274. * regarding copyright ownership. The ASF licenses this file
  58275. * to you under the Apache License, Version 2.0 (the
  58276. * "License"); you may not use this file except in compliance
  58277. * with the License. You may obtain a copy of the License at
  58278. *
  58279. * http://www.apache.org/licenses/LICENSE-2.0
  58280. *
  58281. * Unless required by applicable law or agreed to in writing,
  58282. * software distributed under the License is distributed on an
  58283. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58284. * KIND, either express or implied. See the License for the
  58285. * specific language governing permissions and limitations
  58286. * under the License.
  58287. */
  58288. registerVisual(curry(dataColor, 'sunburst'));
  58289. registerLayout(curry(sunburstLayout, 'sunburst'));
  58290. registerProcessor(curry(dataFilter, 'sunburst'));
  58291. /*
  58292. * Licensed to the Apache Software Foundation (ASF) under one
  58293. * or more contributor license agreements. See the NOTICE file
  58294. * distributed with this work for additional information
  58295. * regarding copyright ownership. The ASF licenses this file
  58296. * to you under the Apache License, Version 2.0 (the
  58297. * "License"); you may not use this file except in compliance
  58298. * with the License. You may obtain a copy of the License at
  58299. *
  58300. * http://www.apache.org/licenses/LICENSE-2.0
  58301. *
  58302. * Unless required by applicable law or agreed to in writing,
  58303. * software distributed under the License is distributed on an
  58304. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58305. * KIND, either express or implied. See the License for the
  58306. * specific language governing permissions and limitations
  58307. * under the License.
  58308. */
  58309. function dataToCoordSize(dataSize, dataItem) {
  58310. // dataItem is necessary in log axis.
  58311. dataItem = dataItem || [0, 0];
  58312. return map(['x', 'y'], function (dim, dimIdx) {
  58313. var axis = this.getAxis(dim);
  58314. var val = dataItem[dimIdx];
  58315. var halfSize = dataSize[dimIdx] / 2;
  58316. return axis.type === 'category'
  58317. ? axis.getBandWidth()
  58318. : Math.abs(axis.dataToCoord(val - halfSize) - axis.dataToCoord(val + halfSize));
  58319. }, this);
  58320. }
  58321. var prepareCartesian2d = function (coordSys) {
  58322. var rect = coordSys.grid.getRect();
  58323. return {
  58324. coordSys: {
  58325. // The name exposed to user is always 'cartesian2d' but not 'grid'.
  58326. type: 'cartesian2d',
  58327. x: rect.x,
  58328. y: rect.y,
  58329. width: rect.width,
  58330. height: rect.height
  58331. },
  58332. api: {
  58333. coord: function (data) {
  58334. // do not provide "out" param
  58335. return coordSys.dataToPoint(data);
  58336. },
  58337. size: bind(dataToCoordSize, coordSys)
  58338. }
  58339. };
  58340. };
  58341. /*
  58342. * Licensed to the Apache Software Foundation (ASF) under one
  58343. * or more contributor license agreements. See the NOTICE file
  58344. * distributed with this work for additional information
  58345. * regarding copyright ownership. The ASF licenses this file
  58346. * to you under the Apache License, Version 2.0 (the
  58347. * "License"); you may not use this file except in compliance
  58348. * with the License. You may obtain a copy of the License at
  58349. *
  58350. * http://www.apache.org/licenses/LICENSE-2.0
  58351. *
  58352. * Unless required by applicable law or agreed to in writing,
  58353. * software distributed under the License is distributed on an
  58354. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58355. * KIND, either express or implied. See the License for the
  58356. * specific language governing permissions and limitations
  58357. * under the License.
  58358. */
  58359. function dataToCoordSize$1(dataSize, dataItem) {
  58360. dataItem = dataItem || [0, 0];
  58361. return map([0, 1], function (dimIdx) {
  58362. var val = dataItem[dimIdx];
  58363. var halfSize = dataSize[dimIdx] / 2;
  58364. var p1 = [];
  58365. var p2 = [];
  58366. p1[dimIdx] = val - halfSize;
  58367. p2[dimIdx] = val + halfSize;
  58368. p1[1 - dimIdx] = p2[1 - dimIdx] = dataItem[1 - dimIdx];
  58369. return Math.abs(this.dataToPoint(p1)[dimIdx] - this.dataToPoint(p2)[dimIdx]);
  58370. }, this);
  58371. }
  58372. var prepareGeo = function (coordSys) {
  58373. var rect = coordSys.getBoundingRect();
  58374. return {
  58375. coordSys: {
  58376. type: 'geo',
  58377. x: rect.x,
  58378. y: rect.y,
  58379. width: rect.width,
  58380. height: rect.height
  58381. },
  58382. api: {
  58383. coord: function (data) {
  58384. // do not provide "out" and noRoam param,
  58385. // Compatible with this usage:
  58386. // echarts.util.map(item.points, api.coord)
  58387. return coordSys.dataToPoint(data);
  58388. },
  58389. size: bind(dataToCoordSize$1, coordSys)
  58390. }
  58391. };
  58392. };
  58393. /*
  58394. * Licensed to the Apache Software Foundation (ASF) under one
  58395. * or more contributor license agreements. See the NOTICE file
  58396. * distributed with this work for additional information
  58397. * regarding copyright ownership. The ASF licenses this file
  58398. * to you under the Apache License, Version 2.0 (the
  58399. * "License"); you may not use this file except in compliance
  58400. * with the License. You may obtain a copy of the License at
  58401. *
  58402. * http://www.apache.org/licenses/LICENSE-2.0
  58403. *
  58404. * Unless required by applicable law or agreed to in writing,
  58405. * software distributed under the License is distributed on an
  58406. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58407. * KIND, either express or implied. See the License for the
  58408. * specific language governing permissions and limitations
  58409. * under the License.
  58410. */
  58411. function dataToCoordSize$2(dataSize, dataItem) {
  58412. // dataItem is necessary in log axis.
  58413. var axis = this.getAxis();
  58414. var val = dataItem instanceof Array ? dataItem[0] : dataItem;
  58415. var halfSize = (dataSize instanceof Array ? dataSize[0] : dataSize) / 2;
  58416. return axis.type === 'category'
  58417. ? axis.getBandWidth()
  58418. : Math.abs(axis.dataToCoord(val - halfSize) - axis.dataToCoord(val + halfSize));
  58419. }
  58420. var prepareSingleAxis = function (coordSys) {
  58421. var rect = coordSys.getRect();
  58422. return {
  58423. coordSys: {
  58424. type: 'singleAxis',
  58425. x: rect.x,
  58426. y: rect.y,
  58427. width: rect.width,
  58428. height: rect.height
  58429. },
  58430. api: {
  58431. coord: function (val) {
  58432. // do not provide "out" param
  58433. return coordSys.dataToPoint(val);
  58434. },
  58435. size: bind(dataToCoordSize$2, coordSys)
  58436. }
  58437. };
  58438. };
  58439. /*
  58440. * Licensed to the Apache Software Foundation (ASF) under one
  58441. * or more contributor license agreements. See the NOTICE file
  58442. * distributed with this work for additional information
  58443. * regarding copyright ownership. The ASF licenses this file
  58444. * to you under the Apache License, Version 2.0 (the
  58445. * "License"); you may not use this file except in compliance
  58446. * with the License. You may obtain a copy of the License at
  58447. *
  58448. * http://www.apache.org/licenses/LICENSE-2.0
  58449. *
  58450. * Unless required by applicable law or agreed to in writing,
  58451. * software distributed under the License is distributed on an
  58452. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58453. * KIND, either express or implied. See the License for the
  58454. * specific language governing permissions and limitations
  58455. * under the License.
  58456. */
  58457. function dataToCoordSize$3(dataSize, dataItem) {
  58458. // dataItem is necessary in log axis.
  58459. return map(['Radius', 'Angle'], function (dim, dimIdx) {
  58460. var axis = this['get' + dim + 'Axis']();
  58461. var val = dataItem[dimIdx];
  58462. var halfSize = dataSize[dimIdx] / 2;
  58463. var method = 'dataTo' + dim;
  58464. var result = axis.type === 'category'
  58465. ? axis.getBandWidth()
  58466. : Math.abs(axis[method](val - halfSize) - axis[method](val + halfSize));
  58467. if (dim === 'Angle') {
  58468. result = result * Math.PI / 180;
  58469. }
  58470. return result;
  58471. }, this);
  58472. }
  58473. var preparePolar = function (coordSys) {
  58474. var radiusAxis = coordSys.getRadiusAxis();
  58475. var angleAxis = coordSys.getAngleAxis();
  58476. var radius = radiusAxis.getExtent();
  58477. radius[0] > radius[1] && radius.reverse();
  58478. return {
  58479. coordSys: {
  58480. type: 'polar',
  58481. cx: coordSys.cx,
  58482. cy: coordSys.cy,
  58483. r: radius[1],
  58484. r0: radius[0]
  58485. },
  58486. api: {
  58487. coord: bind(function (data) {
  58488. var radius = radiusAxis.dataToRadius(data[0]);
  58489. var angle = angleAxis.dataToAngle(data[1]);
  58490. var coord = coordSys.coordToPoint([radius, angle]);
  58491. coord.push(radius, angle * Math.PI / 180);
  58492. return coord;
  58493. }),
  58494. size: bind(dataToCoordSize$3, coordSys)
  58495. }
  58496. };
  58497. };
  58498. /*
  58499. * Licensed to the Apache Software Foundation (ASF) under one
  58500. * or more contributor license agreements. See the NOTICE file
  58501. * distributed with this work for additional information
  58502. * regarding copyright ownership. The ASF licenses this file
  58503. * to you under the Apache License, Version 2.0 (the
  58504. * "License"); you may not use this file except in compliance
  58505. * with the License. You may obtain a copy of the License at
  58506. *
  58507. * http://www.apache.org/licenses/LICENSE-2.0
  58508. *
  58509. * Unless required by applicable law or agreed to in writing,
  58510. * software distributed under the License is distributed on an
  58511. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58512. * KIND, either express or implied. See the License for the
  58513. * specific language governing permissions and limitations
  58514. * under the License.
  58515. */
  58516. var prepareCalendar = function (coordSys) {
  58517. var rect = coordSys.getRect();
  58518. var rangeInfo = coordSys.getRangeInfo();
  58519. return {
  58520. coordSys: {
  58521. type: 'calendar',
  58522. x: rect.x,
  58523. y: rect.y,
  58524. width: rect.width,
  58525. height: rect.height,
  58526. cellWidth: coordSys.getCellWidth(),
  58527. cellHeight: coordSys.getCellHeight(),
  58528. rangeInfo: {
  58529. start: rangeInfo.start,
  58530. end: rangeInfo.end,
  58531. weeks: rangeInfo.weeks,
  58532. dayCount: rangeInfo.allDay
  58533. }
  58534. },
  58535. api: {
  58536. coord: function (data, clamp) {
  58537. return coordSys.dataToPoint(data, clamp);
  58538. }
  58539. }
  58540. };
  58541. };
  58542. /*
  58543. * Licensed to the Apache Software Foundation (ASF) under one
  58544. * or more contributor license agreements. See the NOTICE file
  58545. * distributed with this work for additional information
  58546. * regarding copyright ownership. The ASF licenses this file
  58547. * to you under the Apache License, Version 2.0 (the
  58548. * "License"); you may not use this file except in compliance
  58549. * with the License. You may obtain a copy of the License at
  58550. *
  58551. * http://www.apache.org/licenses/LICENSE-2.0
  58552. *
  58553. * Unless required by applicable law or agreed to in writing,
  58554. * software distributed under the License is distributed on an
  58555. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58556. * KIND, either express or implied. See the License for the
  58557. * specific language governing permissions and limitations
  58558. * under the License.
  58559. */
  58560. var ITEM_STYLE_NORMAL_PATH = ['itemStyle'];
  58561. var ITEM_STYLE_EMPHASIS_PATH = ['emphasis', 'itemStyle'];
  58562. var LABEL_NORMAL = ['label'];
  58563. var LABEL_EMPHASIS = ['emphasis', 'label'];
  58564. // Use prefix to avoid index to be the same as el.name,
  58565. // which will cause weird udpate animation.
  58566. var GROUP_DIFF_PREFIX = 'e\0\0';
  58567. /**
  58568. * To reduce total package size of each coordinate systems, the modules `prepareCustom`
  58569. * of each coordinate systems are not required by each coordinate systems directly, but
  58570. * required by the module `custom`.
  58571. *
  58572. * prepareInfoForCustomSeries {Function}: optional
  58573. * @return {Object} {coordSys: {...}, api: {
  58574. * coord: function (data, clamp) {}, // return point in global.
  58575. * size: function (dataSize, dataItem) {} // return size of each axis in coordSys.
  58576. * }}
  58577. */
  58578. var prepareCustoms = {
  58579. cartesian2d: prepareCartesian2d,
  58580. geo: prepareGeo,
  58581. singleAxis: prepareSingleAxis,
  58582. polar: preparePolar,
  58583. calendar: prepareCalendar
  58584. };
  58585. // ------
  58586. // Model
  58587. // ------
  58588. extendSeriesModel({
  58589. type: 'series.custom',
  58590. dependencies: ['grid', 'polar', 'geo', 'singleAxis', 'calendar'],
  58591. defaultOption: {
  58592. coordinateSystem: 'cartesian2d', // Can be set as 'none'
  58593. zlevel: 0,
  58594. z: 2,
  58595. legendHoverLink: true
  58596. // Cartesian coordinate system
  58597. // xAxisIndex: 0,
  58598. // yAxisIndex: 0,
  58599. // Polar coordinate system
  58600. // polarIndex: 0,
  58601. // Geo coordinate system
  58602. // geoIndex: 0,
  58603. // label: {}
  58604. // itemStyle: {}
  58605. },
  58606. getInitialData: function (option, ecModel) {
  58607. return createListFromArray(this.getSource(), this);
  58608. }
  58609. });
  58610. // -----
  58611. // View
  58612. // -----
  58613. extendChartView({
  58614. type: 'custom',
  58615. /**
  58616. * @private
  58617. * @type {module:echarts/data/List}
  58618. */
  58619. _data: null,
  58620. /**
  58621. * @override
  58622. */
  58623. render: function (customSeries, ecModel, api) {
  58624. var oldData = this._data;
  58625. var data = customSeries.getData();
  58626. var group = this.group;
  58627. var renderItem = makeRenderItem(customSeries, data, ecModel, api);
  58628. this.group.removeAll();
  58629. data.diff(oldData)
  58630. .add(function (newIdx) {
  58631. createOrUpdate$1(
  58632. null, newIdx, renderItem(newIdx), customSeries, group, data
  58633. );
  58634. })
  58635. .update(function (newIdx, oldIdx) {
  58636. var el = oldData.getItemGraphicEl(oldIdx);
  58637. createOrUpdate$1(
  58638. el, newIdx, renderItem(newIdx), customSeries, group, data
  58639. );
  58640. })
  58641. .remove(function (oldIdx) {
  58642. var el = oldData.getItemGraphicEl(oldIdx);
  58643. el && group.remove(el);
  58644. })
  58645. .execute();
  58646. this._data = data;
  58647. },
  58648. incrementalPrepareRender: function (customSeries, ecModel, api) {
  58649. this.group.removeAll();
  58650. this._data = null;
  58651. },
  58652. incrementalRender: function (params, customSeries, ecModel, api) {
  58653. var data = customSeries.getData();
  58654. var renderItem = makeRenderItem(customSeries, data, ecModel, api);
  58655. function setIncrementalAndHoverLayer(el) {
  58656. if (!el.isGroup) {
  58657. el.incremental = true;
  58658. el.useHoverLayer = true;
  58659. }
  58660. }
  58661. for (var idx = params.start; idx < params.end; idx++) {
  58662. var el = createOrUpdate$1(null, idx, renderItem(idx), customSeries, this.group, data);
  58663. el.traverse(setIncrementalAndHoverLayer);
  58664. }
  58665. },
  58666. /**
  58667. * @override
  58668. */
  58669. dispose: noop
  58670. });
  58671. function createEl(elOption) {
  58672. var graphicType = elOption.type;
  58673. var el;
  58674. if (graphicType === 'path') {
  58675. var shape = elOption.shape;
  58676. el = makePath(
  58677. shape.pathData,
  58678. null,
  58679. {
  58680. x: shape.x || 0,
  58681. y: shape.y || 0,
  58682. width: shape.width || 0,
  58683. height: shape.height || 0
  58684. },
  58685. 'center'
  58686. );
  58687. el.__customPathData = elOption.pathData;
  58688. }
  58689. else if (graphicType === 'image') {
  58690. el = new ZImage({
  58691. });
  58692. el.__customImagePath = elOption.style.image;
  58693. }
  58694. else if (graphicType === 'text') {
  58695. el = new Text({
  58696. });
  58697. el.__customText = elOption.style.text;
  58698. }
  58699. else {
  58700. var Clz = graphic[graphicType.charAt(0).toUpperCase() + graphicType.slice(1)];
  58701. if (__DEV__) {
  58702. assert$1(Clz, 'graphic type "' + graphicType + '" can not be found.');
  58703. }
  58704. el = new Clz();
  58705. }
  58706. el.__customGraphicType = graphicType;
  58707. el.name = elOption.name;
  58708. return el;
  58709. }
  58710. function updateEl(el, dataIndex, elOption, animatableModel, data, isInit) {
  58711. var targetProps = {};
  58712. var elOptionStyle = elOption.style || {};
  58713. elOption.shape && (targetProps.shape = clone(elOption.shape));
  58714. elOption.position && (targetProps.position = elOption.position.slice());
  58715. elOption.scale && (targetProps.scale = elOption.scale.slice());
  58716. elOption.origin && (targetProps.origin = elOption.origin.slice());
  58717. elOption.rotation && (targetProps.rotation = elOption.rotation);
  58718. if (el.type === 'image' && elOption.style) {
  58719. var targetStyle = targetProps.style = {};
  58720. each$1(['x', 'y', 'width', 'height'], function (prop) {
  58721. prepareStyleTransition(prop, targetStyle, elOptionStyle, el.style, isInit);
  58722. });
  58723. }
  58724. if (el.type === 'text' && elOption.style) {
  58725. var targetStyle = targetProps.style = {};
  58726. each$1(['x', 'y'], function (prop) {
  58727. prepareStyleTransition(prop, targetStyle, elOptionStyle, el.style, isInit);
  58728. });
  58729. // Compatible with previous: both support
  58730. // textFill and fill, textStroke and stroke in 'text' element.
  58731. !elOptionStyle.hasOwnProperty('textFill') && elOptionStyle.fill && (
  58732. elOptionStyle.textFill = elOptionStyle.fill
  58733. );
  58734. !elOptionStyle.hasOwnProperty('textStroke') && elOptionStyle.stroke && (
  58735. elOptionStyle.textStroke = elOptionStyle.stroke
  58736. );
  58737. }
  58738. if (el.type !== 'group') {
  58739. el.useStyle(elOptionStyle);
  58740. // Init animation.
  58741. if (isInit) {
  58742. el.style.opacity = 0;
  58743. var targetOpacity = elOptionStyle.opacity;
  58744. targetOpacity == null && (targetOpacity = 1);
  58745. initProps(el, {style: {opacity: targetOpacity}}, animatableModel, dataIndex);
  58746. }
  58747. }
  58748. if (isInit) {
  58749. el.attr(targetProps);
  58750. }
  58751. else {
  58752. updateProps(el, targetProps, animatableModel, dataIndex);
  58753. }
  58754. // z2 must not be null/undefined, otherwise sort error may occur.
  58755. el.attr({z2: elOption.z2 || 0, silent: elOption.silent});
  58756. elOption.styleEmphasis !== false && setHoverStyle(el, elOption.styleEmphasis);
  58757. }
  58758. function prepareStyleTransition(prop, targetStyle, elOptionStyle, oldElStyle, isInit) {
  58759. if (elOptionStyle[prop] != null && !isInit) {
  58760. targetStyle[prop] = elOptionStyle[prop];
  58761. elOptionStyle[prop] = oldElStyle[prop];
  58762. }
  58763. }
  58764. function makeRenderItem(customSeries, data, ecModel, api) {
  58765. var renderItem = customSeries.get('renderItem');
  58766. var coordSys = customSeries.coordinateSystem;
  58767. var prepareResult = {};
  58768. if (coordSys) {
  58769. if (__DEV__) {
  58770. assert$1(renderItem, 'series.render is required.');
  58771. assert$1(
  58772. coordSys.prepareCustoms || prepareCustoms[coordSys.type],
  58773. 'This coordSys does not support custom series.'
  58774. );
  58775. }
  58776. prepareResult = coordSys.prepareCustoms
  58777. ? coordSys.prepareCustoms()
  58778. : prepareCustoms[coordSys.type](coordSys);
  58779. }
  58780. var userAPI = defaults({
  58781. getWidth: api.getWidth,
  58782. getHeight: api.getHeight,
  58783. getZr: api.getZr,
  58784. getDevicePixelRatio: api.getDevicePixelRatio,
  58785. value: value,
  58786. style: style,
  58787. styleEmphasis: styleEmphasis,
  58788. visual: visual,
  58789. barLayout: barLayout,
  58790. currentSeriesIndices: currentSeriesIndices,
  58791. font: font
  58792. }, prepareResult.api || {});
  58793. var userParams = {
  58794. context: {},
  58795. seriesId: customSeries.id,
  58796. seriesName: customSeries.name,
  58797. seriesIndex: customSeries.seriesIndex,
  58798. coordSys: prepareResult.coordSys,
  58799. dataInsideLength: data.count(),
  58800. encode: wrapEncodeDef(customSeries.getData())
  58801. };
  58802. // Do not support call `api` asynchronously without dataIndexInside input.
  58803. var currDataIndexInside;
  58804. var currDirty = true;
  58805. var currItemModel;
  58806. var currLabelNormalModel;
  58807. var currLabelEmphasisModel;
  58808. var currVisualColor;
  58809. return function (dataIndexInside) {
  58810. currDataIndexInside = dataIndexInside;
  58811. currDirty = true;
  58812. return renderItem && renderItem(
  58813. defaults({
  58814. dataIndexInside: dataIndexInside,
  58815. dataIndex: data.getRawIndex(dataIndexInside)
  58816. }, userParams),
  58817. userAPI
  58818. ) || {};
  58819. };
  58820. // Do not update cache until api called.
  58821. function updateCache(dataIndexInside) {
  58822. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  58823. if (currDirty) {
  58824. currItemModel = data.getItemModel(dataIndexInside);
  58825. currLabelNormalModel = currItemModel.getModel(LABEL_NORMAL);
  58826. currLabelEmphasisModel = currItemModel.getModel(LABEL_EMPHASIS);
  58827. currVisualColor = data.getItemVisual(dataIndexInside, 'color');
  58828. currDirty = false;
  58829. }
  58830. }
  58831. /**
  58832. * @public
  58833. * @param {number|string} dim
  58834. * @param {number} [dataIndexInside=currDataIndexInside]
  58835. * @return {number|string} value
  58836. */
  58837. function value(dim, dataIndexInside) {
  58838. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  58839. return data.get(data.getDimension(dim || 0), dataIndexInside);
  58840. }
  58841. /**
  58842. * By default, `visual` is applied to style (to support visualMap).
  58843. * `visual.color` is applied at `fill`. If user want apply visual.color on `stroke`,
  58844. * it can be implemented as:
  58845. * `api.style({stroke: api.visual('color'), fill: null})`;
  58846. * @public
  58847. * @param {Object} [extra]
  58848. * @param {number} [dataIndexInside=currDataIndexInside]
  58849. */
  58850. function style(extra, dataIndexInside) {
  58851. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  58852. updateCache(dataIndexInside);
  58853. var itemStyle = currItemModel.getModel(ITEM_STYLE_NORMAL_PATH).getItemStyle();
  58854. currVisualColor != null && (itemStyle.fill = currVisualColor);
  58855. var opacity = data.getItemVisual(dataIndexInside, 'opacity');
  58856. opacity != null && (itemStyle.opacity = opacity);
  58857. setTextStyle(itemStyle, currLabelNormalModel, null, {
  58858. autoColor: currVisualColor,
  58859. isRectText: true
  58860. });
  58861. itemStyle.text = currLabelNormalModel.getShallow('show')
  58862. ? retrieve2(
  58863. customSeries.getFormattedLabel(dataIndexInside, 'normal'),
  58864. getDefaultLabel(data, dataIndexInside)
  58865. )
  58866. : null;
  58867. extra && extend(itemStyle, extra);
  58868. return itemStyle;
  58869. }
  58870. /**
  58871. * @public
  58872. * @param {Object} [extra]
  58873. * @param {number} [dataIndexInside=currDataIndexInside]
  58874. */
  58875. function styleEmphasis(extra, dataIndexInside) {
  58876. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  58877. updateCache(dataIndexInside);
  58878. var itemStyle = currItemModel.getModel(ITEM_STYLE_EMPHASIS_PATH).getItemStyle();
  58879. setTextStyle(itemStyle, currLabelEmphasisModel, null, {
  58880. isRectText: true
  58881. }, true);
  58882. itemStyle.text = currLabelEmphasisModel.getShallow('show')
  58883. ? retrieve3(
  58884. customSeries.getFormattedLabel(dataIndexInside, 'emphasis'),
  58885. customSeries.getFormattedLabel(dataIndexInside, 'normal'),
  58886. getDefaultLabel(data, dataIndexInside)
  58887. )
  58888. : null;
  58889. extra && extend(itemStyle, extra);
  58890. return itemStyle;
  58891. }
  58892. /**
  58893. * @public
  58894. * @param {string} visualType
  58895. * @param {number} [dataIndexInside=currDataIndexInside]
  58896. */
  58897. function visual(visualType, dataIndexInside) {
  58898. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  58899. return data.getItemVisual(dataIndexInside, visualType);
  58900. }
  58901. /**
  58902. * @public
  58903. * @param {number} opt.count Positive interger.
  58904. * @param {number} [opt.barWidth]
  58905. * @param {number} [opt.barMaxWidth]
  58906. * @param {number} [opt.barGap]
  58907. * @param {number} [opt.barCategoryGap]
  58908. * @return {Object} {width, offset, offsetCenter} is not support, return undefined.
  58909. */
  58910. function barLayout(opt) {
  58911. if (coordSys.getBaseAxis) {
  58912. var baseAxis = coordSys.getBaseAxis();
  58913. return getLayoutOnAxis(defaults({axis: baseAxis}, opt), api);
  58914. }
  58915. }
  58916. /**
  58917. * @public
  58918. * @return {Array.<number>}
  58919. */
  58920. function currentSeriesIndices() {
  58921. return ecModel.getCurrentSeriesIndices();
  58922. }
  58923. /**
  58924. * @public
  58925. * @param {Object} opt
  58926. * @param {string} [opt.fontStyle]
  58927. * @param {number} [opt.fontWeight]
  58928. * @param {number} [opt.fontSize]
  58929. * @param {string} [opt.fontFamily]
  58930. * @return {string} font string
  58931. */
  58932. function font(opt) {
  58933. return getFont(opt, ecModel);
  58934. }
  58935. }
  58936. function wrapEncodeDef(data) {
  58937. var encodeDef = {};
  58938. each$1(data.dimensions, function (dimName, dataDimIndex) {
  58939. var dimInfo = data.getDimensionInfo(dimName);
  58940. if (!dimInfo.isExtraCoord) {
  58941. var coordDim = dimInfo.coordDim;
  58942. var dataDims = encodeDef[coordDim] = encodeDef[coordDim] || [];
  58943. dataDims[dimInfo.coordDimIndex] = dataDimIndex;
  58944. }
  58945. });
  58946. return encodeDef;
  58947. }
  58948. function createOrUpdate$1(el, dataIndex, elOption, animatableModel, group, data) {
  58949. el = doCreateOrUpdate(el, dataIndex, elOption, animatableModel, group, data);
  58950. el && data.setItemGraphicEl(dataIndex, el);
  58951. return el;
  58952. }
  58953. function doCreateOrUpdate(el, dataIndex, elOption, animatableModel, group, data) {
  58954. var elOptionType = elOption.type;
  58955. if (el
  58956. && elOptionType !== el.__customGraphicType
  58957. && (elOptionType !== 'path' || elOption.pathData !== el.__customPathData)
  58958. && (elOptionType !== 'image' || elOption.style.image !== el.__customImagePath)
  58959. && (elOptionType !== 'text' || elOption.style.text !== el.__customText)
  58960. ) {
  58961. group.remove(el);
  58962. el = null;
  58963. }
  58964. // `elOption.type` is undefined when `renderItem` returns nothing.
  58965. if (elOptionType == null) {
  58966. return;
  58967. }
  58968. var isInit = !el;
  58969. !el && (el = createEl(elOption));
  58970. updateEl(el, dataIndex, elOption, animatableModel, data, isInit);
  58971. if (elOptionType === 'group') {
  58972. var oldChildren = el.children() || [];
  58973. var newChildren = elOption.children || [];
  58974. if (elOption.diffChildrenByName) {
  58975. // lower performance.
  58976. diffGroupChildren({
  58977. oldChildren: oldChildren,
  58978. newChildren: newChildren,
  58979. dataIndex: dataIndex,
  58980. animatableModel: animatableModel,
  58981. group: el,
  58982. data: data
  58983. });
  58984. }
  58985. else {
  58986. // better performance.
  58987. var index = 0;
  58988. for (; index < newChildren.length; index++) {
  58989. doCreateOrUpdate(
  58990. el.childAt(index),
  58991. dataIndex,
  58992. newChildren[index],
  58993. animatableModel,
  58994. el,
  58995. data
  58996. );
  58997. }
  58998. for (; index < oldChildren.length; index++) {
  58999. oldChildren[index] && el.remove(oldChildren[index]);
  59000. }
  59001. }
  59002. }
  59003. group.add(el);
  59004. return el;
  59005. }
  59006. function diffGroupChildren(context) {
  59007. (new DataDiffer(
  59008. context.oldChildren,
  59009. context.newChildren,
  59010. getKey,
  59011. getKey,
  59012. context
  59013. ))
  59014. .add(processAddUpdate)
  59015. .update(processAddUpdate)
  59016. .remove(processRemove)
  59017. .execute();
  59018. }
  59019. function getKey(item, idx) {
  59020. var name = item && item.name;
  59021. return name != null ? name : GROUP_DIFF_PREFIX + idx;
  59022. }
  59023. function processAddUpdate(newIndex, oldIndex) {
  59024. var context = this.context;
  59025. var childOption = newIndex != null ? context.newChildren[newIndex] : null;
  59026. var child = oldIndex != null ? context.oldChildren[oldIndex] : null;
  59027. doCreateOrUpdate(
  59028. child,
  59029. context.dataIndex,
  59030. childOption,
  59031. context.animatableModel,
  59032. context.group,
  59033. context.data
  59034. );
  59035. }
  59036. function processRemove(oldIndex) {
  59037. var context = this.context;
  59038. var child = context.oldChildren[oldIndex];
  59039. child && context.group.remove(child);
  59040. }
  59041. /*
  59042. * Licensed to the Apache Software Foundation (ASF) under one
  59043. * or more contributor license agreements. See the NOTICE file
  59044. * distributed with this work for additional information
  59045. * regarding copyright ownership. The ASF licenses this file
  59046. * to you under the Apache License, Version 2.0 (the
  59047. * "License"); you may not use this file except in compliance
  59048. * with the License. You may obtain a copy of the License at
  59049. *
  59050. * http://www.apache.org/licenses/LICENSE-2.0
  59051. *
  59052. * Unless required by applicable law or agreed to in writing,
  59053. * software distributed under the License is distributed on an
  59054. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59055. * KIND, either express or implied. See the License for the
  59056. * specific language governing permissions and limitations
  59057. * under the License.
  59058. */
  59059. // -------------
  59060. // Preprocessor
  59061. // -------------
  59062. registerPreprocessor(function (option) {
  59063. var graphicOption = option.graphic;
  59064. // Convert
  59065. // {graphic: [{left: 10, type: 'circle'}, ...]}
  59066. // or
  59067. // {graphic: {left: 10, type: 'circle'}}
  59068. // to
  59069. // {graphic: [{elements: [{left: 10, type: 'circle'}, ...]}]}
  59070. if (isArray(graphicOption)) {
  59071. if (!graphicOption[0] || !graphicOption[0].elements) {
  59072. option.graphic = [{elements: graphicOption}];
  59073. }
  59074. else {
  59075. // Only one graphic instance can be instantiated. (We dont
  59076. // want that too many views are created in echarts._viewMap)
  59077. option.graphic = [option.graphic[0]];
  59078. }
  59079. }
  59080. else if (graphicOption && !graphicOption.elements) {
  59081. option.graphic = [{elements: [graphicOption]}];
  59082. }
  59083. });
  59084. // ------
  59085. // Model
  59086. // ------
  59087. var GraphicModel = extendComponentModel({
  59088. type: 'graphic',
  59089. defaultOption: {
  59090. // Extra properties for each elements:
  59091. //
  59092. // left/right/top/bottom: (like 12, '22%', 'center', default undefined)
  59093. // If left/rigth is set, shape.x/shape.cx/position will not be used.
  59094. // If top/bottom is set, shape.y/shape.cy/position will not be used.
  59095. // This mechanism is useful when you want to position a group/element
  59096. // against the right side or the center of this container.
  59097. //
  59098. // width/height: (can only be pixel value, default 0)
  59099. // Only be used to specify contianer(group) size, if needed. And
  59100. // can not be percentage value (like '33%'). See the reason in the
  59101. // layout algorithm below.
  59102. //
  59103. // bounding: (enum: 'all' (default) | 'raw')
  59104. // Specify how to calculate boundingRect when locating.
  59105. // 'all': Get uioned and transformed boundingRect
  59106. // from both itself and its descendants.
  59107. // This mode simplies confining a group of elements in the bounding
  59108. // of their ancester container (e.g., using 'right: 0').
  59109. // 'raw': Only use the boundingRect of itself and before transformed.
  59110. // This mode is similar to css behavior, which is useful when you
  59111. // want an element to be able to overflow its container. (Consider
  59112. // a rotated circle needs to be located in a corner.)
  59113. // Note: elements is always behind its ancestors in this elements array.
  59114. elements: [],
  59115. parentId: null
  59116. },
  59117. /**
  59118. * Save el options for the sake of the performance (only update modified graphics).
  59119. * The order is the same as those in option. (ancesters -> descendants)
  59120. *
  59121. * @private
  59122. * @type {Array.<Object>}
  59123. */
  59124. _elOptionsToUpdate: null,
  59125. /**
  59126. * @override
  59127. */
  59128. mergeOption: function (option) {
  59129. // Prevent default merge to elements
  59130. var elements = this.option.elements;
  59131. this.option.elements = null;
  59132. GraphicModel.superApply(this, 'mergeOption', arguments);
  59133. this.option.elements = elements;
  59134. },
  59135. /**
  59136. * @override
  59137. */
  59138. optionUpdated: function (newOption, isInit) {
  59139. var thisOption = this.option;
  59140. var newList = (isInit ? thisOption : newOption).elements;
  59141. var existList = thisOption.elements = isInit ? [] : thisOption.elements;
  59142. var flattenedList = [];
  59143. this._flatten(newList, flattenedList);
  59144. var mappingResult = mappingToExists(existList, flattenedList);
  59145. makeIdAndName(mappingResult);
  59146. // Clear elOptionsToUpdate
  59147. var elOptionsToUpdate = this._elOptionsToUpdate = [];
  59148. each$1(mappingResult, function (resultItem, index) {
  59149. var newElOption = resultItem.option;
  59150. if (__DEV__) {
  59151. assert$1(
  59152. isObject$1(newElOption) || resultItem.exist,
  59153. 'Empty graphic option definition'
  59154. );
  59155. }
  59156. if (!newElOption) {
  59157. return;
  59158. }
  59159. elOptionsToUpdate.push(newElOption);
  59160. setKeyInfoToNewElOption(resultItem, newElOption);
  59161. mergeNewElOptionToExist(existList, index, newElOption);
  59162. setLayoutInfoToExist(existList[index], newElOption);
  59163. }, this);
  59164. // Clean
  59165. for (var i = existList.length - 1; i >= 0; i--) {
  59166. if (existList[i] == null) {
  59167. existList.splice(i, 1);
  59168. }
  59169. else {
  59170. // $action should be volatile, otherwise option gotten from
  59171. // `getOption` will contain unexpected $action.
  59172. delete existList[i].$action;
  59173. }
  59174. }
  59175. },
  59176. /**
  59177. * Convert
  59178. * [{
  59179. * type: 'group',
  59180. * id: 'xx',
  59181. * children: [{type: 'circle'}, {type: 'polygon'}]
  59182. * }]
  59183. * to
  59184. * [
  59185. * {type: 'group', id: 'xx'},
  59186. * {type: 'circle', parentId: 'xx'},
  59187. * {type: 'polygon', parentId: 'xx'}
  59188. * ]
  59189. *
  59190. * @private
  59191. * @param {Array.<Object>} optionList option list
  59192. * @param {Array.<Object>} result result of flatten
  59193. * @param {Object} parentOption parent option
  59194. */
  59195. _flatten: function (optionList, result, parentOption) {
  59196. each$1(optionList, function (option) {
  59197. if (!option) {
  59198. return;
  59199. }
  59200. if (parentOption) {
  59201. option.parentOption = parentOption;
  59202. }
  59203. result.push(option);
  59204. var children = option.children;
  59205. if (option.type === 'group' && children) {
  59206. this._flatten(children, result, option);
  59207. }
  59208. // Deleting for JSON output, and for not affecting group creation.
  59209. delete option.children;
  59210. }, this);
  59211. },
  59212. // FIXME
  59213. // Pass to view using payload? setOption has a payload?
  59214. useElOptionsToUpdate: function () {
  59215. var els = this._elOptionsToUpdate;
  59216. // Clear to avoid render duplicately when zooming.
  59217. this._elOptionsToUpdate = null;
  59218. return els;
  59219. }
  59220. });
  59221. // -----
  59222. // View
  59223. // -----
  59224. extendComponentView({
  59225. type: 'graphic',
  59226. /**
  59227. * @override
  59228. */
  59229. init: function (ecModel, api) {
  59230. /**
  59231. * @private
  59232. * @type {module:zrender/core/util.HashMap}
  59233. */
  59234. this._elMap = createHashMap();
  59235. /**
  59236. * @private
  59237. * @type {module:echarts/graphic/GraphicModel}
  59238. */
  59239. this._lastGraphicModel;
  59240. },
  59241. /**
  59242. * @override
  59243. */
  59244. render: function (graphicModel, ecModel, api) {
  59245. // Having leveraged between use cases and algorithm complexity, a very
  59246. // simple layout mechanism is used:
  59247. // The size(width/height) can be determined by itself or its parent (not
  59248. // implemented yet), but can not by its children. (Top-down travel)
  59249. // The location(x/y) can be determined by the bounding rect of itself
  59250. // (can including its descendants or not) and the size of its parent.
  59251. // (Bottom-up travel)
  59252. // When `chart.clear()` or `chart.setOption({...}, true)` with the same id,
  59253. // view will be reused.
  59254. if (graphicModel !== this._lastGraphicModel) {
  59255. this._clear();
  59256. }
  59257. this._lastGraphicModel = graphicModel;
  59258. this._updateElements(graphicModel, api);
  59259. this._relocate(graphicModel, api);
  59260. },
  59261. /**
  59262. * Update graphic elements.
  59263. *
  59264. * @private
  59265. * @param {Object} graphicModel graphic model
  59266. * @param {module:echarts/ExtensionAPI} api extension API
  59267. */
  59268. _updateElements: function (graphicModel, api) {
  59269. var elOptionsToUpdate = graphicModel.useElOptionsToUpdate();
  59270. if (!elOptionsToUpdate) {
  59271. return;
  59272. }
  59273. var elMap = this._elMap;
  59274. var rootGroup = this.group;
  59275. // Top-down tranverse to assign graphic settings to each elements.
  59276. each$1(elOptionsToUpdate, function (elOption) {
  59277. var $action = elOption.$action;
  59278. var id = elOption.id;
  59279. var existEl = elMap.get(id);
  59280. var parentId = elOption.parentId;
  59281. var targetElParent = parentId != null ? elMap.get(parentId) : rootGroup;
  59282. if (elOption.type === 'text') {
  59283. var elOptionStyle = elOption.style;
  59284. // In top/bottom mode, textVerticalAlign should not be used, which cause
  59285. // inaccurately locating.
  59286. if (elOption.hv && elOption.hv[1]) {
  59287. elOptionStyle.textVerticalAlign = elOptionStyle.textBaseline = null;
  59288. }
  59289. // Compatible with previous setting: both support fill and textFill,
  59290. // stroke and textStroke.
  59291. !elOptionStyle.hasOwnProperty('textFill') && elOptionStyle.fill && (
  59292. elOptionStyle.textFill = elOptionStyle.fill
  59293. );
  59294. !elOptionStyle.hasOwnProperty('textStroke') && elOptionStyle.stroke && (
  59295. elOptionStyle.textStroke = elOptionStyle.stroke
  59296. );
  59297. }
  59298. // Remove unnecessary props to avoid potential problems.
  59299. var elOptionCleaned = getCleanedElOption(elOption);
  59300. // For simple, do not support parent change, otherwise reorder is needed.
  59301. if (__DEV__) {
  59302. existEl && assert$1(
  59303. targetElParent === existEl.parent,
  59304. 'Changing parent is not supported.'
  59305. );
  59306. }
  59307. if (!$action || $action === 'merge') {
  59308. existEl
  59309. ? existEl.attr(elOptionCleaned)
  59310. : createEl$1(id, targetElParent, elOptionCleaned, elMap);
  59311. }
  59312. else if ($action === 'replace') {
  59313. removeEl(existEl, elMap);
  59314. createEl$1(id, targetElParent, elOptionCleaned, elMap);
  59315. }
  59316. else if ($action === 'remove') {
  59317. removeEl(existEl, elMap);
  59318. }
  59319. var el = elMap.get(id);
  59320. if (el) {
  59321. el.__ecGraphicWidth = elOption.width;
  59322. el.__ecGraphicHeight = elOption.height;
  59323. }
  59324. });
  59325. },
  59326. /**
  59327. * Locate graphic elements.
  59328. *
  59329. * @private
  59330. * @param {Object} graphicModel graphic model
  59331. * @param {module:echarts/ExtensionAPI} api extension API
  59332. */
  59333. _relocate: function (graphicModel, api) {
  59334. var elOptions = graphicModel.option.elements;
  59335. var rootGroup = this.group;
  59336. var elMap = this._elMap;
  59337. // Bottom-up tranvese all elements (consider ec resize) to locate elements.
  59338. for (var i = elOptions.length - 1; i >= 0; i--) {
  59339. var elOption = elOptions[i];
  59340. var el = elMap.get(elOption.id);
  59341. if (!el) {
  59342. continue;
  59343. }
  59344. var parentEl = el.parent;
  59345. var containerInfo = parentEl === rootGroup
  59346. ? {
  59347. width: api.getWidth(),
  59348. height: api.getHeight()
  59349. }
  59350. : { // Like 'position:absolut' in css, default 0.
  59351. width: parentEl.__ecGraphicWidth || 0,
  59352. height: parentEl.__ecGraphicHeight || 0
  59353. };
  59354. positionElement(
  59355. el, elOption, containerInfo, null,
  59356. {hv: elOption.hv, boundingMode: elOption.bounding}
  59357. );
  59358. }
  59359. },
  59360. /**
  59361. * Clear all elements.
  59362. *
  59363. * @private
  59364. */
  59365. _clear: function () {
  59366. var elMap = this._elMap;
  59367. elMap.each(function (el) {
  59368. removeEl(el, elMap);
  59369. });
  59370. this._elMap = createHashMap();
  59371. },
  59372. /**
  59373. * @override
  59374. */
  59375. dispose: function () {
  59376. this._clear();
  59377. }
  59378. });
  59379. function createEl$1(id, targetElParent, elOption, elMap) {
  59380. var graphicType = elOption.type;
  59381. if (__DEV__) {
  59382. assert$1(graphicType, 'graphic type MUST be set');
  59383. }
  59384. var Clz = graphic[graphicType.charAt(0).toUpperCase() + graphicType.slice(1)];
  59385. if (__DEV__) {
  59386. assert$1(Clz, 'graphic type can not be found');
  59387. }
  59388. var el = new Clz(elOption);
  59389. targetElParent.add(el);
  59390. elMap.set(id, el);
  59391. el.__ecGraphicId = id;
  59392. }
  59393. function removeEl(existEl, elMap) {
  59394. var existElParent = existEl && existEl.parent;
  59395. if (existElParent) {
  59396. existEl.type === 'group' && existEl.traverse(function (el) {
  59397. removeEl(el, elMap);
  59398. });
  59399. elMap.removeKey(existEl.__ecGraphicId);
  59400. existElParent.remove(existEl);
  59401. }
  59402. }
  59403. // Remove unnecessary props to avoid potential problems.
  59404. function getCleanedElOption(elOption) {
  59405. elOption = extend({}, elOption);
  59406. each$1(
  59407. ['id', 'parentId', '$action', 'hv', 'bounding'].concat(LOCATION_PARAMS),
  59408. function (name) {
  59409. delete elOption[name];
  59410. }
  59411. );
  59412. return elOption;
  59413. }
  59414. function isSetLoc(obj, props) {
  59415. var isSet;
  59416. each$1(props, function (prop) {
  59417. obj[prop] != null && obj[prop] !== 'auto' && (isSet = true);
  59418. });
  59419. return isSet;
  59420. }
  59421. function setKeyInfoToNewElOption(resultItem, newElOption) {
  59422. var existElOption = resultItem.exist;
  59423. // Set id and type after id assigned.
  59424. newElOption.id = resultItem.keyInfo.id;
  59425. !newElOption.type && existElOption && (newElOption.type = existElOption.type);
  59426. // Set parent id if not specified
  59427. if (newElOption.parentId == null) {
  59428. var newElParentOption = newElOption.parentOption;
  59429. if (newElParentOption) {
  59430. newElOption.parentId = newElParentOption.id;
  59431. }
  59432. else if (existElOption) {
  59433. newElOption.parentId = existElOption.parentId;
  59434. }
  59435. }
  59436. // Clear
  59437. newElOption.parentOption = null;
  59438. }
  59439. function mergeNewElOptionToExist(existList, index, newElOption) {
  59440. // Update existing options, for `getOption` feature.
  59441. var newElOptCopy = extend({}, newElOption);
  59442. var existElOption = existList[index];
  59443. var $action = newElOption.$action || 'merge';
  59444. if ($action === 'merge') {
  59445. if (existElOption) {
  59446. if (__DEV__) {
  59447. var newType = newElOption.type;
  59448. assert$1(
  59449. !newType || existElOption.type === newType,
  59450. 'Please set $action: "replace" to change `type`'
  59451. );
  59452. }
  59453. // We can ensure that newElOptCopy and existElOption are not
  59454. // the same object, so `merge` will not change newElOptCopy.
  59455. merge(existElOption, newElOptCopy, true);
  59456. // Rigid body, use ignoreSize.
  59457. mergeLayoutParam(existElOption, newElOptCopy, {ignoreSize: true});
  59458. // Will be used in render.
  59459. copyLayoutParams(newElOption, existElOption);
  59460. }
  59461. else {
  59462. existList[index] = newElOptCopy;
  59463. }
  59464. }
  59465. else if ($action === 'replace') {
  59466. existList[index] = newElOptCopy;
  59467. }
  59468. else if ($action === 'remove') {
  59469. // null will be cleaned later.
  59470. existElOption && (existList[index] = null);
  59471. }
  59472. }
  59473. function setLayoutInfoToExist(existItem, newElOption) {
  59474. if (!existItem) {
  59475. return;
  59476. }
  59477. existItem.hv = newElOption.hv = [
  59478. // Rigid body, dont care `width`.
  59479. isSetLoc(newElOption, ['left', 'right']),
  59480. // Rigid body, dont care `height`.
  59481. isSetLoc(newElOption, ['top', 'bottom'])
  59482. ];
  59483. // Give default group size. Otherwise layout error may occur.
  59484. if (existItem.type === 'group') {
  59485. existItem.width == null && (existItem.width = newElOption.width = 0);
  59486. existItem.height == null && (existItem.height = newElOption.height = 0);
  59487. }
  59488. }
  59489. /*
  59490. * Licensed to the Apache Software Foundation (ASF) under one
  59491. * or more contributor license agreements. See the NOTICE file
  59492. * distributed with this work for additional information
  59493. * regarding copyright ownership. The ASF licenses this file
  59494. * to you under the Apache License, Version 2.0 (the
  59495. * "License"); you may not use this file except in compliance
  59496. * with the License. You may obtain a copy of the License at
  59497. *
  59498. * http://www.apache.org/licenses/LICENSE-2.0
  59499. *
  59500. * Unless required by applicable law or agreed to in writing,
  59501. * software distributed under the License is distributed on an
  59502. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59503. * KIND, either express or implied. See the License for the
  59504. * specific language governing permissions and limitations
  59505. * under the License.
  59506. */
  59507. /*
  59508. * Licensed to the Apache Software Foundation (ASF) under one
  59509. * or more contributor license agreements. See the NOTICE file
  59510. * distributed with this work for additional information
  59511. * regarding copyright ownership. The ASF licenses this file
  59512. * to you under the Apache License, Version 2.0 (the
  59513. * "License"); you may not use this file except in compliance
  59514. * with the License. You may obtain a copy of the License at
  59515. *
  59516. * http://www.apache.org/licenses/LICENSE-2.0
  59517. *
  59518. * Unless required by applicable law or agreed to in writing,
  59519. * software distributed under the License is distributed on an
  59520. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59521. * KIND, either express or implied. See the License for the
  59522. * specific language governing permissions and limitations
  59523. * under the License.
  59524. */
  59525. var LegendModel = extendComponentModel({
  59526. type: 'legend.plain',
  59527. dependencies: ['series'],
  59528. layoutMode: {
  59529. type: 'box',
  59530. // legend.width/height are maxWidth/maxHeight actually,
  59531. // whereas realy width/height is calculated by its content.
  59532. // (Setting {left: 10, right: 10} does not make sense).
  59533. // So consider the case:
  59534. // `setOption({legend: {left: 10});`
  59535. // then `setOption({legend: {right: 10});`
  59536. // The previous `left` should be cleared by setting `ignoreSize`.
  59537. ignoreSize: true
  59538. },
  59539. init: function (option, parentModel, ecModel) {
  59540. this.mergeDefaultAndTheme(option, ecModel);
  59541. option.selected = option.selected || {};
  59542. },
  59543. mergeOption: function (option) {
  59544. LegendModel.superCall(this, 'mergeOption', option);
  59545. },
  59546. optionUpdated: function () {
  59547. this._updateData(this.ecModel);
  59548. var legendData = this._data;
  59549. // If selectedMode is single, try to select one
  59550. if (legendData[0] && this.get('selectedMode') === 'single') {
  59551. var hasSelected = false;
  59552. // If has any selected in option.selected
  59553. for (var i = 0; i < legendData.length; i++) {
  59554. var name = legendData[i].get('name');
  59555. if (this.isSelected(name)) {
  59556. // Force to unselect others
  59557. this.select(name);
  59558. hasSelected = true;
  59559. break;
  59560. }
  59561. }
  59562. // Try select the first if selectedMode is single
  59563. !hasSelected && this.select(legendData[0].get('name'));
  59564. }
  59565. },
  59566. _updateData: function (ecModel) {
  59567. var potentialData = [];
  59568. var availableNames = [];
  59569. ecModel.eachRawSeries(function (seriesModel) {
  59570. var seriesName = seriesModel.name;
  59571. availableNames.push(seriesName);
  59572. var isPotential;
  59573. if (seriesModel.legendDataProvider) {
  59574. var data = seriesModel.legendDataProvider();
  59575. var names = data.mapArray(data.getName);
  59576. if (!ecModel.isSeriesFiltered(seriesModel)) {
  59577. availableNames = availableNames.concat(names);
  59578. }
  59579. if (names.length) {
  59580. potentialData = potentialData.concat(names);
  59581. }
  59582. else {
  59583. isPotential = true;
  59584. }
  59585. }
  59586. else {
  59587. isPotential = true;
  59588. }
  59589. if (isPotential && isNameSpecified(seriesModel)) {
  59590. potentialData.push(seriesModel.name);
  59591. }
  59592. });
  59593. /**
  59594. * @type {Array.<string>}
  59595. * @private
  59596. */
  59597. this._availableNames = availableNames;
  59598. // If legend.data not specified in option, use availableNames as data,
  59599. // which is convinient for user preparing option.
  59600. var rawData = this.get('data') || potentialData;
  59601. var legendData = map(rawData, function (dataItem) {
  59602. // Can be string or number
  59603. if (typeof dataItem === 'string' || typeof dataItem === 'number') {
  59604. dataItem = {
  59605. name: dataItem
  59606. };
  59607. }
  59608. return new Model(dataItem, this, this.ecModel);
  59609. }, this);
  59610. /**
  59611. * @type {Array.<module:echarts/model/Model>}
  59612. * @private
  59613. */
  59614. this._data = legendData;
  59615. },
  59616. /**
  59617. * @return {Array.<module:echarts/model/Model>}
  59618. */
  59619. getData: function () {
  59620. return this._data;
  59621. },
  59622. /**
  59623. * @param {string} name
  59624. */
  59625. select: function (name) {
  59626. var selected = this.option.selected;
  59627. var selectedMode = this.get('selectedMode');
  59628. if (selectedMode === 'single') {
  59629. var data = this._data;
  59630. each$1(data, function (dataItem) {
  59631. selected[dataItem.get('name')] = false;
  59632. });
  59633. }
  59634. selected[name] = true;
  59635. },
  59636. /**
  59637. * @param {string} name
  59638. */
  59639. unSelect: function (name) {
  59640. if (this.get('selectedMode') !== 'single') {
  59641. this.option.selected[name] = false;
  59642. }
  59643. },
  59644. /**
  59645. * @param {string} name
  59646. */
  59647. toggleSelected: function (name) {
  59648. var selected = this.option.selected;
  59649. // Default is true
  59650. if (!selected.hasOwnProperty(name)) {
  59651. selected[name] = true;
  59652. }
  59653. this[selected[name] ? 'unSelect' : 'select'](name);
  59654. },
  59655. /**
  59656. * @param {string} name
  59657. */
  59658. isSelected: function (name) {
  59659. var selected = this.option.selected;
  59660. return !(selected.hasOwnProperty(name) && !selected[name])
  59661. && indexOf(this._availableNames, name) >= 0;
  59662. },
  59663. defaultOption: {
  59664. // 一级层叠
  59665. zlevel: 0,
  59666. // 二级层叠
  59667. z: 4,
  59668. show: true,
  59669. // 布局方式,默认为水平布局,可选为:
  59670. // 'horizontal' | 'vertical'
  59671. orient: 'horizontal',
  59672. left: 'center',
  59673. // right: 'center',
  59674. top: 0,
  59675. // bottom: null,
  59676. // 水平对齐
  59677. // 'auto' | 'left' | 'right'
  59678. // 默认为 'auto', 根据 x 的位置判断是左对齐还是右对齐
  59679. align: 'auto',
  59680. backgroundColor: 'rgba(0,0,0,0)',
  59681. // 图例边框颜色
  59682. borderColor: '#ccc',
  59683. borderRadius: 0,
  59684. // 图例边框线宽,单位px,默认为0(无边框)
  59685. borderWidth: 0,
  59686. // 图例内边距,单位px,默认各方向内边距为5,
  59687. // 接受数组分别设定上右下左边距,同css
  59688. padding: 5,
  59689. // 各个item之间的间隔,单位px,默认为10,
  59690. // 横向布局时为水平间隔,纵向布局时为纵向间隔
  59691. itemGap: 10,
  59692. // 图例图形宽度
  59693. itemWidth: 25,
  59694. // 图例图形高度
  59695. itemHeight: 14,
  59696. // 图例关闭时候的颜色
  59697. inactiveColor: '#ccc',
  59698. textStyle: {
  59699. // 图例文字颜色
  59700. color: '#333'
  59701. },
  59702. // formatter: '',
  59703. // 选择模式,默认开启图例开关
  59704. selectedMode: true,
  59705. // 配置默认选中状态,可配合LEGEND.SELECTED事件做动态数据载入
  59706. // selected: null,
  59707. // 图例内容(详见legend.data,数组中每一项代表一个item
  59708. // data: [],
  59709. // Tooltip 相关配置
  59710. tooltip: {
  59711. show: false
  59712. }
  59713. }
  59714. });
  59715. /*
  59716. * Licensed to the Apache Software Foundation (ASF) under one
  59717. * or more contributor license agreements. See the NOTICE file
  59718. * distributed with this work for additional information
  59719. * regarding copyright ownership. The ASF licenses this file
  59720. * to you under the Apache License, Version 2.0 (the
  59721. * "License"); you may not use this file except in compliance
  59722. * with the License. You may obtain a copy of the License at
  59723. *
  59724. * http://www.apache.org/licenses/LICENSE-2.0
  59725. *
  59726. * Unless required by applicable law or agreed to in writing,
  59727. * software distributed under the License is distributed on an
  59728. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59729. * KIND, either express or implied. See the License for the
  59730. * specific language governing permissions and limitations
  59731. * under the License.
  59732. */
  59733. function legendSelectActionHandler(methodName, payload, ecModel) {
  59734. var selectedMap = {};
  59735. var isToggleSelect = methodName === 'toggleSelected';
  59736. var isSelected;
  59737. // Update all legend components
  59738. ecModel.eachComponent('legend', function (legendModel) {
  59739. if (isToggleSelect && isSelected != null) {
  59740. // Force other legend has same selected status
  59741. // Or the first is toggled to true and other are toggled to false
  59742. // In the case one legend has some item unSelected in option. And if other legend
  59743. // doesn't has the item, they will assume it is selected.
  59744. legendModel[isSelected ? 'select' : 'unSelect'](payload.name);
  59745. }
  59746. else {
  59747. legendModel[methodName](payload.name);
  59748. isSelected = legendModel.isSelected(payload.name);
  59749. }
  59750. var legendData = legendModel.getData();
  59751. each$1(legendData, function (model) {
  59752. var name = model.get('name');
  59753. // Wrap element
  59754. if (name === '\n' || name === '') {
  59755. return;
  59756. }
  59757. var isItemSelected = legendModel.isSelected(name);
  59758. if (selectedMap.hasOwnProperty(name)) {
  59759. // Unselected if any legend is unselected
  59760. selectedMap[name] = selectedMap[name] && isItemSelected;
  59761. }
  59762. else {
  59763. selectedMap[name] = isItemSelected;
  59764. }
  59765. });
  59766. });
  59767. // Return the event explicitly
  59768. return {
  59769. name: payload.name,
  59770. selected: selectedMap
  59771. };
  59772. }
  59773. /**
  59774. * @event legendToggleSelect
  59775. * @type {Object}
  59776. * @property {string} type 'legendToggleSelect'
  59777. * @property {string} [from]
  59778. * @property {string} name Series name or data item name
  59779. */
  59780. registerAction(
  59781. 'legendToggleSelect', 'legendselectchanged',
  59782. curry(legendSelectActionHandler, 'toggleSelected')
  59783. );
  59784. /**
  59785. * @event legendSelect
  59786. * @type {Object}
  59787. * @property {string} type 'legendSelect'
  59788. * @property {string} name Series name or data item name
  59789. */
  59790. registerAction(
  59791. 'legendSelect', 'legendselected',
  59792. curry(legendSelectActionHandler, 'select')
  59793. );
  59794. /**
  59795. * @event legendUnSelect
  59796. * @type {Object}
  59797. * @property {string} type 'legendUnSelect'
  59798. * @property {string} name Series name or data item name
  59799. */
  59800. registerAction(
  59801. 'legendUnSelect', 'legendunselected',
  59802. curry(legendSelectActionHandler, 'unSelect')
  59803. );
  59804. /*
  59805. * Licensed to the Apache Software Foundation (ASF) under one
  59806. * or more contributor license agreements. See the NOTICE file
  59807. * distributed with this work for additional information
  59808. * regarding copyright ownership. The ASF licenses this file
  59809. * to you under the Apache License, Version 2.0 (the
  59810. * "License"); you may not use this file except in compliance
  59811. * with the License. You may obtain a copy of the License at
  59812. *
  59813. * http://www.apache.org/licenses/LICENSE-2.0
  59814. *
  59815. * Unless required by applicable law or agreed to in writing,
  59816. * software distributed under the License is distributed on an
  59817. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59818. * KIND, either express or implied. See the License for the
  59819. * specific language governing permissions and limitations
  59820. * under the License.
  59821. */
  59822. /**
  59823. * Layout list like component.
  59824. * It will box layout each items in group of component and then position the whole group in the viewport
  59825. * @param {module:zrender/group/Group} group
  59826. * @param {module:echarts/model/Component} componentModel
  59827. * @param {module:echarts/ExtensionAPI}
  59828. */
  59829. function layout$3(group, componentModel, api) {
  59830. var boxLayoutParams = componentModel.getBoxLayoutParams();
  59831. var padding = componentModel.get('padding');
  59832. var viewportSize = {width: api.getWidth(), height: api.getHeight()};
  59833. var rect = getLayoutRect(
  59834. boxLayoutParams,
  59835. viewportSize,
  59836. padding
  59837. );
  59838. box(
  59839. componentModel.get('orient'),
  59840. group,
  59841. componentModel.get('itemGap'),
  59842. rect.width,
  59843. rect.height
  59844. );
  59845. positionElement(
  59846. group,
  59847. boxLayoutParams,
  59848. viewportSize,
  59849. padding
  59850. );
  59851. }
  59852. function makeBackground(rect, componentModel) {
  59853. var padding = normalizeCssArray$1(
  59854. componentModel.get('padding')
  59855. );
  59856. var style = componentModel.getItemStyle(['color', 'opacity']);
  59857. style.fill = componentModel.get('backgroundColor');
  59858. var rect = new Rect({
  59859. shape: {
  59860. x: rect.x - padding[3],
  59861. y: rect.y - padding[0],
  59862. width: rect.width + padding[1] + padding[3],
  59863. height: rect.height + padding[0] + padding[2],
  59864. r: componentModel.get('borderRadius')
  59865. },
  59866. style: style,
  59867. silent: true,
  59868. z2: -1
  59869. });
  59870. // FIXME
  59871. // `subPixelOptimizeRect` may bring some gap between edge of viewpart
  59872. // and background rect when setting like `left: 0`, `top: 0`.
  59873. // graphic.subPixelOptimizeRect(rect);
  59874. return rect;
  59875. }
  59876. /*
  59877. * Licensed to the Apache Software Foundation (ASF) under one
  59878. * or more contributor license agreements. See the NOTICE file
  59879. * distributed with this work for additional information
  59880. * regarding copyright ownership. The ASF licenses this file
  59881. * to you under the Apache License, Version 2.0 (the
  59882. * "License"); you may not use this file except in compliance
  59883. * with the License. You may obtain a copy of the License at
  59884. *
  59885. * http://www.apache.org/licenses/LICENSE-2.0
  59886. *
  59887. * Unless required by applicable law or agreed to in writing,
  59888. * software distributed under the License is distributed on an
  59889. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59890. * KIND, either express or implied. See the License for the
  59891. * specific language governing permissions and limitations
  59892. * under the License.
  59893. */
  59894. var curry$4 = curry;
  59895. var each$16 = each$1;
  59896. var Group$3 = Group;
  59897. var LegendView = extendComponentView({
  59898. type: 'legend.plain',
  59899. newlineDisabled: false,
  59900. /**
  59901. * @override
  59902. */
  59903. init: function () {
  59904. /**
  59905. * @private
  59906. * @type {module:zrender/container/Group}
  59907. */
  59908. this.group.add(this._contentGroup = new Group$3());
  59909. /**
  59910. * @private
  59911. * @type {module:zrender/Element}
  59912. */
  59913. this._backgroundEl;
  59914. },
  59915. /**
  59916. * @protected
  59917. */
  59918. getContentGroup: function () {
  59919. return this._contentGroup;
  59920. },
  59921. /**
  59922. * @override
  59923. */
  59924. render: function (legendModel, ecModel, api) {
  59925. this.resetInner();
  59926. if (!legendModel.get('show', true)) {
  59927. return;
  59928. }
  59929. var itemAlign = legendModel.get('align');
  59930. if (!itemAlign || itemAlign === 'auto') {
  59931. itemAlign = (
  59932. legendModel.get('left') === 'right'
  59933. && legendModel.get('orient') === 'vertical'
  59934. ) ? 'right' : 'left';
  59935. }
  59936. this.renderInner(itemAlign, legendModel, ecModel, api);
  59937. // Perform layout.
  59938. var positionInfo = legendModel.getBoxLayoutParams();
  59939. var viewportSize = {width: api.getWidth(), height: api.getHeight()};
  59940. var padding = legendModel.get('padding');
  59941. var maxSize = getLayoutRect(positionInfo, viewportSize, padding);
  59942. var mainRect = this.layoutInner(legendModel, itemAlign, maxSize);
  59943. // Place mainGroup, based on the calculated `mainRect`.
  59944. var layoutRect = getLayoutRect(
  59945. defaults({width: mainRect.width, height: mainRect.height}, positionInfo),
  59946. viewportSize,
  59947. padding
  59948. );
  59949. this.group.attr('position', [layoutRect.x - mainRect.x, layoutRect.y - mainRect.y]);
  59950. // Render background after group is layout.
  59951. this.group.add(
  59952. this._backgroundEl = makeBackground(mainRect, legendModel)
  59953. );
  59954. },
  59955. /**
  59956. * @protected
  59957. */
  59958. resetInner: function () {
  59959. this.getContentGroup().removeAll();
  59960. this._backgroundEl && this.group.remove(this._backgroundEl);
  59961. },
  59962. /**
  59963. * @protected
  59964. */
  59965. renderInner: function (itemAlign, legendModel, ecModel, api) {
  59966. var contentGroup = this.getContentGroup();
  59967. var legendDrawnMap = createHashMap();
  59968. var selectMode = legendModel.get('selectedMode');
  59969. var excludeSeriesId = [];
  59970. ecModel.eachRawSeries(function (seriesModel) {
  59971. !seriesModel.get('legendHoverLink') && excludeSeriesId.push(seriesModel.id);
  59972. });
  59973. each$16(legendModel.getData(), function (itemModel, dataIndex) {
  59974. var name = itemModel.get('name');
  59975. // Use empty string or \n as a newline string
  59976. if (!this.newlineDisabled && (name === '' || name === '\n')) {
  59977. contentGroup.add(new Group$3({
  59978. newline: true
  59979. }));
  59980. return;
  59981. }
  59982. // Representitive series.
  59983. var seriesModel = ecModel.getSeriesByName(name)[0];
  59984. if (legendDrawnMap.get(name)) {
  59985. // Have been drawed
  59986. return;
  59987. }
  59988. // Series legend
  59989. if (seriesModel) {
  59990. var data = seriesModel.getData();
  59991. var color = data.getVisual('color');
  59992. // If color is a callback function
  59993. if (typeof color === 'function') {
  59994. // Use the first data
  59995. color = color(seriesModel.getDataParams(0));
  59996. }
  59997. // Using rect symbol defaultly
  59998. var legendSymbolType = data.getVisual('legendSymbol') || 'roundRect';
  59999. var symbolType = data.getVisual('symbol');
  60000. var itemGroup = this._createItem(
  60001. name, dataIndex, itemModel, legendModel,
  60002. legendSymbolType, symbolType,
  60003. itemAlign, color,
  60004. selectMode
  60005. );
  60006. itemGroup.on('click', curry$4(dispatchSelectAction, name, api))
  60007. .on('mouseover', curry$4(dispatchHighlightAction, seriesModel, null, api, excludeSeriesId))
  60008. .on('mouseout', curry$4(dispatchDownplayAction, seriesModel, null, api, excludeSeriesId));
  60009. legendDrawnMap.set(name, true);
  60010. }
  60011. else {
  60012. // Data legend of pie, funnel
  60013. ecModel.eachRawSeries(function (seriesModel) {
  60014. // In case multiple series has same data name
  60015. if (legendDrawnMap.get(name)) {
  60016. return;
  60017. }
  60018. if (seriesModel.legendDataProvider) {
  60019. var data = seriesModel.legendDataProvider();
  60020. var idx = data.indexOfName(name);
  60021. if (idx < 0) {
  60022. return;
  60023. }
  60024. var color = data.getItemVisual(idx, 'color');
  60025. var legendSymbolType = 'roundRect';
  60026. var itemGroup = this._createItem(
  60027. name, dataIndex, itemModel, legendModel,
  60028. legendSymbolType, null,
  60029. itemAlign, color,
  60030. selectMode
  60031. );
  60032. // FIXME: consider different series has items with the same name.
  60033. itemGroup.on('click', curry$4(dispatchSelectAction, name, api))
  60034. // FIXME Should not specify the series name
  60035. .on('mouseover', curry$4(dispatchHighlightAction, seriesModel, name, api, excludeSeriesId))
  60036. .on('mouseout', curry$4(dispatchDownplayAction, seriesModel, name, api, excludeSeriesId));
  60037. legendDrawnMap.set(name, true);
  60038. }
  60039. }, this);
  60040. }
  60041. if (__DEV__) {
  60042. if (!legendDrawnMap.get(name)) {
  60043. console.warn(name + ' series not exists. Legend data should be same with series name or data name.');
  60044. }
  60045. }
  60046. }, this);
  60047. },
  60048. _createItem: function (
  60049. name, dataIndex, itemModel, legendModel,
  60050. legendSymbolType, symbolType,
  60051. itemAlign, color, selectMode
  60052. ) {
  60053. var itemWidth = legendModel.get('itemWidth');
  60054. var itemHeight = legendModel.get('itemHeight');
  60055. var inactiveColor = legendModel.get('inactiveColor');
  60056. var symbolKeepAspect = legendModel.get('symbolKeepAspect');
  60057. var isSelected = legendModel.isSelected(name);
  60058. var itemGroup = new Group$3();
  60059. var textStyleModel = itemModel.getModel('textStyle');
  60060. var itemIcon = itemModel.get('icon');
  60061. var tooltipModel = itemModel.getModel('tooltip');
  60062. var legendGlobalTooltipModel = tooltipModel.parentModel;
  60063. // Use user given icon first
  60064. legendSymbolType = itemIcon || legendSymbolType;
  60065. itemGroup.add(createSymbol(
  60066. legendSymbolType,
  60067. 0,
  60068. 0,
  60069. itemWidth,
  60070. itemHeight,
  60071. isSelected ? color : inactiveColor,
  60072. // symbolKeepAspect default true for legend
  60073. symbolKeepAspect == null ? true : symbolKeepAspect
  60074. ));
  60075. // Compose symbols
  60076. // PENDING
  60077. if (!itemIcon && symbolType
  60078. // At least show one symbol, can't be all none
  60079. && ((symbolType !== legendSymbolType) || symbolType == 'none')
  60080. ) {
  60081. var size = itemHeight * 0.8;
  60082. if (symbolType === 'none') {
  60083. symbolType = 'circle';
  60084. }
  60085. // Put symbol in the center
  60086. itemGroup.add(createSymbol(
  60087. symbolType,
  60088. (itemWidth - size) / 2,
  60089. (itemHeight - size) / 2,
  60090. size,
  60091. size,
  60092. isSelected ? color : inactiveColor,
  60093. // symbolKeepAspect default true for legend
  60094. symbolKeepAspect == null ? true : symbolKeepAspect
  60095. ));
  60096. }
  60097. var textX = itemAlign === 'left' ? itemWidth + 5 : -5;
  60098. var textAlign = itemAlign;
  60099. var formatter = legendModel.get('formatter');
  60100. var content = name;
  60101. if (typeof formatter === 'string' && formatter) {
  60102. content = formatter.replace('{name}', name != null ? name : '');
  60103. }
  60104. else if (typeof formatter === 'function') {
  60105. content = formatter(name);
  60106. }
  60107. itemGroup.add(new Text({
  60108. style: setTextStyle({}, textStyleModel, {
  60109. text: content,
  60110. x: textX,
  60111. y: itemHeight / 2,
  60112. textFill: isSelected ? textStyleModel.getTextColor() : inactiveColor,
  60113. textAlign: textAlign,
  60114. textVerticalAlign: 'middle'
  60115. })
  60116. }));
  60117. // Add a invisible rect to increase the area of mouse hover
  60118. var hitRect = new Rect({
  60119. shape: itemGroup.getBoundingRect(),
  60120. invisible: true,
  60121. tooltip: tooltipModel.get('show') ? extend({
  60122. content: name,
  60123. // Defaul formatter
  60124. formatter: legendGlobalTooltipModel.get('formatter', true) || function () {
  60125. return name;
  60126. },
  60127. formatterParams: {
  60128. componentType: 'legend',
  60129. legendIndex: legendModel.componentIndex,
  60130. name: name,
  60131. $vars: ['name']
  60132. }
  60133. }, tooltipModel.option) : null
  60134. });
  60135. itemGroup.add(hitRect);
  60136. itemGroup.eachChild(function (child) {
  60137. child.silent = true;
  60138. });
  60139. hitRect.silent = !selectMode;
  60140. this.getContentGroup().add(itemGroup);
  60141. setHoverStyle(itemGroup);
  60142. itemGroup.__legendDataIndex = dataIndex;
  60143. return itemGroup;
  60144. },
  60145. /**
  60146. * @protected
  60147. */
  60148. layoutInner: function (legendModel, itemAlign, maxSize) {
  60149. var contentGroup = this.getContentGroup();
  60150. // Place items in contentGroup.
  60151. box(
  60152. legendModel.get('orient'),
  60153. contentGroup,
  60154. legendModel.get('itemGap'),
  60155. maxSize.width,
  60156. maxSize.height
  60157. );
  60158. var contentRect = contentGroup.getBoundingRect();
  60159. contentGroup.attr('position', [-contentRect.x, -contentRect.y]);
  60160. return this.group.getBoundingRect();
  60161. }
  60162. });
  60163. function dispatchSelectAction(name, api) {
  60164. api.dispatchAction({
  60165. type: 'legendToggleSelect',
  60166. name: name
  60167. });
  60168. }
  60169. function dispatchHighlightAction(seriesModel, dataName, api, excludeSeriesId) {
  60170. // If element hover will move to a hoverLayer.
  60171. var el = api.getZr().storage.getDisplayList()[0];
  60172. if (!(el && el.useHoverLayer)) {
  60173. api.dispatchAction({
  60174. type: 'highlight',
  60175. seriesName: seriesModel.name,
  60176. name: dataName,
  60177. excludeSeriesId: excludeSeriesId
  60178. });
  60179. }
  60180. }
  60181. function dispatchDownplayAction(seriesModel, dataName, api, excludeSeriesId) {
  60182. // If element hover will move to a hoverLayer.
  60183. var el = api.getZr().storage.getDisplayList()[0];
  60184. if (!(el && el.useHoverLayer)) {
  60185. api.dispatchAction({
  60186. type: 'downplay',
  60187. seriesName: seriesModel.name,
  60188. name: dataName,
  60189. excludeSeriesId: excludeSeriesId
  60190. });
  60191. }
  60192. }
  60193. /*
  60194. * Licensed to the Apache Software Foundation (ASF) under one
  60195. * or more contributor license agreements. See the NOTICE file
  60196. * distributed with this work for additional information
  60197. * regarding copyright ownership. The ASF licenses this file
  60198. * to you under the Apache License, Version 2.0 (the
  60199. * "License"); you may not use this file except in compliance
  60200. * with the License. You may obtain a copy of the License at
  60201. *
  60202. * http://www.apache.org/licenses/LICENSE-2.0
  60203. *
  60204. * Unless required by applicable law or agreed to in writing,
  60205. * software distributed under the License is distributed on an
  60206. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60207. * KIND, either express or implied. See the License for the
  60208. * specific language governing permissions and limitations
  60209. * under the License.
  60210. */
  60211. var legendFilter = function (ecModel) {
  60212. var legendModels = ecModel.findComponents({
  60213. mainType: 'legend'
  60214. });
  60215. if (legendModels && legendModels.length) {
  60216. ecModel.filterSeries(function (series) {
  60217. // If in any legend component the status is not selected.
  60218. // Because in legend series is assumed selected when it is not in the legend data.
  60219. for (var i = 0; i < legendModels.length; i++) {
  60220. if (!legendModels[i].isSelected(series.name)) {
  60221. return false;
  60222. }
  60223. }
  60224. return true;
  60225. });
  60226. }
  60227. };
  60228. /*
  60229. * Licensed to the Apache Software Foundation (ASF) under one
  60230. * or more contributor license agreements. See the NOTICE file
  60231. * distributed with this work for additional information
  60232. * regarding copyright ownership. The ASF licenses this file
  60233. * to you under the Apache License, Version 2.0 (the
  60234. * "License"); you may not use this file except in compliance
  60235. * with the License. You may obtain a copy of the License at
  60236. *
  60237. * http://www.apache.org/licenses/LICENSE-2.0
  60238. *
  60239. * Unless required by applicable law or agreed to in writing,
  60240. * software distributed under the License is distributed on an
  60241. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60242. * KIND, either express or implied. See the License for the
  60243. * specific language governing permissions and limitations
  60244. * under the License.
  60245. */
  60246. // Do not contain scrollable legend, for sake of file size.
  60247. // Series Filter
  60248. registerProcessor(legendFilter);
  60249. ComponentModel.registerSubTypeDefaulter('legend', function () {
  60250. // Default 'plain' when no type specified.
  60251. return 'plain';
  60252. });
  60253. /*
  60254. * Licensed to the Apache Software Foundation (ASF) under one
  60255. * or more contributor license agreements. See the NOTICE file
  60256. * distributed with this work for additional information
  60257. * regarding copyright ownership. The ASF licenses this file
  60258. * to you under the Apache License, Version 2.0 (the
  60259. * "License"); you may not use this file except in compliance
  60260. * with the License. You may obtain a copy of the License at
  60261. *
  60262. * http://www.apache.org/licenses/LICENSE-2.0
  60263. *
  60264. * Unless required by applicable law or agreed to in writing,
  60265. * software distributed under the License is distributed on an
  60266. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60267. * KIND, either express or implied. See the License for the
  60268. * specific language governing permissions and limitations
  60269. * under the License.
  60270. */
  60271. var ScrollableLegendModel = LegendModel.extend({
  60272. type: 'legend.scroll',
  60273. /**
  60274. * @param {number} scrollDataIndex
  60275. */
  60276. setScrollDataIndex: function (scrollDataIndex) {
  60277. this.option.scrollDataIndex = scrollDataIndex;
  60278. },
  60279. defaultOption: {
  60280. scrollDataIndex: 0,
  60281. pageButtonItemGap: 5,
  60282. pageButtonGap: null,
  60283. pageButtonPosition: 'end', // 'start' or 'end'
  60284. pageFormatter: '{current}/{total}', // If null/undefined, do not show page.
  60285. pageIcons: {
  60286. horizontal: ['M0,0L12,-10L12,10z', 'M0,0L-12,-10L-12,10z'],
  60287. vertical: ['M0,0L20,0L10,-20z', 'M0,0L20,0L10,20z']
  60288. },
  60289. pageIconColor: '#2f4554',
  60290. pageIconInactiveColor: '#aaa',
  60291. pageIconSize: 15, // Can be [10, 3], which represents [width, height]
  60292. pageTextStyle: {
  60293. color: '#333'
  60294. },
  60295. animationDurationUpdate: 800
  60296. },
  60297. /**
  60298. * @override
  60299. */
  60300. init: function (option, parentModel, ecModel, extraOpt) {
  60301. var inputPositionParams = getLayoutParams(option);
  60302. ScrollableLegendModel.superCall(this, 'init', option, parentModel, ecModel, extraOpt);
  60303. mergeAndNormalizeLayoutParams(this, option, inputPositionParams);
  60304. },
  60305. /**
  60306. * @override
  60307. */
  60308. mergeOption: function (option, extraOpt) {
  60309. ScrollableLegendModel.superCall(this, 'mergeOption', option, extraOpt);
  60310. mergeAndNormalizeLayoutParams(this, this.option, option);
  60311. },
  60312. getOrient: function () {
  60313. return this.get('orient') === 'vertical'
  60314. ? {index: 1, name: 'vertical'}
  60315. : {index: 0, name: 'horizontal'};
  60316. }
  60317. });
  60318. // Do not `ignoreSize` to enable setting {left: 10, right: 10}.
  60319. function mergeAndNormalizeLayoutParams(legendModel, target, raw) {
  60320. var orient = legendModel.getOrient();
  60321. var ignoreSize = [1, 1];
  60322. ignoreSize[orient.index] = 0;
  60323. mergeLayoutParam(target, raw, {
  60324. type: 'box', ignoreSize: ignoreSize
  60325. });
  60326. }
  60327. /*
  60328. * Licensed to the Apache Software Foundation (ASF) under one
  60329. * or more contributor license agreements. See the NOTICE file
  60330. * distributed with this work for additional information
  60331. * regarding copyright ownership. The ASF licenses this file
  60332. * to you under the Apache License, Version 2.0 (the
  60333. * "License"); you may not use this file except in compliance
  60334. * with the License. You may obtain a copy of the License at
  60335. *
  60336. * http://www.apache.org/licenses/LICENSE-2.0
  60337. *
  60338. * Unless required by applicable law or agreed to in writing,
  60339. * software distributed under the License is distributed on an
  60340. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60341. * KIND, either express or implied. See the License for the
  60342. * specific language governing permissions and limitations
  60343. * under the License.
  60344. */
  60345. /**
  60346. * Separate legend and scrollable legend to reduce package size.
  60347. */
  60348. var Group$4 = Group;
  60349. var WH$1 = ['width', 'height'];
  60350. var XY$1 = ['x', 'y'];
  60351. var ScrollableLegendView = LegendView.extend({
  60352. type: 'legend.scroll',
  60353. newlineDisabled: true,
  60354. init: function () {
  60355. ScrollableLegendView.superCall(this, 'init');
  60356. /**
  60357. * @private
  60358. * @type {number} For `scroll`.
  60359. */
  60360. this._currentIndex = 0;
  60361. /**
  60362. * @private
  60363. * @type {module:zrender/container/Group}
  60364. */
  60365. this.group.add(this._containerGroup = new Group$4());
  60366. this._containerGroup.add(this.getContentGroup());
  60367. /**
  60368. * @private
  60369. * @type {module:zrender/container/Group}
  60370. */
  60371. this.group.add(this._controllerGroup = new Group$4());
  60372. /**
  60373. *
  60374. * @private
  60375. */
  60376. this._showController;
  60377. },
  60378. /**
  60379. * @override
  60380. */
  60381. resetInner: function () {
  60382. ScrollableLegendView.superCall(this, 'resetInner');
  60383. this._controllerGroup.removeAll();
  60384. this._containerGroup.removeClipPath();
  60385. this._containerGroup.__rectSize = null;
  60386. },
  60387. /**
  60388. * @override
  60389. */
  60390. renderInner: function (itemAlign, legendModel, ecModel, api) {
  60391. var me = this;
  60392. // Render content items.
  60393. ScrollableLegendView.superCall(this, 'renderInner', itemAlign, legendModel, ecModel, api);
  60394. var controllerGroup = this._controllerGroup;
  60395. var pageIconSize = legendModel.get('pageIconSize', true);
  60396. if (!isArray(pageIconSize)) {
  60397. pageIconSize = [pageIconSize, pageIconSize];
  60398. }
  60399. createPageButton('pagePrev', 0);
  60400. var pageTextStyleModel = legendModel.getModel('pageTextStyle');
  60401. controllerGroup.add(new Text({
  60402. name: 'pageText',
  60403. style: {
  60404. textFill: pageTextStyleModel.getTextColor(),
  60405. font: pageTextStyleModel.getFont(),
  60406. textVerticalAlign: 'middle',
  60407. textAlign: 'center'
  60408. },
  60409. silent: true
  60410. }));
  60411. createPageButton('pageNext', 1);
  60412. function createPageButton(name, iconIdx) {
  60413. var pageDataIndexName = name + 'DataIndex';
  60414. var icon = createIcon(
  60415. legendModel.get('pageIcons', true)[legendModel.getOrient().name][iconIdx],
  60416. {
  60417. // Buttons will be created in each render, so we do not need
  60418. // to worry about avoiding using legendModel kept in scope.
  60419. onclick: bind(
  60420. me._pageGo, me, pageDataIndexName, legendModel, api
  60421. )
  60422. },
  60423. {
  60424. x: -pageIconSize[0] / 2,
  60425. y: -pageIconSize[1] / 2,
  60426. width: pageIconSize[0],
  60427. height: pageIconSize[1]
  60428. }
  60429. );
  60430. icon.name = name;
  60431. controllerGroup.add(icon);
  60432. }
  60433. },
  60434. /**
  60435. * @override
  60436. */
  60437. layoutInner: function (legendModel, itemAlign, maxSize) {
  60438. var contentGroup = this.getContentGroup();
  60439. var containerGroup = this._containerGroup;
  60440. var controllerGroup = this._controllerGroup;
  60441. var orientIdx = legendModel.getOrient().index;
  60442. var wh = WH$1[orientIdx];
  60443. var hw = WH$1[1 - orientIdx];
  60444. var yx = XY$1[1 - orientIdx];
  60445. // Place items in contentGroup.
  60446. box(
  60447. legendModel.get('orient'),
  60448. contentGroup,
  60449. legendModel.get('itemGap'),
  60450. !orientIdx ? null : maxSize.width,
  60451. orientIdx ? null : maxSize.height
  60452. );
  60453. box(
  60454. // Buttons in controller are layout always horizontally.
  60455. 'horizontal',
  60456. controllerGroup,
  60457. legendModel.get('pageButtonItemGap', true)
  60458. );
  60459. var contentRect = contentGroup.getBoundingRect();
  60460. var controllerRect = controllerGroup.getBoundingRect();
  60461. var showController = this._showController = contentRect[wh] > maxSize[wh];
  60462. var contentPos = [-contentRect.x, -contentRect.y];
  60463. // Remain contentPos when scroll animation perfroming.
  60464. contentPos[orientIdx] = contentGroup.position[orientIdx];
  60465. // Layout container group based on 0.
  60466. var containerPos = [0, 0];
  60467. var controllerPos = [-controllerRect.x, -controllerRect.y];
  60468. var pageButtonGap = retrieve2(
  60469. legendModel.get('pageButtonGap', true), legendModel.get('itemGap', true)
  60470. );
  60471. // Place containerGroup and controllerGroup and contentGroup.
  60472. if (showController) {
  60473. var pageButtonPosition = legendModel.get('pageButtonPosition', true);
  60474. // controller is on the right / bottom.
  60475. if (pageButtonPosition === 'end') {
  60476. controllerPos[orientIdx] += maxSize[wh] - controllerRect[wh];
  60477. }
  60478. // controller is on the left / top.
  60479. else {
  60480. containerPos[orientIdx] += controllerRect[wh] + pageButtonGap;
  60481. }
  60482. }
  60483. // Always align controller to content as 'middle'.
  60484. controllerPos[1 - orientIdx] += contentRect[hw] / 2 - controllerRect[hw] / 2;
  60485. contentGroup.attr('position', contentPos);
  60486. containerGroup.attr('position', containerPos);
  60487. controllerGroup.attr('position', controllerPos);
  60488. // Calculate `mainRect` and set `clipPath`.
  60489. // mainRect should not be calculated by `this.group.getBoundingRect()`
  60490. // for sake of the overflow.
  60491. var mainRect = this.group.getBoundingRect();
  60492. var mainRect = {x: 0, y: 0};
  60493. // Consider content may be overflow (should be clipped).
  60494. mainRect[wh] = showController ? maxSize[wh] : contentRect[wh];
  60495. mainRect[hw] = Math.max(contentRect[hw], controllerRect[hw]);
  60496. // `containerRect[yx] + containerPos[1 - orientIdx]` is 0.
  60497. mainRect[yx] = Math.min(0, controllerRect[yx] + controllerPos[1 - orientIdx]);
  60498. containerGroup.__rectSize = maxSize[wh];
  60499. if (showController) {
  60500. var clipShape = {x: 0, y: 0};
  60501. clipShape[wh] = Math.max(maxSize[wh] - controllerRect[wh] - pageButtonGap, 0);
  60502. clipShape[hw] = mainRect[hw];
  60503. containerGroup.setClipPath(new Rect({shape: clipShape}));
  60504. // Consider content may be larger than container, container rect
  60505. // can not be obtained from `containerGroup.getBoundingRect()`.
  60506. containerGroup.__rectSize = clipShape[wh];
  60507. }
  60508. else {
  60509. // Do not remove or ignore controller. Keep them set as place holders.
  60510. controllerGroup.eachChild(function (child) {
  60511. child.attr({invisible: true, silent: true});
  60512. });
  60513. }
  60514. // Content translate animation.
  60515. var pageInfo = this._getPageInfo(legendModel);
  60516. pageInfo.pageIndex != null && updateProps(
  60517. contentGroup,
  60518. {position: pageInfo.contentPosition},
  60519. // When switch from "show controller" to "not show controller", view should be
  60520. // updated immediately without animation, otherwise causes weird efffect.
  60521. showController ? legendModel : false
  60522. );
  60523. this._updatePageInfoView(legendModel, pageInfo);
  60524. return mainRect;
  60525. },
  60526. _pageGo: function (to, legendModel, api) {
  60527. var scrollDataIndex = this._getPageInfo(legendModel)[to];
  60528. scrollDataIndex != null && api.dispatchAction({
  60529. type: 'legendScroll',
  60530. scrollDataIndex: scrollDataIndex,
  60531. legendId: legendModel.id
  60532. });
  60533. },
  60534. _updatePageInfoView: function (legendModel, pageInfo) {
  60535. var controllerGroup = this._controllerGroup;
  60536. each$1(['pagePrev', 'pageNext'], function (name) {
  60537. var canJump = pageInfo[name + 'DataIndex'] != null;
  60538. var icon = controllerGroup.childOfName(name);
  60539. if (icon) {
  60540. icon.setStyle(
  60541. 'fill',
  60542. canJump
  60543. ? legendModel.get('pageIconColor', true)
  60544. : legendModel.get('pageIconInactiveColor', true)
  60545. );
  60546. icon.cursor = canJump ? 'pointer' : 'default';
  60547. }
  60548. });
  60549. var pageText = controllerGroup.childOfName('pageText');
  60550. var pageFormatter = legendModel.get('pageFormatter');
  60551. var pageIndex = pageInfo.pageIndex;
  60552. var current = pageIndex != null ? pageIndex + 1 : 0;
  60553. var total = pageInfo.pageCount;
  60554. pageText && pageFormatter && pageText.setStyle(
  60555. 'text',
  60556. isString(pageFormatter)
  60557. ? pageFormatter.replace('{current}', current).replace('{total}', total)
  60558. : pageFormatter({current: current, total: total})
  60559. );
  60560. },
  60561. /**
  60562. * @param {module:echarts/model/Model} legendModel
  60563. * @return {Object} {
  60564. * contentPosition: Array.<number>, null when data item not found.
  60565. * pageIndex: number, null when data item not found.
  60566. * pageCount: number, always be a number, can be 0.
  60567. * pagePrevDataIndex: number, null when no next page.
  60568. * pageNextDataIndex: number, null when no previous page.
  60569. * }
  60570. */
  60571. _getPageInfo: function (legendModel) {
  60572. // Align left or top by the current dataIndex.
  60573. var currDataIndex = legendModel.get('scrollDataIndex', true);
  60574. var contentGroup = this.getContentGroup();
  60575. var contentRect = contentGroup.getBoundingRect();
  60576. var containerRectSize = this._containerGroup.__rectSize;
  60577. var orientIdx = legendModel.getOrient().index;
  60578. var wh = WH$1[orientIdx];
  60579. var hw = WH$1[1 - orientIdx];
  60580. var xy = XY$1[orientIdx];
  60581. var contentPos = contentGroup.position.slice();
  60582. var pageIndex;
  60583. var pagePrevDataIndex;
  60584. var pageNextDataIndex;
  60585. var targetItemGroup;
  60586. if (this._showController) {
  60587. contentGroup.eachChild(function (child) {
  60588. if (child.__legendDataIndex === currDataIndex) {
  60589. targetItemGroup = child;
  60590. }
  60591. });
  60592. }
  60593. else {
  60594. targetItemGroup = contentGroup.childAt(0);
  60595. }
  60596. var pageCount = containerRectSize ? Math.ceil(contentRect[wh] / containerRectSize) : 0;
  60597. if (targetItemGroup) {
  60598. var itemRect = targetItemGroup.getBoundingRect();
  60599. var itemLoc = targetItemGroup.position[orientIdx] + itemRect[xy];
  60600. contentPos[orientIdx] = -itemLoc - contentRect[xy];
  60601. pageIndex = Math.floor(
  60602. pageCount * (itemLoc + itemRect[xy] + containerRectSize / 2) / contentRect[wh]
  60603. );
  60604. pageIndex = (contentRect[wh] && pageCount)
  60605. ? Math.max(0, Math.min(pageCount - 1, pageIndex))
  60606. : -1;
  60607. var winRect = {x: 0, y: 0};
  60608. winRect[wh] = containerRectSize;
  60609. winRect[hw] = contentRect[hw];
  60610. winRect[xy] = -contentPos[orientIdx] - contentRect[xy];
  60611. var startIdx;
  60612. var children = contentGroup.children();
  60613. contentGroup.eachChild(function (child, index) {
  60614. var itemRect = getItemRect(child);
  60615. if (itemRect.intersect(winRect)) {
  60616. startIdx == null && (startIdx = index);
  60617. // It is user-friendly that the last item shown in the
  60618. // current window is shown at the begining of next window.
  60619. pageNextDataIndex = child.__legendDataIndex;
  60620. }
  60621. // If the last item is shown entirely, no next page.
  60622. if (index === children.length - 1
  60623. && itemRect[xy] + itemRect[wh] <= winRect[xy] + winRect[wh]
  60624. ) {
  60625. pageNextDataIndex = null;
  60626. }
  60627. });
  60628. // Always align based on the left/top most item, so the left/top most
  60629. // item in the previous window is needed to be found here.
  60630. if (startIdx != null) {
  60631. var startItem = children[startIdx];
  60632. var startRect = getItemRect(startItem);
  60633. winRect[xy] = startRect[xy] + startRect[wh] - winRect[wh];
  60634. // If the first item is shown entirely, no previous page.
  60635. if (startIdx <= 0 && startRect[xy] >= winRect[xy]) {
  60636. pagePrevDataIndex = null;
  60637. }
  60638. else {
  60639. while (startIdx > 0 && getItemRect(children[startIdx - 1]).intersect(winRect)) {
  60640. startIdx--;
  60641. }
  60642. pagePrevDataIndex = children[startIdx].__legendDataIndex;
  60643. }
  60644. }
  60645. }
  60646. return {
  60647. contentPosition: contentPos,
  60648. pageIndex: pageIndex,
  60649. pageCount: pageCount,
  60650. pagePrevDataIndex: pagePrevDataIndex,
  60651. pageNextDataIndex: pageNextDataIndex
  60652. };
  60653. function getItemRect(el) {
  60654. var itemRect = el.getBoundingRect().clone();
  60655. itemRect[xy] += el.position[orientIdx];
  60656. return itemRect;
  60657. }
  60658. }
  60659. });
  60660. /*
  60661. * Licensed to the Apache Software Foundation (ASF) under one
  60662. * or more contributor license agreements. See the NOTICE file
  60663. * distributed with this work for additional information
  60664. * regarding copyright ownership. The ASF licenses this file
  60665. * to you under the Apache License, Version 2.0 (the
  60666. * "License"); you may not use this file except in compliance
  60667. * with the License. You may obtain a copy of the License at
  60668. *
  60669. * http://www.apache.org/licenses/LICENSE-2.0
  60670. *
  60671. * Unless required by applicable law or agreed to in writing,
  60672. * software distributed under the License is distributed on an
  60673. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60674. * KIND, either express or implied. See the License for the
  60675. * specific language governing permissions and limitations
  60676. * under the License.
  60677. */
  60678. /**
  60679. * @event legendScroll
  60680. * @type {Object}
  60681. * @property {string} type 'legendScroll'
  60682. * @property {string} scrollDataIndex
  60683. */
  60684. registerAction(
  60685. 'legendScroll', 'legendscroll',
  60686. function (payload, ecModel) {
  60687. var scrollDataIndex = payload.scrollDataIndex;
  60688. scrollDataIndex != null && ecModel.eachComponent(
  60689. {mainType: 'legend', subType: 'scroll', query: payload},
  60690. function (legendModel) {
  60691. legendModel.setScrollDataIndex(scrollDataIndex);
  60692. }
  60693. );
  60694. }
  60695. );
  60696. /*
  60697. * Licensed to the Apache Software Foundation (ASF) under one
  60698. * or more contributor license agreements. See the NOTICE file
  60699. * distributed with this work for additional information
  60700. * regarding copyright ownership. The ASF licenses this file
  60701. * to you under the Apache License, Version 2.0 (the
  60702. * "License"); you may not use this file except in compliance
  60703. * with the License. You may obtain a copy of the License at
  60704. *
  60705. * http://www.apache.org/licenses/LICENSE-2.0
  60706. *
  60707. * Unless required by applicable law or agreed to in writing,
  60708. * software distributed under the License is distributed on an
  60709. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60710. * KIND, either express or implied. See the License for the
  60711. * specific language governing permissions and limitations
  60712. * under the License.
  60713. */
  60714. /**
  60715. * Legend component entry file8
  60716. */
  60717. /*
  60718. * Licensed to the Apache Software Foundation (ASF) under one
  60719. * or more contributor license agreements. See the NOTICE file
  60720. * distributed with this work for additional information
  60721. * regarding copyright ownership. The ASF licenses this file
  60722. * to you under the Apache License, Version 2.0 (the
  60723. * "License"); you may not use this file except in compliance
  60724. * with the License. You may obtain a copy of the License at
  60725. *
  60726. * http://www.apache.org/licenses/LICENSE-2.0
  60727. *
  60728. * Unless required by applicable law or agreed to in writing,
  60729. * software distributed under the License is distributed on an
  60730. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60731. * KIND, either express or implied. See the License for the
  60732. * specific language governing permissions and limitations
  60733. * under the License.
  60734. */
  60735. extendComponentModel({
  60736. type: 'tooltip',
  60737. dependencies: ['axisPointer'],
  60738. defaultOption: {
  60739. zlevel: 0,
  60740. z: 8,
  60741. show: true,
  60742. // tooltip主体内容
  60743. showContent: true,
  60744. // 'trigger' only works on coordinate system.
  60745. // 'item' | 'axis' | 'none'
  60746. trigger: 'item',
  60747. // 'click' | 'mousemove' | 'none'
  60748. triggerOn: 'mousemove|click',
  60749. alwaysShowContent: false,
  60750. displayMode: 'single', // 'single' | 'multipleByCoordSys'
  60751. // 位置 {Array} | {Function}
  60752. // position: null
  60753. // Consider triggered from axisPointer handle, verticalAlign should be 'middle'
  60754. // align: null,
  60755. // verticalAlign: null,
  60756. // 是否约束 content 在 viewRect 中。默认 false 是为了兼容以前版本。
  60757. confine: false,
  60758. // 内容格式器:{string}(Template) ¦ {Function}
  60759. // formatter: null
  60760. showDelay: 0,
  60761. // 隐藏延迟,单位ms
  60762. hideDelay: 100,
  60763. // 动画变换时间,单位s
  60764. transitionDuration: 0.4,
  60765. enterable: false,
  60766. // 提示背景颜色,默认为透明度为0.7的黑色
  60767. backgroundColor: 'rgba(50,50,50,0.7)',
  60768. // 提示边框颜色
  60769. borderColor: '#333',
  60770. // 提示边框圆角,单位px,默认为4
  60771. borderRadius: 4,
  60772. // 提示边框线宽,单位px,默认为0(无边框)
  60773. borderWidth: 0,
  60774. // 提示内边距,单位px,默认各方向内边距为5,
  60775. // 接受数组分别设定上右下左边距,同css
  60776. padding: 5,
  60777. // Extra css text
  60778. extraCssText: '',
  60779. // 坐标轴指示器,坐标轴触发有效
  60780. axisPointer: {
  60781. // 默认为直线
  60782. // 可选为:'line' | 'shadow' | 'cross'
  60783. type: 'line',
  60784. // type 为 line 的时候有效,指定 tooltip line 所在的轴,可选
  60785. // 可选 'x' | 'y' | 'angle' | 'radius' | 'auto'
  60786. // 默认 'auto',会选择类型为 category 的轴,对于双数值轴,笛卡尔坐标系会默认选择 x 轴
  60787. // 极坐标系会默认选择 angle 轴
  60788. axis: 'auto',
  60789. animation: 'auto',
  60790. animationDurationUpdate: 200,
  60791. animationEasingUpdate: 'exponentialOut',
  60792. crossStyle: {
  60793. color: '#999',
  60794. width: 1,
  60795. type: 'dashed',
  60796. // TODO formatter
  60797. textStyle: {}
  60798. }
  60799. // lineStyle and shadowStyle should not be specified here,
  60800. // otherwise it will always override those styles on option.axisPointer.
  60801. },
  60802. textStyle: {
  60803. color: '#fff',
  60804. fontSize: 14
  60805. }
  60806. }
  60807. });
  60808. /*
  60809. * Licensed to the Apache Software Foundation (ASF) under one
  60810. * or more contributor license agreements. See the NOTICE file
  60811. * distributed with this work for additional information
  60812. * regarding copyright ownership. The ASF licenses this file
  60813. * to you under the Apache License, Version 2.0 (the
  60814. * "License"); you may not use this file except in compliance
  60815. * with the License. You may obtain a copy of the License at
  60816. *
  60817. * http://www.apache.org/licenses/LICENSE-2.0
  60818. *
  60819. * Unless required by applicable law or agreed to in writing,
  60820. * software distributed under the License is distributed on an
  60821. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60822. * KIND, either express or implied. See the License for the
  60823. * specific language governing permissions and limitations
  60824. * under the License.
  60825. */
  60826. var each$18 = each$1;
  60827. var toCamelCase$1 = toCamelCase;
  60828. var vendors = ['', '-webkit-', '-moz-', '-o-'];
  60829. var gCssText = 'position:absolute;display:block;border-style:solid;white-space:nowrap;z-index:9999999;';
  60830. /**
  60831. * @param {number} duration
  60832. * @return {string}
  60833. * @inner
  60834. */
  60835. function assembleTransition(duration) {
  60836. var transitionCurve = 'cubic-bezier(0.23, 1, 0.32, 1)';
  60837. var transitionText = 'left ' + duration + 's ' + transitionCurve + ','
  60838. + 'top ' + duration + 's ' + transitionCurve;
  60839. return map(vendors, function (vendorPrefix) {
  60840. return vendorPrefix + 'transition:' + transitionText;
  60841. }).join(';');
  60842. }
  60843. /**
  60844. * @param {Object} textStyle
  60845. * @return {string}
  60846. * @inner
  60847. */
  60848. function assembleFont(textStyleModel) {
  60849. var cssText = [];
  60850. var fontSize = textStyleModel.get('fontSize');
  60851. var color = textStyleModel.getTextColor();
  60852. color && cssText.push('color:' + color);
  60853. cssText.push('font:' + textStyleModel.getFont());
  60854. fontSize &&
  60855. cssText.push('line-height:' + Math.round(fontSize * 3 / 2) + 'px');
  60856. each$18(['decoration', 'align'], function (name) {
  60857. var val = textStyleModel.get(name);
  60858. val && cssText.push('text-' + name + ':' + val);
  60859. });
  60860. return cssText.join(';');
  60861. }
  60862. /**
  60863. * @param {Object} tooltipModel
  60864. * @return {string}
  60865. * @inner
  60866. */
  60867. function assembleCssText(tooltipModel) {
  60868. var cssText = [];
  60869. var transitionDuration = tooltipModel.get('transitionDuration');
  60870. var backgroundColor = tooltipModel.get('backgroundColor');
  60871. var textStyleModel = tooltipModel.getModel('textStyle');
  60872. var padding = tooltipModel.get('padding');
  60873. // Animation transition. Do not animate when transitionDuration is 0.
  60874. transitionDuration &&
  60875. cssText.push(assembleTransition(transitionDuration));
  60876. if (backgroundColor) {
  60877. if (env$1.canvasSupported) {
  60878. cssText.push('background-Color:' + backgroundColor);
  60879. }
  60880. else {
  60881. // for ie
  60882. cssText.push(
  60883. 'background-Color:#' + toHex(backgroundColor)
  60884. );
  60885. cssText.push('filter:alpha(opacity=70)');
  60886. }
  60887. }
  60888. // Border style
  60889. each$18(['width', 'color', 'radius'], function (name) {
  60890. var borderName = 'border-' + name;
  60891. var camelCase = toCamelCase$1(borderName);
  60892. var val = tooltipModel.get(camelCase);
  60893. val != null &&
  60894. cssText.push(borderName + ':' + val + (name === 'color' ? '' : 'px'));
  60895. });
  60896. // Text style
  60897. cssText.push(assembleFont(textStyleModel));
  60898. // Padding
  60899. if (padding != null) {
  60900. cssText.push('padding:' + normalizeCssArray$1(padding).join('px ') + 'px');
  60901. }
  60902. return cssText.join(';') + ';';
  60903. }
  60904. /**
  60905. * @alias module:echarts/component/tooltip/TooltipContent
  60906. * @constructor
  60907. */
  60908. function TooltipContent(container, api) {
  60909. if (env$1.wxa) {
  60910. return null;
  60911. }
  60912. var el = document.createElement('div');
  60913. var zr = this._zr = api.getZr();
  60914. this.el = el;
  60915. this._x = api.getWidth() / 2;
  60916. this._y = api.getHeight() / 2;
  60917. container.appendChild(el);
  60918. this._container = container;
  60919. this._show = false;
  60920. /**
  60921. * @private
  60922. */
  60923. this._hideTimeout;
  60924. var self = this;
  60925. el.onmouseenter = function () {
  60926. // clear the timeout in hideLater and keep showing tooltip
  60927. if (self._enterable) {
  60928. clearTimeout(self._hideTimeout);
  60929. self._show = true;
  60930. }
  60931. self._inContent = true;
  60932. };
  60933. el.onmousemove = function (e) {
  60934. e = e || window.event;
  60935. if (!self._enterable) {
  60936. // Try trigger zrender event to avoid mouse
  60937. // in and out shape too frequently
  60938. var handler = zr.handler;
  60939. normalizeEvent(container, e, true);
  60940. handler.dispatch('mousemove', e);
  60941. }
  60942. };
  60943. el.onmouseleave = function () {
  60944. if (self._enterable) {
  60945. if (self._show) {
  60946. self.hideLater(self._hideDelay);
  60947. }
  60948. }
  60949. self._inContent = false;
  60950. };
  60951. }
  60952. TooltipContent.prototype = {
  60953. constructor: TooltipContent,
  60954. /**
  60955. * @private
  60956. * @type {boolean}
  60957. */
  60958. _enterable: true,
  60959. /**
  60960. * Update when tooltip is rendered
  60961. */
  60962. update: function () {
  60963. // FIXME
  60964. // Move this logic to ec main?
  60965. var container = this._container;
  60966. var stl = container.currentStyle
  60967. || document.defaultView.getComputedStyle(container);
  60968. var domStyle = container.style;
  60969. if (domStyle.position !== 'absolute' && stl.position !== 'absolute') {
  60970. domStyle.position = 'relative';
  60971. }
  60972. // Hide the tooltip
  60973. // PENDING
  60974. // this.hide();
  60975. },
  60976. show: function (tooltipModel) {
  60977. clearTimeout(this._hideTimeout);
  60978. var el = this.el;
  60979. el.style.cssText = gCssText + assembleCssText(tooltipModel)
  60980. // http://stackoverflow.com/questions/21125587/css3-transition-not-working-in-chrome-anymore
  60981. + ';left:' + this._x + 'px;top:' + this._y + 'px;'
  60982. + (tooltipModel.get('extraCssText') || '');
  60983. el.style.display = el.innerHTML ? 'block' : 'none';
  60984. this._show = true;
  60985. },
  60986. setContent: function (content) {
  60987. this.el.innerHTML = content == null ? '' : content;
  60988. },
  60989. setEnterable: function (enterable) {
  60990. this._enterable = enterable;
  60991. },
  60992. getSize: function () {
  60993. var el = this.el;
  60994. return [el.clientWidth, el.clientHeight];
  60995. },
  60996. moveTo: function (x, y) {
  60997. // xy should be based on canvas root. But tooltipContent is
  60998. // the sibling of canvas root. So padding of ec container
  60999. // should be considered here.
  61000. var zr = this._zr;
  61001. var viewportRootOffset;
  61002. if (zr && zr.painter && (viewportRootOffset = zr.painter.getViewportRootOffset())) {
  61003. x += viewportRootOffset.offsetLeft;
  61004. y += viewportRootOffset.offsetTop;
  61005. }
  61006. var style = this.el.style;
  61007. style.left = x + 'px';
  61008. style.top = y + 'px';
  61009. this._x = x;
  61010. this._y = y;
  61011. },
  61012. hide: function () {
  61013. this.el.style.display = 'none';
  61014. this._show = false;
  61015. },
  61016. hideLater: function (time) {
  61017. if (this._show && !(this._inContent && this._enterable)) {
  61018. if (time) {
  61019. this._hideDelay = time;
  61020. // Set show false to avoid invoke hideLater mutiple times
  61021. this._show = false;
  61022. this._hideTimeout = setTimeout(bind(this.hide, this), time);
  61023. }
  61024. else {
  61025. this.hide();
  61026. }
  61027. }
  61028. },
  61029. isShow: function () {
  61030. return this._show;
  61031. }
  61032. };
  61033. /*
  61034. * Licensed to the Apache Software Foundation (ASF) under one
  61035. * or more contributor license agreements. See the NOTICE file
  61036. * distributed with this work for additional information
  61037. * regarding copyright ownership. The ASF licenses this file
  61038. * to you under the Apache License, Version 2.0 (the
  61039. * "License"); you may not use this file except in compliance
  61040. * with the License. You may obtain a copy of the License at
  61041. *
  61042. * http://www.apache.org/licenses/LICENSE-2.0
  61043. *
  61044. * Unless required by applicable law or agreed to in writing,
  61045. * software distributed under the License is distributed on an
  61046. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  61047. * KIND, either express or implied. See the License for the
  61048. * specific language governing permissions and limitations
  61049. * under the License.
  61050. */
  61051. var bind$3 = bind;
  61052. var each$17 = each$1;
  61053. var parsePercent$2 = parsePercent$1;
  61054. var proxyRect = new Rect({
  61055. shape: {x: -1, y: -1, width: 2, height: 2}
  61056. });
  61057. extendComponentView({
  61058. type: 'tooltip',
  61059. init: function (ecModel, api) {
  61060. if (env$1.node) {
  61061. return;
  61062. }
  61063. var tooltipContent = new TooltipContent(api.getDom(), api);
  61064. this._tooltipContent = tooltipContent;
  61065. },
  61066. render: function (tooltipModel, ecModel, api) {
  61067. if (env$1.node || env$1.wxa) {
  61068. return;
  61069. }
  61070. // Reset
  61071. this.group.removeAll();
  61072. /**
  61073. * @private
  61074. * @type {module:echarts/component/tooltip/TooltipModel}
  61075. */
  61076. this._tooltipModel = tooltipModel;
  61077. /**
  61078. * @private
  61079. * @type {module:echarts/model/Global}
  61080. */
  61081. this._ecModel = ecModel;
  61082. /**
  61083. * @private
  61084. * @type {module:echarts/ExtensionAPI}
  61085. */
  61086. this._api = api;
  61087. /**
  61088. * Should be cleaned when render.
  61089. * @private
  61090. * @type {Array.<Array.<Object>>}
  61091. */
  61092. this._lastDataByCoordSys = null;
  61093. /**
  61094. * @private
  61095. * @type {boolean}
  61096. */
  61097. this._alwaysShowContent = tooltipModel.get('alwaysShowContent');
  61098. var tooltipContent = this._tooltipContent;
  61099. tooltipContent.update();
  61100. tooltipContent.setEnterable(tooltipModel.get('enterable'));
  61101. this._initGlobalListener();
  61102. this._keepShow();
  61103. },
  61104. _initGlobalListener: function () {
  61105. var tooltipModel = this._tooltipModel;
  61106. var triggerOn = tooltipModel.get('triggerOn');
  61107. register(
  61108. 'itemTooltip',
  61109. this._api,
  61110. bind$3(function (currTrigger, e, dispatchAction) {
  61111. // If 'none', it is not controlled by mouse totally.
  61112. if (triggerOn !== 'none') {
  61113. if (triggerOn.indexOf(currTrigger) >= 0) {
  61114. this._tryShow(e, dispatchAction);
  61115. }
  61116. else if (currTrigger === 'leave') {
  61117. this._hide(dispatchAction);
  61118. }
  61119. }
  61120. }, this)
  61121. );
  61122. },
  61123. _keepShow: function () {
  61124. var tooltipModel = this._tooltipModel;
  61125. var ecModel = this._ecModel;
  61126. var api = this._api;
  61127. // Try to keep the tooltip show when refreshing
  61128. if (this._lastX != null
  61129. && this._lastY != null
  61130. // When user is willing to control tooltip totally using API,
  61131. // self.manuallyShowTip({x, y}) might cause tooltip hide,
  61132. // which is not expected.
  61133. && tooltipModel.get('triggerOn') !== 'none'
  61134. ) {
  61135. var self = this;
  61136. clearTimeout(this._refreshUpdateTimeout);
  61137. this._refreshUpdateTimeout = setTimeout(function () {
  61138. // Show tip next tick after other charts are rendered
  61139. // In case highlight action has wrong result
  61140. // FIXME
  61141. self.manuallyShowTip(tooltipModel, ecModel, api, {
  61142. x: self._lastX,
  61143. y: self._lastY
  61144. });
  61145. });
  61146. }
  61147. },
  61148. /**
  61149. * Show tip manually by
  61150. * dispatchAction({
  61151. * type: 'showTip',
  61152. * x: 10,
  61153. * y: 10
  61154. * });
  61155. * Or
  61156. * dispatchAction({
  61157. * type: 'showTip',
  61158. * seriesIndex: 0,
  61159. * dataIndex or dataIndexInside or name
  61160. * });
  61161. *
  61162. * TODO Batch
  61163. */
  61164. manuallyShowTip: function (tooltipModel, ecModel, api, payload) {
  61165. if (payload.from === this.uid || env$1.node) {
  61166. return;
  61167. }
  61168. var dispatchAction = makeDispatchAction$1(payload, api);
  61169. // Reset ticket
  61170. this._ticket = '';
  61171. // When triggered from axisPointer.
  61172. var dataByCoordSys = payload.dataByCoordSys;
  61173. if (payload.tooltip && payload.x != null && payload.y != null) {
  61174. var el = proxyRect;
  61175. el.position = [payload.x, payload.y];
  61176. el.update();
  61177. el.tooltip = payload.tooltip;
  61178. // Manually show tooltip while view is not using zrender elements.
  61179. this._tryShow({
  61180. offsetX: payload.x,
  61181. offsetY: payload.y,
  61182. target: el
  61183. }, dispatchAction);
  61184. }
  61185. else if (dataByCoordSys) {
  61186. this._tryShow({
  61187. offsetX: payload.x,
  61188. offsetY: payload.y,
  61189. position: payload.position,
  61190. event: {},
  61191. dataByCoordSys: payload.dataByCoordSys,
  61192. tooltipOption: payload.tooltipOption
  61193. }, dispatchAction);
  61194. }
  61195. else if (payload.seriesIndex != null) {
  61196. if (this._manuallyAxisShowTip(tooltipModel, ecModel, api, payload)) {
  61197. return;
  61198. }
  61199. var pointInfo = findPointFromSeries(payload, ecModel);
  61200. var cx = pointInfo.point[0];
  61201. var cy = pointInfo.point[1];
  61202. if (cx != null && cy != null) {
  61203. this._tryShow({
  61204. offsetX: cx,
  61205. offsetY: cy,
  61206. position: payload.position,
  61207. target: pointInfo.el,
  61208. event: {}
  61209. }, dispatchAction);
  61210. }
  61211. }
  61212. else if (payload.x != null && payload.y != null) {
  61213. // FIXME
  61214. // should wrap dispatchAction like `axisPointer/globalListener` ?
  61215. api.dispatchAction({
  61216. type: 'updateAxisPointer',
  61217. x: payload.x,
  61218. y: payload.y
  61219. });
  61220. this._tryShow({
  61221. offsetX: payload.x,
  61222. offsetY: payload.y,
  61223. position: payload.position,
  61224. target: api.getZr().findHover(payload.x, payload.y).target,
  61225. event: {}
  61226. }, dispatchAction);
  61227. }
  61228. },
  61229. manuallyHideTip: function (tooltipModel, ecModel, api, payload) {
  61230. var tooltipContent = this._tooltipContent;
  61231. if (!this._alwaysShowContent && this._tooltipModel) {
  61232. tooltipContent.hideLater(this._tooltipModel.get('hideDelay'));
  61233. }
  61234. this._lastX = this._lastY = null;
  61235. if (payload.from !== this.uid) {
  61236. this._hide(makeDispatchAction$1(payload, api));
  61237. }
  61238. },
  61239. // Be compatible with previous design, that is, when tooltip.type is 'axis' and
  61240. // dispatchAction 'showTip' with seriesIndex and dataIndex will trigger axis pointer
  61241. // and tooltip.
  61242. _manuallyAxisShowTip: function (tooltipModel, ecModel, api, payload) {
  61243. var seriesIndex = payload.seriesIndex;
  61244. var dataIndex = payload.dataIndex;
  61245. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
  61246. if (seriesIndex == null || dataIndex == null || coordSysAxesInfo == null) {
  61247. return;
  61248. }
  61249. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  61250. if (!seriesModel) {
  61251. return;
  61252. }
  61253. var data = seriesModel.getData();
  61254. var tooltipModel = buildTooltipModel([
  61255. data.getItemModel(dataIndex),
  61256. seriesModel,
  61257. (seriesModel.coordinateSystem || {}).model,
  61258. tooltipModel
  61259. ]);
  61260. if (tooltipModel.get('trigger') !== 'axis') {
  61261. return;
  61262. }
  61263. api.dispatchAction({
  61264. type: 'updateAxisPointer',
  61265. seriesIndex: seriesIndex,
  61266. dataIndex: dataIndex,
  61267. position: payload.position
  61268. });
  61269. return true;
  61270. },
  61271. _tryShow: function (e, dispatchAction) {
  61272. var el = e.target;
  61273. var tooltipModel = this._tooltipModel;
  61274. if (!tooltipModel) {
  61275. return;
  61276. }
  61277. // Save mouse x, mouse y. So we can try to keep showing the tip if chart is refreshed
  61278. this._lastX = e.offsetX;
  61279. this._lastY = e.offsetY;
  61280. var dataByCoordSys = e.dataByCoordSys;
  61281. if (dataByCoordSys && dataByCoordSys.length) {
  61282. this._showAxisTooltip(dataByCoordSys, e);
  61283. }
  61284. // Always show item tooltip if mouse is on the element with dataIndex
  61285. else if (el && el.dataIndex != null) {
  61286. this._lastDataByCoordSys = null;
  61287. this._showSeriesItemTooltip(e, el, dispatchAction);
  61288. }
  61289. // Tooltip provided directly. Like legend.
  61290. else if (el && el.tooltip) {
  61291. this._lastDataByCoordSys = null;
  61292. this._showComponentItemTooltip(e, el, dispatchAction);
  61293. }
  61294. else {
  61295. this._lastDataByCoordSys = null;
  61296. this._hide(dispatchAction);
  61297. }
  61298. },
  61299. _showOrMove: function (tooltipModel, cb) {
  61300. // showDelay is used in this case: tooltip.enterable is set
  61301. // as true. User intent to move mouse into tooltip and click
  61302. // something. `showDelay` makes it easyer to enter the content
  61303. // but tooltip do not move immediately.
  61304. var delay = tooltipModel.get('showDelay');
  61305. cb = bind(cb, this);
  61306. clearTimeout(this._showTimout);
  61307. delay > 0
  61308. ? (this._showTimout = setTimeout(cb, delay))
  61309. : cb();
  61310. },
  61311. _showAxisTooltip: function (dataByCoordSys, e) {
  61312. var ecModel = this._ecModel;
  61313. var globalTooltipModel = this._tooltipModel;
  61314. var point = [e.offsetX, e.offsetY];
  61315. var singleDefaultHTML = [];
  61316. var singleParamsList = [];
  61317. var singleTooltipModel = buildTooltipModel([
  61318. e.tooltipOption,
  61319. globalTooltipModel
  61320. ]);
  61321. each$17(dataByCoordSys, function (itemCoordSys) {
  61322. // var coordParamList = [];
  61323. // var coordDefaultHTML = [];
  61324. // var coordTooltipModel = buildTooltipModel([
  61325. // e.tooltipOption,
  61326. // itemCoordSys.tooltipOption,
  61327. // ecModel.getComponent(itemCoordSys.coordSysMainType, itemCoordSys.coordSysIndex),
  61328. // globalTooltipModel
  61329. // ]);
  61330. // var displayMode = coordTooltipModel.get('displayMode');
  61331. // var paramsList = displayMode === 'single' ? singleParamsList : [];
  61332. each$17(itemCoordSys.dataByAxis, function (item) {
  61333. var axisModel = ecModel.getComponent(item.axisDim + 'Axis', item.axisIndex);
  61334. var axisValue = item.value;
  61335. var seriesDefaultHTML = [];
  61336. if (!axisModel || axisValue == null) {
  61337. return;
  61338. }
  61339. var valueLabel = getValueLabel(
  61340. axisValue, axisModel.axis, ecModel,
  61341. item.seriesDataIndices,
  61342. item.valueLabelOpt
  61343. );
  61344. each$1(item.seriesDataIndices, function (idxItem) {
  61345. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  61346. var dataIndex = idxItem.dataIndexInside;
  61347. var dataParams = series && series.getDataParams(dataIndex);
  61348. dataParams.axisDim = item.axisDim;
  61349. dataParams.axisIndex = item.axisIndex;
  61350. dataParams.axisType = item.axisType;
  61351. dataParams.axisId = item.axisId;
  61352. dataParams.axisValue = getAxisRawValue(axisModel.axis, axisValue);
  61353. dataParams.axisValueLabel = valueLabel;
  61354. if (dataParams) {
  61355. singleParamsList.push(dataParams);
  61356. seriesDefaultHTML.push(series.formatTooltip(dataIndex, true));
  61357. }
  61358. });
  61359. // Default tooltip content
  61360. // FIXME
  61361. // (1) shold be the first data which has name?
  61362. // (2) themeRiver, firstDataIndex is array, and first line is unnecessary.
  61363. var firstLine = valueLabel;
  61364. singleDefaultHTML.push(
  61365. (firstLine ? encodeHTML(firstLine) + '<br />' : '')
  61366. + seriesDefaultHTML.join('<br />')
  61367. );
  61368. });
  61369. }, this);
  61370. // In most case, the second axis is shown upper than the first one.
  61371. singleDefaultHTML.reverse();
  61372. singleDefaultHTML = singleDefaultHTML.join('<br /><br />');
  61373. var positionExpr = e.position;
  61374. this._showOrMove(singleTooltipModel, function () {
  61375. if (this._updateContentNotChangedOnAxis(dataByCoordSys)) {
  61376. this._updatePosition(
  61377. singleTooltipModel,
  61378. positionExpr,
  61379. point[0], point[1],
  61380. this._tooltipContent,
  61381. singleParamsList
  61382. );
  61383. }
  61384. else {
  61385. this._showTooltipContent(
  61386. singleTooltipModel, singleDefaultHTML, singleParamsList, Math.random(),
  61387. point[0], point[1], positionExpr
  61388. );
  61389. }
  61390. });
  61391. // Do not trigger events here, because this branch only be entered
  61392. // from dispatchAction.
  61393. },
  61394. _showSeriesItemTooltip: function (e, el, dispatchAction) {
  61395. var ecModel = this._ecModel;
  61396. // Use dataModel in element if possible
  61397. // Used when mouseover on a element like markPoint or edge
  61398. // In which case, the data is not main data in series.
  61399. var seriesIndex = el.seriesIndex;
  61400. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  61401. // For example, graph link.
  61402. var dataModel = el.dataModel || seriesModel;
  61403. var dataIndex = el.dataIndex;
  61404. var dataType = el.dataType;
  61405. var data = dataModel.getData();
  61406. var tooltipModel = buildTooltipModel([
  61407. data.getItemModel(dataIndex),
  61408. dataModel,
  61409. seriesModel && (seriesModel.coordinateSystem || {}).model,
  61410. this._tooltipModel
  61411. ]);
  61412. var tooltipTrigger = tooltipModel.get('trigger');
  61413. if (tooltipTrigger != null && tooltipTrigger !== 'item') {
  61414. return;
  61415. }
  61416. var params = dataModel.getDataParams(dataIndex, dataType);
  61417. var defaultHtml = dataModel.formatTooltip(dataIndex, false, dataType);
  61418. var asyncTicket = 'item_' + dataModel.name + '_' + dataIndex;
  61419. this._showOrMove(tooltipModel, function () {
  61420. this._showTooltipContent(
  61421. tooltipModel, defaultHtml, params, asyncTicket,
  61422. e.offsetX, e.offsetY, e.position, e.target
  61423. );
  61424. });
  61425. // FIXME
  61426. // duplicated showtip if manuallyShowTip is called from dispatchAction.
  61427. dispatchAction({
  61428. type: 'showTip',
  61429. dataIndexInside: dataIndex,
  61430. dataIndex: data.getRawIndex(dataIndex),
  61431. seriesIndex: seriesIndex,
  61432. from: this.uid
  61433. });
  61434. },
  61435. _showComponentItemTooltip: function (e, el, dispatchAction) {
  61436. var tooltipOpt = el.tooltip;
  61437. if (typeof tooltipOpt === 'string') {
  61438. var content = tooltipOpt;
  61439. tooltipOpt = {
  61440. content: content,
  61441. // Fixed formatter
  61442. formatter: content
  61443. };
  61444. }
  61445. var subTooltipModel = new Model(tooltipOpt, this._tooltipModel, this._ecModel);
  61446. var defaultHtml = subTooltipModel.get('content');
  61447. var asyncTicket = Math.random();
  61448. // Do not check whether `trigger` is 'none' here, because `trigger`
  61449. // only works on cooridinate system. In fact, we have not found case
  61450. // that requires setting `trigger` nothing on component yet.
  61451. this._showOrMove(subTooltipModel, function () {
  61452. this._showTooltipContent(
  61453. subTooltipModel, defaultHtml, subTooltipModel.get('formatterParams') || {},
  61454. asyncTicket, e.offsetX, e.offsetY, e.position, el
  61455. );
  61456. });
  61457. // If not dispatch showTip, tip may be hide triggered by axis.
  61458. dispatchAction({
  61459. type: 'showTip',
  61460. from: this.uid
  61461. });
  61462. },
  61463. _showTooltipContent: function (
  61464. tooltipModel, defaultHtml, params, asyncTicket, x, y, positionExpr, el
  61465. ) {
  61466. // Reset ticket
  61467. this._ticket = '';
  61468. if (!tooltipModel.get('showContent') || !tooltipModel.get('show')) {
  61469. return;
  61470. }
  61471. var tooltipContent = this._tooltipContent;
  61472. var formatter = tooltipModel.get('formatter');
  61473. positionExpr = positionExpr || tooltipModel.get('position');
  61474. var html = defaultHtml;
  61475. if (formatter && typeof formatter === 'string') {
  61476. html = formatTpl(formatter, params, true);
  61477. }
  61478. else if (typeof formatter === 'function') {
  61479. var callback = bind$3(function (cbTicket, html) {
  61480. if (cbTicket === this._ticket) {
  61481. tooltipContent.setContent(html);
  61482. this._updatePosition(
  61483. tooltipModel, positionExpr, x, y, tooltipContent, params, el
  61484. );
  61485. }
  61486. }, this);
  61487. this._ticket = asyncTicket;
  61488. html = formatter(params, asyncTicket, callback);
  61489. }
  61490. tooltipContent.setContent(html);
  61491. tooltipContent.show(tooltipModel);
  61492. this._updatePosition(
  61493. tooltipModel, positionExpr, x, y, tooltipContent, params, el
  61494. );
  61495. },
  61496. /**
  61497. * @param {string|Function|Array.<number>|Object} positionExpr
  61498. * @param {number} x Mouse x
  61499. * @param {number} y Mouse y
  61500. * @param {boolean} confine Whether confine tooltip content in view rect.
  61501. * @param {Object|<Array.<Object>} params
  61502. * @param {module:zrender/Element} el target element
  61503. * @param {module:echarts/ExtensionAPI} api
  61504. * @return {Array.<number>}
  61505. */
  61506. _updatePosition: function (tooltipModel, positionExpr, x, y, content, params, el) {
  61507. var viewWidth = this._api.getWidth();
  61508. var viewHeight = this._api.getHeight();
  61509. positionExpr = positionExpr || tooltipModel.get('position');
  61510. var contentSize = content.getSize();
  61511. var align = tooltipModel.get('align');
  61512. var vAlign = tooltipModel.get('verticalAlign');
  61513. var rect = el && el.getBoundingRect().clone();
  61514. el && rect.applyTransform(el.transform);
  61515. if (typeof positionExpr === 'function') {
  61516. // Callback of position can be an array or a string specify the position
  61517. positionExpr = positionExpr([x, y], params, content.el, rect, {
  61518. viewSize: [viewWidth, viewHeight],
  61519. contentSize: contentSize.slice()
  61520. });
  61521. }
  61522. if (isArray(positionExpr)) {
  61523. x = parsePercent$2(positionExpr[0], viewWidth);
  61524. y = parsePercent$2(positionExpr[1], viewHeight);
  61525. }
  61526. else if (isObject$1(positionExpr)) {
  61527. positionExpr.width = contentSize[0];
  61528. positionExpr.height = contentSize[1];
  61529. var layoutRect = getLayoutRect(
  61530. positionExpr, {width: viewWidth, height: viewHeight}
  61531. );
  61532. x = layoutRect.x;
  61533. y = layoutRect.y;
  61534. align = null;
  61535. // When positionExpr is left/top/right/bottom,
  61536. // align and verticalAlign will not work.
  61537. vAlign = null;
  61538. }
  61539. // Specify tooltip position by string 'top' 'bottom' 'left' 'right' around graphic element
  61540. else if (typeof positionExpr === 'string' && el) {
  61541. var pos = calcTooltipPosition(
  61542. positionExpr, rect, contentSize
  61543. );
  61544. x = pos[0];
  61545. y = pos[1];
  61546. }
  61547. else {
  61548. var pos = refixTooltipPosition(
  61549. x, y, content.el, viewWidth, viewHeight, align ? null : 20, vAlign ? null : 20
  61550. );
  61551. x = pos[0];
  61552. y = pos[1];
  61553. }
  61554. align && (x -= isCenterAlign(align) ? contentSize[0] / 2 : align === 'right' ? contentSize[0] : 0);
  61555. vAlign && (y -= isCenterAlign(vAlign) ? contentSize[1] / 2 : vAlign === 'bottom' ? contentSize[1] : 0);
  61556. if (tooltipModel.get('confine')) {
  61557. var pos = confineTooltipPosition(
  61558. x, y, content.el, viewWidth, viewHeight
  61559. );
  61560. x = pos[0];
  61561. y = pos[1];
  61562. }
  61563. content.moveTo(x, y);
  61564. },
  61565. // FIXME
  61566. // Should we remove this but leave this to user?
  61567. _updateContentNotChangedOnAxis: function (dataByCoordSys) {
  61568. var lastCoordSys = this._lastDataByCoordSys;
  61569. var contentNotChanged = !!lastCoordSys
  61570. && lastCoordSys.length === dataByCoordSys.length;
  61571. contentNotChanged && each$17(lastCoordSys, function (lastItemCoordSys, indexCoordSys) {
  61572. var lastDataByAxis = lastItemCoordSys.dataByAxis || {};
  61573. var thisItemCoordSys = dataByCoordSys[indexCoordSys] || {};
  61574. var thisDataByAxis = thisItemCoordSys.dataByAxis || [];
  61575. contentNotChanged &= lastDataByAxis.length === thisDataByAxis.length;
  61576. contentNotChanged && each$17(lastDataByAxis, function (lastItem, indexAxis) {
  61577. var thisItem = thisDataByAxis[indexAxis] || {};
  61578. var lastIndices = lastItem.seriesDataIndices || [];
  61579. var newIndices = thisItem.seriesDataIndices || [];
  61580. contentNotChanged &=
  61581. lastItem.value === thisItem.value
  61582. && lastItem.axisType === thisItem.axisType
  61583. && lastItem.axisId === thisItem.axisId
  61584. && lastIndices.length === newIndices.length;
  61585. contentNotChanged && each$17(lastIndices, function (lastIdxItem, j) {
  61586. var newIdxItem = newIndices[j];
  61587. contentNotChanged &=
  61588. lastIdxItem.seriesIndex === newIdxItem.seriesIndex
  61589. && lastIdxItem.dataIndex === newIdxItem.dataIndex;
  61590. });
  61591. });
  61592. });
  61593. this._lastDataByCoordSys = dataByCoordSys;
  61594. return !!contentNotChanged;
  61595. },
  61596. _hide: function (dispatchAction) {
  61597. // Do not directly hideLater here, because this behavior may be prevented
  61598. // in dispatchAction when showTip is dispatched.
  61599. // FIXME
  61600. // duplicated hideTip if manuallyHideTip is called from dispatchAction.
  61601. this._lastDataByCoordSys = null;
  61602. dispatchAction({
  61603. type: 'hideTip',
  61604. from: this.uid
  61605. });
  61606. },
  61607. dispose: function (ecModel, api) {
  61608. if (env$1.node || env$1.wxa) {
  61609. return;
  61610. }
  61611. this._tooltipContent.hide();
  61612. unregister('itemTooltip', api);
  61613. }
  61614. });
  61615. /**
  61616. * @param {Array.<Object|module:echarts/model/Model>} modelCascade
  61617. * From top to bottom. (the last one should be globalTooltipModel);
  61618. */
  61619. function buildTooltipModel(modelCascade) {
  61620. var resultModel = modelCascade.pop();
  61621. while (modelCascade.length) {
  61622. var tooltipOpt = modelCascade.pop();
  61623. if (tooltipOpt) {
  61624. if (Model.isInstance(tooltipOpt)) {
  61625. tooltipOpt = tooltipOpt.get('tooltip', true);
  61626. }
  61627. // In each data item tooltip can be simply write:
  61628. // {
  61629. // value: 10,
  61630. // tooltip: 'Something you need to know'
  61631. // }
  61632. if (typeof tooltipOpt === 'string') {
  61633. tooltipOpt = {formatter: tooltipOpt};
  61634. }
  61635. resultModel = new Model(tooltipOpt, resultModel, resultModel.ecModel);
  61636. }
  61637. }
  61638. return resultModel;
  61639. }
  61640. function makeDispatchAction$1(payload, api) {
  61641. return payload.dispatchAction || bind(api.dispatchAction, api);
  61642. }
  61643. function refixTooltipPosition(x, y, el, viewWidth, viewHeight, gapH, gapV) {
  61644. var size = getOuterSize(el);
  61645. var width = size.width;
  61646. var height = size.height;
  61647. if (gapH != null) {
  61648. if (x + width + gapH > viewWidth) {
  61649. x -= width + gapH;
  61650. }
  61651. else {
  61652. x += gapH;
  61653. }
  61654. }
  61655. if (gapV != null) {
  61656. if (y + height + gapV > viewHeight) {
  61657. y -= height + gapV;
  61658. }
  61659. else {
  61660. y += gapV;
  61661. }
  61662. }
  61663. return [x, y];
  61664. }
  61665. function confineTooltipPosition(x, y, el, viewWidth, viewHeight) {
  61666. var size = getOuterSize(el);
  61667. var width = size.width;
  61668. var height = size.height;
  61669. x = Math.min(x + width, viewWidth) - width;
  61670. y = Math.min(y + height, viewHeight) - height;
  61671. x = Math.max(x, 0);
  61672. y = Math.max(y, 0);
  61673. return [x, y];
  61674. }
  61675. function getOuterSize(el) {
  61676. var width = el.clientWidth;
  61677. var height = el.clientHeight;
  61678. // Consider browser compatibility.
  61679. // IE8 does not support getComputedStyle.
  61680. if (document.defaultView && document.defaultView.getComputedStyle) {
  61681. var stl = document.defaultView.getComputedStyle(el);
  61682. if (stl) {
  61683. width += parseInt(stl.paddingLeft, 10) + parseInt(stl.paddingRight, 10)
  61684. + parseInt(stl.borderLeftWidth, 10) + parseInt(stl.borderRightWidth, 10);
  61685. height += parseInt(stl.paddingTop, 10) + parseInt(stl.paddingBottom, 10)
  61686. + parseInt(stl.borderTopWidth, 10) + parseInt(stl.borderBottomWidth, 10);
  61687. }
  61688. }
  61689. return {width: width, height: height};
  61690. }
  61691. function calcTooltipPosition(position, rect, contentSize) {
  61692. var domWidth = contentSize[0];
  61693. var domHeight = contentSize[1];
  61694. var gap = 5;
  61695. var x = 0;
  61696. var y = 0;
  61697. var rectWidth = rect.width;
  61698. var rectHeight = rect.height;
  61699. switch (position) {
  61700. case 'inside':
  61701. x = rect.x + rectWidth / 2 - domWidth / 2;
  61702. y = rect.y + rectHeight / 2 - domHeight / 2;
  61703. break;
  61704. case 'top':
  61705. x = rect.x + rectWidth / 2 - domWidth / 2;
  61706. y = rect.y - domHeight - gap;
  61707. break;
  61708. case 'bottom':
  61709. x = rect.x + rectWidth / 2 - domWidth / 2;
  61710. y = rect.y + rectHeight + gap;
  61711. break;
  61712. case 'left':
  61713. x = rect.x - domWidth - gap;
  61714. y = rect.y + rectHeight / 2 - domHeight / 2;
  61715. break;
  61716. case 'right':
  61717. x = rect.x + rectWidth + gap;
  61718. y = rect.y + rectHeight / 2 - domHeight / 2;
  61719. }
  61720. return [x, y];
  61721. }
  61722. function isCenterAlign(align) {
  61723. return align === 'center' || align === 'middle';
  61724. }
  61725. /*
  61726. * Licensed to the Apache Software Foundation (ASF) under one
  61727. * or more contributor license agreements. See the NOTICE file
  61728. * distributed with this work for additional information
  61729. * regarding copyright ownership. The ASF licenses this file
  61730. * to you under the Apache License, Version 2.0 (the
  61731. * "License"); you may not use this file except in compliance
  61732. * with the License. You may obtain a copy of the License at
  61733. *
  61734. * http://www.apache.org/licenses/LICENSE-2.0
  61735. *
  61736. * Unless required by applicable law or agreed to in writing,
  61737. * software distributed under the License is distributed on an
  61738. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  61739. * KIND, either express or implied. See the License for the
  61740. * specific language governing permissions and limitations
  61741. * under the License.
  61742. */
  61743. // FIXME Better way to pack data in graphic element
  61744. /**
  61745. * @action
  61746. * @property {string} type
  61747. * @property {number} seriesIndex
  61748. * @property {number} dataIndex
  61749. * @property {number} [x]
  61750. * @property {number} [y]
  61751. */
  61752. registerAction(
  61753. {
  61754. type: 'showTip',
  61755. event: 'showTip',
  61756. update: 'tooltip:manuallyShowTip'
  61757. },
  61758. // noop
  61759. function () {}
  61760. );
  61761. registerAction(
  61762. {
  61763. type: 'hideTip',
  61764. event: 'hideTip',
  61765. update: 'tooltip:manuallyHideTip'
  61766. },
  61767. // noop
  61768. function () {}
  61769. );
  61770. /*
  61771. * Licensed to the Apache Software Foundation (ASF) under one
  61772. * or more contributor license agreements. See the NOTICE file
  61773. * distributed with this work for additional information
  61774. * regarding copyright ownership. The ASF licenses this file
  61775. * to you under the Apache License, Version 2.0 (the
  61776. * "License"); you may not use this file except in compliance
  61777. * with the License. You may obtain a copy of the License at
  61778. *
  61779. * http://www.apache.org/licenses/LICENSE-2.0
  61780. *
  61781. * Unless required by applicable law or agreed to in writing,
  61782. * software distributed under the License is distributed on an
  61783. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  61784. * KIND, either express or implied. See the License for the
  61785. * specific language governing permissions and limitations
  61786. * under the License.
  61787. */
  61788. function getSeriesStackId$1(seriesModel) {
  61789. return seriesModel.get('stack')
  61790. || '__ec_stack_' + seriesModel.seriesIndex;
  61791. }
  61792. function getAxisKey$1(axis) {
  61793. return axis.dim;
  61794. }
  61795. /**
  61796. * @param {string} seriesType
  61797. * @param {module:echarts/model/Global} ecModel
  61798. * @param {module:echarts/ExtensionAPI} api
  61799. */
  61800. function barLayoutPolar(seriesType, ecModel, api) {
  61801. var width = api.getWidth();
  61802. var height = api.getHeight();
  61803. var lastStackCoords = {};
  61804. var barWidthAndOffset = calRadialBar(
  61805. filter(
  61806. ecModel.getSeriesByType(seriesType),
  61807. function (seriesModel) {
  61808. return !ecModel.isSeriesFiltered(seriesModel)
  61809. && seriesModel.coordinateSystem
  61810. && seriesModel.coordinateSystem.type === 'polar';
  61811. }
  61812. )
  61813. );
  61814. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  61815. // Check series coordinate, do layout for polar only
  61816. if (seriesModel.coordinateSystem.type !== 'polar') {
  61817. return;
  61818. }
  61819. var data = seriesModel.getData();
  61820. var polar = seriesModel.coordinateSystem;
  61821. var baseAxis = polar.getBaseAxis();
  61822. var stackId = getSeriesStackId$1(seriesModel);
  61823. var columnLayoutInfo
  61824. = barWidthAndOffset[getAxisKey$1(baseAxis)][stackId];
  61825. var columnOffset = columnLayoutInfo.offset;
  61826. var columnWidth = columnLayoutInfo.width;
  61827. var valueAxis = polar.getOtherAxis(baseAxis);
  61828. var center = seriesModel.get('center') || ['50%', '50%'];
  61829. var cx = parsePercent$1(center[0], width);
  61830. var cy = parsePercent$1(center[1], height);
  61831. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  61832. var barMinAngle = seriesModel.get('barMinAngle') || 0;
  61833. lastStackCoords[stackId] = lastStackCoords[stackId] || [];
  61834. var valueDim = data.mapDimension(valueAxis.dim);
  61835. var baseDim = data.mapDimension(baseAxis.dim);
  61836. var stacked = isDimensionStacked(data, valueDim, baseDim);
  61837. var valueAxisStart = valueAxis.getExtent()[0];
  61838. for (var idx = 0, len = data.count(); idx < len; idx++) {
  61839. var value = data.get(valueDim, idx);
  61840. var baseValue = data.get(baseDim, idx);
  61841. if (isNaN(value)) {
  61842. continue;
  61843. }
  61844. var sign = value >= 0 ? 'p' : 'n';
  61845. var baseCoord = valueAxisStart;
  61846. // Because of the barMinHeight, we can not use the value in
  61847. // stackResultDimension directly.
  61848. // Only ordinal axis can be stacked.
  61849. if (stacked) {
  61850. if (!lastStackCoords[stackId][baseValue]) {
  61851. lastStackCoords[stackId][baseValue] = {
  61852. p: valueAxisStart, // Positive stack
  61853. n: valueAxisStart // Negative stack
  61854. };
  61855. }
  61856. // Should also consider #4243
  61857. baseCoord = lastStackCoords[stackId][baseValue][sign];
  61858. }
  61859. var r0;
  61860. var r;
  61861. var startAngle;
  61862. var endAngle;
  61863. // radial sector
  61864. if (valueAxis.dim === 'radius') {
  61865. var radiusSpan = valueAxis.dataToRadius(value) - valueAxisStart;
  61866. var angle = baseAxis.dataToAngle(baseValue);
  61867. if (Math.abs(radiusSpan) < barMinHeight) {
  61868. radiusSpan = (radiusSpan < 0 ? -1 : 1) * barMinHeight;
  61869. }
  61870. r0 = baseCoord;
  61871. r = baseCoord + radiusSpan;
  61872. startAngle = angle - columnOffset;
  61873. endAngle = startAngle - columnWidth;
  61874. stacked && (lastStackCoords[stackId][baseValue][sign] = r);
  61875. }
  61876. // tangential sector
  61877. else {
  61878. // angleAxis must be clamped.
  61879. var angleSpan = valueAxis.dataToAngle(value, true) - valueAxisStart;
  61880. var radius = baseAxis.dataToRadius(baseValue);
  61881. if (Math.abs(angleSpan) < barMinAngle) {
  61882. angleSpan = (angleSpan < 0 ? -1 : 1) * barMinAngle;
  61883. }
  61884. r0 = radius + columnOffset;
  61885. r = r0 + columnWidth;
  61886. startAngle = baseCoord;
  61887. endAngle = baseCoord + angleSpan;
  61888. // if the previous stack is at the end of the ring,
  61889. // add a round to differentiate it from origin
  61890. // var extent = angleAxis.getExtent();
  61891. // var stackCoord = angle;
  61892. // if (stackCoord === extent[0] && value > 0) {
  61893. // stackCoord = extent[1];
  61894. // }
  61895. // else if (stackCoord === extent[1] && value < 0) {
  61896. // stackCoord = extent[0];
  61897. // }
  61898. stacked && (lastStackCoords[stackId][baseValue][sign] = endAngle);
  61899. }
  61900. data.setItemLayout(idx, {
  61901. cx: cx,
  61902. cy: cy,
  61903. r0: r0,
  61904. r: r,
  61905. // Consider that positive angle is anti-clockwise,
  61906. // while positive radian of sector is clockwise
  61907. startAngle: -startAngle * Math.PI / 180,
  61908. endAngle: -endAngle * Math.PI / 180
  61909. });
  61910. }
  61911. }, this);
  61912. }
  61913. /**
  61914. * Calculate bar width and offset for radial bar charts
  61915. */
  61916. function calRadialBar(barSeries, api) {
  61917. // Columns info on each category axis. Key is polar name
  61918. var columnsMap = {};
  61919. each$1(barSeries, function (seriesModel, idx) {
  61920. var data = seriesModel.getData();
  61921. var polar = seriesModel.coordinateSystem;
  61922. var baseAxis = polar.getBaseAxis();
  61923. var axisExtent = baseAxis.getExtent();
  61924. var bandWidth = baseAxis.type === 'category'
  61925. ? baseAxis.getBandWidth()
  61926. : (Math.abs(axisExtent[1] - axisExtent[0]) / data.count());
  61927. var columnsOnAxis = columnsMap[getAxisKey$1(baseAxis)] || {
  61928. bandWidth: bandWidth,
  61929. remainedWidth: bandWidth,
  61930. autoWidthCount: 0,
  61931. categoryGap: '20%',
  61932. gap: '30%',
  61933. stacks: {}
  61934. };
  61935. var stacks = columnsOnAxis.stacks;
  61936. columnsMap[getAxisKey$1(baseAxis)] = columnsOnAxis;
  61937. var stackId = getSeriesStackId$1(seriesModel);
  61938. if (!stacks[stackId]) {
  61939. columnsOnAxis.autoWidthCount++;
  61940. }
  61941. stacks[stackId] = stacks[stackId] || {
  61942. width: 0,
  61943. maxWidth: 0
  61944. };
  61945. var barWidth = parsePercent$1(
  61946. seriesModel.get('barWidth'),
  61947. bandWidth
  61948. );
  61949. var barMaxWidth = parsePercent$1(
  61950. seriesModel.get('barMaxWidth'),
  61951. bandWidth
  61952. );
  61953. var barGap = seriesModel.get('barGap');
  61954. var barCategoryGap = seriesModel.get('barCategoryGap');
  61955. if (barWidth && !stacks[stackId].width) {
  61956. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  61957. stacks[stackId].width = barWidth;
  61958. columnsOnAxis.remainedWidth -= barWidth;
  61959. }
  61960. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  61961. (barGap != null) && (columnsOnAxis.gap = barGap);
  61962. (barCategoryGap != null) && (columnsOnAxis.categoryGap = barCategoryGap);
  61963. });
  61964. var result = {};
  61965. each$1(columnsMap, function (columnsOnAxis, coordSysName) {
  61966. result[coordSysName] = {};
  61967. var stacks = columnsOnAxis.stacks;
  61968. var bandWidth = columnsOnAxis.bandWidth;
  61969. var categoryGap = parsePercent$1(columnsOnAxis.categoryGap, bandWidth);
  61970. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  61971. var remainedWidth = columnsOnAxis.remainedWidth;
  61972. var autoWidthCount = columnsOnAxis.autoWidthCount;
  61973. var autoWidth = (remainedWidth - categoryGap)
  61974. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  61975. autoWidth = Math.max(autoWidth, 0);
  61976. // Find if any auto calculated bar exceeded maxBarWidth
  61977. each$1(stacks, function (column, stack) {
  61978. var maxWidth = column.maxWidth;
  61979. if (maxWidth && maxWidth < autoWidth) {
  61980. maxWidth = Math.min(maxWidth, remainedWidth);
  61981. if (column.width) {
  61982. maxWidth = Math.min(maxWidth, column.width);
  61983. }
  61984. remainedWidth -= maxWidth;
  61985. column.width = maxWidth;
  61986. autoWidthCount--;
  61987. }
  61988. });
  61989. // Recalculate width again
  61990. autoWidth = (remainedWidth - categoryGap)
  61991. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  61992. autoWidth = Math.max(autoWidth, 0);
  61993. var widthSum = 0;
  61994. var lastColumn;
  61995. each$1(stacks, function (column, idx) {
  61996. if (!column.width) {
  61997. column.width = autoWidth;
  61998. }
  61999. lastColumn = column;
  62000. widthSum += column.width * (1 + barGapPercent);
  62001. });
  62002. if (lastColumn) {
  62003. widthSum -= lastColumn.width * barGapPercent;
  62004. }
  62005. var offset = -widthSum / 2;
  62006. each$1(stacks, function (column, stackId) {
  62007. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  62008. offset: offset,
  62009. width: column.width
  62010. };
  62011. offset += column.width * (1 + barGapPercent);
  62012. });
  62013. });
  62014. return result;
  62015. }
  62016. /*
  62017. * Licensed to the Apache Software Foundation (ASF) under one
  62018. * or more contributor license agreements. See the NOTICE file
  62019. * distributed with this work for additional information
  62020. * regarding copyright ownership. The ASF licenses this file
  62021. * to you under the Apache License, Version 2.0 (the
  62022. * "License"); you may not use this file except in compliance
  62023. * with the License. You may obtain a copy of the License at
  62024. *
  62025. * http://www.apache.org/licenses/LICENSE-2.0
  62026. *
  62027. * Unless required by applicable law or agreed to in writing,
  62028. * software distributed under the License is distributed on an
  62029. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62030. * KIND, either express or implied. See the License for the
  62031. * specific language governing permissions and limitations
  62032. * under the License.
  62033. */
  62034. function RadiusAxis(scale, radiusExtent) {
  62035. Axis.call(this, 'radius', scale, radiusExtent);
  62036. /**
  62037. * Axis type
  62038. * - 'category'
  62039. * - 'value'
  62040. * - 'time'
  62041. * - 'log'
  62042. * @type {string}
  62043. */
  62044. this.type = 'category';
  62045. }
  62046. RadiusAxis.prototype = {
  62047. constructor: RadiusAxis,
  62048. /**
  62049. * @override
  62050. */
  62051. pointToData: function (point, clamp) {
  62052. return this.polar.pointToData(point, clamp)[this.dim === 'radius' ? 0 : 1];
  62053. },
  62054. dataToRadius: Axis.prototype.dataToCoord,
  62055. radiusToData: Axis.prototype.coordToData
  62056. };
  62057. inherits(RadiusAxis, Axis);
  62058. /*
  62059. * Licensed to the Apache Software Foundation (ASF) under one
  62060. * or more contributor license agreements. See the NOTICE file
  62061. * distributed with this work for additional information
  62062. * regarding copyright ownership. The ASF licenses this file
  62063. * to you under the Apache License, Version 2.0 (the
  62064. * "License"); you may not use this file except in compliance
  62065. * with the License. You may obtain a copy of the License at
  62066. *
  62067. * http://www.apache.org/licenses/LICENSE-2.0
  62068. *
  62069. * Unless required by applicable law or agreed to in writing,
  62070. * software distributed under the License is distributed on an
  62071. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62072. * KIND, either express or implied. See the License for the
  62073. * specific language governing permissions and limitations
  62074. * under the License.
  62075. */
  62076. function AngleAxis(scale, angleExtent) {
  62077. angleExtent = angleExtent || [0, 360];
  62078. Axis.call(this, 'angle', scale, angleExtent);
  62079. /**
  62080. * Axis type
  62081. * - 'category'
  62082. * - 'value'
  62083. * - 'time'
  62084. * - 'log'
  62085. * @type {string}
  62086. */
  62087. this.type = 'category';
  62088. }
  62089. AngleAxis.prototype = {
  62090. constructor: AngleAxis,
  62091. /**
  62092. * @override
  62093. */
  62094. pointToData: function (point, clamp) {
  62095. return this.polar.pointToData(point, clamp)[this.dim === 'radius' ? 0 : 1];
  62096. },
  62097. dataToAngle: Axis.prototype.dataToCoord,
  62098. angleToData: Axis.prototype.coordToData
  62099. };
  62100. inherits(AngleAxis, Axis);
  62101. /*
  62102. * Licensed to the Apache Software Foundation (ASF) under one
  62103. * or more contributor license agreements. See the NOTICE file
  62104. * distributed with this work for additional information
  62105. * regarding copyright ownership. The ASF licenses this file
  62106. * to you under the Apache License, Version 2.0 (the
  62107. * "License"); you may not use this file except in compliance
  62108. * with the License. You may obtain a copy of the License at
  62109. *
  62110. * http://www.apache.org/licenses/LICENSE-2.0
  62111. *
  62112. * Unless required by applicable law or agreed to in writing,
  62113. * software distributed under the License is distributed on an
  62114. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62115. * KIND, either express or implied. See the License for the
  62116. * specific language governing permissions and limitations
  62117. * under the License.
  62118. */
  62119. /**
  62120. * @module echarts/coord/polar/Polar
  62121. */
  62122. /**
  62123. * @alias {module:echarts/coord/polar/Polar}
  62124. * @constructor
  62125. * @param {string} name
  62126. */
  62127. var Polar = function (name) {
  62128. /**
  62129. * @type {string}
  62130. */
  62131. this.name = name || '';
  62132. /**
  62133. * x of polar center
  62134. * @type {number}
  62135. */
  62136. this.cx = 0;
  62137. /**
  62138. * y of polar center
  62139. * @type {number}
  62140. */
  62141. this.cy = 0;
  62142. /**
  62143. * @type {module:echarts/coord/polar/RadiusAxis}
  62144. * @private
  62145. */
  62146. this._radiusAxis = new RadiusAxis();
  62147. /**
  62148. * @type {module:echarts/coord/polar/AngleAxis}
  62149. * @private
  62150. */
  62151. this._angleAxis = new AngleAxis();
  62152. this._radiusAxis.polar = this._angleAxis.polar = this;
  62153. };
  62154. Polar.prototype = {
  62155. type: 'polar',
  62156. axisPointerEnabled: true,
  62157. constructor: Polar,
  62158. /**
  62159. * @param {Array.<string>}
  62160. * @readOnly
  62161. */
  62162. dimensions: ['radius', 'angle'],
  62163. /**
  62164. * @type {module:echarts/coord/PolarModel}
  62165. */
  62166. model: null,
  62167. /**
  62168. * If contain coord
  62169. * @param {Array.<number>} point
  62170. * @return {boolean}
  62171. */
  62172. containPoint: function (point) {
  62173. var coord = this.pointToCoord(point);
  62174. return this._radiusAxis.contain(coord[0])
  62175. && this._angleAxis.contain(coord[1]);
  62176. },
  62177. /**
  62178. * If contain data
  62179. * @param {Array.<number>} data
  62180. * @return {boolean}
  62181. */
  62182. containData: function (data) {
  62183. return this._radiusAxis.containData(data[0])
  62184. && this._angleAxis.containData(data[1]);
  62185. },
  62186. /**
  62187. * @param {string} dim
  62188. * @return {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis}
  62189. */
  62190. getAxis: function (dim) {
  62191. return this['_' + dim + 'Axis'];
  62192. },
  62193. /**
  62194. * @return {Array.<module:echarts/coord/Axis>}
  62195. */
  62196. getAxes: function () {
  62197. return [this._radiusAxis, this._angleAxis];
  62198. },
  62199. /**
  62200. * Get axes by type of scale
  62201. * @param {string} scaleType
  62202. * @return {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis}
  62203. */
  62204. getAxesByScale: function (scaleType) {
  62205. var axes = [];
  62206. var angleAxis = this._angleAxis;
  62207. var radiusAxis = this._radiusAxis;
  62208. angleAxis.scale.type === scaleType && axes.push(angleAxis);
  62209. radiusAxis.scale.type === scaleType && axes.push(radiusAxis);
  62210. return axes;
  62211. },
  62212. /**
  62213. * @return {module:echarts/coord/polar/AngleAxis}
  62214. */
  62215. getAngleAxis: function () {
  62216. return this._angleAxis;
  62217. },
  62218. /**
  62219. * @return {module:echarts/coord/polar/RadiusAxis}
  62220. */
  62221. getRadiusAxis: function () {
  62222. return this._radiusAxis;
  62223. },
  62224. /**
  62225. * @param {module:echarts/coord/polar/Axis}
  62226. * @return {module:echarts/coord/polar/Axis}
  62227. */
  62228. getOtherAxis: function (axis) {
  62229. var angleAxis = this._angleAxis;
  62230. return axis === angleAxis ? this._radiusAxis : angleAxis;
  62231. },
  62232. /**
  62233. * Base axis will be used on stacking.
  62234. *
  62235. * @return {module:echarts/coord/polar/Axis}
  62236. */
  62237. getBaseAxis: function () {
  62238. return this.getAxesByScale('ordinal')[0]
  62239. || this.getAxesByScale('time')[0]
  62240. || this.getAngleAxis();
  62241. },
  62242. /**
  62243. * @param {string} [dim] 'radius' or 'angle' or 'auto' or null/undefined
  62244. * @return {Object} {baseAxes: [], otherAxes: []}
  62245. */
  62246. getTooltipAxes: function (dim) {
  62247. var baseAxis = (dim != null && dim !== 'auto')
  62248. ? this.getAxis(dim) : this.getBaseAxis();
  62249. return {
  62250. baseAxes: [baseAxis],
  62251. otherAxes: [this.getOtherAxis(baseAxis)]
  62252. };
  62253. },
  62254. /**
  62255. * Convert a single data item to (x, y) point.
  62256. * Parameter data is an array which the first element is radius and the second is angle
  62257. * @param {Array.<number>} data
  62258. * @param {boolean} [clamp=false]
  62259. * @return {Array.<number>}
  62260. */
  62261. dataToPoint: function (data, clamp) {
  62262. return this.coordToPoint([
  62263. this._radiusAxis.dataToRadius(data[0], clamp),
  62264. this._angleAxis.dataToAngle(data[1], clamp)
  62265. ]);
  62266. },
  62267. /**
  62268. * Convert a (x, y) point to data
  62269. * @param {Array.<number>} point
  62270. * @param {boolean} [clamp=false]
  62271. * @return {Array.<number>}
  62272. */
  62273. pointToData: function (point, clamp) {
  62274. var coord = this.pointToCoord(point);
  62275. return [
  62276. this._radiusAxis.radiusToData(coord[0], clamp),
  62277. this._angleAxis.angleToData(coord[1], clamp)
  62278. ];
  62279. },
  62280. /**
  62281. * Convert a (x, y) point to (radius, angle) coord
  62282. * @param {Array.<number>} point
  62283. * @return {Array.<number>}
  62284. */
  62285. pointToCoord: function (point) {
  62286. var dx = point[0] - this.cx;
  62287. var dy = point[1] - this.cy;
  62288. var angleAxis = this.getAngleAxis();
  62289. var extent = angleAxis.getExtent();
  62290. var minAngle = Math.min(extent[0], extent[1]);
  62291. var maxAngle = Math.max(extent[0], extent[1]);
  62292. // Fix fixed extent in polarCreator
  62293. // FIXME
  62294. angleAxis.inverse
  62295. ? (minAngle = maxAngle - 360)
  62296. : (maxAngle = minAngle + 360);
  62297. var radius = Math.sqrt(dx * dx + dy * dy);
  62298. dx /= radius;
  62299. dy /= radius;
  62300. var radian = Math.atan2(-dy, dx) / Math.PI * 180;
  62301. // move to angleExtent
  62302. var dir = radian < minAngle ? 1 : -1;
  62303. while (radian < minAngle || radian > maxAngle) {
  62304. radian += dir * 360;
  62305. }
  62306. return [radius, radian];
  62307. },
  62308. /**
  62309. * Convert a (radius, angle) coord to (x, y) point
  62310. * @param {Array.<number>} coord
  62311. * @return {Array.<number>}
  62312. */
  62313. coordToPoint: function (coord) {
  62314. var radius = coord[0];
  62315. var radian = coord[1] / 180 * Math.PI;
  62316. var x = Math.cos(radian) * radius + this.cx;
  62317. // Inverse the y
  62318. var y = -Math.sin(radian) * radius + this.cy;
  62319. return [x, y];
  62320. }
  62321. };
  62322. /*
  62323. * Licensed to the Apache Software Foundation (ASF) under one
  62324. * or more contributor license agreements. See the NOTICE file
  62325. * distributed with this work for additional information
  62326. * regarding copyright ownership. The ASF licenses this file
  62327. * to you under the Apache License, Version 2.0 (the
  62328. * "License"); you may not use this file except in compliance
  62329. * with the License. You may obtain a copy of the License at
  62330. *
  62331. * http://www.apache.org/licenses/LICENSE-2.0
  62332. *
  62333. * Unless required by applicable law or agreed to in writing,
  62334. * software distributed under the License is distributed on an
  62335. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62336. * KIND, either express or implied. See the License for the
  62337. * specific language governing permissions and limitations
  62338. * under the License.
  62339. */
  62340. var PolarAxisModel = ComponentModel.extend({
  62341. type: 'polarAxis',
  62342. /**
  62343. * @type {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis}
  62344. */
  62345. axis: null,
  62346. /**
  62347. * @override
  62348. */
  62349. getCoordSysModel: function () {
  62350. return this.ecModel.queryComponents({
  62351. mainType: 'polar',
  62352. index: this.option.polarIndex,
  62353. id: this.option.polarId
  62354. })[0];
  62355. }
  62356. });
  62357. merge(PolarAxisModel.prototype, axisModelCommonMixin);
  62358. var polarAxisDefaultExtendedOption = {
  62359. angle: {
  62360. // polarIndex: 0,
  62361. // polarId: '',
  62362. startAngle: 90,
  62363. clockwise: true,
  62364. splitNumber: 12,
  62365. axisLabel: {
  62366. rotate: false
  62367. }
  62368. },
  62369. radius: {
  62370. // polarIndex: 0,
  62371. // polarId: '',
  62372. splitNumber: 5
  62373. }
  62374. };
  62375. function getAxisType$3(axisDim, option) {
  62376. // Default axis with data is category axis
  62377. return option.type || (option.data ? 'category' : 'value');
  62378. }
  62379. axisModelCreator('angle', PolarAxisModel, getAxisType$3, polarAxisDefaultExtendedOption.angle);
  62380. axisModelCreator('radius', PolarAxisModel, getAxisType$3, polarAxisDefaultExtendedOption.radius);
  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. extendComponentModel({
  62400. type: 'polar',
  62401. dependencies: ['polarAxis', 'angleAxis'],
  62402. /**
  62403. * @type {module:echarts/coord/polar/Polar}
  62404. */
  62405. coordinateSystem: null,
  62406. /**
  62407. * @param {string} axisType
  62408. * @return {module:echarts/coord/polar/AxisModel}
  62409. */
  62410. findAxisModel: function (axisType) {
  62411. var foundAxisModel;
  62412. var ecModel = this.ecModel;
  62413. ecModel.eachComponent(axisType, function (axisModel) {
  62414. if (axisModel.getCoordSysModel() === this) {
  62415. foundAxisModel = axisModel;
  62416. }
  62417. }, this);
  62418. return foundAxisModel;
  62419. },
  62420. defaultOption: {
  62421. zlevel: 0,
  62422. z: 0,
  62423. center: ['50%', '50%'],
  62424. radius: '80%'
  62425. }
  62426. });
  62427. /*
  62428. * Licensed to the Apache Software Foundation (ASF) under one
  62429. * or more contributor license agreements. See the NOTICE file
  62430. * distributed with this work for additional information
  62431. * regarding copyright ownership. The ASF licenses this file
  62432. * to you under the Apache License, Version 2.0 (the
  62433. * "License"); you may not use this file except in compliance
  62434. * with the License. You may obtain a copy of the License at
  62435. *
  62436. * http://www.apache.org/licenses/LICENSE-2.0
  62437. *
  62438. * Unless required by applicable law or agreed to in writing,
  62439. * software distributed under the License is distributed on an
  62440. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62441. * KIND, either express or implied. See the License for the
  62442. * specific language governing permissions and limitations
  62443. * under the License.
  62444. */
  62445. // TODO Axis scale
  62446. // 依赖 PolarModel 做预处理
  62447. /**
  62448. * Resize method bound to the polar
  62449. * @param {module:echarts/coord/polar/PolarModel} polarModel
  62450. * @param {module:echarts/ExtensionAPI} api
  62451. */
  62452. function resizePolar(polar, polarModel, api) {
  62453. var center = polarModel.get('center');
  62454. var width = api.getWidth();
  62455. var height = api.getHeight();
  62456. polar.cx = parsePercent$1(center[0], width);
  62457. polar.cy = parsePercent$1(center[1], height);
  62458. var radiusAxis = polar.getRadiusAxis();
  62459. var size = Math.min(width, height) / 2;
  62460. var radius = parsePercent$1(polarModel.get('radius'), size);
  62461. radiusAxis.inverse
  62462. ? radiusAxis.setExtent(radius, 0)
  62463. : radiusAxis.setExtent(0, radius);
  62464. }
  62465. /**
  62466. * Update polar
  62467. */
  62468. function updatePolarScale(ecModel, api) {
  62469. var polar = this;
  62470. var angleAxis = polar.getAngleAxis();
  62471. var radiusAxis = polar.getRadiusAxis();
  62472. // Reset scale
  62473. angleAxis.scale.setExtent(Infinity, -Infinity);
  62474. radiusAxis.scale.setExtent(Infinity, -Infinity);
  62475. ecModel.eachSeries(function (seriesModel) {
  62476. if (seriesModel.coordinateSystem === polar) {
  62477. var data = seriesModel.getData();
  62478. each$1(data.mapDimension('radius', true), function (dim) {
  62479. radiusAxis.scale.unionExtentFromData(data, dim);
  62480. });
  62481. each$1(data.mapDimension('angle', true), function (dim) {
  62482. angleAxis.scale.unionExtentFromData(data, dim);
  62483. });
  62484. }
  62485. });
  62486. niceScaleExtent(angleAxis.scale, angleAxis.model);
  62487. niceScaleExtent(radiusAxis.scale, radiusAxis.model);
  62488. // Fix extent of category angle axis
  62489. if (angleAxis.type === 'category' && !angleAxis.onBand) {
  62490. var extent = angleAxis.getExtent();
  62491. var diff = 360 / angleAxis.scale.count();
  62492. angleAxis.inverse ? (extent[1] += diff) : (extent[1] -= diff);
  62493. angleAxis.setExtent(extent[0], extent[1]);
  62494. }
  62495. }
  62496. /**
  62497. * Set common axis properties
  62498. * @param {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis}
  62499. * @param {module:echarts/coord/polar/AxisModel}
  62500. * @inner
  62501. */
  62502. function setAxis(axis, axisModel) {
  62503. axis.type = axisModel.get('type');
  62504. axis.scale = createScaleByModel(axisModel);
  62505. axis.onBand = axisModel.get('boundaryGap') && axis.type === 'category';
  62506. axis.inverse = axisModel.get('inverse');
  62507. if (axisModel.mainType === 'angleAxis') {
  62508. axis.inverse ^= axisModel.get('clockwise');
  62509. var startAngle = axisModel.get('startAngle');
  62510. axis.setExtent(startAngle, startAngle + (axis.inverse ? -360 : 360));
  62511. }
  62512. // Inject axis instance
  62513. axisModel.axis = axis;
  62514. axis.model = axisModel;
  62515. }
  62516. var polarCreator = {
  62517. dimensions: Polar.prototype.dimensions,
  62518. create: function (ecModel, api) {
  62519. var polarList = [];
  62520. ecModel.eachComponent('polar', function (polarModel, idx) {
  62521. var polar = new Polar(idx);
  62522. // Inject resize and update method
  62523. polar.update = updatePolarScale;
  62524. var radiusAxis = polar.getRadiusAxis();
  62525. var angleAxis = polar.getAngleAxis();
  62526. var radiusAxisModel = polarModel.findAxisModel('radiusAxis');
  62527. var angleAxisModel = polarModel.findAxisModel('angleAxis');
  62528. setAxis(radiusAxis, radiusAxisModel);
  62529. setAxis(angleAxis, angleAxisModel);
  62530. resizePolar(polar, polarModel, api);
  62531. polarList.push(polar);
  62532. polarModel.coordinateSystem = polar;
  62533. polar.model = polarModel;
  62534. });
  62535. // Inject coordinateSystem to series
  62536. ecModel.eachSeries(function (seriesModel) {
  62537. if (seriesModel.get('coordinateSystem') === 'polar') {
  62538. var polarModel = ecModel.queryComponents({
  62539. mainType: 'polar',
  62540. index: seriesModel.get('polarIndex'),
  62541. id: seriesModel.get('polarId')
  62542. })[0];
  62543. if (__DEV__) {
  62544. if (!polarModel) {
  62545. throw new Error(
  62546. 'Polar "' + retrieve(
  62547. seriesModel.get('polarIndex'),
  62548. seriesModel.get('polarId'),
  62549. 0
  62550. ) + '" not found'
  62551. );
  62552. }
  62553. }
  62554. seriesModel.coordinateSystem = polarModel.coordinateSystem;
  62555. }
  62556. });
  62557. return polarList;
  62558. }
  62559. };
  62560. CoordinateSystemManager.register('polar', polarCreator);
  62561. /*
  62562. * Licensed to the Apache Software Foundation (ASF) under one
  62563. * or more contributor license agreements. See the NOTICE file
  62564. * distributed with this work for additional information
  62565. * regarding copyright ownership. The ASF licenses this file
  62566. * to you under the Apache License, Version 2.0 (the
  62567. * "License"); you may not use this file except in compliance
  62568. * with the License. You may obtain a copy of the License at
  62569. *
  62570. * http://www.apache.org/licenses/LICENSE-2.0
  62571. *
  62572. * Unless required by applicable law or agreed to in writing,
  62573. * software distributed under the License is distributed on an
  62574. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62575. * KIND, either express or implied. See the License for the
  62576. * specific language governing permissions and limitations
  62577. * under the License.
  62578. */
  62579. var elementList$1 = ['axisLine', 'axisLabel', 'axisTick', 'splitLine', 'splitArea'];
  62580. function getAxisLineShape(polar, rExtent, angle) {
  62581. rExtent[1] > rExtent[0] && (rExtent = rExtent.slice().reverse());
  62582. var start = polar.coordToPoint([rExtent[0], angle]);
  62583. var end = polar.coordToPoint([rExtent[1], angle]);
  62584. return {
  62585. x1: start[0],
  62586. y1: start[1],
  62587. x2: end[0],
  62588. y2: end[1]
  62589. };
  62590. }
  62591. function getRadiusIdx(polar) {
  62592. var radiusAxis = polar.getRadiusAxis();
  62593. return radiusAxis.inverse ? 0 : 1;
  62594. }
  62595. // Remove the last tick which will overlap the first tick
  62596. function fixAngleOverlap(list) {
  62597. var firstItem = list[0];
  62598. var lastItem = list[list.length - 1];
  62599. if (firstItem
  62600. && lastItem
  62601. && Math.abs(Math.abs(firstItem.coord - lastItem.coord) - 360) < 1e-4
  62602. ) {
  62603. list.pop();
  62604. }
  62605. }
  62606. AxisView.extend({
  62607. type: 'angleAxis',
  62608. axisPointerClass: 'PolarAxisPointer',
  62609. render: function (angleAxisModel, ecModel) {
  62610. this.group.removeAll();
  62611. if (!angleAxisModel.get('show')) {
  62612. return;
  62613. }
  62614. var angleAxis = angleAxisModel.axis;
  62615. var polar = angleAxis.polar;
  62616. var radiusExtent = polar.getRadiusAxis().getExtent();
  62617. var ticksAngles = angleAxis.getTicksCoords();
  62618. var labels = map(angleAxis.getViewLabels(), function (labelItem) {
  62619. var labelItem = clone(labelItem);
  62620. labelItem.coord = angleAxis.dataToCoord(labelItem.tickValue);
  62621. return labelItem;
  62622. });
  62623. fixAngleOverlap(labels);
  62624. fixAngleOverlap(ticksAngles);
  62625. each$1(elementList$1, function (name) {
  62626. if (angleAxisModel.get(name +'.show')
  62627. && (!angleAxis.scale.isBlank() || name === 'axisLine')
  62628. ) {
  62629. this['_' + name](angleAxisModel, polar, ticksAngles, radiusExtent, labels);
  62630. }
  62631. }, this);
  62632. },
  62633. /**
  62634. * @private
  62635. */
  62636. _axisLine: function (angleAxisModel, polar, ticksAngles, radiusExtent) {
  62637. var lineStyleModel = angleAxisModel.getModel('axisLine.lineStyle');
  62638. var circle = new Circle({
  62639. shape: {
  62640. cx: polar.cx,
  62641. cy: polar.cy,
  62642. r: radiusExtent[getRadiusIdx(polar)]
  62643. },
  62644. style: lineStyleModel.getLineStyle(),
  62645. z2: 1,
  62646. silent: true
  62647. });
  62648. circle.style.fill = null;
  62649. this.group.add(circle);
  62650. },
  62651. /**
  62652. * @private
  62653. */
  62654. _axisTick: function (angleAxisModel, polar, ticksAngles, radiusExtent) {
  62655. var tickModel = angleAxisModel.getModel('axisTick');
  62656. var tickLen = (tickModel.get('inside') ? -1 : 1) * tickModel.get('length');
  62657. var radius = radiusExtent[getRadiusIdx(polar)];
  62658. var lines = map(ticksAngles, function (tickAngleItem) {
  62659. return new Line({
  62660. shape: getAxisLineShape(polar, [radius, radius + tickLen], tickAngleItem.coord)
  62661. });
  62662. });
  62663. this.group.add(mergePath(
  62664. lines, {
  62665. style: defaults(
  62666. tickModel.getModel('lineStyle').getLineStyle(),
  62667. {
  62668. stroke: angleAxisModel.get('axisLine.lineStyle.color')
  62669. }
  62670. )
  62671. }
  62672. ));
  62673. },
  62674. /**
  62675. * @private
  62676. */
  62677. _axisLabel: function (angleAxisModel, polar, ticksAngles, radiusExtent, labels) {
  62678. var rawCategoryData = angleAxisModel.getCategories(true);
  62679. var commonLabelModel = angleAxisModel.getModel('axisLabel');
  62680. var labelMargin = commonLabelModel.get('margin');
  62681. // Use length of ticksAngles because it may remove the last tick to avoid overlapping
  62682. each$1(labels, function (labelItem, idx) {
  62683. var labelModel = commonLabelModel;
  62684. var tickValue = labelItem.tickValue;
  62685. var r = radiusExtent[getRadiusIdx(polar)];
  62686. var p = polar.coordToPoint([r + labelMargin, labelItem.coord]);
  62687. var cx = polar.cx;
  62688. var cy = polar.cy;
  62689. var labelTextAlign = Math.abs(p[0] - cx) / r < 0.3
  62690. ? 'center' : (p[0] > cx ? 'left' : 'right');
  62691. var labelTextVerticalAlign = Math.abs(p[1] - cy) / r < 0.3
  62692. ? 'middle' : (p[1] > cy ? 'top' : 'bottom');
  62693. if (rawCategoryData && rawCategoryData[tickValue] && rawCategoryData[tickValue].textStyle) {
  62694. labelModel = new Model(rawCategoryData[tickValue].textStyle, commonLabelModel, commonLabelModel.ecModel);
  62695. }
  62696. var textEl = new Text({silent: true});
  62697. this.group.add(textEl);
  62698. setTextStyle(textEl.style, labelModel, {
  62699. x: p[0],
  62700. y: p[1],
  62701. textFill: labelModel.getTextColor() || angleAxisModel.get('axisLine.lineStyle.color'),
  62702. text: labelItem.formattedLabel,
  62703. textAlign: labelTextAlign,
  62704. textVerticalAlign: labelTextVerticalAlign
  62705. });
  62706. }, this);
  62707. },
  62708. /**
  62709. * @private
  62710. */
  62711. _splitLine: function (angleAxisModel, polar, ticksAngles, radiusExtent) {
  62712. var splitLineModel = angleAxisModel.getModel('splitLine');
  62713. var lineStyleModel = splitLineModel.getModel('lineStyle');
  62714. var lineColors = lineStyleModel.get('color');
  62715. var lineCount = 0;
  62716. lineColors = lineColors instanceof Array ? lineColors : [lineColors];
  62717. var splitLines = [];
  62718. for (var i = 0; i < ticksAngles.length; i++) {
  62719. var colorIndex = (lineCount++) % lineColors.length;
  62720. splitLines[colorIndex] = splitLines[colorIndex] || [];
  62721. splitLines[colorIndex].push(new Line({
  62722. shape: getAxisLineShape(polar, radiusExtent, ticksAngles[i].coord)
  62723. }));
  62724. }
  62725. // Simple optimization
  62726. // Batching the lines if color are the same
  62727. for (var i = 0; i < splitLines.length; i++) {
  62728. this.group.add(mergePath(splitLines[i], {
  62729. style: defaults({
  62730. stroke: lineColors[i % lineColors.length]
  62731. }, lineStyleModel.getLineStyle()),
  62732. silent: true,
  62733. z: angleAxisModel.get('z')
  62734. }));
  62735. }
  62736. },
  62737. /**
  62738. * @private
  62739. */
  62740. _splitArea: function (angleAxisModel, polar, ticksAngles, radiusExtent) {
  62741. if (!ticksAngles.length) {
  62742. return;
  62743. }
  62744. var splitAreaModel = angleAxisModel.getModel('splitArea');
  62745. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  62746. var areaColors = areaStyleModel.get('color');
  62747. var lineCount = 0;
  62748. areaColors = areaColors instanceof Array ? areaColors : [areaColors];
  62749. var splitAreas = [];
  62750. var RADIAN = Math.PI / 180;
  62751. var prevAngle = -ticksAngles[0].coord * RADIAN;
  62752. var r0 = Math.min(radiusExtent[0], radiusExtent[1]);
  62753. var r1 = Math.max(radiusExtent[0], radiusExtent[1]);
  62754. var clockwise = angleAxisModel.get('clockwise');
  62755. for (var i = 1; i < ticksAngles.length; i++) {
  62756. var colorIndex = (lineCount++) % areaColors.length;
  62757. splitAreas[colorIndex] = splitAreas[colorIndex] || [];
  62758. splitAreas[colorIndex].push(new Sector({
  62759. shape: {
  62760. cx: polar.cx,
  62761. cy: polar.cy,
  62762. r0: r0,
  62763. r: r1,
  62764. startAngle: prevAngle,
  62765. endAngle: -ticksAngles[i].coord * RADIAN,
  62766. clockwise: clockwise
  62767. },
  62768. silent: true
  62769. }));
  62770. prevAngle = -ticksAngles[i].coord * RADIAN;
  62771. }
  62772. // Simple optimization
  62773. // Batching the lines if color are the same
  62774. for (var i = 0; i < splitAreas.length; i++) {
  62775. this.group.add(mergePath(splitAreas[i], {
  62776. style: defaults({
  62777. fill: areaColors[i % areaColors.length]
  62778. }, areaStyleModel.getAreaStyle()),
  62779. silent: true
  62780. }));
  62781. }
  62782. }
  62783. });
  62784. /*
  62785. * Licensed to the Apache Software Foundation (ASF) under one
  62786. * or more contributor license agreements. See the NOTICE file
  62787. * distributed with this work for additional information
  62788. * regarding copyright ownership. The ASF licenses this file
  62789. * to you under the Apache License, Version 2.0 (the
  62790. * "License"); you may not use this file except in compliance
  62791. * with the License. You may obtain a copy of the License at
  62792. *
  62793. * http://www.apache.org/licenses/LICENSE-2.0
  62794. *
  62795. * Unless required by applicable law or agreed to in writing,
  62796. * software distributed under the License is distributed on an
  62797. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62798. * KIND, either express or implied. See the License for the
  62799. * specific language governing permissions and limitations
  62800. * under the License.
  62801. */
  62802. /*
  62803. * Licensed to the Apache Software Foundation (ASF) under one
  62804. * or more contributor license agreements. See the NOTICE file
  62805. * distributed with this work for additional information
  62806. * regarding copyright ownership. The ASF licenses this file
  62807. * to you under the Apache License, Version 2.0 (the
  62808. * "License"); you may not use this file except in compliance
  62809. * with the License. You may obtain a copy of the License at
  62810. *
  62811. * http://www.apache.org/licenses/LICENSE-2.0
  62812. *
  62813. * Unless required by applicable law or agreed to in writing,
  62814. * software distributed under the License is distributed on an
  62815. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62816. * KIND, either express or implied. See the License for the
  62817. * specific language governing permissions and limitations
  62818. * under the License.
  62819. */
  62820. var axisBuilderAttrs$3 = [
  62821. 'axisLine', 'axisTickLabel', 'axisName'
  62822. ];
  62823. var selfBuilderAttrs$1 = [
  62824. 'splitLine', 'splitArea'
  62825. ];
  62826. AxisView.extend({
  62827. type: 'radiusAxis',
  62828. axisPointerClass: 'PolarAxisPointer',
  62829. render: function (radiusAxisModel, ecModel) {
  62830. this.group.removeAll();
  62831. if (!radiusAxisModel.get('show')) {
  62832. return;
  62833. }
  62834. var radiusAxis = radiusAxisModel.axis;
  62835. var polar = radiusAxis.polar;
  62836. var angleAxis = polar.getAngleAxis();
  62837. var ticksCoords = radiusAxis.getTicksCoords();
  62838. var axisAngle = angleAxis.getExtent()[0];
  62839. var radiusExtent = radiusAxis.getExtent();
  62840. var layout = layoutAxis(polar, radiusAxisModel, axisAngle);
  62841. var axisBuilder = new AxisBuilder(radiusAxisModel, layout);
  62842. each$1(axisBuilderAttrs$3, axisBuilder.add, axisBuilder);
  62843. this.group.add(axisBuilder.getGroup());
  62844. each$1(selfBuilderAttrs$1, function (name) {
  62845. if (radiusAxisModel.get(name +'.show') && !radiusAxis.scale.isBlank()) {
  62846. this['_' + name](radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords);
  62847. }
  62848. }, this);
  62849. },
  62850. /**
  62851. * @private
  62852. */
  62853. _splitLine: function (radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords) {
  62854. var splitLineModel = radiusAxisModel.getModel('splitLine');
  62855. var lineStyleModel = splitLineModel.getModel('lineStyle');
  62856. var lineColors = lineStyleModel.get('color');
  62857. var lineCount = 0;
  62858. lineColors = lineColors instanceof Array ? lineColors : [lineColors];
  62859. var splitLines = [];
  62860. for (var i = 0; i < ticksCoords.length; i++) {
  62861. var colorIndex = (lineCount++) % lineColors.length;
  62862. splitLines[colorIndex] = splitLines[colorIndex] || [];
  62863. splitLines[colorIndex].push(new Circle({
  62864. shape: {
  62865. cx: polar.cx,
  62866. cy: polar.cy,
  62867. r: ticksCoords[i].coord
  62868. },
  62869. silent: true
  62870. }));
  62871. }
  62872. // Simple optimization
  62873. // Batching the lines if color are the same
  62874. for (var i = 0; i < splitLines.length; i++) {
  62875. this.group.add(mergePath(splitLines[i], {
  62876. style: defaults({
  62877. stroke: lineColors[i % lineColors.length],
  62878. fill: null
  62879. }, lineStyleModel.getLineStyle()),
  62880. silent: true
  62881. }));
  62882. }
  62883. },
  62884. /**
  62885. * @private
  62886. */
  62887. _splitArea: function (radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords) {
  62888. if (!ticksCoords.length) {
  62889. return;
  62890. }
  62891. var splitAreaModel = radiusAxisModel.getModel('splitArea');
  62892. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  62893. var areaColors = areaStyleModel.get('color');
  62894. var lineCount = 0;
  62895. areaColors = areaColors instanceof Array ? areaColors : [areaColors];
  62896. var splitAreas = [];
  62897. var prevRadius = ticksCoords[0].coord;
  62898. for (var i = 1; i < ticksCoords.length; i++) {
  62899. var colorIndex = (lineCount++) % areaColors.length;
  62900. splitAreas[colorIndex] = splitAreas[colorIndex] || [];
  62901. splitAreas[colorIndex].push(new Sector({
  62902. shape: {
  62903. cx: polar.cx,
  62904. cy: polar.cy,
  62905. r0: prevRadius,
  62906. r: ticksCoords[i].coord,
  62907. startAngle: 0,
  62908. endAngle: Math.PI * 2
  62909. },
  62910. silent: true
  62911. }));
  62912. prevRadius = ticksCoords[i].coord;
  62913. }
  62914. // Simple optimization
  62915. // Batching the lines if color are the same
  62916. for (var i = 0; i < splitAreas.length; i++) {
  62917. this.group.add(mergePath(splitAreas[i], {
  62918. style: defaults({
  62919. fill: areaColors[i % areaColors.length]
  62920. }, areaStyleModel.getAreaStyle()),
  62921. silent: true
  62922. }));
  62923. }
  62924. }
  62925. });
  62926. /**
  62927. * @inner
  62928. */
  62929. function layoutAxis(polar, radiusAxisModel, axisAngle) {
  62930. return {
  62931. position: [polar.cx, polar.cy],
  62932. rotation: axisAngle / 180 * Math.PI,
  62933. labelDirection: -1,
  62934. tickDirection: -1,
  62935. nameDirection: 1,
  62936. labelRotate: radiusAxisModel.getModel('axisLabel').get('rotate'),
  62937. // Over splitLine and splitArea
  62938. z2: 1
  62939. };
  62940. }
  62941. /*
  62942. * Licensed to the Apache Software Foundation (ASF) under one
  62943. * or more contributor license agreements. See the NOTICE file
  62944. * distributed with this work for additional information
  62945. * regarding copyright ownership. The ASF licenses this file
  62946. * to you under the Apache License, Version 2.0 (the
  62947. * "License"); you may not use this file except in compliance
  62948. * with the License. You may obtain a copy of the License at
  62949. *
  62950. * http://www.apache.org/licenses/LICENSE-2.0
  62951. *
  62952. * Unless required by applicable law or agreed to in writing,
  62953. * software distributed under the License is distributed on an
  62954. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62955. * KIND, either express or implied. See the License for the
  62956. * specific language governing permissions and limitations
  62957. * under the License.
  62958. */
  62959. /*
  62960. * Licensed to the Apache Software Foundation (ASF) under one
  62961. * or more contributor license agreements. See the NOTICE file
  62962. * distributed with this work for additional information
  62963. * regarding copyright ownership. The ASF licenses this file
  62964. * to you under the Apache License, Version 2.0 (the
  62965. * "License"); you may not use this file except in compliance
  62966. * with the License. You may obtain a copy of the License at
  62967. *
  62968. * http://www.apache.org/licenses/LICENSE-2.0
  62969. *
  62970. * Unless required by applicable law or agreed to in writing,
  62971. * software distributed under the License is distributed on an
  62972. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62973. * KIND, either express or implied. See the License for the
  62974. * specific language governing permissions and limitations
  62975. * under the License.
  62976. */
  62977. var PolarAxisPointer = BaseAxisPointer.extend({
  62978. /**
  62979. * @override
  62980. */
  62981. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  62982. var axis = axisModel.axis;
  62983. if (axis.dim === 'angle') {
  62984. this.animationThreshold = Math.PI / 18;
  62985. }
  62986. var polar = axis.polar;
  62987. var otherAxis = polar.getOtherAxis(axis);
  62988. var otherExtent = otherAxis.getExtent();
  62989. var coordValue;
  62990. coordValue = axis['dataTo' + capitalFirst(axis.dim)](value);
  62991. var axisPointerType = axisPointerModel.get('type');
  62992. if (axisPointerType && axisPointerType !== 'none') {
  62993. var elStyle = buildElStyle(axisPointerModel);
  62994. var pointerOption = pointerShapeBuilder$2[axisPointerType](
  62995. axis, polar, coordValue, otherExtent, elStyle
  62996. );
  62997. pointerOption.style = elStyle;
  62998. elOption.graphicKey = pointerOption.type;
  62999. elOption.pointer = pointerOption;
  63000. }
  63001. var labelMargin = axisPointerModel.get('label.margin');
  63002. var labelPos = getLabelPosition(value, axisModel, axisPointerModel, polar, labelMargin);
  63003. buildLabelElOption(elOption, axisModel, axisPointerModel, api, labelPos);
  63004. }
  63005. // Do not support handle, utill any user requires it.
  63006. });
  63007. function getLabelPosition(value, axisModel, axisPointerModel, polar, labelMargin) {
  63008. var axis = axisModel.axis;
  63009. var coord = axis.dataToCoord(value);
  63010. var axisAngle = polar.getAngleAxis().getExtent()[0];
  63011. axisAngle = axisAngle / 180 * Math.PI;
  63012. var radiusExtent = polar.getRadiusAxis().getExtent();
  63013. var position;
  63014. var align;
  63015. var verticalAlign;
  63016. if (axis.dim === 'radius') {
  63017. var transform = create$1();
  63018. rotate(transform, transform, axisAngle);
  63019. translate(transform, transform, [polar.cx, polar.cy]);
  63020. position = applyTransform$1([coord, -labelMargin], transform);
  63021. var labelRotation = axisModel.getModel('axisLabel').get('rotate') || 0;
  63022. var labelLayout = AxisBuilder.innerTextLayout(
  63023. axisAngle, labelRotation * Math.PI / 180, -1
  63024. );
  63025. align = labelLayout.textAlign;
  63026. verticalAlign = labelLayout.textVerticalAlign;
  63027. }
  63028. else { // angle axis
  63029. var r = radiusExtent[1];
  63030. position = polar.coordToPoint([r + labelMargin, coord]);
  63031. var cx = polar.cx;
  63032. var cy = polar.cy;
  63033. align = Math.abs(position[0] - cx) / r < 0.3
  63034. ? 'center' : (position[0] > cx ? 'left' : 'right');
  63035. verticalAlign = Math.abs(position[1] - cy) / r < 0.3
  63036. ? 'middle' : (position[1] > cy ? 'top' : 'bottom');
  63037. }
  63038. return {
  63039. position: position,
  63040. align: align,
  63041. verticalAlign: verticalAlign
  63042. };
  63043. }
  63044. var pointerShapeBuilder$2 = {
  63045. line: function (axis, polar, coordValue, otherExtent, elStyle) {
  63046. return axis.dim === 'angle'
  63047. ? {
  63048. type: 'Line',
  63049. shape: makeLineShape(
  63050. polar.coordToPoint([otherExtent[0], coordValue]),
  63051. polar.coordToPoint([otherExtent[1], coordValue])
  63052. )
  63053. }
  63054. : {
  63055. type: 'Circle',
  63056. shape: {
  63057. cx: polar.cx,
  63058. cy: polar.cy,
  63059. r: coordValue
  63060. }
  63061. };
  63062. },
  63063. shadow: function (axis, polar, coordValue, otherExtent, elStyle) {
  63064. var bandWidth = Math.max(1, axis.getBandWidth());
  63065. var radian = Math.PI / 180;
  63066. return axis.dim === 'angle'
  63067. ? {
  63068. type: 'Sector',
  63069. shape: makeSectorShape(
  63070. polar.cx, polar.cy,
  63071. otherExtent[0], otherExtent[1],
  63072. // In ECharts y is negative if angle is positive
  63073. (-coordValue - bandWidth / 2) * radian,
  63074. (-coordValue + bandWidth / 2) * radian
  63075. )
  63076. }
  63077. : {
  63078. type: 'Sector',
  63079. shape: makeSectorShape(
  63080. polar.cx, polar.cy,
  63081. coordValue - bandWidth / 2,
  63082. coordValue + bandWidth / 2,
  63083. 0, Math.PI * 2
  63084. )
  63085. };
  63086. }
  63087. };
  63088. AxisView.registerAxisPointerClass('PolarAxisPointer', PolarAxisPointer);
  63089. /*
  63090. * Licensed to the Apache Software Foundation (ASF) under one
  63091. * or more contributor license agreements. See the NOTICE file
  63092. * distributed with this work for additional information
  63093. * regarding copyright ownership. The ASF licenses this file
  63094. * to you under the Apache License, Version 2.0 (the
  63095. * "License"); you may not use this file except in compliance
  63096. * with the License. You may obtain a copy of the License at
  63097. *
  63098. * http://www.apache.org/licenses/LICENSE-2.0
  63099. *
  63100. * Unless required by applicable law or agreed to in writing,
  63101. * software distributed under the License is distributed on an
  63102. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63103. * KIND, either express or implied. See the License for the
  63104. * specific language governing permissions and limitations
  63105. * under the License.
  63106. */
  63107. // For reducing size of echarts.min, barLayoutPolar is required by polar.
  63108. registerLayout(curry(barLayoutPolar, 'bar'));
  63109. // Polar view
  63110. extendComponentView({
  63111. type: 'polar'
  63112. });
  63113. /*
  63114. * Licensed to the Apache Software Foundation (ASF) under one
  63115. * or more contributor license agreements. See the NOTICE file
  63116. * distributed with this work for additional information
  63117. * regarding copyright ownership. The ASF licenses this file
  63118. * to you under the Apache License, Version 2.0 (the
  63119. * "License"); you may not use this file except in compliance
  63120. * with the License. You may obtain a copy of the License at
  63121. *
  63122. * http://www.apache.org/licenses/LICENSE-2.0
  63123. *
  63124. * Unless required by applicable law or agreed to in writing,
  63125. * software distributed under the License is distributed on an
  63126. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63127. * KIND, either express or implied. See the License for the
  63128. * specific language governing permissions and limitations
  63129. * under the License.
  63130. */
  63131. var GeoModel = ComponentModel.extend({
  63132. type: 'geo',
  63133. /**
  63134. * @type {module:echarts/coord/geo/Geo}
  63135. */
  63136. coordinateSystem: null,
  63137. layoutMode: 'box',
  63138. init: function (option) {
  63139. ComponentModel.prototype.init.apply(this, arguments);
  63140. // Default label emphasis `show`
  63141. defaultEmphasis(option, 'label', ['show']);
  63142. },
  63143. optionUpdated: function () {
  63144. var option = this.option;
  63145. var self = this;
  63146. option.regions = geoCreator.getFilledRegions(option.regions, option.map, option.nameMap);
  63147. this._optionModelMap = reduce(option.regions || [], function (optionModelMap, regionOpt) {
  63148. if (regionOpt.name) {
  63149. optionModelMap.set(regionOpt.name, new Model(regionOpt, self));
  63150. }
  63151. return optionModelMap;
  63152. }, createHashMap());
  63153. this.updateSelectedMap(option.regions);
  63154. },
  63155. defaultOption: {
  63156. zlevel: 0,
  63157. z: 0,
  63158. show: true,
  63159. left: 'center',
  63160. top: 'center',
  63161. // width:,
  63162. // height:,
  63163. // right
  63164. // bottom
  63165. // Aspect is width / height. Inited to be geoJson bbox aspect
  63166. // This parameter is used for scale this aspect
  63167. aspectScale: 0.75,
  63168. ///// Layout with center and size
  63169. // If you wan't to put map in a fixed size box with right aspect ratio
  63170. // This two properties may more conveninet
  63171. // layoutCenter: [50%, 50%]
  63172. // layoutSize: 100
  63173. silent: false,
  63174. // Map type
  63175. map: '',
  63176. // Define left-top, right-bottom coords to control view
  63177. // For example, [ [180, 90], [-180, -90] ]
  63178. boundingCoords: null,
  63179. // Default on center of map
  63180. center: null,
  63181. zoom: 1,
  63182. scaleLimit: null,
  63183. // selectedMode: false
  63184. label: {
  63185. show: false,
  63186. color: '#000'
  63187. },
  63188. itemStyle: {
  63189. // color: 各异,
  63190. borderWidth: 0.5,
  63191. borderColor: '#444',
  63192. color: '#eee'
  63193. },
  63194. emphasis: {
  63195. label: {
  63196. show: true,
  63197. color: 'rgb(100,0,0)'
  63198. },
  63199. itemStyle: {
  63200. color: 'rgba(255,215,0,0.8)'
  63201. }
  63202. },
  63203. regions: []
  63204. },
  63205. /**
  63206. * Get model of region
  63207. * @param {string} name
  63208. * @return {module:echarts/model/Model}
  63209. */
  63210. getRegionModel: function (name) {
  63211. return this._optionModelMap.get(name) || new Model(null, this, this.ecModel);
  63212. },
  63213. /**
  63214. * Format label
  63215. * @param {string} name Region name
  63216. * @param {string} [status='normal'] 'normal' or 'emphasis'
  63217. * @return {string}
  63218. */
  63219. getFormattedLabel: function (name, status) {
  63220. var regionModel = this.getRegionModel(name);
  63221. var formatter = regionModel.get('label.' + status + '.formatter');
  63222. var params = {
  63223. name: name
  63224. };
  63225. if (typeof formatter === 'function') {
  63226. params.status = status;
  63227. return formatter(params);
  63228. }
  63229. else if (typeof formatter === 'string') {
  63230. return formatter.replace('{a}', name != null ? name : '');
  63231. }
  63232. },
  63233. setZoom: function (zoom) {
  63234. this.option.zoom = zoom;
  63235. },
  63236. setCenter: function (center) {
  63237. this.option.center = center;
  63238. }
  63239. });
  63240. mixin(GeoModel, selectableMixin);
  63241. /*
  63242. * Licensed to the Apache Software Foundation (ASF) under one
  63243. * or more contributor license agreements. See the NOTICE file
  63244. * distributed with this work for additional information
  63245. * regarding copyright ownership. The ASF licenses this file
  63246. * to you under the Apache License, Version 2.0 (the
  63247. * "License"); you may not use this file except in compliance
  63248. * with the License. You may obtain a copy of the License at
  63249. *
  63250. * http://www.apache.org/licenses/LICENSE-2.0
  63251. *
  63252. * Unless required by applicable law or agreed to in writing,
  63253. * software distributed under the License is distributed on an
  63254. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63255. * KIND, either express or implied. See the License for the
  63256. * specific language governing permissions and limitations
  63257. * under the License.
  63258. */
  63259. extendComponentView({
  63260. type: 'geo',
  63261. init: function (ecModel, api) {
  63262. var mapDraw = new MapDraw(api, true);
  63263. this._mapDraw = mapDraw;
  63264. this.group.add(mapDraw.group);
  63265. },
  63266. render: function (geoModel, ecModel, api, payload) {
  63267. // Not render if it is an toggleSelect action from self
  63268. if (payload && payload.type === 'geoToggleSelect'
  63269. && payload.from === this.uid
  63270. ) {
  63271. return;
  63272. }
  63273. var mapDraw = this._mapDraw;
  63274. if (geoModel.get('show')) {
  63275. mapDraw.draw(geoModel, ecModel, api, this, payload);
  63276. }
  63277. else {
  63278. this._mapDraw.group.removeAll();
  63279. }
  63280. this.group.silent = geoModel.get('silent');
  63281. },
  63282. dispose: function () {
  63283. this._mapDraw && this._mapDraw.remove();
  63284. }
  63285. });
  63286. /*
  63287. * Licensed to the Apache Software Foundation (ASF) under one
  63288. * or more contributor license agreements. See the NOTICE file
  63289. * distributed with this work for additional information
  63290. * regarding copyright ownership. The ASF licenses this file
  63291. * to you under the Apache License, Version 2.0 (the
  63292. * "License"); you may not use this file except in compliance
  63293. * with the License. You may obtain a copy of the License at
  63294. *
  63295. * http://www.apache.org/licenses/LICENSE-2.0
  63296. *
  63297. * Unless required by applicable law or agreed to in writing,
  63298. * software distributed under the License is distributed on an
  63299. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63300. * KIND, either express or implied. See the License for the
  63301. * specific language governing permissions and limitations
  63302. * under the License.
  63303. */
  63304. function makeAction(method, actionInfo) {
  63305. actionInfo.update = 'updateView';
  63306. registerAction(actionInfo, function (payload, ecModel) {
  63307. var selected = {};
  63308. ecModel.eachComponent(
  63309. { mainType: 'geo', query: payload},
  63310. function (geoModel) {
  63311. geoModel[method](payload.name);
  63312. var geo = geoModel.coordinateSystem;
  63313. each$1(geo.regions, function (region) {
  63314. selected[region.name] = geoModel.isSelected(region.name) || false;
  63315. });
  63316. }
  63317. );
  63318. return {
  63319. selected: selected,
  63320. name: payload.name
  63321. };
  63322. });
  63323. }
  63324. makeAction('toggleSelected', {
  63325. type: 'geoToggleSelect',
  63326. event: 'geoselectchanged'
  63327. });
  63328. makeAction('select', {
  63329. type: 'geoSelect',
  63330. event: 'geoselected'
  63331. });
  63332. makeAction('unSelect', {
  63333. type: 'geoUnSelect',
  63334. event: 'geounselected'
  63335. });
  63336. /*
  63337. * Licensed to the Apache Software Foundation (ASF) under one
  63338. * or more contributor license agreements. See the NOTICE file
  63339. * distributed with this work for additional information
  63340. * regarding copyright ownership. The ASF licenses this file
  63341. * to you under the Apache License, Version 2.0 (the
  63342. * "License"); you may not use this file except in compliance
  63343. * with the License. You may obtain a copy of the License at
  63344. *
  63345. * http://www.apache.org/licenses/LICENSE-2.0
  63346. *
  63347. * Unless required by applicable law or agreed to in writing,
  63348. * software distributed under the License is distributed on an
  63349. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63350. * KIND, either express or implied. See the License for the
  63351. * specific language governing permissions and limitations
  63352. * under the License.
  63353. */
  63354. var DEFAULT_TOOLBOX_BTNS = ['rect', 'polygon', 'keep', 'clear'];
  63355. var preprocessor$1 = function (option, isNew) {
  63356. var brushComponents = option && option.brush;
  63357. if (!isArray(brushComponents)) {
  63358. brushComponents = brushComponents ? [brushComponents] : [];
  63359. }
  63360. if (!brushComponents.length) {
  63361. return;
  63362. }
  63363. var brushComponentSpecifiedBtns = [];
  63364. each$1(brushComponents, function (brushOpt) {
  63365. var tbs = brushOpt.hasOwnProperty('toolbox')
  63366. ? brushOpt.toolbox : [];
  63367. if (tbs instanceof Array) {
  63368. brushComponentSpecifiedBtns = brushComponentSpecifiedBtns.concat(tbs);
  63369. }
  63370. });
  63371. var toolbox = option && option.toolbox;
  63372. if (isArray(toolbox)) {
  63373. toolbox = toolbox[0];
  63374. }
  63375. if (!toolbox) {
  63376. toolbox = {feature: {}};
  63377. option.toolbox = [toolbox];
  63378. }
  63379. var toolboxFeature = (toolbox.feature || (toolbox.feature = {}));
  63380. var toolboxBrush = toolboxFeature.brush || (toolboxFeature.brush = {});
  63381. var brushTypes = toolboxBrush.type || (toolboxBrush.type = []);
  63382. brushTypes.push.apply(brushTypes, brushComponentSpecifiedBtns);
  63383. removeDuplicate(brushTypes);
  63384. if (isNew && !brushTypes.length) {
  63385. brushTypes.push.apply(brushTypes, DEFAULT_TOOLBOX_BTNS);
  63386. }
  63387. };
  63388. function removeDuplicate(arr) {
  63389. var map$$1 = {};
  63390. each$1(arr, function (val) {
  63391. map$$1[val] = 1;
  63392. });
  63393. arr.length = 0;
  63394. each$1(map$$1, function (flag, val) {
  63395. arr.push(val);
  63396. });
  63397. }
  63398. /*
  63399. * Licensed to the Apache Software Foundation (ASF) under one
  63400. * or more contributor license agreements. See the NOTICE file
  63401. * distributed with this work for additional information
  63402. * regarding copyright ownership. The ASF licenses this file
  63403. * to you under the Apache License, Version 2.0 (the
  63404. * "License"); you may not use this file except in compliance
  63405. * with the License. You may obtain a copy of the License at
  63406. *
  63407. * http://www.apache.org/licenses/LICENSE-2.0
  63408. *
  63409. * Unless required by applicable law or agreed to in writing,
  63410. * software distributed under the License is distributed on an
  63411. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63412. * KIND, either express or implied. See the License for the
  63413. * specific language governing permissions and limitations
  63414. * under the License.
  63415. */
  63416. /**
  63417. * @file Visual solution, for consistent option specification.
  63418. */
  63419. var each$19 = each$1;
  63420. function hasKeys(obj) {
  63421. if (obj) {
  63422. for (var name in obj){
  63423. if (obj.hasOwnProperty(name)) {
  63424. return true;
  63425. }
  63426. }
  63427. }
  63428. }
  63429. /**
  63430. * @param {Object} option
  63431. * @param {Array.<string>} stateList
  63432. * @param {Function} [supplementVisualOption]
  63433. * @return {Object} visualMappings <state, <visualType, module:echarts/visual/VisualMapping>>
  63434. */
  63435. function createVisualMappings(option, stateList, supplementVisualOption) {
  63436. var visualMappings = {};
  63437. each$19(stateList, function (state) {
  63438. var mappings = visualMappings[state] = createMappings();
  63439. each$19(option[state], function (visualData, visualType) {
  63440. if (!VisualMapping.isValidType(visualType)) {
  63441. return;
  63442. }
  63443. var mappingOption = {
  63444. type: visualType,
  63445. visual: visualData
  63446. };
  63447. supplementVisualOption && supplementVisualOption(mappingOption, state);
  63448. mappings[visualType] = new VisualMapping(mappingOption);
  63449. // Prepare a alpha for opacity, for some case that opacity
  63450. // is not supported, such as rendering using gradient color.
  63451. if (visualType === 'opacity') {
  63452. mappingOption = clone(mappingOption);
  63453. mappingOption.type = 'colorAlpha';
  63454. mappings.__hidden.__alphaForOpacity = new VisualMapping(mappingOption);
  63455. }
  63456. });
  63457. });
  63458. return visualMappings;
  63459. function createMappings() {
  63460. var Creater = function () {};
  63461. // Make sure hidden fields will not be visited by
  63462. // object iteration (with hasOwnProperty checking).
  63463. Creater.prototype.__hidden = Creater.prototype;
  63464. var obj = new Creater();
  63465. return obj;
  63466. }
  63467. }
  63468. /**
  63469. * @param {Object} thisOption
  63470. * @param {Object} newOption
  63471. * @param {Array.<string>} keys
  63472. */
  63473. function replaceVisualOption(thisOption, newOption, keys) {
  63474. // Visual attributes merge is not supported, otherwise it
  63475. // brings overcomplicated merge logic. See #2853. So if
  63476. // newOption has anyone of these keys, all of these keys
  63477. // will be reset. Otherwise, all keys remain.
  63478. var has;
  63479. each$1(keys, function (key) {
  63480. if (newOption.hasOwnProperty(key) && hasKeys(newOption[key])) {
  63481. has = true;
  63482. }
  63483. });
  63484. has && each$1(keys, function (key) {
  63485. if (newOption.hasOwnProperty(key) && hasKeys(newOption[key])) {
  63486. thisOption[key] = clone(newOption[key]);
  63487. }
  63488. else {
  63489. delete thisOption[key];
  63490. }
  63491. });
  63492. }
  63493. /**
  63494. * @param {Array.<string>} stateList
  63495. * @param {Object} visualMappings <state, Object.<visualType, module:echarts/visual/VisualMapping>>
  63496. * @param {module:echarts/data/List} list
  63497. * @param {Function} getValueState param: valueOrIndex, return: state.
  63498. * @param {object} [scope] Scope for getValueState
  63499. * @param {string} [dimension] Concrete dimension, if used.
  63500. */
  63501. // ???! handle brush?
  63502. function applyVisual(stateList, visualMappings, data, getValueState, scope, dimension) {
  63503. var visualTypesMap = {};
  63504. each$1(stateList, function (state) {
  63505. var visualTypes = VisualMapping.prepareVisualTypes(visualMappings[state]);
  63506. visualTypesMap[state] = visualTypes;
  63507. });
  63508. var dataIndex;
  63509. function getVisual(key) {
  63510. return data.getItemVisual(dataIndex, key);
  63511. }
  63512. function setVisual(key, value) {
  63513. data.setItemVisual(dataIndex, key, value);
  63514. }
  63515. if (dimension == null) {
  63516. data.each(eachItem);
  63517. }
  63518. else {
  63519. data.each([dimension], eachItem);
  63520. }
  63521. function eachItem(valueOrIndex, index) {
  63522. dataIndex = dimension == null ? valueOrIndex : index;
  63523. var rawDataItem = data.getRawDataItem(dataIndex);
  63524. // Consider performance
  63525. if (rawDataItem && rawDataItem.visualMap === false) {
  63526. return;
  63527. }
  63528. var valueState = getValueState.call(scope, valueOrIndex);
  63529. var mappings = visualMappings[valueState];
  63530. var visualTypes = visualTypesMap[valueState];
  63531. for (var i = 0, len = visualTypes.length; i < len; i++) {
  63532. var type = visualTypes[i];
  63533. mappings[type] && mappings[type].applyVisual(
  63534. valueOrIndex, getVisual, setVisual
  63535. );
  63536. }
  63537. }
  63538. }
  63539. /**
  63540. * @param {module:echarts/data/List} data
  63541. * @param {Array.<string>} stateList
  63542. * @param {Object} visualMappings <state, Object.<visualType, module:echarts/visual/VisualMapping>>
  63543. * @param {Function} getValueState param: valueOrIndex, return: state.
  63544. * @param {number} [dim] dimension or dimension index.
  63545. */
  63546. function incrementalApplyVisual(stateList, visualMappings, getValueState, dim) {
  63547. var visualTypesMap = {};
  63548. each$1(stateList, function (state) {
  63549. var visualTypes = VisualMapping.prepareVisualTypes(visualMappings[state]);
  63550. visualTypesMap[state] = visualTypes;
  63551. });
  63552. function progress(params, data) {
  63553. if (dim != null) {
  63554. dim = data.getDimension(dim);
  63555. }
  63556. function getVisual(key) {
  63557. return data.getItemVisual(dataIndex, key);
  63558. }
  63559. function setVisual(key, value) {
  63560. data.setItemVisual(dataIndex, key, value);
  63561. }
  63562. var dataIndex;
  63563. while ((dataIndex = params.next()) != null) {
  63564. var rawDataItem = data.getRawDataItem(dataIndex);
  63565. // Consider performance
  63566. if (rawDataItem && rawDataItem.visualMap === false) {
  63567. return;
  63568. }
  63569. var value = dim != null
  63570. ? data.get(dim, dataIndex, true)
  63571. : dataIndex;
  63572. var valueState = getValueState(value);
  63573. var mappings = visualMappings[valueState];
  63574. var visualTypes = visualTypesMap[valueState];
  63575. for (var i = 0, len = visualTypes.length; i < len; i++) {
  63576. var type = visualTypes[i];
  63577. mappings[type] && mappings[type].applyVisual(value, getVisual, setVisual);
  63578. }
  63579. }
  63580. }
  63581. return {progress: progress};
  63582. }
  63583. /*
  63584. * Licensed to the Apache Software Foundation (ASF) under one
  63585. * or more contributor license agreements. See the NOTICE file
  63586. * distributed with this work for additional information
  63587. * regarding copyright ownership. The ASF licenses this file
  63588. * to you under the Apache License, Version 2.0 (the
  63589. * "License"); you may not use this file except in compliance
  63590. * with the License. You may obtain a copy of the License at
  63591. *
  63592. * http://www.apache.org/licenses/LICENSE-2.0
  63593. *
  63594. * Unless required by applicable law or agreed to in writing,
  63595. * software distributed under the License is distributed on an
  63596. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63597. * KIND, either express or implied. See the License for the
  63598. * specific language governing permissions and limitations
  63599. * under the License.
  63600. */
  63601. // Key of the first level is brushType: `line`, `rect`, `polygon`.
  63602. // Key of the second level is chart element type: `point`, `rect`.
  63603. // See moudule:echarts/component/helper/BrushController
  63604. // function param:
  63605. // {Object} itemLayout fetch from data.getItemLayout(dataIndex)
  63606. // {Object} selectors {point: selector, rect: selector, ...}
  63607. // {Object} area {range: [[], [], ..], boudingRect}
  63608. // function return:
  63609. // {boolean} Whether in the given brush.
  63610. var selector = {
  63611. lineX: getLineSelectors(0),
  63612. lineY: getLineSelectors(1),
  63613. rect: {
  63614. point: function (itemLayout, selectors, area) {
  63615. return itemLayout && area.boundingRect.contain(itemLayout[0], itemLayout[1]);
  63616. },
  63617. rect: function (itemLayout, selectors, area) {
  63618. return itemLayout && area.boundingRect.intersect(itemLayout);
  63619. }
  63620. },
  63621. polygon: {
  63622. point: function (itemLayout, selectors, area) {
  63623. return itemLayout
  63624. && area.boundingRect.contain(itemLayout[0], itemLayout[1])
  63625. && contain$1(area.range, itemLayout[0], itemLayout[1]);
  63626. },
  63627. rect: function (itemLayout, selectors, area) {
  63628. var points = area.range;
  63629. if (!itemLayout || points.length <= 1) {
  63630. return false;
  63631. }
  63632. var x = itemLayout.x;
  63633. var y = itemLayout.y;
  63634. var width = itemLayout.width;
  63635. var height = itemLayout.height;
  63636. var p = points[0];
  63637. if (contain$1(points, x, y)
  63638. || contain$1(points, x + width, y)
  63639. || contain$1(points, x, y + height)
  63640. || contain$1(points, x + width, y + height)
  63641. || BoundingRect.create(itemLayout).contain(p[0], p[1])
  63642. || lineIntersectPolygon(x, y, x + width, y, points)
  63643. || lineIntersectPolygon(x, y, x, y + height, points)
  63644. || lineIntersectPolygon(x + width, y, x + width, y + height, points)
  63645. || lineIntersectPolygon(x, y + height, x + width, y + height, points)
  63646. ) {
  63647. return true;
  63648. }
  63649. }
  63650. }
  63651. };
  63652. function getLineSelectors(xyIndex) {
  63653. var xy = ['x', 'y'];
  63654. var wh = ['width', 'height'];
  63655. return {
  63656. point: function (itemLayout, selectors, area) {
  63657. if (itemLayout) {
  63658. var range = area.range;
  63659. var p = itemLayout[xyIndex];
  63660. return inLineRange(p, range);
  63661. }
  63662. },
  63663. rect: function (itemLayout, selectors, area) {
  63664. if (itemLayout) {
  63665. var range = area.range;
  63666. var layoutRange = [
  63667. itemLayout[xy[xyIndex]],
  63668. itemLayout[xy[xyIndex]] + itemLayout[wh[xyIndex]]
  63669. ];
  63670. layoutRange[1] < layoutRange[0] && layoutRange.reverse();
  63671. return inLineRange(layoutRange[0], range)
  63672. || inLineRange(layoutRange[1], range)
  63673. || inLineRange(range[0], layoutRange)
  63674. || inLineRange(range[1], layoutRange);
  63675. }
  63676. }
  63677. };
  63678. }
  63679. function inLineRange(p, range) {
  63680. return range[0] <= p && p <= range[1];
  63681. }
  63682. function lineIntersectPolygon(lx, ly, l2x, l2y, points) {
  63683. for (var i = 0, p2 = points[points.length - 1]; i < points.length; i++) {
  63684. var p = points[i];
  63685. if (lineIntersect(lx, ly, l2x, l2y, p[0], p[1], p2[0], p2[1])) {
  63686. return true;
  63687. }
  63688. p2 = p;
  63689. }
  63690. }
  63691. // Code from <http://blog.csdn.net/rickliuxiao/article/details/6259322> with some fix.
  63692. // See <https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection>
  63693. function lineIntersect(a1x, a1y, a2x, a2y, b1x, b1y, b2x, b2y) {
  63694. var delta = determinant(a2x - a1x, b1x - b2x, a2y - a1y, b1y - b2y);
  63695. if (nearZero(delta)) { // parallel
  63696. return false;
  63697. }
  63698. var namenda = determinant(b1x - a1x, b1x - b2x, b1y - a1y, b1y - b2y) / delta;
  63699. if (namenda < 0 || namenda > 1) {
  63700. return false;
  63701. }
  63702. var miu = determinant(a2x - a1x, b1x - a1x, a2y - a1y, b1y - a1y) / delta;
  63703. if (miu < 0 || miu > 1) {
  63704. return false;
  63705. }
  63706. return true;
  63707. }
  63708. function nearZero(val) {
  63709. return val <= (1e-6) && val >= -(1e-6);
  63710. }
  63711. function determinant(v1, v2, v3, v4) {
  63712. return v1 * v4 - v2 * v3;
  63713. }
  63714. /*
  63715. * Licensed to the Apache Software Foundation (ASF) under one
  63716. * or more contributor license agreements. See the NOTICE file
  63717. * distributed with this work for additional information
  63718. * regarding copyright ownership. The ASF licenses this file
  63719. * to you under the Apache License, Version 2.0 (the
  63720. * "License"); you may not use this file except in compliance
  63721. * with the License. You may obtain a copy of the License at
  63722. *
  63723. * http://www.apache.org/licenses/LICENSE-2.0
  63724. *
  63725. * Unless required by applicable law or agreed to in writing,
  63726. * software distributed under the License is distributed on an
  63727. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63728. * KIND, either express or implied. See the License for the
  63729. * specific language governing permissions and limitations
  63730. * under the License.
  63731. */
  63732. var each$20 = each$1;
  63733. var indexOf$1 = indexOf;
  63734. var curry$5 = curry;
  63735. var COORD_CONVERTS = ['dataToPoint', 'pointToData'];
  63736. // FIXME
  63737. // how to genarialize to more coordinate systems.
  63738. var INCLUDE_FINDER_MAIN_TYPES = [
  63739. 'grid', 'xAxis', 'yAxis', 'geo', 'graph',
  63740. 'polar', 'radiusAxis', 'angleAxis', 'bmap'
  63741. ];
  63742. /**
  63743. * [option in constructor]:
  63744. * {
  63745. * Index/Id/Name of geo, xAxis, yAxis, grid: See util/model#parseFinder.
  63746. * }
  63747. *
  63748. *
  63749. * [targetInfo]:
  63750. *
  63751. * There can be multiple axes in a single targetInfo. Consider the case
  63752. * of `grid` component, a targetInfo represents a grid which contains one or more
  63753. * cartesian and one or more axes. And consider the case of parallel system,
  63754. * which has multiple axes in a coordinate system.
  63755. * Can be {
  63756. * panelId: ...,
  63757. * coordSys: <a representitive cartesian in grid (first cartesian by default)>,
  63758. * coordSyses: all cartesians.
  63759. * gridModel: <grid component>
  63760. * xAxes: correspond to coordSyses on index
  63761. * yAxes: correspond to coordSyses on index
  63762. * }
  63763. * or {
  63764. * panelId: ...,
  63765. * coordSys: <geo coord sys>
  63766. * coordSyses: [<geo coord sys>]
  63767. * geoModel: <geo component>
  63768. * }
  63769. *
  63770. *
  63771. * [panelOpt]:
  63772. *
  63773. * Make from targetInfo. Input to BrushController.
  63774. * {
  63775. * panelId: ...,
  63776. * rect: ...
  63777. * }
  63778. *
  63779. *
  63780. * [area]:
  63781. *
  63782. * Generated by BrushController or user input.
  63783. * {
  63784. * panelId: Used to locate coordInfo directly. If user inpput, no panelId.
  63785. * brushType: determine how to convert to/from coord('rect' or 'polygon' or 'lineX/Y').
  63786. * Index/Id/Name of geo, xAxis, yAxis, grid: See util/model#parseFinder.
  63787. * range: pixel range.
  63788. * coordRange: representitive coord range (the first one of coordRanges).
  63789. * coordRanges: <Array> coord ranges, used in multiple cartesian in one grid.
  63790. * }
  63791. */
  63792. /**
  63793. * @param {Object} option contains Index/Id/Name of xAxis/yAxis/geo/grid
  63794. * Each can be {number|Array.<number>}. like: {xAxisIndex: [3, 4]}
  63795. * @param {module:echarts/model/Global} ecModel
  63796. * @param {Object} [opt]
  63797. * @param {Array.<string>} [opt.include] include coordinate system types.
  63798. */
  63799. function BrushTargetManager(option, ecModel, opt) {
  63800. /**
  63801. * @private
  63802. * @type {Array.<Object>}
  63803. */
  63804. var targetInfoList = this._targetInfoList = [];
  63805. var info = {};
  63806. var foundCpts = parseFinder$1(ecModel, option);
  63807. each$20(targetInfoBuilders, function (builder, type) {
  63808. if (!opt || !opt.include || indexOf$1(opt.include, type) >= 0) {
  63809. builder(foundCpts, targetInfoList, info);
  63810. }
  63811. });
  63812. }
  63813. var proto$2 = BrushTargetManager.prototype;
  63814. proto$2.setOutputRanges = function (areas, ecModel) {
  63815. this.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  63816. (area.coordRanges || (area.coordRanges = [])).push(coordRange);
  63817. // area.coordRange is the first of area.coordRanges
  63818. if (!area.coordRange) {
  63819. area.coordRange = coordRange;
  63820. // In 'category' axis, coord to pixel is not reversible, so we can not
  63821. // rebuild range by coordRange accrately, which may bring trouble when
  63822. // brushing only one item. So we use __rangeOffset to rebuilding range
  63823. // by coordRange. And this it only used in brush component so it is no
  63824. // need to be adapted to coordRanges.
  63825. var result = coordConvert[area.brushType](0, coordSys, coordRange);
  63826. area.__rangeOffset = {
  63827. offset: diffProcessor[area.brushType](result.values, area.range, [1, 1]),
  63828. xyMinMax: result.xyMinMax
  63829. };
  63830. }
  63831. });
  63832. };
  63833. proto$2.matchOutputRanges = function (areas, ecModel, cb) {
  63834. each$20(areas, function (area) {
  63835. var targetInfo = this.findTargetInfo(area, ecModel);
  63836. if (targetInfo && targetInfo !== true) {
  63837. each$1(
  63838. targetInfo.coordSyses,
  63839. function (coordSys) {
  63840. var result = coordConvert[area.brushType](1, coordSys, area.range);
  63841. cb(area, result.values, coordSys, ecModel);
  63842. }
  63843. );
  63844. }
  63845. }, this);
  63846. };
  63847. proto$2.setInputRanges = function (areas, ecModel) {
  63848. each$20(areas, function (area) {
  63849. var targetInfo = this.findTargetInfo(area, ecModel);
  63850. if (__DEV__) {
  63851. assert$1(
  63852. !targetInfo || targetInfo === true || area.coordRange,
  63853. 'coordRange must be specified when coord index specified.'
  63854. );
  63855. assert$1(
  63856. !targetInfo || targetInfo !== true || area.range,
  63857. 'range must be specified in global brush.'
  63858. );
  63859. }
  63860. area.range = area.range || [];
  63861. // convert coordRange to global range and set panelId.
  63862. if (targetInfo && targetInfo !== true) {
  63863. area.panelId = targetInfo.panelId;
  63864. // (1) area.range shoule always be calculate from coordRange but does
  63865. // not keep its original value, for the sake of the dataZoom scenario,
  63866. // where area.coordRange remains unchanged but area.range may be changed.
  63867. // (2) Only support converting one coordRange to pixel range in brush
  63868. // component. So do not consider `coordRanges`.
  63869. // (3) About __rangeOffset, see comment above.
  63870. var result = coordConvert[area.brushType](0, targetInfo.coordSys, area.coordRange);
  63871. var rangeOffset = area.__rangeOffset;
  63872. area.range = rangeOffset
  63873. ? diffProcessor[area.brushType](
  63874. result.values,
  63875. rangeOffset.offset,
  63876. getScales(result.xyMinMax, rangeOffset.xyMinMax)
  63877. )
  63878. : result.values;
  63879. }
  63880. }, this);
  63881. };
  63882. proto$2.makePanelOpts = function (api, getDefaultBrushType) {
  63883. return map(this._targetInfoList, function (targetInfo) {
  63884. var rect = targetInfo.getPanelRect();
  63885. return {
  63886. panelId: targetInfo.panelId,
  63887. defaultBrushType: getDefaultBrushType && getDefaultBrushType(targetInfo),
  63888. clipPath: makeRectPanelClipPath(rect),
  63889. isTargetByCursor: makeRectIsTargetByCursor(
  63890. rect, api, targetInfo.coordSysModel
  63891. ),
  63892. getLinearBrushOtherExtent: makeLinearBrushOtherExtent(rect)
  63893. };
  63894. });
  63895. };
  63896. proto$2.controlSeries = function (area, seriesModel, ecModel) {
  63897. // Check whether area is bound in coord, and series do not belong to that coord.
  63898. // If do not do this check, some brush (like lineX) will controll all axes.
  63899. var targetInfo = this.findTargetInfo(area, ecModel);
  63900. return targetInfo === true || (
  63901. targetInfo && indexOf$1(targetInfo.coordSyses, seriesModel.coordinateSystem) >= 0
  63902. );
  63903. };
  63904. /**
  63905. * If return Object, a coord found.
  63906. * If reutrn true, global found.
  63907. * Otherwise nothing found.
  63908. *
  63909. * @param {Object} area
  63910. * @param {Array} targetInfoList
  63911. * @return {Object|boolean}
  63912. */
  63913. proto$2.findTargetInfo = function (area, ecModel) {
  63914. var targetInfoList = this._targetInfoList;
  63915. var foundCpts = parseFinder$1(ecModel, area);
  63916. for (var i = 0; i < targetInfoList.length; i++) {
  63917. var targetInfo = targetInfoList[i];
  63918. var areaPanelId = area.panelId;
  63919. if (areaPanelId) {
  63920. if (targetInfo.panelId === areaPanelId) {
  63921. return targetInfo;
  63922. }
  63923. }
  63924. else {
  63925. for (var i = 0; i < targetInfoMatchers.length; i++) {
  63926. if (targetInfoMatchers[i](foundCpts, targetInfo)) {
  63927. return targetInfo;
  63928. }
  63929. }
  63930. }
  63931. }
  63932. return true;
  63933. };
  63934. function formatMinMax(minMax) {
  63935. minMax[0] > minMax[1] && minMax.reverse();
  63936. return minMax;
  63937. }
  63938. function parseFinder$1(ecModel, option) {
  63939. return parseFinder(
  63940. ecModel, option, {includeMainTypes: INCLUDE_FINDER_MAIN_TYPES}
  63941. );
  63942. }
  63943. var targetInfoBuilders = {
  63944. grid: function (foundCpts, targetInfoList) {
  63945. var xAxisModels = foundCpts.xAxisModels;
  63946. var yAxisModels = foundCpts.yAxisModels;
  63947. var gridModels = foundCpts.gridModels;
  63948. // Remove duplicated.
  63949. var gridModelMap = createHashMap();
  63950. var xAxesHas = {};
  63951. var yAxesHas = {};
  63952. if (!xAxisModels && !yAxisModels && !gridModels) {
  63953. return;
  63954. }
  63955. each$20(xAxisModels, function (axisModel) {
  63956. var gridModel = axisModel.axis.grid.model;
  63957. gridModelMap.set(gridModel.id, gridModel);
  63958. xAxesHas[gridModel.id] = true;
  63959. });
  63960. each$20(yAxisModels, function (axisModel) {
  63961. var gridModel = axisModel.axis.grid.model;
  63962. gridModelMap.set(gridModel.id, gridModel);
  63963. yAxesHas[gridModel.id] = true;
  63964. });
  63965. each$20(gridModels, function (gridModel) {
  63966. gridModelMap.set(gridModel.id, gridModel);
  63967. xAxesHas[gridModel.id] = true;
  63968. yAxesHas[gridModel.id] = true;
  63969. });
  63970. gridModelMap.each(function (gridModel) {
  63971. var grid = gridModel.coordinateSystem;
  63972. var cartesians = [];
  63973. each$20(grid.getCartesians(), function (cartesian, index) {
  63974. if (indexOf$1(xAxisModels, cartesian.getAxis('x').model) >= 0
  63975. || indexOf$1(yAxisModels, cartesian.getAxis('y').model) >= 0
  63976. ) {
  63977. cartesians.push(cartesian);
  63978. }
  63979. });
  63980. targetInfoList.push({
  63981. panelId: 'grid--' + gridModel.id,
  63982. gridModel: gridModel,
  63983. coordSysModel: gridModel,
  63984. // Use the first one as the representitive coordSys.
  63985. coordSys: cartesians[0],
  63986. coordSyses: cartesians,
  63987. getPanelRect: panelRectBuilder.grid,
  63988. xAxisDeclared: xAxesHas[gridModel.id],
  63989. yAxisDeclared: yAxesHas[gridModel.id]
  63990. });
  63991. });
  63992. },
  63993. geo: function (foundCpts, targetInfoList) {
  63994. each$20(foundCpts.geoModels, function (geoModel) {
  63995. var coordSys = geoModel.coordinateSystem;
  63996. targetInfoList.push({
  63997. panelId: 'geo--' + geoModel.id,
  63998. geoModel: geoModel,
  63999. coordSysModel: geoModel,
  64000. coordSys: coordSys,
  64001. coordSyses: [coordSys],
  64002. getPanelRect: panelRectBuilder.geo
  64003. });
  64004. });
  64005. }
  64006. };
  64007. var targetInfoMatchers = [
  64008. // grid
  64009. function (foundCpts, targetInfo) {
  64010. var xAxisModel = foundCpts.xAxisModel;
  64011. var yAxisModel = foundCpts.yAxisModel;
  64012. var gridModel = foundCpts.gridModel;
  64013. !gridModel && xAxisModel && (gridModel = xAxisModel.axis.grid.model);
  64014. !gridModel && yAxisModel && (gridModel = yAxisModel.axis.grid.model);
  64015. return gridModel && gridModel === targetInfo.gridModel;
  64016. },
  64017. // geo
  64018. function (foundCpts, targetInfo) {
  64019. var geoModel = foundCpts.geoModel;
  64020. return geoModel && geoModel === targetInfo.geoModel;
  64021. }
  64022. ];
  64023. var panelRectBuilder = {
  64024. grid: function () {
  64025. // grid is not Transformable.
  64026. return this.coordSys.grid.getRect().clone();
  64027. },
  64028. geo: function () {
  64029. var coordSys = this.coordSys;
  64030. var rect = coordSys.getBoundingRect().clone();
  64031. // geo roam and zoom transform
  64032. rect.applyTransform(getTransform(coordSys));
  64033. return rect;
  64034. }
  64035. };
  64036. var coordConvert = {
  64037. lineX: curry$5(axisConvert, 0),
  64038. lineY: curry$5(axisConvert, 1),
  64039. rect: function (to, coordSys, rangeOrCoordRange) {
  64040. var xminymin = coordSys[COORD_CONVERTS[to]]([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]]);
  64041. var xmaxymax = coordSys[COORD_CONVERTS[to]]([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]]);
  64042. var values = [
  64043. formatMinMax([xminymin[0], xmaxymax[0]]),
  64044. formatMinMax([xminymin[1], xmaxymax[1]])
  64045. ];
  64046. return {values: values, xyMinMax: values};
  64047. },
  64048. polygon: function (to, coordSys, rangeOrCoordRange) {
  64049. var xyMinMax = [[Infinity, -Infinity], [Infinity, -Infinity]];
  64050. var values = map(rangeOrCoordRange, function (item) {
  64051. var p = coordSys[COORD_CONVERTS[to]](item);
  64052. xyMinMax[0][0] = Math.min(xyMinMax[0][0], p[0]);
  64053. xyMinMax[1][0] = Math.min(xyMinMax[1][0], p[1]);
  64054. xyMinMax[0][1] = Math.max(xyMinMax[0][1], p[0]);
  64055. xyMinMax[1][1] = Math.max(xyMinMax[1][1], p[1]);
  64056. return p;
  64057. });
  64058. return {values: values, xyMinMax: xyMinMax};
  64059. }
  64060. };
  64061. function axisConvert(axisNameIndex, to, coordSys, rangeOrCoordRange) {
  64062. if (__DEV__) {
  64063. assert$1(
  64064. coordSys.type === 'cartesian2d',
  64065. 'lineX/lineY brush is available only in cartesian2d.'
  64066. );
  64067. }
  64068. var axis = coordSys.getAxis(['x', 'y'][axisNameIndex]);
  64069. var values = formatMinMax(map([0, 1], function (i) {
  64070. return to
  64071. ? axis.coordToData(axis.toLocalCoord(rangeOrCoordRange[i]))
  64072. : axis.toGlobalCoord(axis.dataToCoord(rangeOrCoordRange[i]));
  64073. }));
  64074. var xyMinMax = [];
  64075. xyMinMax[axisNameIndex] = values;
  64076. xyMinMax[1 - axisNameIndex] = [NaN, NaN];
  64077. return {values: values, xyMinMax: xyMinMax};
  64078. }
  64079. var diffProcessor = {
  64080. lineX: curry$5(axisDiffProcessor, 0),
  64081. lineY: curry$5(axisDiffProcessor, 1),
  64082. rect: function (values, refer, scales) {
  64083. return [
  64084. [values[0][0] - scales[0] * refer[0][0], values[0][1] - scales[0] * refer[0][1]],
  64085. [values[1][0] - scales[1] * refer[1][0], values[1][1] - scales[1] * refer[1][1]]
  64086. ];
  64087. },
  64088. polygon: function (values, refer, scales) {
  64089. return map(values, function (item, idx) {
  64090. return [item[0] - scales[0] * refer[idx][0], item[1] - scales[1] * refer[idx][1]];
  64091. });
  64092. }
  64093. };
  64094. function axisDiffProcessor(axisNameIndex, values, refer, scales) {
  64095. return [
  64096. values[0] - scales[axisNameIndex] * refer[0],
  64097. values[1] - scales[axisNameIndex] * refer[1]
  64098. ];
  64099. }
  64100. // We have to process scale caused by dataZoom manually,
  64101. // although it might be not accurate.
  64102. function getScales(xyMinMaxCurr, xyMinMaxOrigin) {
  64103. var sizeCurr = getSize(xyMinMaxCurr);
  64104. var sizeOrigin = getSize(xyMinMaxOrigin);
  64105. var scales = [sizeCurr[0] / sizeOrigin[0], sizeCurr[1] / sizeOrigin[1]];
  64106. isNaN(scales[0]) && (scales[0] = 1);
  64107. isNaN(scales[1]) && (scales[1] = 1);
  64108. return scales;
  64109. }
  64110. function getSize(xyMinMax) {
  64111. return xyMinMax
  64112. ? [xyMinMax[0][1] - xyMinMax[0][0], xyMinMax[1][1] - xyMinMax[1][0]]
  64113. : [NaN, NaN];
  64114. }
  64115. /*
  64116. * Licensed to the Apache Software Foundation (ASF) under one
  64117. * or more contributor license agreements. See the NOTICE file
  64118. * distributed with this work for additional information
  64119. * regarding copyright ownership. The ASF licenses this file
  64120. * to you under the Apache License, Version 2.0 (the
  64121. * "License"); you may not use this file except in compliance
  64122. * with the License. You may obtain a copy of the License at
  64123. *
  64124. * http://www.apache.org/licenses/LICENSE-2.0
  64125. *
  64126. * Unless required by applicable law or agreed to in writing,
  64127. * software distributed under the License is distributed on an
  64128. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  64129. * KIND, either express or implied. See the License for the
  64130. * specific language governing permissions and limitations
  64131. * under the License.
  64132. */
  64133. var STATE_LIST = ['inBrush', 'outOfBrush'];
  64134. var DISPATCH_METHOD = '__ecBrushSelect';
  64135. var DISPATCH_FLAG = '__ecInBrushSelectEvent';
  64136. var PRIORITY_BRUSH = PRIORITY.VISUAL.BRUSH;
  64137. /**
  64138. * Layout for visual, the priority higher than other layout, and before brush visual.
  64139. */
  64140. registerLayout(PRIORITY_BRUSH, function (ecModel, api, payload) {
  64141. ecModel.eachComponent({mainType: 'brush'}, function (brushModel) {
  64142. payload && payload.type === 'takeGlobalCursor' && brushModel.setBrushOption(
  64143. payload.key === 'brush' ? payload.brushOption : {brushType: false}
  64144. );
  64145. var brushTargetManager = brushModel.brushTargetManager = new BrushTargetManager(brushModel.option, ecModel);
  64146. brushTargetManager.setInputRanges(brushModel.areas, ecModel);
  64147. });
  64148. });
  64149. /**
  64150. * Register the visual encoding if this modules required.
  64151. */
  64152. registerVisual(PRIORITY_BRUSH, function (ecModel, api, payload) {
  64153. var brushSelected = [];
  64154. var throttleType;
  64155. var throttleDelay;
  64156. ecModel.eachComponent({mainType: 'brush'}, function (brushModel, brushIndex) {
  64157. var thisBrushSelected = {
  64158. brushId: brushModel.id,
  64159. brushIndex: brushIndex,
  64160. brushName: brushModel.name,
  64161. areas: clone(brushModel.areas),
  64162. selected: []
  64163. };
  64164. // Every brush component exists in event params, convenient
  64165. // for user to find by index.
  64166. brushSelected.push(thisBrushSelected);
  64167. var brushOption = brushModel.option;
  64168. var brushLink = brushOption.brushLink;
  64169. var linkedSeriesMap = [];
  64170. var selectedDataIndexForLink = [];
  64171. var rangeInfoBySeries = [];
  64172. var hasBrushExists = 0;
  64173. if (!brushIndex) { // Only the first throttle setting works.
  64174. throttleType = brushOption.throttleType;
  64175. throttleDelay = brushOption.throttleDelay;
  64176. }
  64177. // Add boundingRect and selectors to range.
  64178. var areas = map(brushModel.areas, function (area) {
  64179. return bindSelector(
  64180. defaults(
  64181. {boundingRect: boundingRectBuilders[area.brushType](area)},
  64182. area
  64183. )
  64184. );
  64185. });
  64186. var visualMappings = createVisualMappings(
  64187. brushModel.option, STATE_LIST, function (mappingOption) {
  64188. mappingOption.mappingMethod = 'fixed';
  64189. }
  64190. );
  64191. isArray(brushLink) && each$1(brushLink, function (seriesIndex) {
  64192. linkedSeriesMap[seriesIndex] = 1;
  64193. });
  64194. function linkOthers(seriesIndex) {
  64195. return brushLink === 'all' || linkedSeriesMap[seriesIndex];
  64196. }
  64197. // If no supported brush or no brush on the series,
  64198. // all visuals should be in original state.
  64199. function brushed(rangeInfoList) {
  64200. return !!rangeInfoList.length;
  64201. }
  64202. /**
  64203. * Logic for each series: (If the logic has to be modified one day, do it carefully!)
  64204. *
  64205. * ( brushed ┬ && ┬hasBrushExist ┬ && linkOthers ) => StepA: ┬record, ┬ StepB: ┬visualByRecord.
  64206. * !brushed┘ ├hasBrushExist ┤ └nothing,┘ ├visualByRecord.
  64207. * └!hasBrushExist┘ └nothing.
  64208. * ( !brushed && ┬hasBrushExist ┬ && linkOthers ) => StepA: nothing, StepB: ┬visualByRecord.
  64209. * └!hasBrushExist┘ └nothing.
  64210. * ( brushed ┬ && !linkOthers ) => StepA: nothing, StepB: ┬visualByCheck.
  64211. * !brushed┘ └nothing.
  64212. * ( !brushed && !linkOthers ) => StepA: nothing, StepB: nothing.
  64213. */
  64214. // Step A
  64215. ecModel.eachSeries(function (seriesModel, seriesIndex) {
  64216. var rangeInfoList = rangeInfoBySeries[seriesIndex] = [];
  64217. seriesModel.subType === 'parallel'
  64218. ? stepAParallel(seriesModel, seriesIndex, rangeInfoList)
  64219. : stepAOthers(seriesModel, seriesIndex, rangeInfoList);
  64220. });
  64221. function stepAParallel(seriesModel, seriesIndex) {
  64222. var coordSys = seriesModel.coordinateSystem;
  64223. hasBrushExists |= coordSys.hasAxisBrushed();
  64224. linkOthers(seriesIndex) && coordSys.eachActiveState(
  64225. seriesModel.getData(),
  64226. function (activeState, dataIndex) {
  64227. activeState === 'active' && (selectedDataIndexForLink[dataIndex] = 1);
  64228. }
  64229. );
  64230. }
  64231. function stepAOthers(seriesModel, seriesIndex, rangeInfoList) {
  64232. var selectorsByBrushType = getSelectorsByBrushType(seriesModel);
  64233. if (!selectorsByBrushType || brushModelNotControll(brushModel, seriesIndex)) {
  64234. return;
  64235. }
  64236. each$1(areas, function (area) {
  64237. selectorsByBrushType[area.brushType]
  64238. && brushModel.brushTargetManager.controlSeries(area, seriesModel, ecModel)
  64239. && rangeInfoList.push(area);
  64240. hasBrushExists |= brushed(rangeInfoList);
  64241. });
  64242. if (linkOthers(seriesIndex) && brushed(rangeInfoList)) {
  64243. var data = seriesModel.getData();
  64244. data.each(function (dataIndex) {
  64245. if (checkInRange(selectorsByBrushType, rangeInfoList, data, dataIndex)) {
  64246. selectedDataIndexForLink[dataIndex] = 1;
  64247. }
  64248. });
  64249. }
  64250. }
  64251. // Step B
  64252. ecModel.eachSeries(function (seriesModel, seriesIndex) {
  64253. var seriesBrushSelected = {
  64254. seriesId: seriesModel.id,
  64255. seriesIndex: seriesIndex,
  64256. seriesName: seriesModel.name,
  64257. dataIndex: []
  64258. };
  64259. // Every series exists in event params, convenient
  64260. // for user to find series by seriesIndex.
  64261. thisBrushSelected.selected.push(seriesBrushSelected);
  64262. var selectorsByBrushType = getSelectorsByBrushType(seriesModel);
  64263. var rangeInfoList = rangeInfoBySeries[seriesIndex];
  64264. var data = seriesModel.getData();
  64265. var getValueState = linkOthers(seriesIndex)
  64266. ? function (dataIndex) {
  64267. return selectedDataIndexForLink[dataIndex]
  64268. ? (seriesBrushSelected.dataIndex.push(data.getRawIndex(dataIndex)), 'inBrush')
  64269. : 'outOfBrush';
  64270. }
  64271. : function (dataIndex) {
  64272. return checkInRange(selectorsByBrushType, rangeInfoList, data, dataIndex)
  64273. ? (seriesBrushSelected.dataIndex.push(data.getRawIndex(dataIndex)), 'inBrush')
  64274. : 'outOfBrush';
  64275. };
  64276. // If no supported brush or no brush, all visuals are in original state.
  64277. (linkOthers(seriesIndex) ? hasBrushExists : brushed(rangeInfoList))
  64278. && applyVisual(
  64279. STATE_LIST, visualMappings, data, getValueState
  64280. );
  64281. });
  64282. });
  64283. dispatchAction(api, throttleType, throttleDelay, brushSelected, payload);
  64284. });
  64285. function dispatchAction(api, throttleType, throttleDelay, brushSelected, payload) {
  64286. // This event will not be triggered when `setOpion`, otherwise dead lock may
  64287. // triggered when do `setOption` in event listener, which we do not find
  64288. // satisfactory way to solve yet. Some considered resolutions:
  64289. // (a) Diff with prevoius selected data ant only trigger event when changed.
  64290. // But store previous data and diff precisely (i.e., not only by dataIndex, but
  64291. // also detect value changes in selected data) might bring complexity or fragility.
  64292. // (b) Use spectial param like `silent` to suppress event triggering.
  64293. // But such kind of volatile param may be weird in `setOption`.
  64294. if (!payload) {
  64295. return;
  64296. }
  64297. var zr = api.getZr();
  64298. if (zr[DISPATCH_FLAG]) {
  64299. return;
  64300. }
  64301. if (!zr[DISPATCH_METHOD]) {
  64302. zr[DISPATCH_METHOD] = doDispatch;
  64303. }
  64304. var fn = createOrUpdate(zr, DISPATCH_METHOD, throttleDelay, throttleType);
  64305. fn(api, brushSelected);
  64306. }
  64307. function doDispatch(api, brushSelected) {
  64308. if (!api.isDisposed()) {
  64309. var zr = api.getZr();
  64310. zr[DISPATCH_FLAG] = true;
  64311. api.dispatchAction({
  64312. type: 'brushSelect',
  64313. batch: brushSelected
  64314. });
  64315. zr[DISPATCH_FLAG] = false;
  64316. }
  64317. }
  64318. function checkInRange(selectorsByBrushType, rangeInfoList, data, dataIndex) {
  64319. for (var i = 0, len = rangeInfoList.length; i < len; i++) {
  64320. var area = rangeInfoList[i];
  64321. if (selectorsByBrushType[area.brushType](
  64322. dataIndex, data, area.selectors, area
  64323. )) {
  64324. return true;
  64325. }
  64326. }
  64327. }
  64328. function getSelectorsByBrushType(seriesModel) {
  64329. var brushSelector = seriesModel.brushSelector;
  64330. if (isString(brushSelector)) {
  64331. var sels = [];
  64332. each$1(selector, function (selectorsByElementType, brushType) {
  64333. sels[brushType] = function (dataIndex, data, selectors, area) {
  64334. var itemLayout = data.getItemLayout(dataIndex);
  64335. return selectorsByElementType[brushSelector](itemLayout, selectors, area);
  64336. };
  64337. });
  64338. return sels;
  64339. }
  64340. else if (isFunction$1(brushSelector)) {
  64341. var bSelector = {};
  64342. each$1(selector, function (sel, brushType) {
  64343. bSelector[brushType] = brushSelector;
  64344. });
  64345. return bSelector;
  64346. }
  64347. return brushSelector;
  64348. }
  64349. function brushModelNotControll(brushModel, seriesIndex) {
  64350. var seriesIndices = brushModel.option.seriesIndex;
  64351. return seriesIndices != null
  64352. && seriesIndices !== 'all'
  64353. && (
  64354. isArray(seriesIndices)
  64355. ? indexOf(seriesIndices, seriesIndex) < 0
  64356. : seriesIndex !== seriesIndices
  64357. );
  64358. }
  64359. function bindSelector(area) {
  64360. var selectors = area.selectors = {};
  64361. each$1(selector[area.brushType], function (selFn, elType) {
  64362. // Do not use function binding or curry for performance.
  64363. selectors[elType] = function (itemLayout) {
  64364. return selFn(itemLayout, selectors, area);
  64365. };
  64366. });
  64367. return area;
  64368. }
  64369. var boundingRectBuilders = {
  64370. lineX: noop,
  64371. lineY: noop,
  64372. rect: function (area) {
  64373. return getBoundingRectFromMinMax(area.range);
  64374. },
  64375. polygon: function (area) {
  64376. var minMax;
  64377. var range = area.range;
  64378. for (var i = 0, len = range.length; i < len; i++) {
  64379. minMax = minMax || [[Infinity, -Infinity], [Infinity, -Infinity]];
  64380. var rg = range[i];
  64381. rg[0] < minMax[0][0] && (minMax[0][0] = rg[0]);
  64382. rg[0] > minMax[0][1] && (minMax[0][1] = rg[0]);
  64383. rg[1] < minMax[1][0] && (minMax[1][0] = rg[1]);
  64384. rg[1] > minMax[1][1] && (minMax[1][1] = rg[1]);
  64385. }
  64386. return minMax && getBoundingRectFromMinMax(minMax);
  64387. }
  64388. };
  64389. function getBoundingRectFromMinMax(minMax) {
  64390. return new BoundingRect(
  64391. minMax[0][0],
  64392. minMax[1][0],
  64393. minMax[0][1] - minMax[0][0],
  64394. minMax[1][1] - minMax[1][0]
  64395. );
  64396. }
  64397. /*
  64398. * Licensed to the Apache Software Foundation (ASF) under one
  64399. * or more contributor license agreements. See the NOTICE file
  64400. * distributed with this work for additional information
  64401. * regarding copyright ownership. The ASF licenses this file
  64402. * to you under the Apache License, Version 2.0 (the
  64403. * "License"); you may not use this file except in compliance
  64404. * with the License. You may obtain a copy of the License at
  64405. *
  64406. * http://www.apache.org/licenses/LICENSE-2.0
  64407. *
  64408. * Unless required by applicable law or agreed to in writing,
  64409. * software distributed under the License is distributed on an
  64410. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  64411. * KIND, either express or implied. See the License for the
  64412. * specific language governing permissions and limitations
  64413. * under the License.
  64414. */
  64415. var DEFAULT_OUT_OF_BRUSH_COLOR = ['#ddd'];
  64416. var BrushModel = extendComponentModel({
  64417. type: 'brush',
  64418. dependencies: ['geo', 'grid', 'xAxis', 'yAxis', 'parallel', 'series'],
  64419. /**
  64420. * @protected
  64421. */
  64422. defaultOption: {
  64423. // inBrush: null,
  64424. // outOfBrush: null,
  64425. toolbox: null, // Default value see preprocessor.
  64426. brushLink: null, // Series indices array, broadcast using dataIndex.
  64427. // or 'all', which means all series. 'none' or null means no series.
  64428. seriesIndex: 'all', // seriesIndex array, specify series controlled by this brush component.
  64429. geoIndex: null, //
  64430. xAxisIndex: null,
  64431. yAxisIndex: null,
  64432. brushType: 'rect', // Default brushType, see BrushController.
  64433. brushMode: 'single', // Default brushMode, 'single' or 'multiple'
  64434. transformable: true, // Default transformable.
  64435. brushStyle: { // Default brushStyle
  64436. borderWidth: 1,
  64437. color: 'rgba(120,140,180,0.3)',
  64438. borderColor: 'rgba(120,140,180,0.8)'
  64439. },
  64440. throttleType: 'fixRate',// Throttle in brushSelected event. 'fixRate' or 'debounce'.
  64441. // If null, no throttle. Valid only in the first brush component
  64442. throttleDelay: 0, // Unit: ms, 0 means every event will be triggered.
  64443. // FIXME
  64444. // 试验效果
  64445. removeOnClick: true,
  64446. z: 10000
  64447. },
  64448. /**
  64449. * @readOnly
  64450. * @type {Array.<Object>}
  64451. */
  64452. areas: [],
  64453. /**
  64454. * Current activated brush type.
  64455. * If null, brush is inactived.
  64456. * see module:echarts/component/helper/BrushController
  64457. * @readOnly
  64458. * @type {string}
  64459. */
  64460. brushType: null,
  64461. /**
  64462. * Current brush opt.
  64463. * see module:echarts/component/helper/BrushController
  64464. * @readOnly
  64465. * @type {Object}
  64466. */
  64467. brushOption: {},
  64468. /**
  64469. * @readOnly
  64470. * @type {Array.<Object>}
  64471. */
  64472. coordInfoList: [],
  64473. optionUpdated: function (newOption, isInit) {
  64474. var thisOption = this.option;
  64475. !isInit && replaceVisualOption(
  64476. thisOption, newOption, ['inBrush', 'outOfBrush']
  64477. );
  64478. var inBrush = thisOption.inBrush = thisOption.inBrush || {};
  64479. // Always give default visual, consider setOption at the second time.
  64480. thisOption.outOfBrush = thisOption.outOfBrush || {color: DEFAULT_OUT_OF_BRUSH_COLOR};
  64481. if (!inBrush.hasOwnProperty('liftZ')) {
  64482. // Bigger than the highlight z lift, otherwise it will
  64483. // be effected by the highlight z when brush.
  64484. inBrush.liftZ = 5;
  64485. }
  64486. },
  64487. /**
  64488. * If ranges is null/undefined, range state remain.
  64489. *
  64490. * @param {Array.<Object>} [ranges]
  64491. */
  64492. setAreas: function (areas) {
  64493. if (__DEV__) {
  64494. assert$1(isArray(areas));
  64495. each$1(areas, function (area) {
  64496. assert$1(area.brushType, 'Illegal areas');
  64497. });
  64498. }
  64499. // If ranges is null/undefined, range state remain.
  64500. // This helps user to dispatchAction({type: 'brush'}) with no areas
  64501. // set but just want to get the current brush select info from a `brush` event.
  64502. if (!areas) {
  64503. return;
  64504. }
  64505. this.areas = map(areas, function (area) {
  64506. return generateBrushOption(this.option, area);
  64507. }, this);
  64508. },
  64509. /**
  64510. * see module:echarts/component/helper/BrushController
  64511. * @param {Object} brushOption
  64512. */
  64513. setBrushOption: function (brushOption) {
  64514. this.brushOption = generateBrushOption(this.option, brushOption);
  64515. this.brushType = this.brushOption.brushType;
  64516. }
  64517. });
  64518. function generateBrushOption(option, brushOption) {
  64519. return merge(
  64520. {
  64521. brushType: option.brushType,
  64522. brushMode: option.brushMode,
  64523. transformable: option.transformable,
  64524. brushStyle: new Model(option.brushStyle).getItemStyle(),
  64525. removeOnClick: option.removeOnClick,
  64526. z: option.z
  64527. },
  64528. brushOption,
  64529. true
  64530. );
  64531. }
  64532. /*
  64533. * Licensed to the Apache Software Foundation (ASF) under one
  64534. * or more contributor license agreements. See the NOTICE file
  64535. * distributed with this work for additional information
  64536. * regarding copyright ownership. The ASF licenses this file
  64537. * to you under the Apache License, Version 2.0 (the
  64538. * "License"); you may not use this file except in compliance
  64539. * with the License. You may obtain a copy of the License at
  64540. *
  64541. * http://www.apache.org/licenses/LICENSE-2.0
  64542. *
  64543. * Unless required by applicable law or agreed to in writing,
  64544. * software distributed under the License is distributed on an
  64545. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  64546. * KIND, either express or implied. See the License for the
  64547. * specific language governing permissions and limitations
  64548. * under the License.
  64549. */
  64550. extendComponentView({
  64551. type: 'brush',
  64552. init: function (ecModel, api) {
  64553. /**
  64554. * @readOnly
  64555. * @type {module:echarts/model/Global}
  64556. */
  64557. this.ecModel = ecModel;
  64558. /**
  64559. * @readOnly
  64560. * @type {module:echarts/ExtensionAPI}
  64561. */
  64562. this.api = api;
  64563. /**
  64564. * @readOnly
  64565. * @type {module:echarts/component/brush/BrushModel}
  64566. */
  64567. this.model;
  64568. /**
  64569. * @private
  64570. * @type {module:echarts/component/helper/BrushController}
  64571. */
  64572. (this._brushController = new BrushController(api.getZr()))
  64573. .on('brush', bind(this._onBrush, this))
  64574. .mount();
  64575. },
  64576. /**
  64577. * @override
  64578. */
  64579. render: function (brushModel) {
  64580. this.model = brushModel;
  64581. return updateController.apply(this, arguments);
  64582. },
  64583. /**
  64584. * @override
  64585. */
  64586. updateTransform: updateController,
  64587. /**
  64588. * @override
  64589. */
  64590. updateView: updateController,
  64591. // /**
  64592. // * @override
  64593. // */
  64594. // updateLayout: updateController,
  64595. // /**
  64596. // * @override
  64597. // */
  64598. // updateVisual: updateController,
  64599. /**
  64600. * @override
  64601. */
  64602. dispose: function () {
  64603. this._brushController.dispose();
  64604. },
  64605. /**
  64606. * @private
  64607. */
  64608. _onBrush: function (areas, opt) {
  64609. var modelId = this.model.id;
  64610. this.model.brushTargetManager.setOutputRanges(areas, this.ecModel);
  64611. // Action is not dispatched on drag end, because the drag end
  64612. // emits the same params with the last drag move event, and
  64613. // may have some delay when using touch pad, which makes
  64614. // animation not smooth (when using debounce).
  64615. (!opt.isEnd || opt.removeOnClick) && this.api.dispatchAction({
  64616. type: 'brush',
  64617. brushId: modelId,
  64618. areas: clone(areas),
  64619. $from: modelId
  64620. });
  64621. }
  64622. });
  64623. function updateController(brushModel, ecModel, api, payload) {
  64624. // Do not update controller when drawing.
  64625. (!payload || payload.$from !== brushModel.id) && this._brushController
  64626. .setPanels(brushModel.brushTargetManager.makePanelOpts(api))
  64627. .enableBrush(brushModel.brushOption)
  64628. .updateCovers(brushModel.areas.slice());
  64629. }
  64630. /*
  64631. * Licensed to the Apache Software Foundation (ASF) under one
  64632. * or more contributor license agreements. See the NOTICE file
  64633. * distributed with this work for additional information
  64634. * regarding copyright ownership. The ASF licenses this file
  64635. * to you under the Apache License, Version 2.0 (the
  64636. * "License"); you may not use this file except in compliance
  64637. * with the License. You may obtain a copy of the License at
  64638. *
  64639. * http://www.apache.org/licenses/LICENSE-2.0
  64640. *
  64641. * Unless required by applicable law or agreed to in writing,
  64642. * software distributed under the License is distributed on an
  64643. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  64644. * KIND, either express or implied. See the License for the
  64645. * specific language governing permissions and limitations
  64646. * under the License.
  64647. */
  64648. /**
  64649. * payload: {
  64650. * brushIndex: number, or,
  64651. * brushId: string, or,
  64652. * brushName: string,
  64653. * globalRanges: Array
  64654. * }
  64655. */
  64656. registerAction(
  64657. {type: 'brush', event: 'brush' /*, update: 'updateView' */},
  64658. function (payload, ecModel) {
  64659. ecModel.eachComponent({mainType: 'brush', query: payload}, function (brushModel) {
  64660. brushModel.setAreas(payload.areas);
  64661. });
  64662. }
  64663. );
  64664. /**
  64665. * payload: {
  64666. * brushComponents: [
  64667. * {
  64668. * brushId,
  64669. * brushIndex,
  64670. * brushName,
  64671. * series: [
  64672. * {
  64673. * seriesId,
  64674. * seriesIndex,
  64675. * seriesName,
  64676. * rawIndices: [21, 34, ...]
  64677. * },
  64678. * ...
  64679. * ]
  64680. * },
  64681. * ...
  64682. * ]
  64683. * }
  64684. */
  64685. registerAction(
  64686. {type: 'brushSelect', event: 'brushSelected', update: 'none'},
  64687. function () {}
  64688. );
  64689. /*
  64690. * Licensed to the Apache Software Foundation (ASF) under one
  64691. * or more contributor license agreements. See the NOTICE file
  64692. * distributed with this work for additional information
  64693. * regarding copyright ownership. The ASF licenses this file
  64694. * to you under the Apache License, Version 2.0 (the
  64695. * "License"); you may not use this file except in compliance
  64696. * with the License. You may obtain a copy of the License at
  64697. *
  64698. * http://www.apache.org/licenses/LICENSE-2.0
  64699. *
  64700. * Unless required by applicable law or agreed to in writing,
  64701. * software distributed under the License is distributed on an
  64702. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  64703. * KIND, either express or implied. See the License for the
  64704. * specific language governing permissions and limitations
  64705. * under the License.
  64706. */
  64707. var features = {};
  64708. function register$1(name, ctor) {
  64709. features[name] = ctor;
  64710. }
  64711. function get$1(name) {
  64712. return features[name];
  64713. }
  64714. /*
  64715. * Licensed to the Apache Software Foundation (ASF) under one
  64716. * or more contributor license agreements. See the NOTICE file
  64717. * distributed with this work for additional information
  64718. * regarding copyright ownership. The ASF licenses this file
  64719. * to you under the Apache License, Version 2.0 (the
  64720. * "License"); you may not use this file except in compliance
  64721. * with the License. You may obtain a copy of the License at
  64722. *
  64723. * http://www.apache.org/licenses/LICENSE-2.0
  64724. *
  64725. * Unless required by applicable law or agreed to in writing,
  64726. * software distributed under the License is distributed on an
  64727. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  64728. * KIND, either express or implied. See the License for the
  64729. * specific language governing permissions and limitations
  64730. * under the License.
  64731. */
  64732. var brushLang = lang.toolbox.brush;
  64733. function Brush(model, ecModel, api) {
  64734. this.model = model;
  64735. this.ecModel = ecModel;
  64736. this.api = api;
  64737. /**
  64738. * @private
  64739. * @type {string}
  64740. */
  64741. this._brushType;
  64742. /**
  64743. * @private
  64744. * @type {string}
  64745. */
  64746. this._brushMode;
  64747. }
  64748. Brush.defaultOption = {
  64749. show: true,
  64750. type: ['rect', 'polygon', 'lineX', 'lineY', 'keep', 'clear'],
  64751. icon: {
  64752. 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
  64753. 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
  64754. 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
  64755. 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
  64756. 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
  64757. 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
  64758. },
  64759. // `rect`, `polygon`, `lineX`, `lineY`, `keep`, `clear`
  64760. title: clone(brushLang.title)
  64761. };
  64762. var proto$3 = Brush.prototype;
  64763. // proto.updateLayout = function (featureModel, ecModel, api) {
  64764. proto$3.render =
  64765. proto$3.updateView = function (featureModel, ecModel, api) {
  64766. var brushType;
  64767. var brushMode;
  64768. var isBrushed;
  64769. ecModel.eachComponent({mainType: 'brush'}, function (brushModel) {
  64770. brushType = brushModel.brushType;
  64771. brushMode = brushModel.brushOption.brushMode || 'single';
  64772. isBrushed |= brushModel.areas.length;
  64773. });
  64774. this._brushType = brushType;
  64775. this._brushMode = brushMode;
  64776. each$1(featureModel.get('type', true), function (type) {
  64777. featureModel.setIconStatus(
  64778. type,
  64779. (
  64780. type === 'keep'
  64781. ? brushMode === 'multiple'
  64782. : type === 'clear'
  64783. ? isBrushed
  64784. : type === brushType
  64785. ) ? 'emphasis' : 'normal'
  64786. );
  64787. });
  64788. };
  64789. proto$3.getIcons = function () {
  64790. var model = this.model;
  64791. var availableIcons = model.get('icon', true);
  64792. var icons = {};
  64793. each$1(model.get('type', true), function (type) {
  64794. if (availableIcons[type]) {
  64795. icons[type] = availableIcons[type];
  64796. }
  64797. });
  64798. return icons;
  64799. };
  64800. proto$3.onclick = function (ecModel, api, type) {
  64801. var brushType = this._brushType;
  64802. var brushMode = this._brushMode;
  64803. if (type === 'clear') {
  64804. // Trigger parallel action firstly
  64805. api.dispatchAction({
  64806. type: 'axisAreaSelect',
  64807. intervals: []
  64808. });
  64809. api.dispatchAction({
  64810. type: 'brush',
  64811. command: 'clear',
  64812. // Clear all areas of all brush components.
  64813. areas: []
  64814. });
  64815. }
  64816. else {
  64817. api.dispatchAction({
  64818. type: 'takeGlobalCursor',
  64819. key: 'brush',
  64820. brushOption: {
  64821. brushType: type === 'keep'
  64822. ? brushType
  64823. : (brushType === type ? false : type),
  64824. brushMode: type === 'keep'
  64825. ? (brushMode === 'multiple' ? 'single' : 'multiple')
  64826. : brushMode
  64827. }
  64828. });
  64829. }
  64830. };
  64831. register$1('brush', Brush);
  64832. /*
  64833. * Licensed to the Apache Software Foundation (ASF) under one
  64834. * or more contributor license agreements. See the NOTICE file
  64835. * distributed with this work for additional information
  64836. * regarding copyright ownership. The ASF licenses this file
  64837. * to you under the Apache License, Version 2.0 (the
  64838. * "License"); you may not use this file except in compliance
  64839. * with the License. You may obtain a copy of the License at
  64840. *
  64841. * http://www.apache.org/licenses/LICENSE-2.0
  64842. *
  64843. * Unless required by applicable law or agreed to in writing,
  64844. * software distributed under the License is distributed on an
  64845. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  64846. * KIND, either express or implied. See the License for the
  64847. * specific language governing permissions and limitations
  64848. * under the License.
  64849. */
  64850. /**
  64851. * Brush component entry
  64852. */
  64853. registerPreprocessor(preprocessor$1);
  64854. /*
  64855. * Licensed to the Apache Software Foundation (ASF) under one
  64856. * or more contributor license agreements. See the NOTICE file
  64857. * distributed with this work for additional information
  64858. * regarding copyright ownership. The ASF licenses this file
  64859. * to you under the Apache License, Version 2.0 (the
  64860. * "License"); you may not use this file except in compliance
  64861. * with the License. You may obtain a copy of the License at
  64862. *
  64863. * http://www.apache.org/licenses/LICENSE-2.0
  64864. *
  64865. * Unless required by applicable law or agreed to in writing,
  64866. * software distributed under the License is distributed on an
  64867. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  64868. * KIND, either express or implied. See the License for the
  64869. * specific language governing permissions and limitations
  64870. * under the License.
  64871. */
  64872. // (24*60*60*1000)
  64873. var PROXIMATE_ONE_DAY = 86400000;
  64874. /**
  64875. * Calendar
  64876. *
  64877. * @constructor
  64878. *
  64879. * @param {Object} calendarModel calendarModel
  64880. * @param {Object} ecModel ecModel
  64881. * @param {Object} api api
  64882. */
  64883. function Calendar(calendarModel, ecModel, api) {
  64884. this._model = calendarModel;
  64885. }
  64886. Calendar.prototype = {
  64887. constructor: Calendar,
  64888. type: 'calendar',
  64889. dimensions: ['time', 'value'],
  64890. // Required in createListFromData
  64891. getDimensionsInfo: function () {
  64892. return [{name: 'time', type: 'time'}, 'value'];
  64893. },
  64894. getRangeInfo: function () {
  64895. return this._rangeInfo;
  64896. },
  64897. getModel: function () {
  64898. return this._model;
  64899. },
  64900. getRect: function () {
  64901. return this._rect;
  64902. },
  64903. getCellWidth: function () {
  64904. return this._sw;
  64905. },
  64906. getCellHeight: function () {
  64907. return this._sh;
  64908. },
  64909. getOrient: function () {
  64910. return this._orient;
  64911. },
  64912. /**
  64913. * getFirstDayOfWeek
  64914. *
  64915. * @example
  64916. * 0 : start at Sunday
  64917. * 1 : start at Monday
  64918. *
  64919. * @return {number}
  64920. */
  64921. getFirstDayOfWeek: function () {
  64922. return this._firstDayOfWeek;
  64923. },
  64924. /**
  64925. * get date info
  64926. *
  64927. * @param {string|number} date date
  64928. * @return {Object}
  64929. * {
  64930. * y: string, local full year, eg., '1940',
  64931. * m: string, local month, from '01' ot '12',
  64932. * d: string, local date, from '01' to '31' (if exists),
  64933. * day: It is not date.getDay(). It is the location of the cell in a week, from 0 to 6,
  64934. * time: timestamp,
  64935. * formatedDate: string, yyyy-MM-dd,
  64936. * date: original date object.
  64937. * }
  64938. */
  64939. getDateInfo: function (date) {
  64940. date = parseDate(date);
  64941. var y = date.getFullYear();
  64942. var m = date.getMonth() + 1;
  64943. m = m < 10 ? '0' + m : m;
  64944. var d = date.getDate();
  64945. d = d < 10 ? '0' + d : d;
  64946. var day = date.getDay();
  64947. day = Math.abs((day + 7 - this.getFirstDayOfWeek()) % 7);
  64948. return {
  64949. y: y,
  64950. m: m,
  64951. d: d,
  64952. day: day,
  64953. time: date.getTime(),
  64954. formatedDate: y + '-' + m + '-' + d,
  64955. date: date
  64956. };
  64957. },
  64958. getNextNDay: function (date, n) {
  64959. n = n || 0;
  64960. if (n === 0) {
  64961. return this.getDateInfo(date);
  64962. }
  64963. date = new Date(this.getDateInfo(date).time);
  64964. date.setDate(date.getDate() + n);
  64965. return this.getDateInfo(date);
  64966. },
  64967. update: function (ecModel, api) {
  64968. this._firstDayOfWeek = +this._model.getModel('dayLabel').get('firstDay');
  64969. this._orient = this._model.get('orient');
  64970. this._lineWidth = this._model.getModel('itemStyle').getItemStyle().lineWidth || 0;
  64971. this._rangeInfo = this._getRangeInfo(this._initRangeOption());
  64972. var weeks = this._rangeInfo.weeks || 1;
  64973. var whNames = ['width', 'height'];
  64974. var cellSize = this._model.get('cellSize').slice();
  64975. var layoutParams = this._model.getBoxLayoutParams();
  64976. var cellNumbers = this._orient === 'horizontal' ? [weeks, 7] : [7, weeks];
  64977. each$1([0, 1], function (idx) {
  64978. if (cellSizeSpecified(cellSize, idx)) {
  64979. layoutParams[whNames[idx]] = cellSize[idx] * cellNumbers[idx];
  64980. }
  64981. });
  64982. var whGlobal = {
  64983. width: api.getWidth(),
  64984. height: api.getHeight()
  64985. };
  64986. var calendarRect = this._rect = getLayoutRect(layoutParams, whGlobal);
  64987. each$1([0, 1], function (idx) {
  64988. if (!cellSizeSpecified(cellSize, idx)) {
  64989. cellSize[idx] = calendarRect[whNames[idx]] / cellNumbers[idx];
  64990. }
  64991. });
  64992. function cellSizeSpecified(cellSize, idx) {
  64993. return cellSize[idx] != null && cellSize[idx] !== 'auto';
  64994. }
  64995. this._sw = cellSize[0];
  64996. this._sh = cellSize[1];
  64997. },
  64998. /**
  64999. * Convert a time data(time, value) item to (x, y) point.
  65000. *
  65001. * @override
  65002. * @param {Array|number} data data
  65003. * @param {boolean} [clamp=true] out of range
  65004. * @return {Array} point
  65005. */
  65006. dataToPoint: function (data, clamp) {
  65007. isArray(data) && (data = data[0]);
  65008. clamp == null && (clamp = true);
  65009. var dayInfo = this.getDateInfo(data);
  65010. var range = this._rangeInfo;
  65011. var date = dayInfo.formatedDate;
  65012. // if not in range return [NaN, NaN]
  65013. if (clamp && !(
  65014. dayInfo.time >= range.start.time
  65015. && dayInfo.time < range.end.time + PROXIMATE_ONE_DAY
  65016. )) {
  65017. return [NaN, NaN];
  65018. }
  65019. var week = dayInfo.day;
  65020. var nthWeek = this._getRangeInfo([range.start.time, date]).nthWeek;
  65021. if (this._orient === 'vertical') {
  65022. return [
  65023. this._rect.x + week * this._sw + this._sw / 2,
  65024. this._rect.y + nthWeek * this._sh + this._sh / 2
  65025. ];
  65026. }
  65027. return [
  65028. this._rect.x + nthWeek * this._sw + this._sw / 2,
  65029. this._rect.y + week * this._sh + this._sh / 2
  65030. ];
  65031. },
  65032. /**
  65033. * Convert a (x, y) point to time data
  65034. *
  65035. * @override
  65036. * @param {string} point point
  65037. * @return {string} data
  65038. */
  65039. pointToData: function (point) {
  65040. var date = this.pointToDate(point);
  65041. return date && date.time;
  65042. },
  65043. /**
  65044. * Convert a time date item to (x, y) four point.
  65045. *
  65046. * @param {Array} data date[0] is date
  65047. * @param {boolean} [clamp=true] out of range
  65048. * @return {Object} point
  65049. */
  65050. dataToRect: function (data, clamp) {
  65051. var point = this.dataToPoint(data, clamp);
  65052. return {
  65053. contentShape: {
  65054. x: point[0] - (this._sw - this._lineWidth) / 2,
  65055. y: point[1] - (this._sh - this._lineWidth) / 2,
  65056. width: this._sw - this._lineWidth,
  65057. height: this._sh - this._lineWidth
  65058. },
  65059. center: point,
  65060. tl: [
  65061. point[0] - this._sw / 2,
  65062. point[1] - this._sh / 2
  65063. ],
  65064. tr: [
  65065. point[0] + this._sw / 2,
  65066. point[1] - this._sh / 2
  65067. ],
  65068. br: [
  65069. point[0] + this._sw / 2,
  65070. point[1] + this._sh / 2
  65071. ],
  65072. bl: [
  65073. point[0] - this._sw / 2,
  65074. point[1] + this._sh / 2
  65075. ]
  65076. };
  65077. },
  65078. /**
  65079. * Convert a (x, y) point to time date
  65080. *
  65081. * @param {Array} point point
  65082. * @return {Object} date
  65083. */
  65084. pointToDate: function (point) {
  65085. var nthX = Math.floor((point[0] - this._rect.x) / this._sw) + 1;
  65086. var nthY = Math.floor((point[1] - this._rect.y) / this._sh) + 1;
  65087. var range = this._rangeInfo.range;
  65088. if (this._orient === 'vertical') {
  65089. return this._getDateByWeeksAndDay(nthY, nthX - 1, range);
  65090. }
  65091. return this._getDateByWeeksAndDay(nthX, nthY - 1, range);
  65092. },
  65093. /**
  65094. * @inheritDoc
  65095. */
  65096. convertToPixel: curry(doConvert$2, 'dataToPoint'),
  65097. /**
  65098. * @inheritDoc
  65099. */
  65100. convertFromPixel: curry(doConvert$2, 'pointToData'),
  65101. /**
  65102. * initRange
  65103. *
  65104. * @private
  65105. * @return {Array} [start, end]
  65106. */
  65107. _initRangeOption: function () {
  65108. var range = this._model.get('range');
  65109. var rg = range;
  65110. if (isArray(rg) && rg.length === 1) {
  65111. rg = rg[0];
  65112. }
  65113. if (/^\d{4}$/.test(rg)) {
  65114. range = [rg + '-01-01', rg + '-12-31'];
  65115. }
  65116. if (/^\d{4}[\/|-]\d{1,2}$/.test(rg)) {
  65117. var start = this.getDateInfo(rg);
  65118. var firstDay = start.date;
  65119. firstDay.setMonth(firstDay.getMonth() + 1);
  65120. var end = this.getNextNDay(firstDay, -1);
  65121. range = [start.formatedDate, end.formatedDate];
  65122. }
  65123. if (/^\d{4}[\/|-]\d{1,2}[\/|-]\d{1,2}$/.test(rg)) {
  65124. range = [rg, rg];
  65125. }
  65126. var tmp = this._getRangeInfo(range);
  65127. if (tmp.start.time > tmp.end.time) {
  65128. range.reverse();
  65129. }
  65130. return range;
  65131. },
  65132. /**
  65133. * range info
  65134. *
  65135. * @private
  65136. * @param {Array} range range ['2017-01-01', '2017-07-08']
  65137. * If range[0] > range[1], they will not be reversed.
  65138. * @return {Object} obj
  65139. */
  65140. _getRangeInfo: function (range) {
  65141. range = [
  65142. this.getDateInfo(range[0]),
  65143. this.getDateInfo(range[1])
  65144. ];
  65145. var reversed;
  65146. if (range[0].time > range[1].time) {
  65147. reversed = true;
  65148. range.reverse();
  65149. }
  65150. var allDay = Math.floor(range[1].time / PROXIMATE_ONE_DAY)
  65151. - Math.floor(range[0].time / PROXIMATE_ONE_DAY) + 1;
  65152. // Consider case:
  65153. // Firstly set system timezone as "Time Zone: America/Toronto",
  65154. // ```
  65155. // var first = new Date(1478412000000 - 3600 * 1000 * 2.5);
  65156. // var second = new Date(1478412000000);
  65157. // var allDays = Math.floor(second / ONE_DAY) - Math.floor(first / ONE_DAY) + 1;
  65158. // ```
  65159. // will get wrong result because of DST. So we should fix it.
  65160. var date = new Date(range[0].time);
  65161. var startDateNum = date.getDate();
  65162. var endDateNum = range[1].date.getDate();
  65163. date.setDate(startDateNum + allDay - 1);
  65164. // The bias can not over a month, so just compare date.
  65165. if (date.getDate() !== endDateNum) {
  65166. var sign = date.getTime() - range[1].time > 0 ? 1 : -1;
  65167. while (date.getDate() !== endDateNum && (date.getTime() - range[1].time) * sign > 0) {
  65168. allDay -= sign;
  65169. date.setDate(startDateNum + allDay - 1);
  65170. }
  65171. }
  65172. var weeks = Math.floor((allDay + range[0].day + 6) / 7);
  65173. var nthWeek = reversed ? -weeks + 1: weeks - 1;
  65174. reversed && range.reverse();
  65175. return {
  65176. range: [range[0].formatedDate, range[1].formatedDate],
  65177. start: range[0],
  65178. end: range[1],
  65179. allDay: allDay,
  65180. weeks: weeks,
  65181. // From 0.
  65182. nthWeek: nthWeek,
  65183. fweek: range[0].day,
  65184. lweek: range[1].day
  65185. };
  65186. },
  65187. /**
  65188. * get date by nthWeeks and week day in range
  65189. *
  65190. * @private
  65191. * @param {number} nthWeek the week
  65192. * @param {number} day the week day
  65193. * @param {Array} range [d1, d2]
  65194. * @return {Object}
  65195. */
  65196. _getDateByWeeksAndDay: function (nthWeek, day, range) {
  65197. var rangeInfo = this._getRangeInfo(range);
  65198. if (nthWeek > rangeInfo.weeks
  65199. || (nthWeek === 0 && day < rangeInfo.fweek)
  65200. || (nthWeek === rangeInfo.weeks && day > rangeInfo.lweek)
  65201. ) {
  65202. return false;
  65203. }
  65204. var nthDay = (nthWeek - 1) * 7 - rangeInfo.fweek + day;
  65205. var date = new Date(rangeInfo.start.time);
  65206. date.setDate(rangeInfo.start.d + nthDay);
  65207. return this.getDateInfo(date);
  65208. }
  65209. };
  65210. Calendar.dimensions = Calendar.prototype.dimensions;
  65211. Calendar.getDimensionsInfo = Calendar.prototype.getDimensionsInfo;
  65212. Calendar.create = function (ecModel, api) {
  65213. var calendarList = [];
  65214. ecModel.eachComponent('calendar', function (calendarModel) {
  65215. var calendar = new Calendar(calendarModel, ecModel, api);
  65216. calendarList.push(calendar);
  65217. calendarModel.coordinateSystem = calendar;
  65218. });
  65219. ecModel.eachSeries(function (calendarSeries) {
  65220. if (calendarSeries.get('coordinateSystem') === 'calendar') {
  65221. // Inject coordinate system
  65222. calendarSeries.coordinateSystem = calendarList[calendarSeries.get('calendarIndex') || 0];
  65223. }
  65224. });
  65225. return calendarList;
  65226. };
  65227. function doConvert$2(methodName, ecModel, finder, value) {
  65228. var calendarModel = finder.calendarModel;
  65229. var seriesModel = finder.seriesModel;
  65230. var coordSys = calendarModel
  65231. ? calendarModel.coordinateSystem
  65232. : seriesModel
  65233. ? seriesModel.coordinateSystem
  65234. : null;
  65235. return coordSys === this ? coordSys[methodName](value) : null;
  65236. }
  65237. CoordinateSystemManager.register('calendar', Calendar);
  65238. /*
  65239. * Licensed to the Apache Software Foundation (ASF) under one
  65240. * or more contributor license agreements. See the NOTICE file
  65241. * distributed with this work for additional information
  65242. * regarding copyright ownership. The ASF licenses this file
  65243. * to you under the Apache License, Version 2.0 (the
  65244. * "License"); you may not use this file except in compliance
  65245. * with the License. You may obtain a copy of the License at
  65246. *
  65247. * http://www.apache.org/licenses/LICENSE-2.0
  65248. *
  65249. * Unless required by applicable law or agreed to in writing,
  65250. * software distributed under the License is distributed on an
  65251. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65252. * KIND, either express or implied. See the License for the
  65253. * specific language governing permissions and limitations
  65254. * under the License.
  65255. */
  65256. var CalendarModel = ComponentModel.extend({
  65257. type: 'calendar',
  65258. /**
  65259. * @type {module:echarts/coord/calendar/Calendar}
  65260. */
  65261. coordinateSystem: null,
  65262. defaultOption: {
  65263. zlevel: 0,
  65264. z: 2,
  65265. left: 80,
  65266. top: 60,
  65267. cellSize: 20,
  65268. // horizontal vertical
  65269. orient: 'horizontal',
  65270. // month separate line style
  65271. splitLine: {
  65272. show: true,
  65273. lineStyle: {
  65274. color: '#000',
  65275. width: 1,
  65276. type: 'solid'
  65277. }
  65278. },
  65279. // rect style temporarily unused emphasis
  65280. itemStyle: {
  65281. color: '#fff',
  65282. borderWidth: 1,
  65283. borderColor: '#ccc'
  65284. },
  65285. // week text style
  65286. dayLabel: {
  65287. show: true,
  65288. // a week first day
  65289. firstDay: 0,
  65290. // start end
  65291. position: 'start',
  65292. margin: '50%', // 50% of cellSize
  65293. nameMap: 'en',
  65294. color: '#000'
  65295. },
  65296. // month text style
  65297. monthLabel: {
  65298. show: true,
  65299. // start end
  65300. position: 'start',
  65301. margin: 5,
  65302. // center or left
  65303. align: 'center',
  65304. // cn en []
  65305. nameMap: 'en',
  65306. formatter: null,
  65307. color: '#000'
  65308. },
  65309. // year text style
  65310. yearLabel: {
  65311. show: true,
  65312. // top bottom left right
  65313. position: null,
  65314. margin: 30,
  65315. formatter: null,
  65316. color: '#ccc',
  65317. fontFamily: 'sans-serif',
  65318. fontWeight: 'bolder',
  65319. fontSize: 20
  65320. }
  65321. },
  65322. /**
  65323. * @override
  65324. */
  65325. init: function (option, parentModel, ecModel, extraOpt) {
  65326. var inputPositionParams = getLayoutParams(option);
  65327. CalendarModel.superApply(this, 'init', arguments);
  65328. mergeAndNormalizeLayoutParams$1(option, inputPositionParams);
  65329. },
  65330. /**
  65331. * @override
  65332. */
  65333. mergeOption: function (option, extraOpt) {
  65334. CalendarModel.superApply(this, 'mergeOption', arguments);
  65335. mergeAndNormalizeLayoutParams$1(this.option, option);
  65336. }
  65337. });
  65338. function mergeAndNormalizeLayoutParams$1(target, raw) {
  65339. // Normalize cellSize
  65340. var cellSize = target.cellSize;
  65341. if (!isArray(cellSize)) {
  65342. cellSize = target.cellSize = [cellSize, cellSize];
  65343. }
  65344. else if (cellSize.length === 1) {
  65345. cellSize[1] = cellSize[0];
  65346. }
  65347. var ignoreSize = map([0, 1], function (hvIdx) {
  65348. // If user have set `width` or both `left` and `right`, cellSize
  65349. // will be automatically set to 'auto', otherwise the default
  65350. // setting of cellSize will make `width` setting not work.
  65351. if (sizeCalculable(raw, hvIdx)) {
  65352. cellSize[hvIdx] = 'auto';
  65353. }
  65354. return cellSize[hvIdx] != null && cellSize[hvIdx] !== 'auto';
  65355. });
  65356. mergeLayoutParam(target, raw, {
  65357. type: 'box', ignoreSize: ignoreSize
  65358. });
  65359. }
  65360. /*
  65361. * Licensed to the Apache Software Foundation (ASF) under one
  65362. * or more contributor license agreements. See the NOTICE file
  65363. * distributed with this work for additional information
  65364. * regarding copyright ownership. The ASF licenses this file
  65365. * to you under the Apache License, Version 2.0 (the
  65366. * "License"); you may not use this file except in compliance
  65367. * with the License. You may obtain a copy of the License at
  65368. *
  65369. * http://www.apache.org/licenses/LICENSE-2.0
  65370. *
  65371. * Unless required by applicable law or agreed to in writing,
  65372. * software distributed under the License is distributed on an
  65373. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65374. * KIND, either express or implied. See the License for the
  65375. * specific language governing permissions and limitations
  65376. * under the License.
  65377. */
  65378. var MONTH_TEXT = {
  65379. EN: [
  65380. 'Jan', 'Feb', 'Mar',
  65381. 'Apr', 'May', 'Jun',
  65382. 'Jul', 'Aug', 'Sep',
  65383. 'Oct', 'Nov', 'Dec'
  65384. ],
  65385. CN: [
  65386. '一月', '二月', '三月',
  65387. '四月', '五月', '六月',
  65388. '七月', '八月', '九月',
  65389. '十月', '十一月', '十二月'
  65390. ]
  65391. };
  65392. var WEEK_TEXT = {
  65393. EN: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
  65394. CN: ['日', '一', '二', '三', '四', '五', '六']
  65395. };
  65396. extendComponentView({
  65397. type: 'calendar',
  65398. /**
  65399. * top/left line points
  65400. * @private
  65401. */
  65402. _tlpoints: null,
  65403. /**
  65404. * bottom/right line points
  65405. * @private
  65406. */
  65407. _blpoints: null,
  65408. /**
  65409. * first day of month
  65410. * @private
  65411. */
  65412. _firstDayOfMonth: null,
  65413. /**
  65414. * first day point of month
  65415. * @private
  65416. */
  65417. _firstDayPoints: null,
  65418. render: function (calendarModel, ecModel, api) {
  65419. var group = this.group;
  65420. group.removeAll();
  65421. var coordSys = calendarModel.coordinateSystem;
  65422. // range info
  65423. var rangeData = coordSys.getRangeInfo();
  65424. var orient = coordSys.getOrient();
  65425. this._renderDayRect(calendarModel, rangeData, group);
  65426. // _renderLines must be called prior to following function
  65427. this._renderLines(calendarModel, rangeData, orient, group);
  65428. this._renderYearText(calendarModel, rangeData, orient, group);
  65429. this._renderMonthText(calendarModel, orient, group);
  65430. this._renderWeekText(calendarModel, rangeData, orient, group);
  65431. },
  65432. // render day rect
  65433. _renderDayRect: function (calendarModel, rangeData, group) {
  65434. var coordSys = calendarModel.coordinateSystem;
  65435. var itemRectStyleModel = calendarModel.getModel('itemStyle').getItemStyle();
  65436. var sw = coordSys.getCellWidth();
  65437. var sh = coordSys.getCellHeight();
  65438. for (var i = rangeData.start.time;
  65439. i <= rangeData.end.time;
  65440. i = coordSys.getNextNDay(i, 1).time
  65441. ) {
  65442. var point = coordSys.dataToRect([i], false).tl;
  65443. // every rect
  65444. var rect = new Rect({
  65445. shape: {
  65446. x: point[0],
  65447. y: point[1],
  65448. width: sw,
  65449. height: sh
  65450. },
  65451. cursor: 'default',
  65452. style: itemRectStyleModel
  65453. });
  65454. group.add(rect);
  65455. }
  65456. },
  65457. // render separate line
  65458. _renderLines: function (calendarModel, rangeData, orient, group) {
  65459. var self = this;
  65460. var coordSys = calendarModel.coordinateSystem;
  65461. var lineStyleModel = calendarModel.getModel('splitLine.lineStyle').getLineStyle();
  65462. var show = calendarModel.get('splitLine.show');
  65463. var lineWidth = lineStyleModel.lineWidth;
  65464. this._tlpoints = [];
  65465. this._blpoints = [];
  65466. this._firstDayOfMonth = [];
  65467. this._firstDayPoints = [];
  65468. var firstDay = rangeData.start;
  65469. for (var i = 0; firstDay.time <= rangeData.end.time; i++) {
  65470. addPoints(firstDay.formatedDate);
  65471. if (i === 0) {
  65472. firstDay = coordSys.getDateInfo(rangeData.start.y + '-' + rangeData.start.m);
  65473. }
  65474. var date = firstDay.date;
  65475. date.setMonth(date.getMonth() + 1);
  65476. firstDay = coordSys.getDateInfo(date);
  65477. }
  65478. addPoints(coordSys.getNextNDay(rangeData.end.time, 1).formatedDate);
  65479. function addPoints(date) {
  65480. self._firstDayOfMonth.push(coordSys.getDateInfo(date));
  65481. self._firstDayPoints.push(coordSys.dataToRect([date], false).tl);
  65482. var points = self._getLinePointsOfOneWeek(calendarModel, date, orient);
  65483. self._tlpoints.push(points[0]);
  65484. self._blpoints.push(points[points.length - 1]);
  65485. show && self._drawSplitline(points, lineStyleModel, group);
  65486. }
  65487. // render top/left line
  65488. show && this._drawSplitline(self._getEdgesPoints(self._tlpoints, lineWidth, orient), lineStyleModel, group);
  65489. // render bottom/right line
  65490. show && this._drawSplitline(self._getEdgesPoints(self._blpoints, lineWidth, orient), lineStyleModel, group);
  65491. },
  65492. // get points at both ends
  65493. _getEdgesPoints: function (points, lineWidth, orient) {
  65494. var rs = [points[0].slice(), points[points.length - 1].slice()];
  65495. var idx = orient === 'horizontal' ? 0 : 1;
  65496. // both ends of the line are extend half lineWidth
  65497. rs[0][idx] = rs[0][idx] - lineWidth / 2;
  65498. rs[1][idx] = rs[1][idx] + lineWidth / 2;
  65499. return rs;
  65500. },
  65501. // render split line
  65502. _drawSplitline: function (points, lineStyleModel, group) {
  65503. var poyline = new Polyline({
  65504. z2: 20,
  65505. shape: {
  65506. points: points
  65507. },
  65508. style: lineStyleModel
  65509. });
  65510. group.add(poyline);
  65511. },
  65512. // render month line of one week points
  65513. _getLinePointsOfOneWeek: function (calendarModel, date, orient) {
  65514. var coordSys = calendarModel.coordinateSystem;
  65515. date = coordSys.getDateInfo(date);
  65516. var points = [];
  65517. for (var i = 0; i < 7; i++) {
  65518. var tmpD = coordSys.getNextNDay(date.time, i);
  65519. var point = coordSys.dataToRect([tmpD.time], false);
  65520. points[2 * tmpD.day] = point.tl;
  65521. points[2 * tmpD.day + 1] = point[orient === 'horizontal' ? 'bl' : 'tr'];
  65522. }
  65523. return points;
  65524. },
  65525. _formatterLabel: function (formatter, params) {
  65526. if (typeof formatter === 'string' && formatter) {
  65527. return formatTplSimple(formatter, params);
  65528. }
  65529. if (typeof formatter === 'function') {
  65530. return formatter(params);
  65531. }
  65532. return params.nameMap;
  65533. },
  65534. _yearTextPositionControl: function (textEl, point, orient, position, margin) {
  65535. point = point.slice();
  65536. var aligns = ['center', 'bottom'];
  65537. if (position === 'bottom') {
  65538. point[1] += margin;
  65539. aligns = ['center', 'top'];
  65540. }
  65541. else if (position === 'left') {
  65542. point[0] -= margin;
  65543. }
  65544. else if (position === 'right') {
  65545. point[0] += margin;
  65546. aligns = ['center', 'top'];
  65547. }
  65548. else { // top
  65549. point[1] -= margin;
  65550. }
  65551. var rotate = 0;
  65552. if (position === 'left' || position === 'right') {
  65553. rotate = Math.PI / 2;
  65554. }
  65555. return {
  65556. rotation: rotate,
  65557. position: point,
  65558. style: {
  65559. textAlign: aligns[0],
  65560. textVerticalAlign: aligns[1]
  65561. }
  65562. };
  65563. },
  65564. // render year
  65565. _renderYearText: function (calendarModel, rangeData, orient, group) {
  65566. var yearLabel = calendarModel.getModel('yearLabel');
  65567. if (!yearLabel.get('show')) {
  65568. return;
  65569. }
  65570. var margin = yearLabel.get('margin');
  65571. var pos = yearLabel.get('position');
  65572. if (!pos) {
  65573. pos = orient !== 'horizontal' ? 'top' : 'left';
  65574. }
  65575. var points = [this._tlpoints[this._tlpoints.length - 1], this._blpoints[0]];
  65576. var xc = (points[0][0] + points[1][0]) / 2;
  65577. var yc = (points[0][1] + points[1][1]) / 2;
  65578. var idx = orient === 'horizontal' ? 0 : 1;
  65579. var posPoints = {
  65580. top: [xc, points[idx][1]],
  65581. bottom: [xc, points[1 - idx][1]],
  65582. left: [points[1 - idx][0], yc],
  65583. right: [points[idx][0], yc]
  65584. };
  65585. var name = rangeData.start.y;
  65586. if (+rangeData.end.y > +rangeData.start.y) {
  65587. name = name + '-' + rangeData.end.y;
  65588. }
  65589. var formatter = yearLabel.get('formatter');
  65590. var params = {
  65591. start: rangeData.start.y,
  65592. end: rangeData.end.y,
  65593. nameMap: name
  65594. };
  65595. var content = this._formatterLabel(formatter, params);
  65596. var yearText = new Text({z2: 30});
  65597. setTextStyle(yearText.style, yearLabel, {text: content}),
  65598. yearText.attr(this._yearTextPositionControl(yearText, posPoints[pos], orient, pos, margin));
  65599. group.add(yearText);
  65600. },
  65601. _monthTextPositionControl: function (point, isCenter, orient, position, margin) {
  65602. var align = 'left';
  65603. var vAlign = 'top';
  65604. var x = point[0];
  65605. var y = point[1];
  65606. if (orient === 'horizontal') {
  65607. y = y + margin;
  65608. if (isCenter) {
  65609. align = 'center';
  65610. }
  65611. if (position === 'start') {
  65612. vAlign = 'bottom';
  65613. }
  65614. }
  65615. else {
  65616. x = x + margin;
  65617. if (isCenter) {
  65618. vAlign = 'middle';
  65619. }
  65620. if (position === 'start') {
  65621. align = 'right';
  65622. }
  65623. }
  65624. return {
  65625. x: x,
  65626. y: y,
  65627. textAlign: align,
  65628. textVerticalAlign: vAlign
  65629. };
  65630. },
  65631. // render month and year text
  65632. _renderMonthText: function (calendarModel, orient, group) {
  65633. var monthLabel = calendarModel.getModel('monthLabel');
  65634. if (!monthLabel.get('show')) {
  65635. return;
  65636. }
  65637. var nameMap = monthLabel.get('nameMap');
  65638. var margin = monthLabel.get('margin');
  65639. var pos = monthLabel.get('position');
  65640. var align = monthLabel.get('align');
  65641. var termPoints = [this._tlpoints, this._blpoints];
  65642. if (isString(nameMap)) {
  65643. nameMap = MONTH_TEXT[nameMap.toUpperCase()] || [];
  65644. }
  65645. var idx = pos === 'start' ? 0 : 1;
  65646. var axis = orient === 'horizontal' ? 0 : 1;
  65647. margin = pos === 'start' ? -margin : margin;
  65648. var isCenter = (align === 'center');
  65649. for (var i = 0; i < termPoints[idx].length - 1; i++) {
  65650. var tmp = termPoints[idx][i].slice();
  65651. var firstDay = this._firstDayOfMonth[i];
  65652. if (isCenter) {
  65653. var firstDayPoints = this._firstDayPoints[i];
  65654. tmp[axis] = (firstDayPoints[axis] + termPoints[0][i + 1][axis]) / 2;
  65655. }
  65656. var formatter = monthLabel.get('formatter');
  65657. var name = nameMap[+firstDay.m - 1];
  65658. var params = {
  65659. yyyy: firstDay.y,
  65660. yy: (firstDay.y + '').slice(2),
  65661. MM: firstDay.m,
  65662. M: +firstDay.m,
  65663. nameMap: name
  65664. };
  65665. var content = this._formatterLabel(formatter, params);
  65666. var monthText = new Text({z2: 30});
  65667. extend(
  65668. setTextStyle(monthText.style, monthLabel, {text: content}),
  65669. this._monthTextPositionControl(tmp, isCenter, orient, pos, margin)
  65670. );
  65671. group.add(monthText);
  65672. }
  65673. },
  65674. _weekTextPositionControl: function (point, orient, position, margin, cellSize) {
  65675. var align = 'center';
  65676. var vAlign = 'middle';
  65677. var x = point[0];
  65678. var y = point[1];
  65679. var isStart = position === 'start';
  65680. if (orient === 'horizontal') {
  65681. x = x + margin + (isStart ? 1 : -1) * cellSize[0] / 2;
  65682. align = isStart ? 'right' : 'left';
  65683. }
  65684. else {
  65685. y = y + margin + (isStart ? 1 : -1) * cellSize[1] / 2;
  65686. vAlign = isStart ? 'bottom' : 'top';
  65687. }
  65688. return {
  65689. x: x,
  65690. y: y,
  65691. textAlign: align,
  65692. textVerticalAlign: vAlign
  65693. };
  65694. },
  65695. // render weeks
  65696. _renderWeekText: function (calendarModel, rangeData, orient, group) {
  65697. var dayLabel = calendarModel.getModel('dayLabel');
  65698. if (!dayLabel.get('show')) {
  65699. return;
  65700. }
  65701. var coordSys = calendarModel.coordinateSystem;
  65702. var pos = dayLabel.get('position');
  65703. var nameMap = dayLabel.get('nameMap');
  65704. var margin = dayLabel.get('margin');
  65705. var firstDayOfWeek = coordSys.getFirstDayOfWeek();
  65706. if (isString(nameMap)) {
  65707. nameMap = WEEK_TEXT[nameMap.toUpperCase()] || [];
  65708. }
  65709. var start = coordSys.getNextNDay(
  65710. rangeData.end.time, (7 - rangeData.lweek)
  65711. ).time;
  65712. var cellSize = [coordSys.getCellWidth(), coordSys.getCellHeight()];
  65713. margin = parsePercent$1(margin, cellSize[orient === 'horizontal' ? 0 : 1]);
  65714. if (pos === 'start') {
  65715. start = coordSys.getNextNDay(
  65716. rangeData.start.time, -(7 + rangeData.fweek)
  65717. ).time;
  65718. margin = -margin;
  65719. }
  65720. for (var i = 0; i < 7; i++) {
  65721. var tmpD = coordSys.getNextNDay(start, i);
  65722. var point = coordSys.dataToRect([tmpD.time], false).center;
  65723. var day = i;
  65724. day = Math.abs((i + firstDayOfWeek) % 7);
  65725. var weekText = new Text({z2: 30});
  65726. extend(
  65727. setTextStyle(weekText.style, dayLabel, {text: nameMap[day]}),
  65728. this._weekTextPositionControl(point, orient, pos, margin, cellSize)
  65729. );
  65730. group.add(weekText);
  65731. }
  65732. }
  65733. });
  65734. /*
  65735. * Licensed to the Apache Software Foundation (ASF) under one
  65736. * or more contributor license agreements. See the NOTICE file
  65737. * distributed with this work for additional information
  65738. * regarding copyright ownership. The ASF licenses this file
  65739. * to you under the Apache License, Version 2.0 (the
  65740. * "License"); you may not use this file except in compliance
  65741. * with the License. You may obtain a copy of the License at
  65742. *
  65743. * http://www.apache.org/licenses/LICENSE-2.0
  65744. *
  65745. * Unless required by applicable law or agreed to in writing,
  65746. * software distributed under the License is distributed on an
  65747. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65748. * KIND, either express or implied. See the License for the
  65749. * specific language governing permissions and limitations
  65750. * under the License.
  65751. */
  65752. /**
  65753. * @file calendar.js
  65754. * @author dxh
  65755. */
  65756. /*
  65757. * Licensed to the Apache Software Foundation (ASF) under one
  65758. * or more contributor license agreements. See the NOTICE file
  65759. * distributed with this work for additional information
  65760. * regarding copyright ownership. The ASF licenses this file
  65761. * to you under the Apache License, Version 2.0 (the
  65762. * "License"); you may not use this file except in compliance
  65763. * with the License. You may obtain a copy of the License at
  65764. *
  65765. * http://www.apache.org/licenses/LICENSE-2.0
  65766. *
  65767. * Unless required by applicable law or agreed to in writing,
  65768. * software distributed under the License is distributed on an
  65769. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65770. * KIND, either express or implied. See the License for the
  65771. * specific language governing permissions and limitations
  65772. * under the License.
  65773. */
  65774. // Model
  65775. extendComponentModel({
  65776. type: 'title',
  65777. layoutMode: {type: 'box', ignoreSize: true},
  65778. defaultOption: {
  65779. // 一级层叠
  65780. zlevel: 0,
  65781. // 二级层叠
  65782. z: 6,
  65783. show: true,
  65784. text: '',
  65785. // 超链接跳转
  65786. // link: null,
  65787. // 仅支持self | blank
  65788. target: 'blank',
  65789. subtext: '',
  65790. // 超链接跳转
  65791. // sublink: null,
  65792. // 仅支持self | blank
  65793. subtarget: 'blank',
  65794. // 'center' ¦ 'left' ¦ 'right'
  65795. // ¦ {number}(x坐标,单位px)
  65796. left: 0,
  65797. // 'top' ¦ 'bottom' ¦ 'center'
  65798. // ¦ {number}(y坐标,单位px)
  65799. top: 0,
  65800. // 水平对齐
  65801. // 'auto' | 'left' | 'right' | 'center'
  65802. // 默认根据 left 的位置判断是左对齐还是右对齐
  65803. // textAlign: null
  65804. //
  65805. // 垂直对齐
  65806. // 'auto' | 'top' | 'bottom' | 'middle'
  65807. // 默认根据 top 位置判断是上对齐还是下对齐
  65808. // textBaseline: null
  65809. backgroundColor: 'rgba(0,0,0,0)',
  65810. // 标题边框颜色
  65811. borderColor: '#ccc',
  65812. // 标题边框线宽,单位px,默认为0(无边框)
  65813. borderWidth: 0,
  65814. // 标题内边距,单位px,默认各方向内边距为5,
  65815. // 接受数组分别设定上右下左边距,同css
  65816. padding: 5,
  65817. // 主副标题纵向间隔,单位px,默认为10,
  65818. itemGap: 10,
  65819. textStyle: {
  65820. fontSize: 18,
  65821. fontWeight: 'bolder',
  65822. color: '#333'
  65823. },
  65824. subtextStyle: {
  65825. color: '#aaa'
  65826. }
  65827. }
  65828. });
  65829. // View
  65830. extendComponentView({
  65831. type: 'title',
  65832. render: function (titleModel, ecModel, api) {
  65833. this.group.removeAll();
  65834. if (!titleModel.get('show')) {
  65835. return;
  65836. }
  65837. var group = this.group;
  65838. var textStyleModel = titleModel.getModel('textStyle');
  65839. var subtextStyleModel = titleModel.getModel('subtextStyle');
  65840. var textAlign = titleModel.get('textAlign');
  65841. var textBaseline = titleModel.get('textBaseline');
  65842. var textEl = new Text({
  65843. style: setTextStyle({}, textStyleModel, {
  65844. text: titleModel.get('text'),
  65845. textFill: textStyleModel.getTextColor()
  65846. }, {disableBox: true}),
  65847. z2: 10
  65848. });
  65849. var textRect = textEl.getBoundingRect();
  65850. var subText = titleModel.get('subtext');
  65851. var subTextEl = new Text({
  65852. style: setTextStyle({}, subtextStyleModel, {
  65853. text: subText,
  65854. textFill: subtextStyleModel.getTextColor(),
  65855. y: textRect.height + titleModel.get('itemGap'),
  65856. textVerticalAlign: 'top'
  65857. }, {disableBox: true}),
  65858. z2: 10
  65859. });
  65860. var link = titleModel.get('link');
  65861. var sublink = titleModel.get('sublink');
  65862. textEl.silent = !link;
  65863. subTextEl.silent = !sublink;
  65864. if (link) {
  65865. textEl.on('click', function () {
  65866. window.open(link, '_' + titleModel.get('target'));
  65867. });
  65868. }
  65869. if (sublink) {
  65870. subTextEl.on('click', function () {
  65871. window.open(sublink, '_' + titleModel.get('subtarget'));
  65872. });
  65873. }
  65874. group.add(textEl);
  65875. subText && group.add(subTextEl);
  65876. // If no subText, but add subTextEl, there will be an empty line.
  65877. var groupRect = group.getBoundingRect();
  65878. var layoutOption = titleModel.getBoxLayoutParams();
  65879. layoutOption.width = groupRect.width;
  65880. layoutOption.height = groupRect.height;
  65881. var layoutRect = getLayoutRect(
  65882. layoutOption, {
  65883. width: api.getWidth(),
  65884. height: api.getHeight()
  65885. }, titleModel.get('padding')
  65886. );
  65887. // Adjust text align based on position
  65888. if (!textAlign) {
  65889. // Align left if title is on the left. center and right is same
  65890. textAlign = titleModel.get('left') || titleModel.get('right');
  65891. if (textAlign === 'middle') {
  65892. textAlign = 'center';
  65893. }
  65894. // Adjust layout by text align
  65895. if (textAlign === 'right') {
  65896. layoutRect.x += layoutRect.width;
  65897. }
  65898. else if (textAlign === 'center') {
  65899. layoutRect.x += layoutRect.width / 2;
  65900. }
  65901. }
  65902. if (!textBaseline) {
  65903. textBaseline = titleModel.get('top') || titleModel.get('bottom');
  65904. if (textBaseline === 'center') {
  65905. textBaseline = 'middle';
  65906. }
  65907. if (textBaseline === 'bottom') {
  65908. layoutRect.y += layoutRect.height;
  65909. }
  65910. else if (textBaseline === 'middle') {
  65911. layoutRect.y += layoutRect.height / 2;
  65912. }
  65913. textBaseline = textBaseline || 'top';
  65914. }
  65915. group.attr('position', [layoutRect.x, layoutRect.y]);
  65916. var alignStyle = {
  65917. textAlign: textAlign,
  65918. textVerticalAlign: textBaseline
  65919. };
  65920. textEl.setStyle(alignStyle);
  65921. subTextEl.setStyle(alignStyle);
  65922. // Render background
  65923. // Get groupRect again because textAlign has been changed
  65924. groupRect = group.getBoundingRect();
  65925. var padding = layoutRect.margin;
  65926. var style = titleModel.getItemStyle(['color', 'opacity']);
  65927. style.fill = titleModel.get('backgroundColor');
  65928. var rect = new Rect({
  65929. shape: {
  65930. x: groupRect.x - padding[3],
  65931. y: groupRect.y - padding[0],
  65932. width: groupRect.width + padding[1] + padding[3],
  65933. height: groupRect.height + padding[0] + padding[2],
  65934. r: titleModel.get('borderRadius')
  65935. },
  65936. style: style,
  65937. silent: true
  65938. });
  65939. subPixelOptimizeRect(rect);
  65940. group.add(rect);
  65941. }
  65942. });
  65943. /*
  65944. * Licensed to the Apache Software Foundation (ASF) under one
  65945. * or more contributor license agreements. See the NOTICE file
  65946. * distributed with this work for additional information
  65947. * regarding copyright ownership. The ASF licenses this file
  65948. * to you under the Apache License, Version 2.0 (the
  65949. * "License"); you may not use this file except in compliance
  65950. * with the License. You may obtain a copy of the License at
  65951. *
  65952. * http://www.apache.org/licenses/LICENSE-2.0
  65953. *
  65954. * Unless required by applicable law or agreed to in writing,
  65955. * software distributed under the License is distributed on an
  65956. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65957. * KIND, either express or implied. See the License for the
  65958. * specific language governing permissions and limitations
  65959. * under the License.
  65960. */
  65961. ComponentModel.registerSubTypeDefaulter('dataZoom', function () {
  65962. // Default 'slider' when no type specified.
  65963. return 'slider';
  65964. });
  65965. /*
  65966. * Licensed to the Apache Software Foundation (ASF) under one
  65967. * or more contributor license agreements. See the NOTICE file
  65968. * distributed with this work for additional information
  65969. * regarding copyright ownership. The ASF licenses this file
  65970. * to you under the Apache License, Version 2.0 (the
  65971. * "License"); you may not use this file except in compliance
  65972. * with the License. You may obtain a copy of the License at
  65973. *
  65974. * http://www.apache.org/licenses/LICENSE-2.0
  65975. *
  65976. * Unless required by applicable law or agreed to in writing,
  65977. * software distributed under the License is distributed on an
  65978. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65979. * KIND, either express or implied. See the License for the
  65980. * specific language governing permissions and limitations
  65981. * under the License.
  65982. */
  65983. var AXIS_DIMS = ['x', 'y', 'z', 'radius', 'angle', 'single'];
  65984. // Supported coords.
  65985. var COORDS = ['cartesian2d', 'polar', 'singleAxis'];
  65986. /**
  65987. * @param {string} coordType
  65988. * @return {boolean}
  65989. */
  65990. function isCoordSupported(coordType) {
  65991. return indexOf(COORDS, coordType) >= 0;
  65992. }
  65993. /**
  65994. * Create "each" method to iterate names.
  65995. *
  65996. * @pubilc
  65997. * @param {Array.<string>} names
  65998. * @param {Array.<string>=} attrs
  65999. * @return {Function}
  66000. */
  66001. function createNameEach(names, attrs) {
  66002. names = names.slice();
  66003. var capitalNames = map(names, capitalFirst);
  66004. attrs = (attrs || []).slice();
  66005. var capitalAttrs = map(attrs, capitalFirst);
  66006. return function (callback, context) {
  66007. each$1(names, function (name, index) {
  66008. var nameObj = {name: name, capital: capitalNames[index]};
  66009. for (var j = 0; j < attrs.length; j++) {
  66010. nameObj[attrs[j]] = name + capitalAttrs[j];
  66011. }
  66012. callback.call(context, nameObj);
  66013. });
  66014. };
  66015. }
  66016. /**
  66017. * Iterate each dimension name.
  66018. *
  66019. * @public
  66020. * @param {Function} callback The parameter is like:
  66021. * {
  66022. * name: 'angle',
  66023. * capital: 'Angle',
  66024. * axis: 'angleAxis',
  66025. * axisIndex: 'angleAixs',
  66026. * index: 'angleIndex'
  66027. * }
  66028. * @param {Object} context
  66029. */
  66030. var eachAxisDim$1 = createNameEach(AXIS_DIMS, ['axisIndex', 'axis', 'index', 'id']);
  66031. /**
  66032. * If tow dataZoomModels has the same axis controlled, we say that they are 'linked'.
  66033. * dataZoomModels and 'links' make up one or more graphics.
  66034. * This function finds the graphic where the source dataZoomModel is in.
  66035. *
  66036. * @public
  66037. * @param {Function} forEachNode Node iterator.
  66038. * @param {Function} forEachEdgeType edgeType iterator
  66039. * @param {Function} edgeIdGetter Giving node and edgeType, return an array of edge id.
  66040. * @return {Function} Input: sourceNode, Output: Like {nodes: [], dims: {}}
  66041. */
  66042. function createLinkedNodesFinder(forEachNode, forEachEdgeType, edgeIdGetter) {
  66043. return function (sourceNode) {
  66044. var result = {
  66045. nodes: [],
  66046. records: {} // key: edgeType.name, value: Object (key: edge id, value: boolean).
  66047. };
  66048. forEachEdgeType(function (edgeType) {
  66049. result.records[edgeType.name] = {};
  66050. });
  66051. if (!sourceNode) {
  66052. return result;
  66053. }
  66054. absorb(sourceNode, result);
  66055. var existsLink;
  66056. do {
  66057. existsLink = false;
  66058. forEachNode(processSingleNode);
  66059. }
  66060. while (existsLink);
  66061. function processSingleNode(node) {
  66062. if (!isNodeAbsorded(node, result) && isLinked(node, result)) {
  66063. absorb(node, result);
  66064. existsLink = true;
  66065. }
  66066. }
  66067. return result;
  66068. };
  66069. function isNodeAbsorded(node, result) {
  66070. return indexOf(result.nodes, node) >= 0;
  66071. }
  66072. function isLinked(node, result) {
  66073. var hasLink = false;
  66074. forEachEdgeType(function (edgeType) {
  66075. each$1(edgeIdGetter(node, edgeType) || [], function (edgeId) {
  66076. result.records[edgeType.name][edgeId] && (hasLink = true);
  66077. });
  66078. });
  66079. return hasLink;
  66080. }
  66081. function absorb(node, result) {
  66082. result.nodes.push(node);
  66083. forEachEdgeType(function (edgeType) {
  66084. each$1(edgeIdGetter(node, edgeType) || [], function (edgeId) {
  66085. result.records[edgeType.name][edgeId] = true;
  66086. });
  66087. });
  66088. }
  66089. }
  66090. /*
  66091. * Licensed to the Apache Software Foundation (ASF) under one
  66092. * or more contributor license agreements. See the NOTICE file
  66093. * distributed with this work for additional information
  66094. * regarding copyright ownership. The ASF licenses this file
  66095. * to you under the Apache License, Version 2.0 (the
  66096. * "License"); you may not use this file except in compliance
  66097. * with the License. You may obtain a copy of the License at
  66098. *
  66099. * http://www.apache.org/licenses/LICENSE-2.0
  66100. *
  66101. * Unless required by applicable law or agreed to in writing,
  66102. * software distributed under the License is distributed on an
  66103. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66104. * KIND, either express or implied. See the License for the
  66105. * specific language governing permissions and limitations
  66106. * under the License.
  66107. */
  66108. var each$22 = each$1;
  66109. var asc$1 = asc;
  66110. /**
  66111. * Operate single axis.
  66112. * One axis can only operated by one axis operator.
  66113. * Different dataZoomModels may be defined to operate the same axis.
  66114. * (i.e. 'inside' data zoom and 'slider' data zoom components)
  66115. * So dataZoomModels share one axisProxy in that case.
  66116. *
  66117. * @class
  66118. */
  66119. var AxisProxy = function (dimName, axisIndex, dataZoomModel, ecModel) {
  66120. /**
  66121. * @private
  66122. * @type {string}
  66123. */
  66124. this._dimName = dimName;
  66125. /**
  66126. * @private
  66127. */
  66128. this._axisIndex = axisIndex;
  66129. /**
  66130. * @private
  66131. * @type {Array.<number>}
  66132. */
  66133. this._valueWindow;
  66134. /**
  66135. * @private
  66136. * @type {Array.<number>}
  66137. */
  66138. this._percentWindow;
  66139. /**
  66140. * @private
  66141. * @type {Array.<number>}
  66142. */
  66143. this._dataExtent;
  66144. /**
  66145. * {minSpan, maxSpan, minValueSpan, maxValueSpan}
  66146. * @private
  66147. * @type {Object}
  66148. */
  66149. this._minMaxSpan;
  66150. /**
  66151. * @readOnly
  66152. * @type {module: echarts/model/Global}
  66153. */
  66154. this.ecModel = ecModel;
  66155. /**
  66156. * @private
  66157. * @type {module: echarts/component/dataZoom/DataZoomModel}
  66158. */
  66159. this._dataZoomModel = dataZoomModel;
  66160. // /**
  66161. // * @readOnly
  66162. // * @private
  66163. // */
  66164. // this.hasSeriesStacked;
  66165. };
  66166. AxisProxy.prototype = {
  66167. constructor: AxisProxy,
  66168. /**
  66169. * Whether the axisProxy is hosted by dataZoomModel.
  66170. *
  66171. * @public
  66172. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  66173. * @return {boolean}
  66174. */
  66175. hostedBy: function (dataZoomModel) {
  66176. return this._dataZoomModel === dataZoomModel;
  66177. },
  66178. /**
  66179. * @return {Array.<number>} Value can only be NaN or finite value.
  66180. */
  66181. getDataValueWindow: function () {
  66182. return this._valueWindow.slice();
  66183. },
  66184. /**
  66185. * @return {Array.<number>}
  66186. */
  66187. getDataPercentWindow: function () {
  66188. return this._percentWindow.slice();
  66189. },
  66190. /**
  66191. * @public
  66192. * @param {number} axisIndex
  66193. * @return {Array} seriesModels
  66194. */
  66195. getTargetSeriesModels: function () {
  66196. var seriesModels = [];
  66197. var ecModel = this.ecModel;
  66198. ecModel.eachSeries(function (seriesModel) {
  66199. if (isCoordSupported(seriesModel.get('coordinateSystem'))) {
  66200. var dimName = this._dimName;
  66201. var axisModel = ecModel.queryComponents({
  66202. mainType: dimName + 'Axis',
  66203. index: seriesModel.get(dimName + 'AxisIndex'),
  66204. id: seriesModel.get(dimName + 'AxisId')
  66205. })[0];
  66206. if (this._axisIndex === (axisModel && axisModel.componentIndex)) {
  66207. seriesModels.push(seriesModel);
  66208. }
  66209. }
  66210. }, this);
  66211. return seriesModels;
  66212. },
  66213. getAxisModel: function () {
  66214. return this.ecModel.getComponent(this._dimName + 'Axis', this._axisIndex);
  66215. },
  66216. getOtherAxisModel: function () {
  66217. var axisDim = this._dimName;
  66218. var ecModel = this.ecModel;
  66219. var axisModel = this.getAxisModel();
  66220. var isCartesian = axisDim === 'x' || axisDim === 'y';
  66221. var otherAxisDim;
  66222. var coordSysIndexName;
  66223. if (isCartesian) {
  66224. coordSysIndexName = 'gridIndex';
  66225. otherAxisDim = axisDim === 'x' ? 'y' : 'x';
  66226. }
  66227. else {
  66228. coordSysIndexName = 'polarIndex';
  66229. otherAxisDim = axisDim === 'angle' ? 'radius' : 'angle';
  66230. }
  66231. var foundOtherAxisModel;
  66232. ecModel.eachComponent(otherAxisDim + 'Axis', function (otherAxisModel) {
  66233. if ((otherAxisModel.get(coordSysIndexName) || 0)
  66234. === (axisModel.get(coordSysIndexName) || 0)
  66235. ) {
  66236. foundOtherAxisModel = otherAxisModel;
  66237. }
  66238. });
  66239. return foundOtherAxisModel;
  66240. },
  66241. getMinMaxSpan: function () {
  66242. return clone(this._minMaxSpan);
  66243. },
  66244. /**
  66245. * Only calculate by given range and this._dataExtent, do not change anything.
  66246. *
  66247. * @param {Object} opt
  66248. * @param {number} [opt.start]
  66249. * @param {number} [opt.end]
  66250. * @param {number} [opt.startValue]
  66251. * @param {number} [opt.endValue]
  66252. */
  66253. calculateDataWindow: function (opt) {
  66254. var dataExtent = this._dataExtent;
  66255. var axisModel = this.getAxisModel();
  66256. var scale = axisModel.axis.scale;
  66257. var rangePropMode = this._dataZoomModel.getRangePropMode();
  66258. var percentExtent = [0, 100];
  66259. var percentWindow = [
  66260. opt.start,
  66261. opt.end
  66262. ];
  66263. var valueWindow = [];
  66264. each$22(['startValue', 'endValue'], function (prop) {
  66265. valueWindow.push(opt[prop] != null ? scale.parse(opt[prop]) : null);
  66266. });
  66267. // Normalize bound.
  66268. each$22([0, 1], function (idx) {
  66269. var boundValue = valueWindow[idx];
  66270. var boundPercent = percentWindow[idx];
  66271. // Notice: dataZoom is based either on `percentProp` ('start', 'end') or
  66272. // on `valueProp` ('startValue', 'endValue'). The former one is suitable
  66273. // for cases that a dataZoom component controls multiple axes with different
  66274. // unit or extent, and the latter one is suitable for accurate zoom by pixel
  66275. // (e.g., in dataZoomSelect). `valueProp` can be calculated from `percentProp`,
  66276. // but it is awkward that `percentProp` can not be obtained from `valueProp`
  66277. // accurately (because all of values that are overflow the `dataExtent` will
  66278. // be calculated to percent '100%'). So we have to use
  66279. // `dataZoom.getRangePropMode()` to mark which prop is used.
  66280. // `rangePropMode` is updated only when setOption or dispatchAction, otherwise
  66281. // it remains its original value.
  66282. if (rangePropMode[idx] === 'percent') {
  66283. if (boundPercent == null) {
  66284. boundPercent = percentExtent[idx];
  66285. }
  66286. // Use scale.parse to math round for category or time axis.
  66287. boundValue = scale.parse(linearMap(
  66288. boundPercent, percentExtent, dataExtent, true
  66289. ));
  66290. }
  66291. else {
  66292. // Calculating `percent` from `value` may be not accurate, because
  66293. // This calculation can not be inversed, because all of values that
  66294. // are overflow the `dataExtent` will be calculated to percent '100%'
  66295. boundPercent = linearMap(
  66296. boundValue, dataExtent, percentExtent, true
  66297. );
  66298. }
  66299. // valueWindow[idx] = round(boundValue);
  66300. // percentWindow[idx] = round(boundPercent);
  66301. valueWindow[idx] = boundValue;
  66302. percentWindow[idx] = boundPercent;
  66303. });
  66304. return {
  66305. valueWindow: asc$1(valueWindow),
  66306. percentWindow: asc$1(percentWindow)
  66307. };
  66308. },
  66309. /**
  66310. * Notice: reset should not be called before series.restoreData() called,
  66311. * so it is recommanded to be called in "process stage" but not "model init
  66312. * stage".
  66313. *
  66314. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  66315. */
  66316. reset: function (dataZoomModel) {
  66317. if (dataZoomModel !== this._dataZoomModel) {
  66318. return;
  66319. }
  66320. var targetSeries = this.getTargetSeriesModels();
  66321. // Culculate data window and data extent, and record them.
  66322. this._dataExtent = calculateDataExtent(this, this._dimName, targetSeries);
  66323. // this.hasSeriesStacked = false;
  66324. // each(targetSeries, function (series) {
  66325. // var data = series.getData();
  66326. // var dataDim = data.mapDimension(this._dimName);
  66327. // var stackedDimension = data.getCalculationInfo('stackedDimension');
  66328. // if (stackedDimension && stackedDimension === dataDim) {
  66329. // this.hasSeriesStacked = true;
  66330. // }
  66331. // }, this);
  66332. var dataWindow = this.calculateDataWindow(dataZoomModel.option);
  66333. this._valueWindow = dataWindow.valueWindow;
  66334. this._percentWindow = dataWindow.percentWindow;
  66335. setMinMaxSpan(this);
  66336. // Update axis setting then.
  66337. setAxisModel(this);
  66338. },
  66339. /**
  66340. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  66341. */
  66342. restore: function (dataZoomModel) {
  66343. if (dataZoomModel !== this._dataZoomModel) {
  66344. return;
  66345. }
  66346. this._valueWindow = this._percentWindow = null;
  66347. setAxisModel(this, true);
  66348. },
  66349. /**
  66350. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  66351. */
  66352. filterData: function (dataZoomModel, api) {
  66353. if (dataZoomModel !== this._dataZoomModel) {
  66354. return;
  66355. }
  66356. var axisDim = this._dimName;
  66357. var seriesModels = this.getTargetSeriesModels();
  66358. var filterMode = dataZoomModel.get('filterMode');
  66359. var valueWindow = this._valueWindow;
  66360. if (filterMode === 'none') {
  66361. return;
  66362. }
  66363. // FIXME
  66364. // Toolbox may has dataZoom injected. And if there are stacked bar chart
  66365. // with NaN data, NaN will be filtered and stack will be wrong.
  66366. // So we need to force the mode to be set empty.
  66367. // In fect, it is not a big deal that do not support filterMode-'filter'
  66368. // when using toolbox#dataZoom, utill tooltip#dataZoom support "single axis
  66369. // selection" some day, which might need "adapt to data extent on the
  66370. // otherAxis", which is disabled by filterMode-'empty'.
  66371. // But currently, stack has been fixed to based on value but not index,
  66372. // so this is not an issue any more.
  66373. // var otherAxisModel = this.getOtherAxisModel();
  66374. // if (dataZoomModel.get('$fromToolbox')
  66375. // && otherAxisModel
  66376. // && otherAxisModel.hasSeriesStacked
  66377. // ) {
  66378. // filterMode = 'empty';
  66379. // }
  66380. // TODO
  66381. // filterMode 'weakFilter' and 'empty' is not optimized for huge data yet.
  66382. // Process series data
  66383. each$22(seriesModels, function (seriesModel) {
  66384. var seriesData = seriesModel.getData();
  66385. var dataDims = seriesData.mapDimension(axisDim, true);
  66386. if (filterMode === 'weakFilter') {
  66387. seriesData.filterSelf(function (dataIndex) {
  66388. var leftOut;
  66389. var rightOut;
  66390. var hasValue;
  66391. for (var i = 0; i < dataDims.length; i++) {
  66392. var value = seriesData.get(dataDims[i], dataIndex);
  66393. var thisHasValue = !isNaN(value);
  66394. var thisLeftOut = value < valueWindow[0];
  66395. var thisRightOut = value > valueWindow[1];
  66396. if (thisHasValue && !thisLeftOut && !thisRightOut) {
  66397. return true;
  66398. }
  66399. thisHasValue && (hasValue = true);
  66400. thisLeftOut && (leftOut = true);
  66401. thisRightOut && (rightOut = true);
  66402. }
  66403. // If both left out and right out, do not filter.
  66404. return hasValue && leftOut && rightOut;
  66405. });
  66406. }
  66407. else {
  66408. each$22(dataDims, function (dim) {
  66409. if (filterMode === 'empty') {
  66410. seriesModel.setData(
  66411. seriesData.map(dim, function (value) {
  66412. return !isInWindow(value) ? NaN : value;
  66413. })
  66414. );
  66415. }
  66416. else {
  66417. var range = {};
  66418. range[dim] = valueWindow;
  66419. // console.time('select');
  66420. seriesData.selectRange(range);
  66421. // console.timeEnd('select');
  66422. }
  66423. });
  66424. }
  66425. each$22(dataDims, function (dim) {
  66426. seriesData.setApproximateExtent(valueWindow, dim);
  66427. });
  66428. });
  66429. function isInWindow(value) {
  66430. return value >= valueWindow[0] && value <= valueWindow[1];
  66431. }
  66432. }
  66433. };
  66434. function calculateDataExtent(axisProxy, axisDim, seriesModels) {
  66435. var dataExtent = [Infinity, -Infinity];
  66436. each$22(seriesModels, function (seriesModel) {
  66437. var seriesData = seriesModel.getData();
  66438. if (seriesData) {
  66439. each$22(seriesData.mapDimension(axisDim, true), function (dim) {
  66440. var seriesExtent = seriesData.getApproximateExtent(dim);
  66441. seriesExtent[0] < dataExtent[0] && (dataExtent[0] = seriesExtent[0]);
  66442. seriesExtent[1] > dataExtent[1] && (dataExtent[1] = seriesExtent[1]);
  66443. });
  66444. }
  66445. });
  66446. if (dataExtent[1] < dataExtent[0]) {
  66447. dataExtent = [NaN, NaN];
  66448. }
  66449. // It is important to get "consistent" extent when more then one axes is
  66450. // controlled by a `dataZoom`, otherwise those axes will not be synchronized
  66451. // when zooming. But it is difficult to know what is "consistent", considering
  66452. // axes have different type or even different meanings (For example, two
  66453. // time axes are used to compare data of the same date in different years).
  66454. // So basically dataZoom just obtains extent by series.data (in category axis
  66455. // extent can be obtained from axis.data).
  66456. // Nevertheless, user can set min/max/scale on axes to make extent of axes
  66457. // consistent.
  66458. fixExtentByAxis(axisProxy, dataExtent);
  66459. return dataExtent;
  66460. }
  66461. function fixExtentByAxis(axisProxy, dataExtent) {
  66462. var axisModel = axisProxy.getAxisModel();
  66463. var min = axisModel.getMin(true);
  66464. // For category axis, if min/max/scale are not set, extent is determined
  66465. // by axis.data by default.
  66466. var isCategoryAxis = axisModel.get('type') === 'category';
  66467. var axisDataLen = isCategoryAxis && axisModel.getCategories().length;
  66468. if (min != null && min !== 'dataMin' && typeof min !== 'function') {
  66469. dataExtent[0] = min;
  66470. }
  66471. else if (isCategoryAxis) {
  66472. dataExtent[0] = axisDataLen > 0 ? 0 : NaN;
  66473. }
  66474. var max = axisModel.getMax(true);
  66475. if (max != null && max !== 'dataMax' && typeof max !== 'function') {
  66476. dataExtent[1] = max;
  66477. }
  66478. else if (isCategoryAxis) {
  66479. dataExtent[1] = axisDataLen > 0 ? axisDataLen - 1 : NaN;
  66480. }
  66481. if (!axisModel.get('scale', true)) {
  66482. dataExtent[0] > 0 && (dataExtent[0] = 0);
  66483. dataExtent[1] < 0 && (dataExtent[1] = 0);
  66484. }
  66485. // For value axis, if min/max/scale are not set, we just use the extent obtained
  66486. // by series data, which may be a little different from the extent calculated by
  66487. // `axisHelper.getScaleExtent`. But the different just affects the experience a
  66488. // little when zooming. So it will not be fixed until some users require it strongly.
  66489. return dataExtent;
  66490. }
  66491. function setAxisModel(axisProxy, isRestore) {
  66492. var axisModel = axisProxy.getAxisModel();
  66493. var percentWindow = axisProxy._percentWindow;
  66494. var valueWindow = axisProxy._valueWindow;
  66495. if (!percentWindow) {
  66496. return;
  66497. }
  66498. // [0, 500]: arbitrary value, guess axis extent.
  66499. var precision = getPixelPrecision(valueWindow, [0, 500]);
  66500. precision = Math.min(precision, 20);
  66501. // isRestore or isFull
  66502. var useOrigin = isRestore || (percentWindow[0] === 0 && percentWindow[1] === 100);
  66503. axisModel.setRange(
  66504. useOrigin ? null : +valueWindow[0].toFixed(precision),
  66505. useOrigin ? null : +valueWindow[1].toFixed(precision)
  66506. );
  66507. }
  66508. function setMinMaxSpan(axisProxy) {
  66509. var minMaxSpan = axisProxy._minMaxSpan = {};
  66510. var dataZoomModel = axisProxy._dataZoomModel;
  66511. each$22(['min', 'max'], function (minMax) {
  66512. minMaxSpan[minMax + 'Span'] = dataZoomModel.get(minMax + 'Span');
  66513. // minValueSpan and maxValueSpan has higher priority than minSpan and maxSpan
  66514. var valueSpan = dataZoomModel.get(minMax + 'ValueSpan');
  66515. if (valueSpan != null) {
  66516. minMaxSpan[minMax + 'ValueSpan'] = valueSpan;
  66517. valueSpan = axisProxy.getAxisModel().axis.scale.parse(valueSpan);
  66518. if (valueSpan != null) {
  66519. var dataExtent = axisProxy._dataExtent;
  66520. minMaxSpan[minMax + 'Span'] = linearMap(
  66521. dataExtent[0] + valueSpan, dataExtent, [0, 100], true
  66522. );
  66523. }
  66524. }
  66525. });
  66526. }
  66527. /*
  66528. * Licensed to the Apache Software Foundation (ASF) under one
  66529. * or more contributor license agreements. See the NOTICE file
  66530. * distributed with this work for additional information
  66531. * regarding copyright ownership. The ASF licenses this file
  66532. * to you under the Apache License, Version 2.0 (the
  66533. * "License"); you may not use this file except in compliance
  66534. * with the License. You may obtain a copy of the License at
  66535. *
  66536. * http://www.apache.org/licenses/LICENSE-2.0
  66537. *
  66538. * Unless required by applicable law or agreed to in writing,
  66539. * software distributed under the License is distributed on an
  66540. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66541. * KIND, either express or implied. See the License for the
  66542. * specific language governing permissions and limitations
  66543. * under the License.
  66544. */
  66545. var each$21 = each$1;
  66546. var eachAxisDim = eachAxisDim$1;
  66547. var DataZoomModel = extendComponentModel({
  66548. type: 'dataZoom',
  66549. dependencies: [
  66550. 'xAxis', 'yAxis', 'zAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'series'
  66551. ],
  66552. /**
  66553. * @protected
  66554. */
  66555. defaultOption: {
  66556. zlevel: 0,
  66557. z: 4, // Higher than normal component (z: 2).
  66558. orient: null, // Default auto by axisIndex. Possible value: 'horizontal', 'vertical'.
  66559. xAxisIndex: null, // Default the first horizontal category axis.
  66560. yAxisIndex: null, // Default the first vertical category axis.
  66561. filterMode: 'filter', // Possible values: 'filter' or 'empty' or 'weakFilter'.
  66562. // 'filter': data items which are out of window will be removed. This option is
  66563. // applicable when filtering outliers. For each data item, it will be
  66564. // filtered if one of the relevant dimensions is out of the window.
  66565. // 'weakFilter': data items which are out of window will be removed. This option
  66566. // is applicable when filtering outliers. For each data item, it will be
  66567. // filtered only if all of the relevant dimensions are out of the same
  66568. // side of the window.
  66569. // 'empty': data items which are out of window will be set to empty.
  66570. // This option is applicable when user should not neglect
  66571. // that there are some data items out of window.
  66572. // 'none': Do not filter.
  66573. // Taking line chart as an example, line will be broken in
  66574. // the filtered points when filterModel is set to 'empty', but
  66575. // be connected when set to 'filter'.
  66576. throttle: null, // Dispatch action by the fixed rate, avoid frequency.
  66577. // default 100. Do not throttle when use null/undefined.
  66578. // If animation === true and animationDurationUpdate > 0,
  66579. // default value is 100, otherwise 20.
  66580. start: 0, // Start percent. 0 ~ 100
  66581. end: 100, // End percent. 0 ~ 100
  66582. startValue: null, // Start value. If startValue specified, start is ignored.
  66583. endValue: null, // End value. If endValue specified, end is ignored.
  66584. minSpan: null, // 0 ~ 100
  66585. maxSpan: null, // 0 ~ 100
  66586. minValueSpan: null, // The range of dataZoom can not be smaller than that.
  66587. maxValueSpan: null, // The range of dataZoom can not be larger than that.
  66588. rangeMode: null // Array, can be 'value' or 'percent'.
  66589. },
  66590. /**
  66591. * @override
  66592. */
  66593. init: function (option, parentModel, ecModel) {
  66594. /**
  66595. * key like x_0, y_1
  66596. * @private
  66597. * @type {Object}
  66598. */
  66599. this._dataIntervalByAxis = {};
  66600. /**
  66601. * @private
  66602. */
  66603. this._dataInfo = {};
  66604. /**
  66605. * key like x_0, y_1
  66606. * @private
  66607. */
  66608. this._axisProxies = {};
  66609. /**
  66610. * @readOnly
  66611. */
  66612. this.textStyleModel;
  66613. /**
  66614. * @private
  66615. */
  66616. this._autoThrottle = true;
  66617. /**
  66618. * 'percent' or 'value'
  66619. * @private
  66620. */
  66621. this._rangePropMode = ['percent', 'percent'];
  66622. var rawOption = retrieveRaw(option);
  66623. this.mergeDefaultAndTheme(option, ecModel);
  66624. this.doInit(rawOption);
  66625. },
  66626. /**
  66627. * @override
  66628. */
  66629. mergeOption: function (newOption) {
  66630. var rawOption = retrieveRaw(newOption);
  66631. //FIX #2591
  66632. merge(this.option, newOption, true);
  66633. this.doInit(rawOption);
  66634. },
  66635. /**
  66636. * @protected
  66637. */
  66638. doInit: function (rawOption) {
  66639. var thisOption = this.option;
  66640. // Disable realtime view update if canvas is not supported.
  66641. if (!env$1.canvasSupported) {
  66642. thisOption.realtime = false;
  66643. }
  66644. this._setDefaultThrottle(rawOption);
  66645. updateRangeUse(this, rawOption);
  66646. each$21([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  66647. // start/end has higher priority over startValue/endValue if they
  66648. // both set, but we should make chart.setOption({endValue: 1000})
  66649. // effective, rather than chart.setOption({endValue: 1000, end: null}).
  66650. if (this._rangePropMode[index] === 'value') {
  66651. thisOption[names[0]] = null;
  66652. }
  66653. // Otherwise do nothing and use the merge result.
  66654. }, this);
  66655. this.textStyleModel = this.getModel('textStyle');
  66656. this._resetTarget();
  66657. this._giveAxisProxies();
  66658. },
  66659. /**
  66660. * @private
  66661. */
  66662. _giveAxisProxies: function () {
  66663. var axisProxies = this._axisProxies;
  66664. this.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel, ecModel) {
  66665. var axisModel = this.dependentModels[dimNames.axis][axisIndex];
  66666. // If exists, share axisProxy with other dataZoomModels.
  66667. var axisProxy = axisModel.__dzAxisProxy || (
  66668. // Use the first dataZoomModel as the main model of axisProxy.
  66669. axisModel.__dzAxisProxy = new AxisProxy(
  66670. dimNames.name, axisIndex, this, ecModel
  66671. )
  66672. );
  66673. // FIXME
  66674. // dispose __dzAxisProxy
  66675. axisProxies[dimNames.name + '_' + axisIndex] = axisProxy;
  66676. }, this);
  66677. },
  66678. /**
  66679. * @private
  66680. */
  66681. _resetTarget: function () {
  66682. var thisOption = this.option;
  66683. var autoMode = this._judgeAutoMode();
  66684. eachAxisDim(function (dimNames) {
  66685. var axisIndexName = dimNames.axisIndex;
  66686. thisOption[axisIndexName] = normalizeToArray(
  66687. thisOption[axisIndexName]
  66688. );
  66689. }, this);
  66690. if (autoMode === 'axisIndex') {
  66691. this._autoSetAxisIndex();
  66692. }
  66693. else if (autoMode === 'orient') {
  66694. this._autoSetOrient();
  66695. }
  66696. },
  66697. /**
  66698. * @private
  66699. */
  66700. _judgeAutoMode: function () {
  66701. // Auto set only works for setOption at the first time.
  66702. // The following is user's reponsibility. So using merged
  66703. // option is OK.
  66704. var thisOption = this.option;
  66705. var hasIndexSpecified = false;
  66706. eachAxisDim(function (dimNames) {
  66707. // When user set axisIndex as a empty array, we think that user specify axisIndex
  66708. // but do not want use auto mode. Because empty array may be encountered when
  66709. // some error occured.
  66710. if (thisOption[dimNames.axisIndex] != null) {
  66711. hasIndexSpecified = true;
  66712. }
  66713. }, this);
  66714. var orient = thisOption.orient;
  66715. if (orient == null && hasIndexSpecified) {
  66716. return 'orient';
  66717. }
  66718. else if (!hasIndexSpecified) {
  66719. if (orient == null) {
  66720. thisOption.orient = 'horizontal';
  66721. }
  66722. return 'axisIndex';
  66723. }
  66724. },
  66725. /**
  66726. * @private
  66727. */
  66728. _autoSetAxisIndex: function () {
  66729. var autoAxisIndex = true;
  66730. var orient = this.get('orient', true);
  66731. var thisOption = this.option;
  66732. var dependentModels = this.dependentModels;
  66733. if (autoAxisIndex) {
  66734. // Find axis that parallel to dataZoom as default.
  66735. var dimName = orient === 'vertical' ? 'y' : 'x';
  66736. if (dependentModels[dimName + 'Axis'].length) {
  66737. thisOption[dimName + 'AxisIndex'] = [0];
  66738. autoAxisIndex = false;
  66739. }
  66740. else {
  66741. each$21(dependentModels.singleAxis, function (singleAxisModel) {
  66742. if (autoAxisIndex && singleAxisModel.get('orient', true) === orient) {
  66743. thisOption.singleAxisIndex = [singleAxisModel.componentIndex];
  66744. autoAxisIndex = false;
  66745. }
  66746. });
  66747. }
  66748. }
  66749. if (autoAxisIndex) {
  66750. // Find the first category axis as default. (consider polar)
  66751. eachAxisDim(function (dimNames) {
  66752. if (!autoAxisIndex) {
  66753. return;
  66754. }
  66755. var axisIndices = [];
  66756. var axisModels = this.dependentModels[dimNames.axis];
  66757. if (axisModels.length && !axisIndices.length) {
  66758. for (var i = 0, len = axisModels.length; i < len; i++) {
  66759. if (axisModels[i].get('type') === 'category') {
  66760. axisIndices.push(i);
  66761. }
  66762. }
  66763. }
  66764. thisOption[dimNames.axisIndex] = axisIndices;
  66765. if (axisIndices.length) {
  66766. autoAxisIndex = false;
  66767. }
  66768. }, this);
  66769. }
  66770. if (autoAxisIndex) {
  66771. // FIXME
  66772. // 这里是兼容ec2的写法(没指定xAxisIndex和yAxisIndex时把scatter和双数值轴折柱纳入dataZoom控制),
  66773. // 但是实际是否需要Grid.js#getScaleByOption来判断(考虑time,log等axis type)?
  66774. // If both dataZoom.xAxisIndex and dataZoom.yAxisIndex is not specified,
  66775. // dataZoom component auto adopts series that reference to
  66776. // both xAxis and yAxis which type is 'value'.
  66777. this.ecModel.eachSeries(function (seriesModel) {
  66778. if (this._isSeriesHasAllAxesTypeOf(seriesModel, 'value')) {
  66779. eachAxisDim(function (dimNames) {
  66780. var axisIndices = thisOption[dimNames.axisIndex];
  66781. var axisIndex = seriesModel.get(dimNames.axisIndex);
  66782. var axisId = seriesModel.get(dimNames.axisId);
  66783. var axisModel = seriesModel.ecModel.queryComponents({
  66784. mainType: dimNames.axis,
  66785. index: axisIndex,
  66786. id: axisId
  66787. })[0];
  66788. if (__DEV__) {
  66789. if (!axisModel) {
  66790. throw new Error(
  66791. dimNames.axis + ' "' + retrieve(
  66792. axisIndex,
  66793. axisId,
  66794. 0
  66795. ) + '" not found'
  66796. );
  66797. }
  66798. }
  66799. axisIndex = axisModel.componentIndex;
  66800. if (indexOf(axisIndices, axisIndex) < 0) {
  66801. axisIndices.push(axisIndex);
  66802. }
  66803. });
  66804. }
  66805. }, this);
  66806. }
  66807. },
  66808. /**
  66809. * @private
  66810. */
  66811. _autoSetOrient: function () {
  66812. var dim;
  66813. // Find the first axis
  66814. this.eachTargetAxis(function (dimNames) {
  66815. !dim && (dim = dimNames.name);
  66816. }, this);
  66817. this.option.orient = dim === 'y' ? 'vertical' : 'horizontal';
  66818. },
  66819. /**
  66820. * @private
  66821. */
  66822. _isSeriesHasAllAxesTypeOf: function (seriesModel, axisType) {
  66823. // FIXME
  66824. // 需要series的xAxisIndex和yAxisIndex都首先自动设置上。
  66825. // 例如series.type === scatter时。
  66826. var is = true;
  66827. eachAxisDim(function (dimNames) {
  66828. var seriesAxisIndex = seriesModel.get(dimNames.axisIndex);
  66829. var axisModel = this.dependentModels[dimNames.axis][seriesAxisIndex];
  66830. if (!axisModel || axisModel.get('type') !== axisType) {
  66831. is = false;
  66832. }
  66833. }, this);
  66834. return is;
  66835. },
  66836. /**
  66837. * @private
  66838. */
  66839. _setDefaultThrottle: function (rawOption) {
  66840. // When first time user set throttle, auto throttle ends.
  66841. if (rawOption.hasOwnProperty('throttle')) {
  66842. this._autoThrottle = false;
  66843. }
  66844. if (this._autoThrottle) {
  66845. var globalOption = this.ecModel.option;
  66846. this.option.throttle =
  66847. (globalOption.animation && globalOption.animationDurationUpdate > 0)
  66848. ? 100 : 20;
  66849. }
  66850. },
  66851. /**
  66852. * @public
  66853. */
  66854. getFirstTargetAxisModel: function () {
  66855. var firstAxisModel;
  66856. eachAxisDim(function (dimNames) {
  66857. if (firstAxisModel == null) {
  66858. var indices = this.get(dimNames.axisIndex);
  66859. if (indices.length) {
  66860. firstAxisModel = this.dependentModels[dimNames.axis][indices[0]];
  66861. }
  66862. }
  66863. }, this);
  66864. return firstAxisModel;
  66865. },
  66866. /**
  66867. * @public
  66868. * @param {Function} callback param: axisModel, dimNames, axisIndex, dataZoomModel, ecModel
  66869. */
  66870. eachTargetAxis: function (callback, context) {
  66871. var ecModel = this.ecModel;
  66872. eachAxisDim(function (dimNames) {
  66873. each$21(
  66874. this.get(dimNames.axisIndex),
  66875. function (axisIndex) {
  66876. callback.call(context, dimNames, axisIndex, this, ecModel);
  66877. },
  66878. this
  66879. );
  66880. }, this);
  66881. },
  66882. /**
  66883. * @param {string} dimName
  66884. * @param {number} axisIndex
  66885. * @return {module:echarts/component/dataZoom/AxisProxy} If not found, return null/undefined.
  66886. */
  66887. getAxisProxy: function (dimName, axisIndex) {
  66888. return this._axisProxies[dimName + '_' + axisIndex];
  66889. },
  66890. /**
  66891. * @param {string} dimName
  66892. * @param {number} axisIndex
  66893. * @return {module:echarts/model/Model} If not found, return null/undefined.
  66894. */
  66895. getAxisModel: function (dimName, axisIndex) {
  66896. var axisProxy = this.getAxisProxy(dimName, axisIndex);
  66897. return axisProxy && axisProxy.getAxisModel();
  66898. },
  66899. /**
  66900. * If not specified, set to undefined.
  66901. *
  66902. * @public
  66903. * @param {Object} opt
  66904. * @param {number} [opt.start]
  66905. * @param {number} [opt.end]
  66906. * @param {number} [opt.startValue]
  66907. * @param {number} [opt.endValue]
  66908. * @param {boolean} [ignoreUpdateRangeUsg=false]
  66909. */
  66910. setRawRange: function (opt, ignoreUpdateRangeUsg) {
  66911. var option = this.option;
  66912. each$21([['start', 'startValue'], ['end', 'endValue']], function (names) {
  66913. // If only one of 'start' and 'startValue' is not null/undefined, the other
  66914. // should be cleared, which enable clear the option.
  66915. // If both of them are not set, keep option with the original value, which
  66916. // enable use only set start but not set end when calling `dispatchAction`.
  66917. // The same as 'end' and 'endValue'.
  66918. if (opt[names[0]] != null || opt[names[1]] != null) {
  66919. option[names[0]] = opt[names[0]];
  66920. option[names[1]] = opt[names[1]];
  66921. }
  66922. }, this);
  66923. !ignoreUpdateRangeUsg && updateRangeUse(this, opt);
  66924. },
  66925. /**
  66926. * @public
  66927. * @return {Array.<number>} [startPercent, endPercent]
  66928. */
  66929. getPercentRange: function () {
  66930. var axisProxy = this.findRepresentativeAxisProxy();
  66931. if (axisProxy) {
  66932. return axisProxy.getDataPercentWindow();
  66933. }
  66934. },
  66935. /**
  66936. * @public
  66937. * For example, chart.getModel().getComponent('dataZoom').getValueRange('y', 0);
  66938. *
  66939. * @param {string} [axisDimName]
  66940. * @param {number} [axisIndex]
  66941. * @return {Array.<number>} [startValue, endValue] value can only be '-' or finite number.
  66942. */
  66943. getValueRange: function (axisDimName, axisIndex) {
  66944. if (axisDimName == null && axisIndex == null) {
  66945. var axisProxy = this.findRepresentativeAxisProxy();
  66946. if (axisProxy) {
  66947. return axisProxy.getDataValueWindow();
  66948. }
  66949. }
  66950. else {
  66951. return this.getAxisProxy(axisDimName, axisIndex).getDataValueWindow();
  66952. }
  66953. },
  66954. /**
  66955. * @public
  66956. * @param {module:echarts/model/Model} [axisModel] If axisModel given, find axisProxy
  66957. * corresponding to the axisModel
  66958. * @return {module:echarts/component/dataZoom/AxisProxy}
  66959. */
  66960. findRepresentativeAxisProxy: function (axisModel) {
  66961. if (axisModel) {
  66962. return axisModel.__dzAxisProxy;
  66963. }
  66964. // Find the first hosted axisProxy
  66965. var axisProxies = this._axisProxies;
  66966. for (var key in axisProxies) {
  66967. if (axisProxies.hasOwnProperty(key) && axisProxies[key].hostedBy(this)) {
  66968. return axisProxies[key];
  66969. }
  66970. }
  66971. // If no hosted axis find not hosted axisProxy.
  66972. // Consider this case: dataZoomModel1 and dataZoomModel2 control the same axis,
  66973. // and the option.start or option.end settings are different. The percentRange
  66974. // should follow axisProxy.
  66975. // (We encounter this problem in toolbox data zoom.)
  66976. for (var key in axisProxies) {
  66977. if (axisProxies.hasOwnProperty(key) && !axisProxies[key].hostedBy(this)) {
  66978. return axisProxies[key];
  66979. }
  66980. }
  66981. },
  66982. /**
  66983. * @return {Array.<string>}
  66984. */
  66985. getRangePropMode: function () {
  66986. return this._rangePropMode.slice();
  66987. }
  66988. });
  66989. function retrieveRaw(option) {
  66990. var ret = {};
  66991. each$21(
  66992. ['start', 'end', 'startValue', 'endValue', 'throttle'],
  66993. function (name) {
  66994. option.hasOwnProperty(name) && (ret[name] = option[name]);
  66995. }
  66996. );
  66997. return ret;
  66998. }
  66999. function updateRangeUse(dataZoomModel, rawOption) {
  67000. var rangePropMode = dataZoomModel._rangePropMode;
  67001. var rangeModeInOption = dataZoomModel.get('rangeMode');
  67002. each$21([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  67003. var percentSpecified = rawOption[names[0]] != null;
  67004. var valueSpecified = rawOption[names[1]] != null;
  67005. if (percentSpecified && !valueSpecified) {
  67006. rangePropMode[index] = 'percent';
  67007. }
  67008. else if (!percentSpecified && valueSpecified) {
  67009. rangePropMode[index] = 'value';
  67010. }
  67011. else if (rangeModeInOption) {
  67012. rangePropMode[index] = rangeModeInOption[index];
  67013. }
  67014. else if (percentSpecified) { // percentSpecified && valueSpecified
  67015. rangePropMode[index] = 'percent';
  67016. }
  67017. // else remain its original setting.
  67018. });
  67019. }
  67020. /*
  67021. * Licensed to the Apache Software Foundation (ASF) under one
  67022. * or more contributor license agreements. See the NOTICE file
  67023. * distributed with this work for additional information
  67024. * regarding copyright ownership. The ASF licenses this file
  67025. * to you under the Apache License, Version 2.0 (the
  67026. * "License"); you may not use this file except in compliance
  67027. * with the License. You may obtain a copy of the License at
  67028. *
  67029. * http://www.apache.org/licenses/LICENSE-2.0
  67030. *
  67031. * Unless required by applicable law or agreed to in writing,
  67032. * software distributed under the License is distributed on an
  67033. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  67034. * KIND, either express or implied. See the License for the
  67035. * specific language governing permissions and limitations
  67036. * under the License.
  67037. */
  67038. var DataZoomView = Component.extend({
  67039. type: 'dataZoom',
  67040. render: function (dataZoomModel, ecModel, api, payload) {
  67041. this.dataZoomModel = dataZoomModel;
  67042. this.ecModel = ecModel;
  67043. this.api = api;
  67044. },
  67045. /**
  67046. * Find the first target coordinate system.
  67047. *
  67048. * @protected
  67049. * @return {Object} {
  67050. * grid: [
  67051. * {model: coord0, axisModels: [axis1, axis3], coordIndex: 1},
  67052. * {model: coord1, axisModels: [axis0, axis2], coordIndex: 0},
  67053. * ...
  67054. * ], // cartesians must not be null/undefined.
  67055. * polar: [
  67056. * {model: coord0, axisModels: [axis4], coordIndex: 0},
  67057. * ...
  67058. * ], // polars must not be null/undefined.
  67059. * singleAxis: [
  67060. * {model: coord0, axisModels: [], coordIndex: 0}
  67061. * ]
  67062. */
  67063. getTargetCoordInfo: function () {
  67064. var dataZoomModel = this.dataZoomModel;
  67065. var ecModel = this.ecModel;
  67066. var coordSysLists = {};
  67067. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex) {
  67068. var axisModel = ecModel.getComponent(dimNames.axis, axisIndex);
  67069. if (axisModel) {
  67070. var coordModel = axisModel.getCoordSysModel();
  67071. coordModel && save(
  67072. coordModel,
  67073. axisModel,
  67074. coordSysLists[coordModel.mainType] || (coordSysLists[coordModel.mainType] = []),
  67075. coordModel.componentIndex
  67076. );
  67077. }
  67078. }, this);
  67079. function save(coordModel, axisModel, store, coordIndex) {
  67080. var item;
  67081. for (var i = 0; i < store.length; i++) {
  67082. if (store[i].model === coordModel) {
  67083. item = store[i];
  67084. break;
  67085. }
  67086. }
  67087. if (!item) {
  67088. store.push(item = {
  67089. model: coordModel, axisModels: [], coordIndex: coordIndex
  67090. });
  67091. }
  67092. item.axisModels.push(axisModel);
  67093. }
  67094. return coordSysLists;
  67095. }
  67096. });
  67097. /*
  67098. * Licensed to the Apache Software Foundation (ASF) under one
  67099. * or more contributor license agreements. See the NOTICE file
  67100. * distributed with this work for additional information
  67101. * regarding copyright ownership. The ASF licenses this file
  67102. * to you under the Apache License, Version 2.0 (the
  67103. * "License"); you may not use this file except in compliance
  67104. * with the License. You may obtain a copy of the License at
  67105. *
  67106. * http://www.apache.org/licenses/LICENSE-2.0
  67107. *
  67108. * Unless required by applicable law or agreed to in writing,
  67109. * software distributed under the License is distributed on an
  67110. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  67111. * KIND, either express or implied. See the License for the
  67112. * specific language governing permissions and limitations
  67113. * under the License.
  67114. */
  67115. var SliderZoomModel = DataZoomModel.extend({
  67116. type: 'dataZoom.slider',
  67117. layoutMode: 'box',
  67118. /**
  67119. * @protected
  67120. */
  67121. defaultOption: {
  67122. show: true,
  67123. // ph => placeholder. Using placehoder here because
  67124. // deault value can only be drived in view stage.
  67125. right: 'ph', // Default align to grid rect.
  67126. top: 'ph', // Default align to grid rect.
  67127. width: 'ph', // Default align to grid rect.
  67128. height: 'ph', // Default align to grid rect.
  67129. left: null, // Default align to grid rect.
  67130. bottom: null, // Default align to grid rect.
  67131. backgroundColor: 'rgba(47,69,84,0)', // Background of slider zoom component.
  67132. // dataBackgroundColor: '#ddd', // Background coor of data shadow and border of box,
  67133. // highest priority, remain for compatibility of
  67134. // previous version, but not recommended any more.
  67135. dataBackground: {
  67136. lineStyle: {
  67137. color: '#2f4554',
  67138. width: 0.5,
  67139. opacity: 0.3
  67140. },
  67141. areaStyle: {
  67142. color: 'rgba(47,69,84,0.3)',
  67143. opacity: 0.3
  67144. }
  67145. },
  67146. borderColor: '#ddd', // border color of the box. For compatibility,
  67147. // if dataBackgroundColor is set, borderColor
  67148. // is ignored.
  67149. fillerColor: 'rgba(167,183,204,0.4)', // Color of selected area.
  67150. // handleColor: 'rgba(89,170,216,0.95)', // Color of handle.
  67151. // 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',
  67152. 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',
  67153. // Percent of the slider height
  67154. handleSize: '100%',
  67155. handleStyle: {
  67156. color: '#a7b7cc'
  67157. },
  67158. labelPrecision: null,
  67159. labelFormatter: null,
  67160. showDetail: true,
  67161. showDataShadow: 'auto', // Default auto decision.
  67162. realtime: true,
  67163. zoomLock: false, // Whether disable zoom.
  67164. textStyle: {
  67165. color: '#333'
  67166. }
  67167. }
  67168. });
  67169. /*
  67170. * Licensed to the Apache Software Foundation (ASF) under one
  67171. * or more contributor license agreements. See the NOTICE file
  67172. * distributed with this work for additional information
  67173. * regarding copyright ownership. The ASF licenses this file
  67174. * to you under the Apache License, Version 2.0 (the
  67175. * "License"); you may not use this file except in compliance
  67176. * with the License. You may obtain a copy of the License at
  67177. *
  67178. * http://www.apache.org/licenses/LICENSE-2.0
  67179. *
  67180. * Unless required by applicable law or agreed to in writing,
  67181. * software distributed under the License is distributed on an
  67182. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  67183. * KIND, either express or implied. See the License for the
  67184. * specific language governing permissions and limitations
  67185. * under the License.
  67186. */
  67187. var Rect$2 = Rect;
  67188. var linearMap$1 = linearMap;
  67189. var asc$2 = asc;
  67190. var bind$4 = bind;
  67191. var each$23 = each$1;
  67192. // Constants
  67193. var DEFAULT_LOCATION_EDGE_GAP = 7;
  67194. var DEFAULT_FRAME_BORDER_WIDTH = 1;
  67195. var DEFAULT_FILLER_SIZE = 30;
  67196. var HORIZONTAL = 'horizontal';
  67197. var VERTICAL = 'vertical';
  67198. var LABEL_GAP = 5;
  67199. var SHOW_DATA_SHADOW_SERIES_TYPE = ['line', 'bar', 'candlestick', 'scatter'];
  67200. var SliderZoomView = DataZoomView.extend({
  67201. type: 'dataZoom.slider',
  67202. init: function (ecModel, api) {
  67203. /**
  67204. * @private
  67205. * @type {Object}
  67206. */
  67207. this._displayables = {};
  67208. /**
  67209. * @private
  67210. * @type {string}
  67211. */
  67212. this._orient;
  67213. /**
  67214. * [0, 100]
  67215. * @private
  67216. */
  67217. this._range;
  67218. /**
  67219. * [coord of the first handle, coord of the second handle]
  67220. * @private
  67221. */
  67222. this._handleEnds;
  67223. /**
  67224. * [length, thick]
  67225. * @private
  67226. * @type {Array.<number>}
  67227. */
  67228. this._size;
  67229. /**
  67230. * @private
  67231. * @type {number}
  67232. */
  67233. this._handleWidth;
  67234. /**
  67235. * @private
  67236. * @type {number}
  67237. */
  67238. this._handleHeight;
  67239. /**
  67240. * @private
  67241. */
  67242. this._location;
  67243. /**
  67244. * @private
  67245. */
  67246. this._dragging;
  67247. /**
  67248. * @private
  67249. */
  67250. this._dataShadowInfo;
  67251. this.api = api;
  67252. },
  67253. /**
  67254. * @override
  67255. */
  67256. render: function (dataZoomModel, ecModel, api, payload) {
  67257. SliderZoomView.superApply(this, 'render', arguments);
  67258. createOrUpdate(
  67259. this,
  67260. '_dispatchZoomAction',
  67261. this.dataZoomModel.get('throttle'),
  67262. 'fixRate'
  67263. );
  67264. this._orient = dataZoomModel.get('orient');
  67265. if (this.dataZoomModel.get('show') === false) {
  67266. this.group.removeAll();
  67267. return;
  67268. }
  67269. // Notice: this._resetInterval() should not be executed when payload.type
  67270. // is 'dataZoom', origin this._range should be maintained, otherwise 'pan'
  67271. // or 'zoom' info will be missed because of 'throttle' of this.dispatchAction,
  67272. if (!payload || payload.type !== 'dataZoom' || payload.from !== this.uid) {
  67273. this._buildView();
  67274. }
  67275. this._updateView();
  67276. },
  67277. /**
  67278. * @override
  67279. */
  67280. remove: function () {
  67281. SliderZoomView.superApply(this, 'remove', arguments);
  67282. clear(this, '_dispatchZoomAction');
  67283. },
  67284. /**
  67285. * @override
  67286. */
  67287. dispose: function () {
  67288. SliderZoomView.superApply(this, 'dispose', arguments);
  67289. clear(this, '_dispatchZoomAction');
  67290. },
  67291. _buildView: function () {
  67292. var thisGroup = this.group;
  67293. thisGroup.removeAll();
  67294. this._resetLocation();
  67295. this._resetInterval();
  67296. var barGroup = this._displayables.barGroup = new Group();
  67297. this._renderBackground();
  67298. this._renderHandle();
  67299. this._renderDataShadow();
  67300. thisGroup.add(barGroup);
  67301. this._positionGroup();
  67302. },
  67303. /**
  67304. * @private
  67305. */
  67306. _resetLocation: function () {
  67307. var dataZoomModel = this.dataZoomModel;
  67308. var api = this.api;
  67309. // If some of x/y/width/height are not specified,
  67310. // auto-adapt according to target grid.
  67311. var coordRect = this._findCoordRect();
  67312. var ecSize = {width: api.getWidth(), height: api.getHeight()};
  67313. // Default align by coordinate system rect.
  67314. var positionInfo = this._orient === HORIZONTAL
  67315. ? {
  67316. // Why using 'right', because right should be used in vertical,
  67317. // and it is better to be consistent for dealing with position param merge.
  67318. right: ecSize.width - coordRect.x - coordRect.width,
  67319. top: (ecSize.height - DEFAULT_FILLER_SIZE - DEFAULT_LOCATION_EDGE_GAP),
  67320. width: coordRect.width,
  67321. height: DEFAULT_FILLER_SIZE
  67322. }
  67323. : { // vertical
  67324. right: DEFAULT_LOCATION_EDGE_GAP,
  67325. top: coordRect.y,
  67326. width: DEFAULT_FILLER_SIZE,
  67327. height: coordRect.height
  67328. };
  67329. // Do not write back to option and replace value 'ph', because
  67330. // the 'ph' value should be recalculated when resize.
  67331. var layoutParams = getLayoutParams(dataZoomModel.option);
  67332. // Replace the placeholder value.
  67333. each$1(['right', 'top', 'width', 'height'], function (name) {
  67334. if (layoutParams[name] === 'ph') {
  67335. layoutParams[name] = positionInfo[name];
  67336. }
  67337. });
  67338. var layoutRect = getLayoutRect(
  67339. layoutParams,
  67340. ecSize,
  67341. dataZoomModel.padding
  67342. );
  67343. this._location = {x: layoutRect.x, y: layoutRect.y};
  67344. this._size = [layoutRect.width, layoutRect.height];
  67345. this._orient === VERTICAL && this._size.reverse();
  67346. },
  67347. /**
  67348. * @private
  67349. */
  67350. _positionGroup: function () {
  67351. var thisGroup = this.group;
  67352. var location = this._location;
  67353. var orient = this._orient;
  67354. // Just use the first axis to determine mapping.
  67355. var targetAxisModel = this.dataZoomModel.getFirstTargetAxisModel();
  67356. var inverse = targetAxisModel && targetAxisModel.get('inverse');
  67357. var barGroup = this._displayables.barGroup;
  67358. var otherAxisInverse = (this._dataShadowInfo || {}).otherAxisInverse;
  67359. // Transform barGroup.
  67360. barGroup.attr(
  67361. (orient === HORIZONTAL && !inverse)
  67362. ? {scale: otherAxisInverse ? [1, 1] : [1, -1]}
  67363. : (orient === HORIZONTAL && inverse)
  67364. ? {scale: otherAxisInverse ? [-1, 1] : [-1, -1]}
  67365. : (orient === VERTICAL && !inverse)
  67366. ? {scale: otherAxisInverse ? [1, -1] : [1, 1], rotation: Math.PI / 2}
  67367. // Dont use Math.PI, considering shadow direction.
  67368. : {scale: otherAxisInverse ? [-1, -1] : [-1, 1], rotation: Math.PI / 2}
  67369. );
  67370. // Position barGroup
  67371. var rect = thisGroup.getBoundingRect([barGroup]);
  67372. thisGroup.attr('position', [location.x - rect.x, location.y - rect.y]);
  67373. },
  67374. /**
  67375. * @private
  67376. */
  67377. _getViewExtent: function () {
  67378. return [0, this._size[0]];
  67379. },
  67380. _renderBackground: function () {
  67381. var dataZoomModel = this.dataZoomModel;
  67382. var size = this._size;
  67383. var barGroup = this._displayables.barGroup;
  67384. barGroup.add(new Rect$2({
  67385. silent: true,
  67386. shape: {
  67387. x: 0, y: 0, width: size[0], height: size[1]
  67388. },
  67389. style: {
  67390. fill: dataZoomModel.get('backgroundColor')
  67391. },
  67392. z2: -40
  67393. }));
  67394. // Click panel, over shadow, below handles.
  67395. barGroup.add(new Rect$2({
  67396. shape: {
  67397. x: 0, y: 0, width: size[0], height: size[1]
  67398. },
  67399. style: {
  67400. fill: 'transparent'
  67401. },
  67402. z2: 0,
  67403. onclick: bind(this._onClickPanelClick, this)
  67404. }));
  67405. },
  67406. _renderDataShadow: function () {
  67407. var info = this._dataShadowInfo = this._prepareDataShadowInfo();
  67408. if (!info) {
  67409. return;
  67410. }
  67411. var size = this._size;
  67412. var seriesModel = info.series;
  67413. var data = seriesModel.getRawData();
  67414. var otherDim = seriesModel.getShadowDim
  67415. ? seriesModel.getShadowDim() // @see candlestick
  67416. : info.otherDim;
  67417. if (otherDim == null) {
  67418. return;
  67419. }
  67420. var otherDataExtent = data.getDataExtent(otherDim);
  67421. // Nice extent.
  67422. var otherOffset = (otherDataExtent[1] - otherDataExtent[0]) * 0.3;
  67423. otherDataExtent = [
  67424. otherDataExtent[0] - otherOffset,
  67425. otherDataExtent[1] + otherOffset
  67426. ];
  67427. var otherShadowExtent = [0, size[1]];
  67428. var thisShadowExtent = [0, size[0]];
  67429. var areaPoints = [[size[0], 0], [0, 0]];
  67430. var linePoints = [];
  67431. var step = thisShadowExtent[1] / (data.count() - 1);
  67432. var thisCoord = 0;
  67433. // Optimize for large data shadow
  67434. var stride = Math.round(data.count() / size[0]);
  67435. var lastIsEmpty;
  67436. data.each([otherDim], function (value, index) {
  67437. if (stride > 0 && (index % stride)) {
  67438. thisCoord += step;
  67439. return;
  67440. }
  67441. // FIXME
  67442. // Should consider axis.min/axis.max when drawing dataShadow.
  67443. // FIXME
  67444. // 应该使用统一的空判断?还是在list里进行空判断?
  67445. var isEmpty = value == null || isNaN(value) || value === '';
  67446. // See #4235.
  67447. var otherCoord = isEmpty
  67448. ? 0 : linearMap$1(value, otherDataExtent, otherShadowExtent, true);
  67449. // Attempt to draw data shadow precisely when there are empty value.
  67450. if (isEmpty && !lastIsEmpty && index) {
  67451. areaPoints.push([areaPoints[areaPoints.length - 1][0], 0]);
  67452. linePoints.push([linePoints[linePoints.length - 1][0], 0]);
  67453. }
  67454. else if (!isEmpty && lastIsEmpty) {
  67455. areaPoints.push([thisCoord, 0]);
  67456. linePoints.push([thisCoord, 0]);
  67457. }
  67458. areaPoints.push([thisCoord, otherCoord]);
  67459. linePoints.push([thisCoord, otherCoord]);
  67460. thisCoord += step;
  67461. lastIsEmpty = isEmpty;
  67462. });
  67463. var dataZoomModel = this.dataZoomModel;
  67464. // var dataBackgroundModel = dataZoomModel.getModel('dataBackground');
  67465. this._displayables.barGroup.add(new Polygon({
  67466. shape: {points: areaPoints},
  67467. style: defaults(
  67468. {fill: dataZoomModel.get('dataBackgroundColor')},
  67469. dataZoomModel.getModel('dataBackground.areaStyle').getAreaStyle()
  67470. ),
  67471. silent: true,
  67472. z2: -20
  67473. }));
  67474. this._displayables.barGroup.add(new Polyline({
  67475. shape: {points: linePoints},
  67476. style: dataZoomModel.getModel('dataBackground.lineStyle').getLineStyle(),
  67477. silent: true,
  67478. z2: -19
  67479. }));
  67480. },
  67481. _prepareDataShadowInfo: function () {
  67482. var dataZoomModel = this.dataZoomModel;
  67483. var showDataShadow = dataZoomModel.get('showDataShadow');
  67484. if (showDataShadow === false) {
  67485. return;
  67486. }
  67487. // Find a representative series.
  67488. var result;
  67489. var ecModel = this.ecModel;
  67490. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex) {
  67491. var seriesModels = dataZoomModel
  67492. .getAxisProxy(dimNames.name, axisIndex)
  67493. .getTargetSeriesModels();
  67494. each$1(seriesModels, function (seriesModel) {
  67495. if (result) {
  67496. return;
  67497. }
  67498. if (showDataShadow !== true && indexOf(
  67499. SHOW_DATA_SHADOW_SERIES_TYPE, seriesModel.get('type')
  67500. ) < 0
  67501. ) {
  67502. return;
  67503. }
  67504. var thisAxis = ecModel.getComponent(dimNames.axis, axisIndex).axis;
  67505. var otherDim = getOtherDim(dimNames.name);
  67506. var otherAxisInverse;
  67507. var coordSys = seriesModel.coordinateSystem;
  67508. if (otherDim != null && coordSys.getOtherAxis) {
  67509. otherAxisInverse = coordSys.getOtherAxis(thisAxis).inverse;
  67510. }
  67511. otherDim = seriesModel.getData().mapDimension(otherDim);
  67512. result = {
  67513. thisAxis: thisAxis,
  67514. series: seriesModel,
  67515. thisDim: dimNames.name,
  67516. otherDim: otherDim,
  67517. otherAxisInverse: otherAxisInverse
  67518. };
  67519. }, this);
  67520. }, this);
  67521. return result;
  67522. },
  67523. _renderHandle: function () {
  67524. var displaybles = this._displayables;
  67525. var handles = displaybles.handles = [];
  67526. var handleLabels = displaybles.handleLabels = [];
  67527. var barGroup = this._displayables.barGroup;
  67528. var size = this._size;
  67529. var dataZoomModel = this.dataZoomModel;
  67530. barGroup.add(displaybles.filler = new Rect$2({
  67531. draggable: true,
  67532. cursor: getCursor(this._orient),
  67533. drift: bind$4(this._onDragMove, this, 'all'),
  67534. onmousemove: function (e) {
  67535. // Fot mobile devicem, prevent screen slider on the button.
  67536. stop(e.event);
  67537. },
  67538. ondragstart: bind$4(this._showDataInfo, this, true),
  67539. ondragend: bind$4(this._onDragEnd, this),
  67540. onmouseover: bind$4(this._showDataInfo, this, true),
  67541. onmouseout: bind$4(this._showDataInfo, this, false),
  67542. style: {
  67543. fill: dataZoomModel.get('fillerColor'),
  67544. textPosition : 'inside'
  67545. }
  67546. }));
  67547. // Frame border.
  67548. barGroup.add(new Rect$2(subPixelOptimizeRect({
  67549. silent: true,
  67550. shape: {
  67551. x: 0,
  67552. y: 0,
  67553. width: size[0],
  67554. height: size[1]
  67555. },
  67556. style: {
  67557. stroke: dataZoomModel.get('dataBackgroundColor')
  67558. || dataZoomModel.get('borderColor'),
  67559. lineWidth: DEFAULT_FRAME_BORDER_WIDTH,
  67560. fill: 'rgba(0,0,0,0)'
  67561. }
  67562. })));
  67563. each$23([0, 1], function (handleIndex) {
  67564. var path = createIcon(
  67565. dataZoomModel.get('handleIcon'),
  67566. {
  67567. cursor: getCursor(this._orient),
  67568. draggable: true,
  67569. drift: bind$4(this._onDragMove, this, handleIndex),
  67570. onmousemove: function (e) {
  67571. // Fot mobile devicem, prevent screen slider on the button.
  67572. stop(e.event);
  67573. },
  67574. ondragend: bind$4(this._onDragEnd, this),
  67575. onmouseover: bind$4(this._showDataInfo, this, true),
  67576. onmouseout: bind$4(this._showDataInfo, this, false)
  67577. },
  67578. {x: -1, y: 0, width: 2, height: 2}
  67579. );
  67580. var bRect = path.getBoundingRect();
  67581. this._handleHeight = parsePercent$1(dataZoomModel.get('handleSize'), this._size[1]);
  67582. this._handleWidth = bRect.width / bRect.height * this._handleHeight;
  67583. path.setStyle(dataZoomModel.getModel('handleStyle').getItemStyle());
  67584. var handleColor = dataZoomModel.get('handleColor');
  67585. // Compatitable with previous version
  67586. if (handleColor != null) {
  67587. path.style.fill = handleColor;
  67588. }
  67589. barGroup.add(handles[handleIndex] = path);
  67590. var textStyleModel = dataZoomModel.textStyleModel;
  67591. this.group.add(
  67592. handleLabels[handleIndex] = new Text({
  67593. silent: true,
  67594. invisible: true,
  67595. style: {
  67596. x: 0, y: 0, text: '',
  67597. textVerticalAlign: 'middle',
  67598. textAlign: 'center',
  67599. textFill: textStyleModel.getTextColor(),
  67600. textFont: textStyleModel.getFont()
  67601. },
  67602. z2: 10
  67603. }));
  67604. }, this);
  67605. },
  67606. /**
  67607. * @private
  67608. */
  67609. _resetInterval: function () {
  67610. var range = this._range = this.dataZoomModel.getPercentRange();
  67611. var viewExtent = this._getViewExtent();
  67612. this._handleEnds = [
  67613. linearMap$1(range[0], [0, 100], viewExtent, true),
  67614. linearMap$1(range[1], [0, 100], viewExtent, true)
  67615. ];
  67616. },
  67617. /**
  67618. * @private
  67619. * @param {(number|string)} handleIndex 0 or 1 or 'all'
  67620. * @param {number} delta
  67621. * @return {boolean} changed
  67622. */
  67623. _updateInterval: function (handleIndex, delta) {
  67624. var dataZoomModel = this.dataZoomModel;
  67625. var handleEnds = this._handleEnds;
  67626. var viewExtend = this._getViewExtent();
  67627. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  67628. var percentExtent = [0, 100];
  67629. sliderMove(
  67630. delta,
  67631. handleEnds,
  67632. viewExtend,
  67633. dataZoomModel.get('zoomLock') ? 'all' : handleIndex,
  67634. minMaxSpan.minSpan != null
  67635. ? linearMap$1(minMaxSpan.minSpan, percentExtent, viewExtend, true) : null,
  67636. minMaxSpan.maxSpan != null
  67637. ? linearMap$1(minMaxSpan.maxSpan, percentExtent, viewExtend, true) : null
  67638. );
  67639. var lastRange = this._range;
  67640. var range = this._range = asc$2([
  67641. linearMap$1(handleEnds[0], viewExtend, percentExtent, true),
  67642. linearMap$1(handleEnds[1], viewExtend, percentExtent, true)
  67643. ]);
  67644. return !lastRange || lastRange[0] !== range[0] || lastRange[1] !== range[1];
  67645. },
  67646. /**
  67647. * @private
  67648. */
  67649. _updateView: function (nonRealtime) {
  67650. var displaybles = this._displayables;
  67651. var handleEnds = this._handleEnds;
  67652. var handleInterval = asc$2(handleEnds.slice());
  67653. var size = this._size;
  67654. each$23([0, 1], function (handleIndex) {
  67655. // Handles
  67656. var handle = displaybles.handles[handleIndex];
  67657. var handleHeight = this._handleHeight;
  67658. handle.attr({
  67659. scale: [handleHeight / 2, handleHeight / 2],
  67660. position: [handleEnds[handleIndex], size[1] / 2 - handleHeight / 2]
  67661. });
  67662. }, this);
  67663. // Filler
  67664. displaybles.filler.setShape({
  67665. x: handleInterval[0],
  67666. y: 0,
  67667. width: handleInterval[1] - handleInterval[0],
  67668. height: size[1]
  67669. });
  67670. this._updateDataInfo(nonRealtime);
  67671. },
  67672. /**
  67673. * @private
  67674. */
  67675. _updateDataInfo: function (nonRealtime) {
  67676. var dataZoomModel = this.dataZoomModel;
  67677. var displaybles = this._displayables;
  67678. var handleLabels = displaybles.handleLabels;
  67679. var orient = this._orient;
  67680. var labelTexts = ['', ''];
  67681. // FIXME
  67682. // date型,支持formatter,autoformatter(ec2 date.getAutoFormatter)
  67683. if (dataZoomModel.get('showDetail')) {
  67684. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  67685. if (axisProxy) {
  67686. var axis = axisProxy.getAxisModel().axis;
  67687. var range = this._range;
  67688. var dataInterval = nonRealtime
  67689. // See #4434, data and axis are not processed and reset yet in non-realtime mode.
  67690. ? axisProxy.calculateDataWindow({
  67691. start: range[0], end: range[1]
  67692. }).valueWindow
  67693. : axisProxy.getDataValueWindow();
  67694. labelTexts = [
  67695. this._formatLabel(dataInterval[0], axis),
  67696. this._formatLabel(dataInterval[1], axis)
  67697. ];
  67698. }
  67699. }
  67700. var orderedHandleEnds = asc$2(this._handleEnds.slice());
  67701. setLabel.call(this, 0);
  67702. setLabel.call(this, 1);
  67703. function setLabel(handleIndex) {
  67704. // Label
  67705. // Text should not transform by barGroup.
  67706. // Ignore handlers transform
  67707. var barTransform = getTransform(
  67708. displaybles.handles[handleIndex].parent, this.group
  67709. );
  67710. var direction = transformDirection(
  67711. handleIndex === 0 ? 'right' : 'left', barTransform
  67712. );
  67713. var offset = this._handleWidth / 2 + LABEL_GAP;
  67714. var textPoint = applyTransform$1(
  67715. [
  67716. orderedHandleEnds[handleIndex] + (handleIndex === 0 ? -offset : offset),
  67717. this._size[1] / 2
  67718. ],
  67719. barTransform
  67720. );
  67721. handleLabels[handleIndex].setStyle({
  67722. x: textPoint[0],
  67723. y: textPoint[1],
  67724. textVerticalAlign: orient === HORIZONTAL ? 'middle' : direction,
  67725. textAlign: orient === HORIZONTAL ? direction : 'center',
  67726. text: labelTexts[handleIndex]
  67727. });
  67728. }
  67729. },
  67730. /**
  67731. * @private
  67732. */
  67733. _formatLabel: function (value, axis) {
  67734. var dataZoomModel = this.dataZoomModel;
  67735. var labelFormatter = dataZoomModel.get('labelFormatter');
  67736. var labelPrecision = dataZoomModel.get('labelPrecision');
  67737. if (labelPrecision == null || labelPrecision === 'auto') {
  67738. labelPrecision = axis.getPixelPrecision();
  67739. }
  67740. var valueStr = (value == null || isNaN(value))
  67741. ? ''
  67742. // FIXME Glue code
  67743. : (axis.type === 'category' || axis.type === 'time')
  67744. ? axis.scale.getLabel(Math.round(value))
  67745. // param of toFixed should less then 20.
  67746. : value.toFixed(Math.min(labelPrecision, 20));
  67747. return isFunction$1(labelFormatter)
  67748. ? labelFormatter(value, valueStr)
  67749. : isString(labelFormatter)
  67750. ? labelFormatter.replace('{value}', valueStr)
  67751. : valueStr;
  67752. },
  67753. /**
  67754. * @private
  67755. * @param {boolean} showOrHide true: show, false: hide
  67756. */
  67757. _showDataInfo: function (showOrHide) {
  67758. // Always show when drgging.
  67759. showOrHide = this._dragging || showOrHide;
  67760. var handleLabels = this._displayables.handleLabels;
  67761. handleLabels[0].attr('invisible', !showOrHide);
  67762. handleLabels[1].attr('invisible', !showOrHide);
  67763. },
  67764. _onDragMove: function (handleIndex, dx, dy) {
  67765. this._dragging = true;
  67766. // Transform dx, dy to bar coordination.
  67767. var barTransform = this._displayables.barGroup.getLocalTransform();
  67768. var vertex = applyTransform$1([dx, dy], barTransform, true);
  67769. var changed = this._updateInterval(handleIndex, vertex[0]);
  67770. var realtime = this.dataZoomModel.get('realtime');
  67771. this._updateView(!realtime);
  67772. // Avoid dispatch dataZoom repeatly but range not changed,
  67773. // which cause bad visual effect when progressive enabled.
  67774. changed && realtime && this._dispatchZoomAction();
  67775. },
  67776. _onDragEnd: function () {
  67777. this._dragging = false;
  67778. this._showDataInfo(false);
  67779. // While in realtime mode and stream mode, dispatch action when
  67780. // drag end will cause the whole view rerender, which is unnecessary.
  67781. var realtime = this.dataZoomModel.get('realtime');
  67782. !realtime && this._dispatchZoomAction();
  67783. },
  67784. _onClickPanelClick: function (e) {
  67785. var size = this._size;
  67786. var localPoint = this._displayables.barGroup.transformCoordToLocal(e.offsetX, e.offsetY);
  67787. if (localPoint[0] < 0 || localPoint[0] > size[0]
  67788. || localPoint[1] < 0 || localPoint[1] > size[1]
  67789. ) {
  67790. return;
  67791. }
  67792. var handleEnds = this._handleEnds;
  67793. var center = (handleEnds[0] + handleEnds[1]) / 2;
  67794. var changed = this._updateInterval('all', localPoint[0] - center);
  67795. this._updateView();
  67796. changed && this._dispatchZoomAction();
  67797. },
  67798. /**
  67799. * This action will be throttled.
  67800. * @private
  67801. */
  67802. _dispatchZoomAction: function () {
  67803. var range = this._range;
  67804. this.api.dispatchAction({
  67805. type: 'dataZoom',
  67806. from: this.uid,
  67807. dataZoomId: this.dataZoomModel.id,
  67808. start: range[0],
  67809. end: range[1]
  67810. });
  67811. },
  67812. /**
  67813. * @private
  67814. */
  67815. _findCoordRect: function () {
  67816. // Find the grid coresponding to the first axis referred by dataZoom.
  67817. var rect;
  67818. each$23(this.getTargetCoordInfo(), function (coordInfoList) {
  67819. if (!rect && coordInfoList.length) {
  67820. var coordSys = coordInfoList[0].model.coordinateSystem;
  67821. rect = coordSys.getRect && coordSys.getRect();
  67822. }
  67823. });
  67824. if (!rect) {
  67825. var width = this.api.getWidth();
  67826. var height = this.api.getHeight();
  67827. rect = {
  67828. x: width * 0.2,
  67829. y: height * 0.2,
  67830. width: width * 0.6,
  67831. height: height * 0.6
  67832. };
  67833. }
  67834. return rect;
  67835. }
  67836. });
  67837. function getOtherDim(thisDim) {
  67838. // FIXME
  67839. // 这个逻辑和getOtherAxis里一致,但是写在这里是否不好
  67840. var map$$1 = {x: 'y', y: 'x', radius: 'angle', angle: 'radius'};
  67841. return map$$1[thisDim];
  67842. }
  67843. function getCursor(orient) {
  67844. return orient === 'vertical' ? 'ns-resize' : 'ew-resize';
  67845. }
  67846. /*
  67847. * Licensed to the Apache Software Foundation (ASF) under one
  67848. * or more contributor license agreements. See the NOTICE file
  67849. * distributed with this work for additional information
  67850. * regarding copyright ownership. The ASF licenses this file
  67851. * to you under the Apache License, Version 2.0 (the
  67852. * "License"); you may not use this file except in compliance
  67853. * with the License. You may obtain a copy of the License at
  67854. *
  67855. * http://www.apache.org/licenses/LICENSE-2.0
  67856. *
  67857. * Unless required by applicable law or agreed to in writing,
  67858. * software distributed under the License is distributed on an
  67859. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  67860. * KIND, either express or implied. See the License for the
  67861. * specific language governing permissions and limitations
  67862. * under the License.
  67863. */
  67864. DataZoomModel.extend({
  67865. type: 'dataZoom.inside',
  67866. /**
  67867. * @protected
  67868. */
  67869. defaultOption: {
  67870. disabled: false, // Whether disable this inside zoom.
  67871. zoomLock: false, // Whether disable zoom but only pan.
  67872. zoomOnMouseWheel: true, // Can be: true / false / 'shift' / 'ctrl' / 'alt'.
  67873. moveOnMouseMove: true, // Can be: true / false / 'shift' / 'ctrl' / 'alt'.
  67874. preventDefaultMouseMove: true
  67875. }
  67876. });
  67877. /*
  67878. * Licensed to the Apache Software Foundation (ASF) under one
  67879. * or more contributor license agreements. See the NOTICE file
  67880. * distributed with this work for additional information
  67881. * regarding copyright ownership. The ASF licenses this file
  67882. * to you under the Apache License, Version 2.0 (the
  67883. * "License"); you may not use this file except in compliance
  67884. * with the License. You may obtain a copy of the License at
  67885. *
  67886. * http://www.apache.org/licenses/LICENSE-2.0
  67887. *
  67888. * Unless required by applicable law or agreed to in writing,
  67889. * software distributed under the License is distributed on an
  67890. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  67891. * KIND, either express or implied. See the License for the
  67892. * specific language governing permissions and limitations
  67893. * under the License.
  67894. */
  67895. // Only create one roam controller for each coordinate system.
  67896. // one roam controller might be refered by two inside data zoom
  67897. // components (for example, one for x and one for y). When user
  67898. // pan or zoom, only dispatch one action for those data zoom
  67899. // components.
  67900. var curry$6 = curry;
  67901. var ATTR$1 = '\0_ec_dataZoom_roams';
  67902. /**
  67903. * @public
  67904. * @param {module:echarts/ExtensionAPI} api
  67905. * @param {Object} dataZoomInfo
  67906. * @param {string} dataZoomInfo.coordId
  67907. * @param {Function} dataZoomInfo.containsPoint
  67908. * @param {Array.<string>} dataZoomInfo.allCoordIds
  67909. * @param {string} dataZoomInfo.dataZoomId
  67910. * @param {number} dataZoomInfo.throttleRate
  67911. * @param {Function} dataZoomInfo.panGetRange
  67912. * @param {Function} dataZoomInfo.zoomGetRange
  67913. * @param {boolean} [dataZoomInfo.zoomLock]
  67914. * @param {boolean} [dataZoomInfo.disabled]
  67915. */
  67916. function register$2(api, dataZoomInfo) {
  67917. var store = giveStore(api);
  67918. var theDataZoomId = dataZoomInfo.dataZoomId;
  67919. var theCoordId = dataZoomInfo.coordId;
  67920. // Do clean when a dataZoom changes its target coordnate system.
  67921. // Avoid memory leak, dispose all not-used-registered.
  67922. each$1(store, function (record, coordId) {
  67923. var dataZoomInfos = record.dataZoomInfos;
  67924. if (dataZoomInfos[theDataZoomId]
  67925. && indexOf(dataZoomInfo.allCoordIds, theCoordId) < 0
  67926. ) {
  67927. delete dataZoomInfos[theDataZoomId];
  67928. record.count--;
  67929. }
  67930. });
  67931. cleanStore(store);
  67932. var record = store[theCoordId];
  67933. // Create if needed.
  67934. if (!record) {
  67935. record = store[theCoordId] = {
  67936. coordId: theCoordId,
  67937. dataZoomInfos: {},
  67938. count: 0
  67939. };
  67940. record.controller = createController(api, record);
  67941. record.dispatchAction = curry(dispatchAction$1, api);
  67942. }
  67943. // Update reference of dataZoom.
  67944. !(record.dataZoomInfos[theDataZoomId]) && record.count++;
  67945. record.dataZoomInfos[theDataZoomId] = dataZoomInfo;
  67946. var controllerParams = mergeControllerParams(record.dataZoomInfos);
  67947. record.controller.enable(controllerParams.controlType, controllerParams.opt);
  67948. // Consider resize, area should be always updated.
  67949. record.controller.setPointerChecker(dataZoomInfo.containsPoint);
  67950. // Update throttle.
  67951. createOrUpdate(
  67952. record,
  67953. 'dispatchAction',
  67954. dataZoomInfo.throttleRate,
  67955. 'fixRate'
  67956. );
  67957. }
  67958. /**
  67959. * @public
  67960. * @param {module:echarts/ExtensionAPI} api
  67961. * @param {string} dataZoomId
  67962. */
  67963. function unregister$1(api, dataZoomId) {
  67964. var store = giveStore(api);
  67965. each$1(store, function (record) {
  67966. record.controller.dispose();
  67967. var dataZoomInfos = record.dataZoomInfos;
  67968. if (dataZoomInfos[dataZoomId]) {
  67969. delete dataZoomInfos[dataZoomId];
  67970. record.count--;
  67971. }
  67972. });
  67973. cleanStore(store);
  67974. }
  67975. /**
  67976. * @public
  67977. */
  67978. function generateCoordId(coordModel) {
  67979. return coordModel.type + '\0_' + coordModel.id;
  67980. }
  67981. /**
  67982. * Key: coordId, value: {dataZoomInfos: [], count, controller}
  67983. * @type {Array.<Object>}
  67984. */
  67985. function giveStore(api) {
  67986. // Mount store on zrender instance, so that we do not
  67987. // need to worry about dispose.
  67988. var zr = api.getZr();
  67989. return zr[ATTR$1] || (zr[ATTR$1] = {});
  67990. }
  67991. function createController(api, newRecord) {
  67992. var controller = new RoamController(api.getZr());
  67993. controller.on('pan', curry$6(onPan, newRecord));
  67994. controller.on('zoom', curry$6(onZoom, newRecord));
  67995. return controller;
  67996. }
  67997. function cleanStore(store) {
  67998. each$1(store, function (record, coordId) {
  67999. if (!record.count) {
  68000. record.controller.dispose();
  68001. delete store[coordId];
  68002. }
  68003. });
  68004. }
  68005. function onPan(record, dx, dy, oldX, oldY, newX, newY) {
  68006. wrapAndDispatch(record, function (info) {
  68007. return info.panGetRange(record.controller, dx, dy, oldX, oldY, newX, newY);
  68008. });
  68009. }
  68010. function onZoom(record, scale, mouseX, mouseY) {
  68011. wrapAndDispatch(record, function (info) {
  68012. return info.zoomGetRange(record.controller, scale, mouseX, mouseY);
  68013. });
  68014. }
  68015. function wrapAndDispatch(record, getRange) {
  68016. var batch = [];
  68017. each$1(record.dataZoomInfos, function (info) {
  68018. var range = getRange(info);
  68019. !info.disabled && range && batch.push({
  68020. dataZoomId: info.dataZoomId,
  68021. start: range[0],
  68022. end: range[1]
  68023. });
  68024. });
  68025. batch.length && record.dispatchAction(batch);
  68026. }
  68027. /**
  68028. * This action will be throttled.
  68029. */
  68030. function dispatchAction$1(api, batch) {
  68031. api.dispatchAction({
  68032. type: 'dataZoom',
  68033. batch: batch
  68034. });
  68035. }
  68036. /**
  68037. * Merge roamController settings when multiple dataZooms share one roamController.
  68038. */
  68039. function mergeControllerParams(dataZoomInfos) {
  68040. var controlType;
  68041. var opt = {};
  68042. // DO NOT use reserved word (true, false, undefined) as key literally. Even if encapsulated
  68043. // as string, it is probably revert to reserved word by compress tool. See #7411.
  68044. var prefix = 'type_';
  68045. var typePriority = {
  68046. 'type_true': 2,
  68047. 'type_move': 1,
  68048. 'type_false': 0,
  68049. 'type_undefined': -1
  68050. };
  68051. each$1(dataZoomInfos, function (dataZoomInfo) {
  68052. var oneType = dataZoomInfo.disabled ? false : dataZoomInfo.zoomLock ? 'move' : true;
  68053. if (typePriority[prefix + oneType] > typePriority[prefix + controlType]) {
  68054. controlType = oneType;
  68055. }
  68056. // Do not support that different 'shift'/'ctrl'/'alt' setting used in one coord sys.
  68057. extend(opt, dataZoomInfo.roamControllerOpt);
  68058. });
  68059. return {
  68060. controlType: controlType,
  68061. opt: opt
  68062. };
  68063. }
  68064. /*
  68065. * Licensed to the Apache Software Foundation (ASF) under one
  68066. * or more contributor license agreements. See the NOTICE file
  68067. * distributed with this work for additional information
  68068. * regarding copyright ownership. The ASF licenses this file
  68069. * to you under the Apache License, Version 2.0 (the
  68070. * "License"); you may not use this file except in compliance
  68071. * with the License. You may obtain a copy of the License at
  68072. *
  68073. * http://www.apache.org/licenses/LICENSE-2.0
  68074. *
  68075. * Unless required by applicable law or agreed to in writing,
  68076. * software distributed under the License is distributed on an
  68077. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68078. * KIND, either express or implied. See the License for the
  68079. * specific language governing permissions and limitations
  68080. * under the License.
  68081. */
  68082. var bind$5 = bind;
  68083. var InsideZoomView = DataZoomView.extend({
  68084. type: 'dataZoom.inside',
  68085. /**
  68086. * @override
  68087. */
  68088. init: function (ecModel, api) {
  68089. /**
  68090. * 'throttle' is used in this.dispatchAction, so we save range
  68091. * to avoid missing some 'pan' info.
  68092. * @private
  68093. * @type {Array.<number>}
  68094. */
  68095. this._range;
  68096. },
  68097. /**
  68098. * @override
  68099. */
  68100. render: function (dataZoomModel, ecModel, api, payload) {
  68101. InsideZoomView.superApply(this, 'render', arguments);
  68102. // Hance the `throttle` util ensures to preserve command order,
  68103. // here simply updating range all the time will not cause missing
  68104. // any of the the roam change.
  68105. this._range = dataZoomModel.getPercentRange();
  68106. // Reset controllers.
  68107. each$1(this.getTargetCoordInfo(), function (coordInfoList, coordSysName) {
  68108. var allCoordIds = map(coordInfoList, function (coordInfo) {
  68109. return generateCoordId(coordInfo.model);
  68110. });
  68111. each$1(coordInfoList, function (coordInfo) {
  68112. var coordModel = coordInfo.model;
  68113. var dataZoomOption = dataZoomModel.option;
  68114. register$2(
  68115. api,
  68116. {
  68117. coordId: generateCoordId(coordModel),
  68118. allCoordIds: allCoordIds,
  68119. containsPoint: function (e, x, y) {
  68120. return coordModel.coordinateSystem.containPoint([x, y]);
  68121. },
  68122. dataZoomId: dataZoomModel.id,
  68123. throttleRate: dataZoomModel.get('throttle', true),
  68124. panGetRange: bind$5(this._onPan, this, coordInfo, coordSysName),
  68125. zoomGetRange: bind$5(this._onZoom, this, coordInfo, coordSysName),
  68126. zoomLock: dataZoomOption.zoomLock,
  68127. disabled: dataZoomOption.disabled,
  68128. roamControllerOpt: {
  68129. zoomOnMouseWheel: dataZoomOption.zoomOnMouseWheel,
  68130. moveOnMouseMove: dataZoomOption.moveOnMouseMove,
  68131. preventDefaultMouseMove: dataZoomOption.preventDefaultMouseMove
  68132. }
  68133. }
  68134. );
  68135. }, this);
  68136. }, this);
  68137. },
  68138. /**
  68139. * @override
  68140. */
  68141. dispose: function () {
  68142. unregister$1(this.api, this.dataZoomModel.id);
  68143. InsideZoomView.superApply(this, 'dispose', arguments);
  68144. this._range = null;
  68145. },
  68146. /**
  68147. * @private
  68148. */
  68149. _onPan: function (coordInfo, coordSysName, controller, dx, dy, oldX, oldY, newX, newY) {
  68150. var lastRange = this._range;
  68151. var range = lastRange.slice();
  68152. // Calculate transform by the first axis.
  68153. var axisModel = coordInfo.axisModels[0];
  68154. if (!axisModel) {
  68155. return;
  68156. }
  68157. var directionInfo = getDirectionInfo[coordSysName](
  68158. [oldX, oldY], [newX, newY], axisModel, controller, coordInfo
  68159. );
  68160. var percentDelta = directionInfo.signal
  68161. * (range[1] - range[0])
  68162. * directionInfo.pixel / directionInfo.pixelLength;
  68163. sliderMove(percentDelta, range, [0, 100], 'all');
  68164. this._range = range;
  68165. if (lastRange[0] !== range[0] || lastRange[1] !== range[1]) {
  68166. return range;
  68167. }
  68168. },
  68169. /**
  68170. * @private
  68171. */
  68172. _onZoom: function (coordInfo, coordSysName, controller, scale, mouseX, mouseY) {
  68173. var lastRange = this._range;
  68174. var range = lastRange.slice();
  68175. // Calculate transform by the first axis.
  68176. var axisModel = coordInfo.axisModels[0];
  68177. if (!axisModel) {
  68178. return;
  68179. }
  68180. var directionInfo = getDirectionInfo[coordSysName](
  68181. null, [mouseX, mouseY], axisModel, controller, coordInfo
  68182. );
  68183. var percentPoint = (
  68184. directionInfo.signal > 0
  68185. ? (directionInfo.pixelStart + directionInfo.pixelLength - directionInfo.pixel)
  68186. : (directionInfo.pixel - directionInfo.pixelStart)
  68187. ) / directionInfo.pixelLength * (range[1] - range[0]) + range[0];
  68188. scale = Math.max(1 / scale, 0);
  68189. range[0] = (range[0] - percentPoint) * scale + percentPoint;
  68190. range[1] = (range[1] - percentPoint) * scale + percentPoint;
  68191. // Restrict range.
  68192. var minMaxSpan = this.dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  68193. sliderMove(0, range, [0, 100], 0, minMaxSpan.minSpan, minMaxSpan.maxSpan);
  68194. this._range = range;
  68195. if (lastRange[0] !== range[0] || lastRange[1] !== range[1]) {
  68196. return range;
  68197. }
  68198. }
  68199. });
  68200. var getDirectionInfo = {
  68201. grid: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  68202. var axis = axisModel.axis;
  68203. var ret = {};
  68204. var rect = coordInfo.model.coordinateSystem.getRect();
  68205. oldPoint = oldPoint || [0, 0];
  68206. if (axis.dim === 'x') {
  68207. ret.pixel = newPoint[0] - oldPoint[0];
  68208. ret.pixelLength = rect.width;
  68209. ret.pixelStart = rect.x;
  68210. ret.signal = axis.inverse ? 1 : -1;
  68211. }
  68212. else { // axis.dim === 'y'
  68213. ret.pixel = newPoint[1] - oldPoint[1];
  68214. ret.pixelLength = rect.height;
  68215. ret.pixelStart = rect.y;
  68216. ret.signal = axis.inverse ? -1 : 1;
  68217. }
  68218. return ret;
  68219. },
  68220. polar: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  68221. var axis = axisModel.axis;
  68222. var ret = {};
  68223. var polar = coordInfo.model.coordinateSystem;
  68224. var radiusExtent = polar.getRadiusAxis().getExtent();
  68225. var angleExtent = polar.getAngleAxis().getExtent();
  68226. oldPoint = oldPoint ? polar.pointToCoord(oldPoint) : [0, 0];
  68227. newPoint = polar.pointToCoord(newPoint);
  68228. if (axisModel.mainType === 'radiusAxis') {
  68229. ret.pixel = newPoint[0] - oldPoint[0];
  68230. // ret.pixelLength = Math.abs(radiusExtent[1] - radiusExtent[0]);
  68231. // ret.pixelStart = Math.min(radiusExtent[0], radiusExtent[1]);
  68232. ret.pixelLength = radiusExtent[1] - radiusExtent[0];
  68233. ret.pixelStart = radiusExtent[0];
  68234. ret.signal = axis.inverse ? 1 : -1;
  68235. }
  68236. else { // 'angleAxis'
  68237. ret.pixel = newPoint[1] - oldPoint[1];
  68238. // ret.pixelLength = Math.abs(angleExtent[1] - angleExtent[0]);
  68239. // ret.pixelStart = Math.min(angleExtent[0], angleExtent[1]);
  68240. ret.pixelLength = angleExtent[1] - angleExtent[0];
  68241. ret.pixelStart = angleExtent[0];
  68242. ret.signal = axis.inverse ? -1 : 1;
  68243. }
  68244. return ret;
  68245. },
  68246. singleAxis: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  68247. var axis = axisModel.axis;
  68248. var rect = coordInfo.model.coordinateSystem.getRect();
  68249. var ret = {};
  68250. oldPoint = oldPoint || [0, 0];
  68251. if (axis.orient === 'horizontal') {
  68252. ret.pixel = newPoint[0] - oldPoint[0];
  68253. ret.pixelLength = rect.width;
  68254. ret.pixelStart = rect.x;
  68255. ret.signal = axis.inverse ? 1 : -1;
  68256. }
  68257. else { // 'vertical'
  68258. ret.pixel = newPoint[1] - oldPoint[1];
  68259. ret.pixelLength = rect.height;
  68260. ret.pixelStart = rect.y;
  68261. ret.signal = axis.inverse ? -1 : 1;
  68262. }
  68263. return ret;
  68264. }
  68265. };
  68266. /*
  68267. * Licensed to the Apache Software Foundation (ASF) under one
  68268. * or more contributor license agreements. See the NOTICE file
  68269. * distributed with this work for additional information
  68270. * regarding copyright ownership. The ASF licenses this file
  68271. * to you under the Apache License, Version 2.0 (the
  68272. * "License"); you may not use this file except in compliance
  68273. * with the License. You may obtain a copy of the License at
  68274. *
  68275. * http://www.apache.org/licenses/LICENSE-2.0
  68276. *
  68277. * Unless required by applicable law or agreed to in writing,
  68278. * software distributed under the License is distributed on an
  68279. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68280. * KIND, either express or implied. See the License for the
  68281. * specific language governing permissions and limitations
  68282. * under the License.
  68283. */
  68284. registerProcessor({
  68285. // `dataZoomProcessor` will only be performed in needed series. Consider if
  68286. // there is a line series and a pie series, it is better not to update the
  68287. // line series if only pie series is needed to be updated.
  68288. getTargetSeries: function (ecModel) {
  68289. var seriesModelMap = createHashMap();
  68290. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  68291. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  68292. var axisProxy = dataZoomModel.getAxisProxy(dimNames.name, axisIndex);
  68293. each$1(axisProxy.getTargetSeriesModels(), function (seriesModel) {
  68294. seriesModelMap.set(seriesModel.uid, seriesModel);
  68295. });
  68296. });
  68297. });
  68298. return seriesModelMap;
  68299. },
  68300. modifyOutputEnd: true,
  68301. // Consider appendData, where filter should be performed. Because data process is
  68302. // in block mode currently, it is not need to worry about that the overallProgress
  68303. // execute every frame.
  68304. overallReset: function (ecModel, api) {
  68305. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  68306. // We calculate window and reset axis here but not in model
  68307. // init stage and not after action dispatch handler, because
  68308. // reset should be called after seriesData.restoreData.
  68309. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  68310. dataZoomModel.getAxisProxy(dimNames.name, axisIndex).reset(dataZoomModel, api);
  68311. });
  68312. // Caution: data zoom filtering is order sensitive when using
  68313. // percent range and no min/max/scale set on axis.
  68314. // For example, we have dataZoom definition:
  68315. // [
  68316. // {xAxisIndex: 0, start: 30, end: 70},
  68317. // {yAxisIndex: 0, start: 20, end: 80}
  68318. // ]
  68319. // In this case, [20, 80] of y-dataZoom should be based on data
  68320. // that have filtered by x-dataZoom using range of [30, 70],
  68321. // but should not be based on full raw data. Thus sliding
  68322. // x-dataZoom will change both ranges of xAxis and yAxis,
  68323. // while sliding y-dataZoom will only change the range of yAxis.
  68324. // So we should filter x-axis after reset x-axis immediately,
  68325. // and then reset y-axis and filter y-axis.
  68326. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  68327. dataZoomModel.getAxisProxy(dimNames.name, axisIndex).filterData(dataZoomModel, api);
  68328. });
  68329. });
  68330. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  68331. // Fullfill all of the range props so that user
  68332. // is able to get them from chart.getOption().
  68333. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  68334. var percentRange = axisProxy.getDataPercentWindow();
  68335. var valueRange = axisProxy.getDataValueWindow();
  68336. dataZoomModel.setRawRange({
  68337. start: percentRange[0],
  68338. end: percentRange[1],
  68339. startValue: valueRange[0],
  68340. endValue: valueRange[1]
  68341. }, true);
  68342. });
  68343. }
  68344. });
  68345. /*
  68346. * Licensed to the Apache Software Foundation (ASF) under one
  68347. * or more contributor license agreements. See the NOTICE file
  68348. * distributed with this work for additional information
  68349. * regarding copyright ownership. The ASF licenses this file
  68350. * to you under the Apache License, Version 2.0 (the
  68351. * "License"); you may not use this file except in compliance
  68352. * with the License. You may obtain a copy of the License at
  68353. *
  68354. * http://www.apache.org/licenses/LICENSE-2.0
  68355. *
  68356. * Unless required by applicable law or agreed to in writing,
  68357. * software distributed under the License is distributed on an
  68358. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68359. * KIND, either express or implied. See the License for the
  68360. * specific language governing permissions and limitations
  68361. * under the License.
  68362. */
  68363. registerAction('dataZoom', function (payload, ecModel) {
  68364. var linkedNodesFinder = createLinkedNodesFinder(
  68365. bind(ecModel.eachComponent, ecModel, 'dataZoom'),
  68366. eachAxisDim$1,
  68367. function (model, dimNames) {
  68368. return model.get(dimNames.axisIndex);
  68369. }
  68370. );
  68371. var effectedModels = [];
  68372. ecModel.eachComponent(
  68373. {mainType: 'dataZoom', query: payload},
  68374. function (model, index) {
  68375. effectedModels.push.apply(
  68376. effectedModels, linkedNodesFinder(model).nodes
  68377. );
  68378. }
  68379. );
  68380. each$1(effectedModels, function (dataZoomModel, index) {
  68381. dataZoomModel.setRawRange({
  68382. start: payload.start,
  68383. end: payload.end,
  68384. startValue: payload.startValue,
  68385. endValue: payload.endValue
  68386. });
  68387. });
  68388. });
  68389. /*
  68390. * Licensed to the Apache Software Foundation (ASF) under one
  68391. * or more contributor license agreements. See the NOTICE file
  68392. * distributed with this work for additional information
  68393. * regarding copyright ownership. The ASF licenses this file
  68394. * to you under the Apache License, Version 2.0 (the
  68395. * "License"); you may not use this file except in compliance
  68396. * with the License. You may obtain a copy of the License at
  68397. *
  68398. * http://www.apache.org/licenses/LICENSE-2.0
  68399. *
  68400. * Unless required by applicable law or agreed to in writing,
  68401. * software distributed under the License is distributed on an
  68402. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68403. * KIND, either express or implied. See the License for the
  68404. * specific language governing permissions and limitations
  68405. * under the License.
  68406. */
  68407. /**
  68408. * DataZoom component entry
  68409. */
  68410. /*
  68411. * Licensed to the Apache Software Foundation (ASF) under one
  68412. * or more contributor license agreements. See the NOTICE file
  68413. * distributed with this work for additional information
  68414. * regarding copyright ownership. The ASF licenses this file
  68415. * to you under the Apache License, Version 2.0 (the
  68416. * "License"); you may not use this file except in compliance
  68417. * with the License. You may obtain a copy of the License at
  68418. *
  68419. * http://www.apache.org/licenses/LICENSE-2.0
  68420. *
  68421. * Unless required by applicable law or agreed to in writing,
  68422. * software distributed under the License is distributed on an
  68423. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68424. * KIND, either express or implied. See the License for the
  68425. * specific language governing permissions and limitations
  68426. * under the License.
  68427. */
  68428. var each$24 = each$1;
  68429. var preprocessor$2 = function (option) {
  68430. var visualMap = option && option.visualMap;
  68431. if (!isArray(visualMap)) {
  68432. visualMap = visualMap ? [visualMap] : [];
  68433. }
  68434. each$24(visualMap, function (opt) {
  68435. if (!opt) {
  68436. return;
  68437. }
  68438. // rename splitList to pieces
  68439. if (has$1(opt, 'splitList') && !has$1(opt, 'pieces')) {
  68440. opt.pieces = opt.splitList;
  68441. delete opt.splitList;
  68442. }
  68443. var pieces = opt.pieces;
  68444. if (pieces && isArray(pieces)) {
  68445. each$24(pieces, function (piece) {
  68446. if (isObject$1(piece)) {
  68447. if (has$1(piece, 'start') && !has$1(piece, 'min')) {
  68448. piece.min = piece.start;
  68449. }
  68450. if (has$1(piece, 'end') && !has$1(piece, 'max')) {
  68451. piece.max = piece.end;
  68452. }
  68453. }
  68454. });
  68455. }
  68456. });
  68457. };
  68458. function has$1(obj, name) {
  68459. return obj && obj.hasOwnProperty && obj.hasOwnProperty(name);
  68460. }
  68461. /*
  68462. * Licensed to the Apache Software Foundation (ASF) under one
  68463. * or more contributor license agreements. See the NOTICE file
  68464. * distributed with this work for additional information
  68465. * regarding copyright ownership. The ASF licenses this file
  68466. * to you under the Apache License, Version 2.0 (the
  68467. * "License"); you may not use this file except in compliance
  68468. * with the License. You may obtain a copy of the License at
  68469. *
  68470. * http://www.apache.org/licenses/LICENSE-2.0
  68471. *
  68472. * Unless required by applicable law or agreed to in writing,
  68473. * software distributed under the License is distributed on an
  68474. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68475. * KIND, either express or implied. See the License for the
  68476. * specific language governing permissions and limitations
  68477. * under the License.
  68478. */
  68479. ComponentModel.registerSubTypeDefaulter('visualMap', function (option) {
  68480. // Compatible with ec2, when splitNumber === 0, continuous visualMap will be used.
  68481. return (
  68482. !option.categories
  68483. && (
  68484. !(
  68485. option.pieces
  68486. ? option.pieces.length > 0
  68487. : option.splitNumber > 0
  68488. )
  68489. || option.calculable
  68490. )
  68491. )
  68492. ? 'continuous' : 'piecewise';
  68493. });
  68494. /*
  68495. * Licensed to the Apache Software Foundation (ASF) under one
  68496. * or more contributor license agreements. See the NOTICE file
  68497. * distributed with this work for additional information
  68498. * regarding copyright ownership. The ASF licenses this file
  68499. * to you under the Apache License, Version 2.0 (the
  68500. * "License"); you may not use this file except in compliance
  68501. * with the License. You may obtain a copy of the License at
  68502. *
  68503. * http://www.apache.org/licenses/LICENSE-2.0
  68504. *
  68505. * Unless required by applicable law or agreed to in writing,
  68506. * software distributed under the License is distributed on an
  68507. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68508. * KIND, either express or implied. See the License for the
  68509. * specific language governing permissions and limitations
  68510. * under the License.
  68511. */
  68512. var VISUAL_PRIORITY = PRIORITY.VISUAL.COMPONENT;
  68513. registerVisual(VISUAL_PRIORITY, {
  68514. createOnAllSeries: true,
  68515. reset: function (seriesModel, ecModel) {
  68516. var resetDefines = [];
  68517. ecModel.eachComponent('visualMap', function (visualMapModel) {
  68518. var pipelineContext = seriesModel.pipelineContext;
  68519. if (!visualMapModel.isTargetSeries(seriesModel)
  68520. || (pipelineContext && pipelineContext.large)
  68521. ) {
  68522. return;
  68523. }
  68524. resetDefines.push(incrementalApplyVisual(
  68525. visualMapModel.stateList,
  68526. visualMapModel.targetVisuals,
  68527. bind(visualMapModel.getValueState, visualMapModel),
  68528. visualMapModel.getDataDimension(seriesModel.getData())
  68529. ));
  68530. });
  68531. return resetDefines;
  68532. }
  68533. });
  68534. // Only support color.
  68535. registerVisual(VISUAL_PRIORITY, {
  68536. createOnAllSeries: true,
  68537. reset: function (seriesModel, ecModel) {
  68538. var data = seriesModel.getData();
  68539. var visualMetaList = [];
  68540. ecModel.eachComponent('visualMap', function (visualMapModel) {
  68541. if (visualMapModel.isTargetSeries(seriesModel)) {
  68542. var visualMeta = visualMapModel.getVisualMeta(
  68543. bind(getColorVisual, null, seriesModel, visualMapModel)
  68544. ) || {stops: [], outerColors: []};
  68545. var concreteDim = visualMapModel.getDataDimension(data);
  68546. var dimInfo = data.getDimensionInfo(concreteDim);
  68547. if (dimInfo != null) {
  68548. // visualMeta.dimension should be dimension index, but not concrete dimension.
  68549. visualMeta.dimension = dimInfo.index;
  68550. visualMetaList.push(visualMeta);
  68551. }
  68552. }
  68553. });
  68554. // console.log(JSON.stringify(visualMetaList.map(a => a.stops)));
  68555. seriesModel.getData().setVisual('visualMeta', visualMetaList);
  68556. }
  68557. });
  68558. // FIXME
  68559. // performance and export for heatmap?
  68560. // value can be Infinity or -Infinity
  68561. function getColorVisual(seriesModel, visualMapModel, value, valueState) {
  68562. var mappings = visualMapModel.targetVisuals[valueState];
  68563. var visualTypes = VisualMapping.prepareVisualTypes(mappings);
  68564. var resultVisual = {
  68565. color: seriesModel.getData().getVisual('color') // default color.
  68566. };
  68567. for (var i = 0, len = visualTypes.length; i < len; i++) {
  68568. var type = visualTypes[i];
  68569. var mapping = mappings[
  68570. type === 'opacity' ? '__alphaForOpacity' : type
  68571. ];
  68572. mapping && mapping.applyVisual(value, getVisual, setVisual);
  68573. }
  68574. return resultVisual.color;
  68575. function getVisual(key) {
  68576. return resultVisual[key];
  68577. }
  68578. function setVisual(key, value) {
  68579. resultVisual[key] = value;
  68580. }
  68581. }
  68582. /*
  68583. * Licensed to the Apache Software Foundation (ASF) under one
  68584. * or more contributor license agreements. See the NOTICE file
  68585. * distributed with this work for additional information
  68586. * regarding copyright ownership. The ASF licenses this file
  68587. * to you under the Apache License, Version 2.0 (the
  68588. * "License"); you may not use this file except in compliance
  68589. * with the License. You may obtain a copy of the License at
  68590. *
  68591. * http://www.apache.org/licenses/LICENSE-2.0
  68592. *
  68593. * Unless required by applicable law or agreed to in writing,
  68594. * software distributed under the License is distributed on an
  68595. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68596. * KIND, either express or implied. See the License for the
  68597. * specific language governing permissions and limitations
  68598. * under the License.
  68599. */
  68600. /**
  68601. * @file Visual mapping.
  68602. */
  68603. var visualDefault = {
  68604. /**
  68605. * @public
  68606. */
  68607. get: function (visualType, key, isCategory) {
  68608. var value = clone(
  68609. (defaultOption$3[visualType] || {})[key]
  68610. );
  68611. return isCategory
  68612. ? (isArray(value) ? value[value.length - 1] : value)
  68613. : value;
  68614. }
  68615. };
  68616. var defaultOption$3 = {
  68617. color: {
  68618. active: ['#006edd', '#e0ffff'],
  68619. inactive: ['rgba(0,0,0,0)']
  68620. },
  68621. colorHue: {
  68622. active: [0, 360],
  68623. inactive: [0, 0]
  68624. },
  68625. colorSaturation: {
  68626. active: [0.3, 1],
  68627. inactive: [0, 0]
  68628. },
  68629. colorLightness: {
  68630. active: [0.9, 0.5],
  68631. inactive: [0, 0]
  68632. },
  68633. colorAlpha: {
  68634. active: [0.3, 1],
  68635. inactive: [0, 0]
  68636. },
  68637. opacity: {
  68638. active: [0.3, 1],
  68639. inactive: [0, 0]
  68640. },
  68641. symbol: {
  68642. active: ['circle', 'roundRect', 'diamond'],
  68643. inactive: ['none']
  68644. },
  68645. symbolSize: {
  68646. active: [10, 50],
  68647. inactive: [0, 0]
  68648. }
  68649. };
  68650. /*
  68651. * Licensed to the Apache Software Foundation (ASF) under one
  68652. * or more contributor license agreements. See the NOTICE file
  68653. * distributed with this work for additional information
  68654. * regarding copyright ownership. The ASF licenses this file
  68655. * to you under the Apache License, Version 2.0 (the
  68656. * "License"); you may not use this file except in compliance
  68657. * with the License. You may obtain a copy of the License at
  68658. *
  68659. * http://www.apache.org/licenses/LICENSE-2.0
  68660. *
  68661. * Unless required by applicable law or agreed to in writing,
  68662. * software distributed under the License is distributed on an
  68663. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68664. * KIND, either express or implied. See the License for the
  68665. * specific language governing permissions and limitations
  68666. * under the License.
  68667. */
  68668. var mapVisual$2 = VisualMapping.mapVisual;
  68669. var eachVisual = VisualMapping.eachVisual;
  68670. var isArray$3 = isArray;
  68671. var each$25 = each$1;
  68672. var asc$3 = asc;
  68673. var linearMap$2 = linearMap;
  68674. var noop$2 = noop;
  68675. var VisualMapModel = extendComponentModel({
  68676. type: 'visualMap',
  68677. dependencies: ['series'],
  68678. /**
  68679. * @readOnly
  68680. * @type {Array.<string>}
  68681. */
  68682. stateList: ['inRange', 'outOfRange'],
  68683. /**
  68684. * @readOnly
  68685. * @type {Array.<string>}
  68686. */
  68687. replacableOptionKeys: [
  68688. 'inRange', 'outOfRange', 'target', 'controller', 'color'
  68689. ],
  68690. /**
  68691. * [lowerBound, upperBound]
  68692. *
  68693. * @readOnly
  68694. * @type {Array.<number>}
  68695. */
  68696. dataBound: [-Infinity, Infinity],
  68697. /**
  68698. * @readOnly
  68699. * @type {string|Object}
  68700. */
  68701. layoutMode: {type: 'box', ignoreSize: true},
  68702. /**
  68703. * @protected
  68704. */
  68705. defaultOption: {
  68706. show: true,
  68707. zlevel: 0,
  68708. z: 4,
  68709. seriesIndex: 'all', // 'all' or null/undefined: all series.
  68710. // A number or an array of number: the specified series.
  68711. // set min: 0, max: 200, only for campatible with ec2.
  68712. // In fact min max should not have default value.
  68713. min: 0, // min value, must specified if pieces is not specified.
  68714. max: 200, // max value, must specified if pieces is not specified.
  68715. dimension: null,
  68716. inRange: null, // 'color', 'colorHue', 'colorSaturation', 'colorLightness', 'colorAlpha',
  68717. // 'symbol', 'symbolSize'
  68718. outOfRange: null, // 'color', 'colorHue', 'colorSaturation',
  68719. // 'colorLightness', 'colorAlpha',
  68720. // 'symbol', 'symbolSize'
  68721. left: 0, // 'center' ¦ 'left' ¦ 'right' ¦ {number} (px)
  68722. right: null, // The same as left.
  68723. top: null, // 'top' ¦ 'bottom' ¦ 'center' ¦ {number} (px)
  68724. bottom: 0, // The same as top.
  68725. itemWidth: null,
  68726. itemHeight: null,
  68727. inverse: false,
  68728. orient: 'vertical', // 'horizontal' ¦ 'vertical'
  68729. backgroundColor: 'rgba(0,0,0,0)',
  68730. borderColor: '#ccc', // 值域边框颜色
  68731. contentColor: '#5793f3',
  68732. inactiveColor: '#aaa',
  68733. borderWidth: 0, // 值域边框线宽,单位px,默认为0(无边框)
  68734. padding: 5, // 值域内边距,单位px,默认各方向内边距为5,
  68735. // 接受数组分别设定上右下左边距,同css
  68736. textGap: 10, //
  68737. precision: 0, // 小数精度,默认为0,无小数点
  68738. color: null, //颜色(deprecated,兼容ec2,顺序同pieces,不同于inRange/outOfRange)
  68739. formatter: null,
  68740. text: null, // 文本,如['高', '低'],兼容ec2,text[0]对应高值,text[1]对应低值
  68741. textStyle: {
  68742. color: '#333' // 值域文字颜色
  68743. }
  68744. },
  68745. /**
  68746. * @protected
  68747. */
  68748. init: function (option, parentModel, ecModel) {
  68749. /**
  68750. * @private
  68751. * @type {Array.<number>}
  68752. */
  68753. this._dataExtent;
  68754. /**
  68755. * @readOnly
  68756. */
  68757. this.targetVisuals = {};
  68758. /**
  68759. * @readOnly
  68760. */
  68761. this.controllerVisuals = {};
  68762. /**
  68763. * @readOnly
  68764. */
  68765. this.textStyleModel;
  68766. /**
  68767. * [width, height]
  68768. * @readOnly
  68769. * @type {Array.<number>}
  68770. */
  68771. this.itemSize;
  68772. this.mergeDefaultAndTheme(option, ecModel);
  68773. },
  68774. /**
  68775. * @protected
  68776. */
  68777. optionUpdated: function (newOption, isInit) {
  68778. var thisOption = this.option;
  68779. // FIXME
  68780. // necessary?
  68781. // Disable realtime view update if canvas is not supported.
  68782. if (!env$1.canvasSupported) {
  68783. thisOption.realtime = false;
  68784. }
  68785. !isInit && replaceVisualOption(
  68786. thisOption, newOption, this.replacableOptionKeys
  68787. );
  68788. this.textStyleModel = this.getModel('textStyle');
  68789. this.resetItemSize();
  68790. this.completeVisualOption();
  68791. },
  68792. /**
  68793. * @protected
  68794. */
  68795. resetVisual: function (supplementVisualOption) {
  68796. var stateList = this.stateList;
  68797. supplementVisualOption = bind(supplementVisualOption, this);
  68798. this.controllerVisuals = createVisualMappings(
  68799. this.option.controller, stateList, supplementVisualOption
  68800. );
  68801. this.targetVisuals = createVisualMappings(
  68802. this.option.target, stateList, supplementVisualOption
  68803. );
  68804. },
  68805. /**
  68806. * @protected
  68807. * @return {Array.<number>} An array of series indices.
  68808. */
  68809. getTargetSeriesIndices: function () {
  68810. var optionSeriesIndex = this.option.seriesIndex;
  68811. var seriesIndices = [];
  68812. if (optionSeriesIndex == null || optionSeriesIndex === 'all') {
  68813. this.ecModel.eachSeries(function (seriesModel, index) {
  68814. seriesIndices.push(index);
  68815. });
  68816. }
  68817. else {
  68818. seriesIndices = normalizeToArray(optionSeriesIndex);
  68819. }
  68820. return seriesIndices;
  68821. },
  68822. /**
  68823. * @public
  68824. */
  68825. eachTargetSeries: function (callback, context) {
  68826. each$1(this.getTargetSeriesIndices(), function (seriesIndex) {
  68827. callback.call(context, this.ecModel.getSeriesByIndex(seriesIndex));
  68828. }, this);
  68829. },
  68830. /**
  68831. * @pubilc
  68832. */
  68833. isTargetSeries: function (seriesModel) {
  68834. var is = false;
  68835. this.eachTargetSeries(function (model) {
  68836. model === seriesModel && (is = true);
  68837. });
  68838. return is;
  68839. },
  68840. /**
  68841. * @example
  68842. * this.formatValueText(someVal); // format single numeric value to text.
  68843. * this.formatValueText(someVal, true); // format single category value to text.
  68844. * this.formatValueText([min, max]); // format numeric min-max to text.
  68845. * this.formatValueText([this.dataBound[0], max]); // using data lower bound.
  68846. * this.formatValueText([min, this.dataBound[1]]); // using data upper bound.
  68847. *
  68848. * @param {number|Array.<number>} value Real value, or this.dataBound[0 or 1].
  68849. * @param {boolean} [isCategory=false] Only available when value is number.
  68850. * @param {Array.<string>} edgeSymbols Open-close symbol when value is interval.
  68851. * @return {string}
  68852. * @protected
  68853. */
  68854. formatValueText: function(value, isCategory, edgeSymbols) {
  68855. var option = this.option;
  68856. var precision = option.precision;
  68857. var dataBound = this.dataBound;
  68858. var formatter = option.formatter;
  68859. var isMinMax;
  68860. var textValue;
  68861. edgeSymbols = edgeSymbols || ['<', '>'];
  68862. if (isArray(value)) {
  68863. value = value.slice();
  68864. isMinMax = true;
  68865. }
  68866. textValue = isCategory
  68867. ? value
  68868. : (isMinMax
  68869. ? [toFixed(value[0]), toFixed(value[1])]
  68870. : toFixed(value)
  68871. );
  68872. if (isString(formatter)) {
  68873. return formatter
  68874. .replace('{value}', isMinMax ? textValue[0] : textValue)
  68875. .replace('{value2}', isMinMax ? textValue[1] : textValue);
  68876. }
  68877. else if (isFunction$1(formatter)) {
  68878. return isMinMax
  68879. ? formatter(value[0], value[1])
  68880. : formatter(value);
  68881. }
  68882. if (isMinMax) {
  68883. if (value[0] === dataBound[0]) {
  68884. return edgeSymbols[0] + ' ' + textValue[1];
  68885. }
  68886. else if (value[1] === dataBound[1]) {
  68887. return edgeSymbols[1] + ' ' + textValue[0];
  68888. }
  68889. else {
  68890. return textValue[0] + ' - ' + textValue[1];
  68891. }
  68892. }
  68893. else { // Format single value (includes category case).
  68894. return textValue;
  68895. }
  68896. function toFixed(val) {
  68897. return val === dataBound[0]
  68898. ? 'min'
  68899. : val === dataBound[1]
  68900. ? 'max'
  68901. : (+val).toFixed(Math.min(precision, 20));
  68902. }
  68903. },
  68904. /**
  68905. * @protected
  68906. */
  68907. resetExtent: function () {
  68908. var thisOption = this.option;
  68909. // Can not calculate data extent by data here.
  68910. // Because series and data may be modified in processing stage.
  68911. // So we do not support the feature "auto min/max".
  68912. var extent = asc$3([thisOption.min, thisOption.max]);
  68913. this._dataExtent = extent;
  68914. },
  68915. /**
  68916. * @public
  68917. * @param {module:echarts/data/List} list
  68918. * @return {string} Concrete dimention. If return null/undefined,
  68919. * no dimension used.
  68920. */
  68921. getDataDimension: function (list) {
  68922. var optDim = this.option.dimension;
  68923. var listDimensions = list.dimensions;
  68924. if (optDim == null && !listDimensions.length) {
  68925. return;
  68926. }
  68927. if (optDim != null) {
  68928. return list.getDimension(optDim);
  68929. }
  68930. var dimNames = list.dimensions;
  68931. for (var i = dimNames.length - 1; i >= 0; i--) {
  68932. var dimName = dimNames[i];
  68933. var dimInfo = list.getDimensionInfo(dimName);
  68934. if (!dimInfo.isCalculationCoord) {
  68935. return dimName;
  68936. }
  68937. }
  68938. },
  68939. /**
  68940. * @public
  68941. * @override
  68942. */
  68943. getExtent: function () {
  68944. return this._dataExtent.slice();
  68945. },
  68946. /**
  68947. * @protected
  68948. */
  68949. completeVisualOption: function () {
  68950. var ecModel = this.ecModel;
  68951. var thisOption = this.option;
  68952. var base = {inRange: thisOption.inRange, outOfRange: thisOption.outOfRange};
  68953. var target = thisOption.target || (thisOption.target = {});
  68954. var controller = thisOption.controller || (thisOption.controller = {});
  68955. merge(target, base); // Do not override
  68956. merge(controller, base); // Do not override
  68957. var isCategory = this.isCategory();
  68958. completeSingle.call(this, target);
  68959. completeSingle.call(this, controller);
  68960. completeInactive.call(this, target, 'inRange', 'outOfRange');
  68961. // completeInactive.call(this, target, 'outOfRange', 'inRange');
  68962. completeController.call(this, controller);
  68963. function completeSingle(base) {
  68964. // Compatible with ec2 dataRange.color.
  68965. // The mapping order of dataRange.color is: [high value, ..., low value]
  68966. // whereas inRange.color and outOfRange.color is [low value, ..., high value]
  68967. // Notice: ec2 has no inverse.
  68968. if (isArray$3(thisOption.color)
  68969. // If there has been inRange: {symbol: ...}, adding color is a mistake.
  68970. // So adding color only when no inRange defined.
  68971. && !base.inRange
  68972. ) {
  68973. base.inRange = {color: thisOption.color.slice().reverse()};
  68974. }
  68975. // Compatible with previous logic, always give a defautl color, otherwise
  68976. // simple config with no inRange and outOfRange will not work.
  68977. // Originally we use visualMap.color as the default color, but setOption at
  68978. // the second time the default color will be erased. So we change to use
  68979. // constant DEFAULT_COLOR.
  68980. // If user do not want the defualt color, set inRange: {color: null}.
  68981. base.inRange = base.inRange || {color: ecModel.get('gradientColor')};
  68982. // If using shortcut like: {inRange: 'symbol'}, complete default value.
  68983. each$25(this.stateList, function (state) {
  68984. var visualType = base[state];
  68985. if (isString(visualType)) {
  68986. var defa = visualDefault.get(visualType, 'active', isCategory);
  68987. if (defa) {
  68988. base[state] = {};
  68989. base[state][visualType] = defa;
  68990. }
  68991. else {
  68992. // Mark as not specified.
  68993. delete base[state];
  68994. }
  68995. }
  68996. }, this);
  68997. }
  68998. function completeInactive(base, stateExist, stateAbsent) {
  68999. var optExist = base[stateExist];
  69000. var optAbsent = base[stateAbsent];
  69001. if (optExist && !optAbsent) {
  69002. optAbsent = base[stateAbsent] = {};
  69003. each$25(optExist, function (visualData, visualType) {
  69004. if (!VisualMapping.isValidType(visualType)) {
  69005. return;
  69006. }
  69007. var defa = visualDefault.get(visualType, 'inactive', isCategory);
  69008. if (defa != null) {
  69009. optAbsent[visualType] = defa;
  69010. // Compatibable with ec2:
  69011. // Only inactive color to rgba(0,0,0,0) can not
  69012. // make label transparent, so use opacity also.
  69013. if (visualType === 'color'
  69014. && !optAbsent.hasOwnProperty('opacity')
  69015. && !optAbsent.hasOwnProperty('colorAlpha')
  69016. ) {
  69017. optAbsent.opacity = [0, 0];
  69018. }
  69019. }
  69020. });
  69021. }
  69022. }
  69023. function completeController(controller) {
  69024. var symbolExists = (controller.inRange || {}).symbol
  69025. || (controller.outOfRange || {}).symbol;
  69026. var symbolSizeExists = (controller.inRange || {}).symbolSize
  69027. || (controller.outOfRange || {}).symbolSize;
  69028. var inactiveColor = this.get('inactiveColor');
  69029. each$25(this.stateList, function (state) {
  69030. var itemSize = this.itemSize;
  69031. var visuals = controller[state];
  69032. // Set inactive color for controller if no other color
  69033. // attr (like colorAlpha) specified.
  69034. if (!visuals) {
  69035. visuals = controller[state] = {
  69036. color: isCategory ? inactiveColor : [inactiveColor]
  69037. };
  69038. }
  69039. // Consistent symbol and symbolSize if not specified.
  69040. if (visuals.symbol == null) {
  69041. visuals.symbol = symbolExists
  69042. && clone(symbolExists)
  69043. || (isCategory ? 'roundRect' : ['roundRect']);
  69044. }
  69045. if (visuals.symbolSize == null) {
  69046. visuals.symbolSize = symbolSizeExists
  69047. && clone(symbolSizeExists)
  69048. || (isCategory ? itemSize[0] : [itemSize[0], itemSize[0]]);
  69049. }
  69050. // Filter square and none.
  69051. visuals.symbol = mapVisual$2(visuals.symbol, function (symbol) {
  69052. return (symbol === 'none' || symbol === 'square') ? 'roundRect' : symbol;
  69053. });
  69054. // Normalize symbolSize
  69055. var symbolSize = visuals.symbolSize;
  69056. if (symbolSize != null) {
  69057. var max = -Infinity;
  69058. // symbolSize can be object when categories defined.
  69059. eachVisual(symbolSize, function (value) {
  69060. value > max && (max = value);
  69061. });
  69062. visuals.symbolSize = mapVisual$2(symbolSize, function (value) {
  69063. return linearMap$2(value, [0, max], [0, itemSize[0]], true);
  69064. });
  69065. }
  69066. }, this);
  69067. }
  69068. },
  69069. /**
  69070. * @protected
  69071. */
  69072. resetItemSize: function () {
  69073. this.itemSize = [
  69074. parseFloat(this.get('itemWidth')),
  69075. parseFloat(this.get('itemHeight'))
  69076. ];
  69077. },
  69078. /**
  69079. * @public
  69080. */
  69081. isCategory: function () {
  69082. return !!this.option.categories;
  69083. },
  69084. /**
  69085. * @public
  69086. * @abstract
  69087. */
  69088. setSelected: noop$2,
  69089. /**
  69090. * @public
  69091. * @abstract
  69092. * @param {*|module:echarts/data/List} valueOrData
  69093. * @param {number} dataIndex
  69094. * @return {string} state See this.stateList
  69095. */
  69096. getValueState: noop$2,
  69097. /**
  69098. * FIXME
  69099. * Do not publish to thirt-part-dev temporarily
  69100. * util the interface is stable. (Should it return
  69101. * a function but not visual meta?)
  69102. *
  69103. * @pubilc
  69104. * @abstract
  69105. * @param {Function} getColorVisual
  69106. * params: value, valueState
  69107. * return: color
  69108. * @return {Object} visualMeta
  69109. * should includes {stops, outerColors}
  69110. * outerColor means [colorBeyondMinValue, colorBeyondMaxValue]
  69111. */
  69112. getVisualMeta: noop$2
  69113. });
  69114. /*
  69115. * Licensed to the Apache Software Foundation (ASF) under one
  69116. * or more contributor license agreements. See the NOTICE file
  69117. * distributed with this work for additional information
  69118. * regarding copyright ownership. The ASF licenses this file
  69119. * to you under the Apache License, Version 2.0 (the
  69120. * "License"); you may not use this file except in compliance
  69121. * with the License. You may obtain a copy of the License at
  69122. *
  69123. * http://www.apache.org/licenses/LICENSE-2.0
  69124. *
  69125. * Unless required by applicable law or agreed to in writing,
  69126. * software distributed under the License is distributed on an
  69127. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  69128. * KIND, either express or implied. See the License for the
  69129. * specific language governing permissions and limitations
  69130. * under the License.
  69131. */
  69132. // Constant
  69133. var DEFAULT_BAR_BOUND = [20, 140];
  69134. var ContinuousModel = VisualMapModel.extend({
  69135. type: 'visualMap.continuous',
  69136. /**
  69137. * @protected
  69138. */
  69139. defaultOption: {
  69140. align: 'auto', // 'auto', 'left', 'right', 'top', 'bottom'
  69141. calculable: false, // This prop effect default component type determine,
  69142. // See echarts/component/visualMap/typeDefaulter.
  69143. range: null, // selected range. In default case `range` is [min, max]
  69144. // and can auto change along with modification of min max,
  69145. // util use specifid a range.
  69146. realtime: true, // Whether realtime update.
  69147. itemHeight: null, // The length of the range control edge.
  69148. itemWidth: null, // The length of the other side.
  69149. hoverLink: true, // Enable hover highlight.
  69150. hoverLinkDataSize: null,// The size of hovered data.
  69151. hoverLinkOnHandle: null // Whether trigger hoverLink when hover handle.
  69152. // If not specified, follow the value of `realtime`.
  69153. },
  69154. /**
  69155. * @override
  69156. */
  69157. optionUpdated: function (newOption, isInit) {
  69158. ContinuousModel.superApply(this, 'optionUpdated', arguments);
  69159. this.resetExtent();
  69160. this.resetVisual(function (mappingOption) {
  69161. mappingOption.mappingMethod = 'linear';
  69162. mappingOption.dataExtent = this.getExtent();
  69163. });
  69164. this._resetRange();
  69165. },
  69166. /**
  69167. * @protected
  69168. * @override
  69169. */
  69170. resetItemSize: function () {
  69171. ContinuousModel.superApply(this, 'resetItemSize', arguments);
  69172. var itemSize = this.itemSize;
  69173. this._orient === 'horizontal' && itemSize.reverse();
  69174. (itemSize[0] == null || isNaN(itemSize[0])) && (itemSize[0] = DEFAULT_BAR_BOUND[0]);
  69175. (itemSize[1] == null || isNaN(itemSize[1])) && (itemSize[1] = DEFAULT_BAR_BOUND[1]);
  69176. },
  69177. /**
  69178. * @private
  69179. */
  69180. _resetRange: function () {
  69181. var dataExtent = this.getExtent();
  69182. var range = this.option.range;
  69183. if (!range || range.auto) {
  69184. // `range` should always be array (so we dont use other
  69185. // value like 'auto') for user-friend. (consider getOption).
  69186. dataExtent.auto = 1;
  69187. this.option.range = dataExtent;
  69188. }
  69189. else if (isArray(range)) {
  69190. if (range[0] > range[1]) {
  69191. range.reverse();
  69192. }
  69193. range[0] = Math.max(range[0], dataExtent[0]);
  69194. range[1] = Math.min(range[1], dataExtent[1]);
  69195. }
  69196. },
  69197. /**
  69198. * @protected
  69199. * @override
  69200. */
  69201. completeVisualOption: function () {
  69202. VisualMapModel.prototype.completeVisualOption.apply(this, arguments);
  69203. each$1(this.stateList, function (state) {
  69204. var symbolSize = this.option.controller[state].symbolSize;
  69205. if (symbolSize && symbolSize[0] !== symbolSize[1]) {
  69206. symbolSize[0] = 0; // For good looking.
  69207. }
  69208. }, this);
  69209. },
  69210. /**
  69211. * @override
  69212. */
  69213. setSelected: function (selected) {
  69214. this.option.range = selected.slice();
  69215. this._resetRange();
  69216. },
  69217. /**
  69218. * @public
  69219. */
  69220. getSelected: function () {
  69221. var dataExtent = this.getExtent();
  69222. var dataInterval = asc(
  69223. (this.get('range') || []).slice()
  69224. );
  69225. // Clamp
  69226. dataInterval[0] > dataExtent[1] && (dataInterval[0] = dataExtent[1]);
  69227. dataInterval[1] > dataExtent[1] && (dataInterval[1] = dataExtent[1]);
  69228. dataInterval[0] < dataExtent[0] && (dataInterval[0] = dataExtent[0]);
  69229. dataInterval[1] < dataExtent[0] && (dataInterval[1] = dataExtent[0]);
  69230. return dataInterval;
  69231. },
  69232. /**
  69233. * @override
  69234. */
  69235. getValueState: function (value) {
  69236. var range = this.option.range;
  69237. var dataExtent = this.getExtent();
  69238. // When range[0] === dataExtent[0], any value larger than dataExtent[0] maps to 'inRange'.
  69239. // range[1] is processed likewise.
  69240. return (
  69241. (range[0] <= dataExtent[0] || range[0] <= value)
  69242. && (range[1] >= dataExtent[1] || value <= range[1])
  69243. ) ? 'inRange' : 'outOfRange';
  69244. },
  69245. /**
  69246. * @params {Array.<number>} range target value: range[0] <= value && value <= range[1]
  69247. * @return {Array.<Object>} [{seriesId, dataIndices: <Array.<number>>}, ...]
  69248. */
  69249. findTargetDataIndices: function (range) {
  69250. var result = [];
  69251. this.eachTargetSeries(function (seriesModel) {
  69252. var dataIndices = [];
  69253. var data = seriesModel.getData();
  69254. data.each(this.getDataDimension(data), function (value, dataIndex) {
  69255. range[0] <= value && value <= range[1] && dataIndices.push(dataIndex);
  69256. }, this);
  69257. result.push({seriesId: seriesModel.id, dataIndex: dataIndices});
  69258. }, this);
  69259. return result;
  69260. },
  69261. /**
  69262. * @implement
  69263. */
  69264. getVisualMeta: function (getColorVisual) {
  69265. var oVals = getColorStopValues(this, 'outOfRange', this.getExtent());
  69266. var iVals = getColorStopValues(this, 'inRange', this.option.range.slice());
  69267. var stops = [];
  69268. function setStop(value, valueState) {
  69269. stops.push({
  69270. value: value,
  69271. color: getColorVisual(value, valueState)
  69272. });
  69273. }
  69274. // Format to: outOfRange -- inRange -- outOfRange.
  69275. var iIdx = 0;
  69276. var oIdx = 0;
  69277. var iLen = iVals.length;
  69278. var oLen = oVals.length;
  69279. for (; oIdx < oLen && (!iVals.length || oVals[oIdx] <= iVals[0]); oIdx++) {
  69280. // If oVal[oIdx] === iVals[iIdx], oVal[oIdx] should be ignored.
  69281. if (oVals[oIdx] < iVals[iIdx]) {
  69282. setStop(oVals[oIdx], 'outOfRange');
  69283. }
  69284. }
  69285. for (var first = 1; iIdx < iLen; iIdx++, first = 0) {
  69286. // If range is full, value beyond min, max will be clamped.
  69287. // make a singularity
  69288. first && stops.length && setStop(iVals[iIdx], 'outOfRange');
  69289. setStop(iVals[iIdx], 'inRange');
  69290. }
  69291. for (var first = 1; oIdx < oLen; oIdx++) {
  69292. if (!iVals.length || iVals[iVals.length - 1] < oVals[oIdx]) {
  69293. // make a singularity
  69294. if (first) {
  69295. stops.length && setStop(stops[stops.length - 1].value, 'outOfRange');
  69296. first = 0;
  69297. }
  69298. setStop(oVals[oIdx], 'outOfRange');
  69299. }
  69300. }
  69301. var stopsLen = stops.length;
  69302. return {
  69303. stops: stops,
  69304. outerColors: [
  69305. stopsLen ? stops[0].color : 'transparent',
  69306. stopsLen ? stops[stopsLen - 1].color : 'transparent'
  69307. ]
  69308. };
  69309. }
  69310. });
  69311. function getColorStopValues(visualMapModel, valueState, dataExtent) {
  69312. if (dataExtent[0] === dataExtent[1]) {
  69313. return dataExtent.slice();
  69314. }
  69315. // When using colorHue mapping, it is not linear color any more.
  69316. // Moreover, canvas gradient seems not to be accurate linear.
  69317. // FIXME
  69318. // Should be arbitrary value 100? or based on pixel size?
  69319. var count = 200;
  69320. var step = (dataExtent[1] - dataExtent[0]) / count;
  69321. var value = dataExtent[0];
  69322. var stopValues = [];
  69323. for (var i = 0; i <= count && value < dataExtent[1]; i++) {
  69324. stopValues.push(value);
  69325. value += step;
  69326. }
  69327. stopValues.push(dataExtent[1]);
  69328. return stopValues;
  69329. }
  69330. /*
  69331. * Licensed to the Apache Software Foundation (ASF) under one
  69332. * or more contributor license agreements. See the NOTICE file
  69333. * distributed with this work for additional information
  69334. * regarding copyright ownership. The ASF licenses this file
  69335. * to you under the Apache License, Version 2.0 (the
  69336. * "License"); you may not use this file except in compliance
  69337. * with the License. You may obtain a copy of the License at
  69338. *
  69339. * http://www.apache.org/licenses/LICENSE-2.0
  69340. *
  69341. * Unless required by applicable law or agreed to in writing,
  69342. * software distributed under the License is distributed on an
  69343. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  69344. * KIND, either express or implied. See the License for the
  69345. * specific language governing permissions and limitations
  69346. * under the License.
  69347. */
  69348. var VisualMapView = extendComponentView({
  69349. type: 'visualMap',
  69350. /**
  69351. * @readOnly
  69352. * @type {Object}
  69353. */
  69354. autoPositionValues: {left: 1, right: 1, top: 1, bottom: 1},
  69355. init: function (ecModel, api) {
  69356. /**
  69357. * @readOnly
  69358. * @type {module:echarts/model/Global}
  69359. */
  69360. this.ecModel = ecModel;
  69361. /**
  69362. * @readOnly
  69363. * @type {module:echarts/ExtensionAPI}
  69364. */
  69365. this.api = api;
  69366. /**
  69367. * @readOnly
  69368. * @type {module:echarts/component/visualMap/visualMapModel}
  69369. */
  69370. this.visualMapModel;
  69371. },
  69372. /**
  69373. * @protected
  69374. */
  69375. render: function (visualMapModel, ecModel, api, payload) {
  69376. this.visualMapModel = visualMapModel;
  69377. if (visualMapModel.get('show') === false) {
  69378. this.group.removeAll();
  69379. return;
  69380. }
  69381. this.doRender.apply(this, arguments);
  69382. },
  69383. /**
  69384. * @protected
  69385. */
  69386. renderBackground: function (group) {
  69387. var visualMapModel = this.visualMapModel;
  69388. var padding = normalizeCssArray$1(visualMapModel.get('padding') || 0);
  69389. var rect = group.getBoundingRect();
  69390. group.add(new Rect({
  69391. z2: -1, // Lay background rect on the lowest layer.
  69392. silent: true,
  69393. shape: {
  69394. x: rect.x - padding[3],
  69395. y: rect.y - padding[0],
  69396. width: rect.width + padding[3] + padding[1],
  69397. height: rect.height + padding[0] + padding[2]
  69398. },
  69399. style: {
  69400. fill: visualMapModel.get('backgroundColor'),
  69401. stroke: visualMapModel.get('borderColor'),
  69402. lineWidth: visualMapModel.get('borderWidth')
  69403. }
  69404. }));
  69405. },
  69406. /**
  69407. * @protected
  69408. * @param {number} targetValue can be Infinity or -Infinity
  69409. * @param {string=} visualCluster Only can be 'color' 'opacity' 'symbol' 'symbolSize'
  69410. * @param {Object} [opts]
  69411. * @param {string=} [opts.forceState] Specify state, instead of using getValueState method.
  69412. * @param {string=} [opts.convertOpacityToAlpha=false] For color gradient in controller widget.
  69413. * @return {*} Visual value.
  69414. */
  69415. getControllerVisual: function (targetValue, visualCluster, opts) {
  69416. opts = opts || {};
  69417. var forceState = opts.forceState;
  69418. var visualMapModel = this.visualMapModel;
  69419. var visualObj = {};
  69420. // Default values.
  69421. if (visualCluster === 'symbol') {
  69422. visualObj.symbol = visualMapModel.get('itemSymbol');
  69423. }
  69424. if (visualCluster === 'color') {
  69425. var defaultColor = visualMapModel.get('contentColor');
  69426. visualObj.color = defaultColor;
  69427. }
  69428. function getter(key) {
  69429. return visualObj[key];
  69430. }
  69431. function setter(key, value) {
  69432. visualObj[key] = value;
  69433. }
  69434. var mappings = visualMapModel.controllerVisuals[
  69435. forceState || visualMapModel.getValueState(targetValue)
  69436. ];
  69437. var visualTypes = VisualMapping.prepareVisualTypes(mappings);
  69438. each$1(visualTypes, function (type) {
  69439. var visualMapping = mappings[type];
  69440. if (opts.convertOpacityToAlpha && type === 'opacity') {
  69441. type = 'colorAlpha';
  69442. visualMapping = mappings.__alphaForOpacity;
  69443. }
  69444. if (VisualMapping.dependsOn(type, visualCluster)) {
  69445. visualMapping && visualMapping.applyVisual(
  69446. targetValue, getter, setter
  69447. );
  69448. }
  69449. });
  69450. return visualObj[visualCluster];
  69451. },
  69452. /**
  69453. * @protected
  69454. */
  69455. positionGroup: function (group) {
  69456. var model = this.visualMapModel;
  69457. var api = this.api;
  69458. positionElement(
  69459. group,
  69460. model.getBoxLayoutParams(),
  69461. {width: api.getWidth(), height: api.getHeight()}
  69462. );
  69463. },
  69464. /**
  69465. * @protected
  69466. * @abstract
  69467. */
  69468. doRender: noop
  69469. });
  69470. /*
  69471. * Licensed to the Apache Software Foundation (ASF) under one
  69472. * or more contributor license agreements. See the NOTICE file
  69473. * distributed with this work for additional information
  69474. * regarding copyright ownership. The ASF licenses this file
  69475. * to you under the Apache License, Version 2.0 (the
  69476. * "License"); you may not use this file except in compliance
  69477. * with the License. You may obtain a copy of the License at
  69478. *
  69479. * http://www.apache.org/licenses/LICENSE-2.0
  69480. *
  69481. * Unless required by applicable law or agreed to in writing,
  69482. * software distributed under the License is distributed on an
  69483. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  69484. * KIND, either express or implied. See the License for the
  69485. * specific language governing permissions and limitations
  69486. * under the License.
  69487. */
  69488. /**
  69489. * @param {module:echarts/component/visualMap/VisualMapModel} visualMapModel\
  69490. * @param {module:echarts/ExtensionAPI} api
  69491. * @param {Array.<number>} itemSize always [short, long]
  69492. * @return {string} 'left' or 'right' or 'top' or 'bottom'
  69493. */
  69494. function getItemAlign(visualMapModel, api, itemSize) {
  69495. var modelOption = visualMapModel.option;
  69496. var itemAlign = modelOption.align;
  69497. if (itemAlign != null && itemAlign !== 'auto') {
  69498. return itemAlign;
  69499. }
  69500. // Auto decision align.
  69501. var ecSize = {width: api.getWidth(), height: api.getHeight()};
  69502. var realIndex = modelOption.orient === 'horizontal' ? 1 : 0;
  69503. var paramsSet = [
  69504. ['left', 'right', 'width'],
  69505. ['top', 'bottom', 'height']
  69506. ];
  69507. var reals = paramsSet[realIndex];
  69508. var fakeValue = [0, null, 10];
  69509. var layoutInput = {};
  69510. for (var i = 0; i < 3; i++) {
  69511. layoutInput[paramsSet[1 - realIndex][i]] = fakeValue[i];
  69512. layoutInput[reals[i]] = i === 2 ? itemSize[0] : modelOption[reals[i]];
  69513. }
  69514. var rParam = [['x', 'width', 3], ['y', 'height', 0]][realIndex];
  69515. var rect = getLayoutRect(layoutInput, ecSize, modelOption.padding);
  69516. return reals[
  69517. (rect.margin[rParam[2]] || 0) + rect[rParam[0]] + rect[rParam[1]] * 0.5
  69518. < ecSize[rParam[1]] * 0.5 ? 0 : 1
  69519. ];
  69520. }
  69521. /**
  69522. * Prepare dataIndex for outside usage, where dataIndex means rawIndex, and
  69523. * dataIndexInside means filtered index.
  69524. */
  69525. function convertDataIndex(batch) {
  69526. each$1(batch || [], function (batchItem) {
  69527. if (batch.dataIndex != null) {
  69528. batch.dataIndexInside = batch.dataIndex;
  69529. batch.dataIndex = null;
  69530. }
  69531. });
  69532. return batch;
  69533. }
  69534. /*
  69535. * Licensed to the Apache Software Foundation (ASF) under one
  69536. * or more contributor license agreements. See the NOTICE file
  69537. * distributed with this work for additional information
  69538. * regarding copyright ownership. The ASF licenses this file
  69539. * to you under the Apache License, Version 2.0 (the
  69540. * "License"); you may not use this file except in compliance
  69541. * with the License. You may obtain a copy of the License at
  69542. *
  69543. * http://www.apache.org/licenses/LICENSE-2.0
  69544. *
  69545. * Unless required by applicable law or agreed to in writing,
  69546. * software distributed under the License is distributed on an
  69547. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  69548. * KIND, either express or implied. See the License for the
  69549. * specific language governing permissions and limitations
  69550. * under the License.
  69551. */
  69552. var linearMap$3 = linearMap;
  69553. var each$26 = each$1;
  69554. var mathMin$7 = Math.min;
  69555. var mathMax$7 = Math.max;
  69556. // Arbitrary value
  69557. var HOVER_LINK_SIZE = 12;
  69558. var HOVER_LINK_OUT = 6;
  69559. // Notice:
  69560. // Any "interval" should be by the order of [low, high].
  69561. // "handle0" (handleIndex === 0) maps to
  69562. // low data value: this._dataInterval[0] and has low coord.
  69563. // "handle1" (handleIndex === 1) maps to
  69564. // high data value: this._dataInterval[1] and has high coord.
  69565. // The logic of transform is implemented in this._createBarGroup.
  69566. var ContinuousView = VisualMapView.extend({
  69567. type: 'visualMap.continuous',
  69568. /**
  69569. * @override
  69570. */
  69571. init: function () {
  69572. ContinuousView.superApply(this, 'init', arguments);
  69573. /**
  69574. * @private
  69575. */
  69576. this._shapes = {};
  69577. /**
  69578. * @private
  69579. */
  69580. this._dataInterval = [];
  69581. /**
  69582. * @private
  69583. */
  69584. this._handleEnds = [];
  69585. /**
  69586. * @private
  69587. */
  69588. this._orient;
  69589. /**
  69590. * @private
  69591. */
  69592. this._useHandle;
  69593. /**
  69594. * @private
  69595. */
  69596. this._hoverLinkDataIndices = [];
  69597. /**
  69598. * @private
  69599. */
  69600. this._dragging;
  69601. /**
  69602. * @private
  69603. */
  69604. this._hovering;
  69605. },
  69606. /**
  69607. * @protected
  69608. * @override
  69609. */
  69610. doRender: function (visualMapModel, ecModel, api, payload) {
  69611. if (!payload || payload.type !== 'selectDataRange' || payload.from !== this.uid) {
  69612. this._buildView();
  69613. }
  69614. },
  69615. /**
  69616. * @private
  69617. */
  69618. _buildView: function () {
  69619. this.group.removeAll();
  69620. var visualMapModel = this.visualMapModel;
  69621. var thisGroup = this.group;
  69622. this._orient = visualMapModel.get('orient');
  69623. this._useHandle = visualMapModel.get('calculable');
  69624. this._resetInterval();
  69625. this._renderBar(thisGroup);
  69626. var dataRangeText = visualMapModel.get('text');
  69627. this._renderEndsText(thisGroup, dataRangeText, 0);
  69628. this._renderEndsText(thisGroup, dataRangeText, 1);
  69629. // Do this for background size calculation.
  69630. this._updateView(true);
  69631. // After updating view, inner shapes is built completely,
  69632. // and then background can be rendered.
  69633. this.renderBackground(thisGroup);
  69634. // Real update view
  69635. this._updateView();
  69636. this._enableHoverLinkToSeries();
  69637. this._enableHoverLinkFromSeries();
  69638. this.positionGroup(thisGroup);
  69639. },
  69640. /**
  69641. * @private
  69642. */
  69643. _renderEndsText: function (group, dataRangeText, endsIndex) {
  69644. if (!dataRangeText) {
  69645. return;
  69646. }
  69647. // Compatible with ec2, text[0] map to high value, text[1] map low value.
  69648. var text = dataRangeText[1 - endsIndex];
  69649. text = text != null ? text + '' : '';
  69650. var visualMapModel = this.visualMapModel;
  69651. var textGap = visualMapModel.get('textGap');
  69652. var itemSize = visualMapModel.itemSize;
  69653. var barGroup = this._shapes.barGroup;
  69654. var position = this._applyTransform(
  69655. [
  69656. itemSize[0] / 2,
  69657. endsIndex === 0 ? -textGap : itemSize[1] + textGap
  69658. ],
  69659. barGroup
  69660. );
  69661. var align = this._applyTransform(
  69662. endsIndex === 0 ? 'bottom' : 'top',
  69663. barGroup
  69664. );
  69665. var orient = this._orient;
  69666. var textStyleModel = this.visualMapModel.textStyleModel;
  69667. this.group.add(new Text({
  69668. style: {
  69669. x: position[0],
  69670. y: position[1],
  69671. textVerticalAlign: orient === 'horizontal' ? 'middle' : align,
  69672. textAlign: orient === 'horizontal' ? align : 'center',
  69673. text: text,
  69674. textFont: textStyleModel.getFont(),
  69675. textFill: textStyleModel.getTextColor()
  69676. }
  69677. }));
  69678. },
  69679. /**
  69680. * @private
  69681. */
  69682. _renderBar: function (targetGroup) {
  69683. var visualMapModel = this.visualMapModel;
  69684. var shapes = this._shapes;
  69685. var itemSize = visualMapModel.itemSize;
  69686. var orient = this._orient;
  69687. var useHandle = this._useHandle;
  69688. var itemAlign = getItemAlign(visualMapModel, this.api, itemSize);
  69689. var barGroup = shapes.barGroup = this._createBarGroup(itemAlign);
  69690. // Bar
  69691. barGroup.add(shapes.outOfRange = createPolygon());
  69692. barGroup.add(shapes.inRange = createPolygon(
  69693. null,
  69694. useHandle ? getCursor$1(this._orient) : null,
  69695. bind(this._dragHandle, this, 'all', false),
  69696. bind(this._dragHandle, this, 'all', true)
  69697. ));
  69698. var textRect = visualMapModel.textStyleModel.getTextRect('国');
  69699. var textSize = mathMax$7(textRect.width, textRect.height);
  69700. // Handle
  69701. if (useHandle) {
  69702. shapes.handleThumbs = [];
  69703. shapes.handleLabels = [];
  69704. shapes.handleLabelPoints = [];
  69705. this._createHandle(barGroup, 0, itemSize, textSize, orient, itemAlign);
  69706. this._createHandle(barGroup, 1, itemSize, textSize, orient, itemAlign);
  69707. }
  69708. this._createIndicator(barGroup, itemSize, textSize, orient);
  69709. targetGroup.add(barGroup);
  69710. },
  69711. /**
  69712. * @private
  69713. */
  69714. _createHandle: function (barGroup, handleIndex, itemSize, textSize, orient) {
  69715. var onDrift = bind(this._dragHandle, this, handleIndex, false);
  69716. var onDragEnd = bind(this._dragHandle, this, handleIndex, true);
  69717. var handleThumb = createPolygon(
  69718. createHandlePoints(handleIndex, textSize),
  69719. getCursor$1(this._orient),
  69720. onDrift,
  69721. onDragEnd
  69722. );
  69723. handleThumb.position[0] = itemSize[0];
  69724. barGroup.add(handleThumb);
  69725. // Text is always horizontal layout but should not be effected by
  69726. // transform (orient/inverse). So label is built separately but not
  69727. // use zrender/graphic/helper/RectText, and is located based on view
  69728. // group (according to handleLabelPoint) but not barGroup.
  69729. var textStyleModel = this.visualMapModel.textStyleModel;
  69730. var handleLabel = new Text({
  69731. draggable: true,
  69732. drift: onDrift,
  69733. onmousemove: function (e) {
  69734. // Fot mobile devicem, prevent screen slider on the button.
  69735. stop(e.event);
  69736. },
  69737. ondragend: onDragEnd,
  69738. style: {
  69739. x: 0, y: 0, text: '',
  69740. textFont: textStyleModel.getFont(),
  69741. textFill: textStyleModel.getTextColor()
  69742. }
  69743. });
  69744. this.group.add(handleLabel);
  69745. var handleLabelPoint = [
  69746. orient === 'horizontal'
  69747. ? textSize / 2
  69748. : textSize * 1.5,
  69749. orient === 'horizontal'
  69750. ? (handleIndex === 0 ? -(textSize * 1.5) : (textSize * 1.5))
  69751. : (handleIndex === 0 ? -textSize / 2 : textSize / 2)
  69752. ];
  69753. var shapes = this._shapes;
  69754. shapes.handleThumbs[handleIndex] = handleThumb;
  69755. shapes.handleLabelPoints[handleIndex] = handleLabelPoint;
  69756. shapes.handleLabels[handleIndex] = handleLabel;
  69757. },
  69758. /**
  69759. * @private
  69760. */
  69761. _createIndicator: function (barGroup, itemSize, textSize, orient) {
  69762. var indicator = createPolygon([[0, 0]], 'move');
  69763. indicator.position[0] = itemSize[0];
  69764. indicator.attr({invisible: true, silent: true});
  69765. barGroup.add(indicator);
  69766. var textStyleModel = this.visualMapModel.textStyleModel;
  69767. var indicatorLabel = new Text({
  69768. silent: true,
  69769. invisible: true,
  69770. style: {
  69771. x: 0, y: 0, text: '',
  69772. textFont: textStyleModel.getFont(),
  69773. textFill: textStyleModel.getTextColor()
  69774. }
  69775. });
  69776. this.group.add(indicatorLabel);
  69777. var indicatorLabelPoint = [
  69778. orient === 'horizontal' ? textSize / 2 : HOVER_LINK_OUT + 3,
  69779. 0
  69780. ];
  69781. var shapes = this._shapes;
  69782. shapes.indicator = indicator;
  69783. shapes.indicatorLabel = indicatorLabel;
  69784. shapes.indicatorLabelPoint = indicatorLabelPoint;
  69785. },
  69786. /**
  69787. * @private
  69788. */
  69789. _dragHandle: function (handleIndex, isEnd, dx, dy) {
  69790. if (!this._useHandle) {
  69791. return;
  69792. }
  69793. this._dragging = !isEnd;
  69794. if (!isEnd) {
  69795. // Transform dx, dy to bar coordination.
  69796. var vertex = this._applyTransform([dx, dy], this._shapes.barGroup, true);
  69797. this._updateInterval(handleIndex, vertex[1]);
  69798. // Considering realtime, update view should be executed
  69799. // before dispatch action.
  69800. this._updateView();
  69801. }
  69802. // dragEnd do not dispatch action when realtime.
  69803. if (isEnd === !this.visualMapModel.get('realtime')) { // jshint ignore:line
  69804. this.api.dispatchAction({
  69805. type: 'selectDataRange',
  69806. from: this.uid,
  69807. visualMapId: this.visualMapModel.id,
  69808. selected: this._dataInterval.slice()
  69809. });
  69810. }
  69811. if (isEnd) {
  69812. !this._hovering && this._clearHoverLinkToSeries();
  69813. }
  69814. else if (useHoverLinkOnHandle(this.visualMapModel)) {
  69815. this._doHoverLinkToSeries(this._handleEnds[handleIndex], false);
  69816. }
  69817. },
  69818. /**
  69819. * @private
  69820. */
  69821. _resetInterval: function () {
  69822. var visualMapModel = this.visualMapModel;
  69823. var dataInterval = this._dataInterval = visualMapModel.getSelected();
  69824. var dataExtent = visualMapModel.getExtent();
  69825. var sizeExtent = [0, visualMapModel.itemSize[1]];
  69826. this._handleEnds = [
  69827. linearMap$3(dataInterval[0], dataExtent, sizeExtent, true),
  69828. linearMap$3(dataInterval[1], dataExtent, sizeExtent, true)
  69829. ];
  69830. },
  69831. /**
  69832. * @private
  69833. * @param {(number|string)} handleIndex 0 or 1 or 'all'
  69834. * @param {number} dx
  69835. * @param {number} dy
  69836. */
  69837. _updateInterval: function (handleIndex, delta) {
  69838. delta = delta || 0;
  69839. var visualMapModel = this.visualMapModel;
  69840. var handleEnds = this._handleEnds;
  69841. var sizeExtent = [0, visualMapModel.itemSize[1]];
  69842. sliderMove(
  69843. delta,
  69844. handleEnds,
  69845. sizeExtent,
  69846. handleIndex,
  69847. // cross is forbiden
  69848. 0
  69849. );
  69850. var dataExtent = visualMapModel.getExtent();
  69851. // Update data interval.
  69852. this._dataInterval = [
  69853. linearMap$3(handleEnds[0], sizeExtent, dataExtent, true),
  69854. linearMap$3(handleEnds[1], sizeExtent, dataExtent, true)
  69855. ];
  69856. },
  69857. /**
  69858. * @private
  69859. */
  69860. _updateView: function (forSketch) {
  69861. var visualMapModel = this.visualMapModel;
  69862. var dataExtent = visualMapModel.getExtent();
  69863. var shapes = this._shapes;
  69864. var outOfRangeHandleEnds = [0, visualMapModel.itemSize[1]];
  69865. var inRangeHandleEnds = forSketch ? outOfRangeHandleEnds : this._handleEnds;
  69866. var visualInRange = this._createBarVisual(
  69867. this._dataInterval, dataExtent, inRangeHandleEnds, 'inRange'
  69868. );
  69869. var visualOutOfRange = this._createBarVisual(
  69870. dataExtent, dataExtent, outOfRangeHandleEnds, 'outOfRange'
  69871. );
  69872. shapes.inRange
  69873. .setStyle({
  69874. fill: visualInRange.barColor,
  69875. opacity: visualInRange.opacity
  69876. })
  69877. .setShape('points', visualInRange.barPoints);
  69878. shapes.outOfRange
  69879. .setStyle({
  69880. fill: visualOutOfRange.barColor,
  69881. opacity: visualOutOfRange.opacity
  69882. })
  69883. .setShape('points', visualOutOfRange.barPoints);
  69884. this._updateHandle(inRangeHandleEnds, visualInRange);
  69885. },
  69886. /**
  69887. * @private
  69888. */
  69889. _createBarVisual: function (dataInterval, dataExtent, handleEnds, forceState) {
  69890. var opts = {
  69891. forceState: forceState,
  69892. convertOpacityToAlpha: true
  69893. };
  69894. var colorStops = this._makeColorGradient(dataInterval, opts);
  69895. var symbolSizes = [
  69896. this.getControllerVisual(dataInterval[0], 'symbolSize', opts),
  69897. this.getControllerVisual(dataInterval[1], 'symbolSize', opts)
  69898. ];
  69899. var barPoints = this._createBarPoints(handleEnds, symbolSizes);
  69900. return {
  69901. barColor: new LinearGradient(0, 0, 0, 1, colorStops),
  69902. barPoints: barPoints,
  69903. handlesColor: [
  69904. colorStops[0].color,
  69905. colorStops[colorStops.length - 1].color
  69906. ]
  69907. };
  69908. },
  69909. /**
  69910. * @private
  69911. */
  69912. _makeColorGradient: function (dataInterval, opts) {
  69913. // Considering colorHue, which is not linear, so we have to sample
  69914. // to calculate gradient color stops, but not only caculate head
  69915. // and tail.
  69916. var sampleNumber = 100; // Arbitrary value.
  69917. var colorStops = [];
  69918. var step = (dataInterval[1] - dataInterval[0]) / sampleNumber;
  69919. colorStops.push({
  69920. color: this.getControllerVisual(dataInterval[0], 'color', opts),
  69921. offset: 0
  69922. });
  69923. for (var i = 1; i < sampleNumber; i++) {
  69924. var currValue = dataInterval[0] + step * i;
  69925. if (currValue > dataInterval[1]) {
  69926. break;
  69927. }
  69928. colorStops.push({
  69929. color: this.getControllerVisual(currValue, 'color', opts),
  69930. offset: i / sampleNumber
  69931. });
  69932. }
  69933. colorStops.push({
  69934. color: this.getControllerVisual(dataInterval[1], 'color', opts),
  69935. offset: 1
  69936. });
  69937. return colorStops;
  69938. },
  69939. /**
  69940. * @private
  69941. */
  69942. _createBarPoints: function (handleEnds, symbolSizes) {
  69943. var itemSize = this.visualMapModel.itemSize;
  69944. return [
  69945. [itemSize[0] - symbolSizes[0], handleEnds[0]],
  69946. [itemSize[0], handleEnds[0]],
  69947. [itemSize[0], handleEnds[1]],
  69948. [itemSize[0] - symbolSizes[1], handleEnds[1]]
  69949. ];
  69950. },
  69951. /**
  69952. * @private
  69953. */
  69954. _createBarGroup: function (itemAlign) {
  69955. var orient = this._orient;
  69956. var inverse = this.visualMapModel.get('inverse');
  69957. return new Group(
  69958. (orient === 'horizontal' && !inverse)
  69959. ? {scale: itemAlign === 'bottom' ? [1, 1] : [-1, 1], rotation: Math.PI / 2}
  69960. : (orient === 'horizontal' && inverse)
  69961. ? {scale: itemAlign === 'bottom' ? [-1, 1] : [1, 1], rotation: -Math.PI / 2}
  69962. : (orient === 'vertical' && !inverse)
  69963. ? {scale: itemAlign === 'left' ? [1, -1] : [-1, -1]}
  69964. : {scale: itemAlign === 'left' ? [1, 1] : [-1, 1]}
  69965. );
  69966. },
  69967. /**
  69968. * @private
  69969. */
  69970. _updateHandle: function (handleEnds, visualInRange) {
  69971. if (!this._useHandle) {
  69972. return;
  69973. }
  69974. var shapes = this._shapes;
  69975. var visualMapModel = this.visualMapModel;
  69976. var handleThumbs = shapes.handleThumbs;
  69977. var handleLabels = shapes.handleLabels;
  69978. each$26([0, 1], function (handleIndex) {
  69979. var handleThumb = handleThumbs[handleIndex];
  69980. handleThumb.setStyle('fill', visualInRange.handlesColor[handleIndex]);
  69981. handleThumb.position[1] = handleEnds[handleIndex];
  69982. // Update handle label position.
  69983. var textPoint = applyTransform$1(
  69984. shapes.handleLabelPoints[handleIndex],
  69985. getTransform(handleThumb, this.group)
  69986. );
  69987. handleLabels[handleIndex].setStyle({
  69988. x: textPoint[0],
  69989. y: textPoint[1],
  69990. text: visualMapModel.formatValueText(this._dataInterval[handleIndex]),
  69991. textVerticalAlign: 'middle',
  69992. textAlign: this._applyTransform(
  69993. this._orient === 'horizontal'
  69994. ? (handleIndex === 0 ? 'bottom' : 'top')
  69995. : 'left',
  69996. shapes.barGroup
  69997. )
  69998. });
  69999. }, this);
  70000. },
  70001. /**
  70002. * @private
  70003. * @param {number} cursorValue
  70004. * @param {number} textValue
  70005. * @param {string} [rangeSymbol]
  70006. * @param {number} [halfHoverLinkSize]
  70007. */
  70008. _showIndicator: function (cursorValue, textValue, rangeSymbol, halfHoverLinkSize) {
  70009. var visualMapModel = this.visualMapModel;
  70010. var dataExtent = visualMapModel.getExtent();
  70011. var itemSize = visualMapModel.itemSize;
  70012. var sizeExtent = [0, itemSize[1]];
  70013. var pos = linearMap$3(cursorValue, dataExtent, sizeExtent, true);
  70014. var shapes = this._shapes;
  70015. var indicator = shapes.indicator;
  70016. if (!indicator) {
  70017. return;
  70018. }
  70019. indicator.position[1] = pos;
  70020. indicator.attr('invisible', false);
  70021. indicator.setShape('points', createIndicatorPoints(
  70022. !!rangeSymbol, halfHoverLinkSize, pos, itemSize[1]
  70023. ));
  70024. var opts = {convertOpacityToAlpha: true};
  70025. var color = this.getControllerVisual(cursorValue, 'color', opts);
  70026. indicator.setStyle('fill', color);
  70027. // Update handle label position.
  70028. var textPoint = applyTransform$1(
  70029. shapes.indicatorLabelPoint,
  70030. getTransform(indicator, this.group)
  70031. );
  70032. var indicatorLabel = shapes.indicatorLabel;
  70033. indicatorLabel.attr('invisible', false);
  70034. var align = this._applyTransform('left', shapes.barGroup);
  70035. var orient = this._orient;
  70036. indicatorLabel.setStyle({
  70037. text: (rangeSymbol ? rangeSymbol : '') + visualMapModel.formatValueText(textValue),
  70038. textVerticalAlign: orient === 'horizontal' ? align : 'middle',
  70039. textAlign: orient === 'horizontal' ? 'center' : align,
  70040. x: textPoint[0],
  70041. y: textPoint[1]
  70042. });
  70043. },
  70044. /**
  70045. * @private
  70046. */
  70047. _enableHoverLinkToSeries: function () {
  70048. var self = this;
  70049. this._shapes.barGroup
  70050. .on('mousemove', function (e) {
  70051. self._hovering = true;
  70052. if (!self._dragging) {
  70053. var itemSize = self.visualMapModel.itemSize;
  70054. var pos = self._applyTransform(
  70055. [e.offsetX, e.offsetY], self._shapes.barGroup, true, true
  70056. );
  70057. // For hover link show when hover handle, which might be
  70058. // below or upper than sizeExtent.
  70059. pos[1] = mathMin$7(mathMax$7(0, pos[1]), itemSize[1]);
  70060. self._doHoverLinkToSeries(
  70061. pos[1],
  70062. 0 <= pos[0] && pos[0] <= itemSize[0]
  70063. );
  70064. }
  70065. })
  70066. .on('mouseout', function () {
  70067. // When mouse is out of handle, hoverLink still need
  70068. // to be displayed when realtime is set as false.
  70069. self._hovering = false;
  70070. !self._dragging && self._clearHoverLinkToSeries();
  70071. });
  70072. },
  70073. /**
  70074. * @private
  70075. */
  70076. _enableHoverLinkFromSeries: function () {
  70077. var zr = this.api.getZr();
  70078. if (this.visualMapModel.option.hoverLink) {
  70079. zr.on('mouseover', this._hoverLinkFromSeriesMouseOver, this);
  70080. zr.on('mouseout', this._hideIndicator, this);
  70081. }
  70082. else {
  70083. this._clearHoverLinkFromSeries();
  70084. }
  70085. },
  70086. /**
  70087. * @private
  70088. */
  70089. _doHoverLinkToSeries: function (cursorPos, hoverOnBar) {
  70090. var visualMapModel = this.visualMapModel;
  70091. var itemSize = visualMapModel.itemSize;
  70092. if (!visualMapModel.option.hoverLink) {
  70093. return;
  70094. }
  70095. var sizeExtent = [0, itemSize[1]];
  70096. var dataExtent = visualMapModel.getExtent();
  70097. // For hover link show when hover handle, which might be below or upper than sizeExtent.
  70098. cursorPos = mathMin$7(mathMax$7(sizeExtent[0], cursorPos), sizeExtent[1]);
  70099. var halfHoverLinkSize = getHalfHoverLinkSize(visualMapModel, dataExtent, sizeExtent);
  70100. var hoverRange = [cursorPos - halfHoverLinkSize, cursorPos + halfHoverLinkSize];
  70101. var cursorValue = linearMap$3(cursorPos, sizeExtent, dataExtent, true);
  70102. var valueRange = [
  70103. linearMap$3(hoverRange[0], sizeExtent, dataExtent, true),
  70104. linearMap$3(hoverRange[1], sizeExtent, dataExtent, true)
  70105. ];
  70106. // Consider data range is out of visualMap range, see test/visualMap-continuous.html,
  70107. // where china and india has very large population.
  70108. hoverRange[0] < sizeExtent[0] && (valueRange[0] = -Infinity);
  70109. hoverRange[1] > sizeExtent[1] && (valueRange[1] = Infinity);
  70110. // Do not show indicator when mouse is over handle,
  70111. // otherwise labels overlap, especially when dragging.
  70112. if (hoverOnBar) {
  70113. if (valueRange[0] === -Infinity) {
  70114. this._showIndicator(cursorValue, valueRange[1], '< ', halfHoverLinkSize);
  70115. }
  70116. else if (valueRange[1] === Infinity) {
  70117. this._showIndicator(cursorValue, valueRange[0], '> ', halfHoverLinkSize);
  70118. }
  70119. else {
  70120. this._showIndicator(cursorValue, cursorValue, '≈ ', halfHoverLinkSize);
  70121. }
  70122. }
  70123. // When realtime is set as false, handles, which are in barGroup,
  70124. // also trigger hoverLink, which help user to realize where they
  70125. // focus on when dragging. (see test/heatmap-large.html)
  70126. // When realtime is set as true, highlight will not show when hover
  70127. // handle, because the label on handle, which displays a exact value
  70128. // but not range, might mislead users.
  70129. var oldBatch = this._hoverLinkDataIndices;
  70130. var newBatch = [];
  70131. if (hoverOnBar || useHoverLinkOnHandle(visualMapModel)) {
  70132. newBatch = this._hoverLinkDataIndices = visualMapModel.findTargetDataIndices(valueRange);
  70133. }
  70134. var resultBatches = compressBatches(oldBatch, newBatch);
  70135. this._dispatchHighDown('downplay', convertDataIndex(resultBatches[0]));
  70136. this._dispatchHighDown('highlight', convertDataIndex(resultBatches[1]));
  70137. },
  70138. /**
  70139. * @private
  70140. */
  70141. _hoverLinkFromSeriesMouseOver: function (e) {
  70142. var el = e.target;
  70143. var visualMapModel = this.visualMapModel;
  70144. if (!el || el.dataIndex == null) {
  70145. return;
  70146. }
  70147. var dataModel = this.ecModel.getSeriesByIndex(el.seriesIndex);
  70148. if (!visualMapModel.isTargetSeries(dataModel)) {
  70149. return;
  70150. }
  70151. var data = dataModel.getData(el.dataType);
  70152. var value = data.get(visualMapModel.getDataDimension(data), el.dataIndex, true);
  70153. if (!isNaN(value)) {
  70154. this._showIndicator(value, value);
  70155. }
  70156. },
  70157. /**
  70158. * @private
  70159. */
  70160. _hideIndicator: function () {
  70161. var shapes = this._shapes;
  70162. shapes.indicator && shapes.indicator.attr('invisible', true);
  70163. shapes.indicatorLabel && shapes.indicatorLabel.attr('invisible', true);
  70164. },
  70165. /**
  70166. * @private
  70167. */
  70168. _clearHoverLinkToSeries: function () {
  70169. this._hideIndicator();
  70170. var indices = this._hoverLinkDataIndices;
  70171. this._dispatchHighDown('downplay', convertDataIndex(indices));
  70172. indices.length = 0;
  70173. },
  70174. /**
  70175. * @private
  70176. */
  70177. _clearHoverLinkFromSeries: function () {
  70178. this._hideIndicator();
  70179. var zr = this.api.getZr();
  70180. zr.off('mouseover', this._hoverLinkFromSeriesMouseOver);
  70181. zr.off('mouseout', this._hideIndicator);
  70182. },
  70183. /**
  70184. * @private
  70185. */
  70186. _applyTransform: function (vertex, element, inverse, global) {
  70187. var transform = getTransform(element, global ? null : this.group);
  70188. return graphic[
  70189. isArray(vertex) ? 'applyTransform' : 'transformDirection'
  70190. ](vertex, transform, inverse);
  70191. },
  70192. /**
  70193. * @private
  70194. */
  70195. _dispatchHighDown: function (type, batch) {
  70196. batch && batch.length && this.api.dispatchAction({
  70197. type: type,
  70198. batch: batch
  70199. });
  70200. },
  70201. /**
  70202. * @override
  70203. */
  70204. dispose: function () {
  70205. this._clearHoverLinkFromSeries();
  70206. this._clearHoverLinkToSeries();
  70207. },
  70208. /**
  70209. * @override
  70210. */
  70211. remove: function () {
  70212. this._clearHoverLinkFromSeries();
  70213. this._clearHoverLinkToSeries();
  70214. }
  70215. });
  70216. function createPolygon(points, cursor, onDrift, onDragEnd) {
  70217. return new Polygon({
  70218. shape: {points: points},
  70219. draggable: !!onDrift,
  70220. cursor: cursor,
  70221. drift: onDrift,
  70222. onmousemove: function (e) {
  70223. // Fot mobile devicem, prevent screen slider on the button.
  70224. stop(e.event);
  70225. },
  70226. ondragend: onDragEnd
  70227. });
  70228. }
  70229. function createHandlePoints(handleIndex, textSize) {
  70230. return handleIndex === 0
  70231. ? [[0, 0], [textSize, 0], [textSize, -textSize]]
  70232. : [[0, 0], [textSize, 0], [textSize, textSize]];
  70233. }
  70234. function createIndicatorPoints(isRange, halfHoverLinkSize, pos, extentMax) {
  70235. return isRange
  70236. ? [ // indicate range
  70237. [0, -mathMin$7(halfHoverLinkSize, mathMax$7(pos, 0))],
  70238. [HOVER_LINK_OUT, 0],
  70239. [0, mathMin$7(halfHoverLinkSize, mathMax$7(extentMax - pos, 0))]
  70240. ]
  70241. : [ // indicate single value
  70242. [0, 0], [5, -5], [5, 5]
  70243. ];
  70244. }
  70245. function getHalfHoverLinkSize(visualMapModel, dataExtent, sizeExtent) {
  70246. var halfHoverLinkSize = HOVER_LINK_SIZE / 2;
  70247. var hoverLinkDataSize = visualMapModel.get('hoverLinkDataSize');
  70248. if (hoverLinkDataSize) {
  70249. halfHoverLinkSize = linearMap$3(hoverLinkDataSize, dataExtent, sizeExtent, true) / 2;
  70250. }
  70251. return halfHoverLinkSize;
  70252. }
  70253. function useHoverLinkOnHandle(visualMapModel) {
  70254. var hoverLinkOnHandle = visualMapModel.get('hoverLinkOnHandle');
  70255. return !!(hoverLinkOnHandle == null ? visualMapModel.get('realtime') : hoverLinkOnHandle);
  70256. }
  70257. function getCursor$1(orient) {
  70258. return orient === 'vertical' ? 'ns-resize' : 'ew-resize';
  70259. }
  70260. /*
  70261. * Licensed to the Apache Software Foundation (ASF) under one
  70262. * or more contributor license agreements. See the NOTICE file
  70263. * distributed with this work for additional information
  70264. * regarding copyright ownership. The ASF licenses this file
  70265. * to you under the Apache License, Version 2.0 (the
  70266. * "License"); you may not use this file except in compliance
  70267. * with the License. You may obtain a copy of the License at
  70268. *
  70269. * http://www.apache.org/licenses/LICENSE-2.0
  70270. *
  70271. * Unless required by applicable law or agreed to in writing,
  70272. * software distributed under the License is distributed on an
  70273. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  70274. * KIND, either express or implied. See the License for the
  70275. * specific language governing permissions and limitations
  70276. * under the License.
  70277. */
  70278. var actionInfo$2 = {
  70279. type: 'selectDataRange',
  70280. event: 'dataRangeSelected',
  70281. // FIXME use updateView appears wrong
  70282. update: 'update'
  70283. };
  70284. registerAction(actionInfo$2, function (payload, ecModel) {
  70285. ecModel.eachComponent({mainType: 'visualMap', query: payload}, function (model) {
  70286. model.setSelected(payload.selected);
  70287. });
  70288. });
  70289. /*
  70290. * Licensed to the Apache Software Foundation (ASF) under one
  70291. * or more contributor license agreements. See the NOTICE file
  70292. * distributed with this work for additional information
  70293. * regarding copyright ownership. The ASF licenses this file
  70294. * to you under the Apache License, Version 2.0 (the
  70295. * "License"); you may not use this file except in compliance
  70296. * with the License. You may obtain a copy of the License at
  70297. *
  70298. * http://www.apache.org/licenses/LICENSE-2.0
  70299. *
  70300. * Unless required by applicable law or agreed to in writing,
  70301. * software distributed under the License is distributed on an
  70302. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  70303. * KIND, either express or implied. See the License for the
  70304. * specific language governing permissions and limitations
  70305. * under the License.
  70306. */
  70307. /**
  70308. * DataZoom component entry
  70309. */
  70310. registerPreprocessor(preprocessor$2);
  70311. /*
  70312. * Licensed to the Apache Software Foundation (ASF) under one
  70313. * or more contributor license agreements. See the NOTICE file
  70314. * distributed with this work for additional information
  70315. * regarding copyright ownership. The ASF licenses this file
  70316. * to you under the Apache License, Version 2.0 (the
  70317. * "License"); you may not use this file except in compliance
  70318. * with the License. You may obtain a copy of the License at
  70319. *
  70320. * http://www.apache.org/licenses/LICENSE-2.0
  70321. *
  70322. * Unless required by applicable law or agreed to in writing,
  70323. * software distributed under the License is distributed on an
  70324. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  70325. * KIND, either express or implied. See the License for the
  70326. * specific language governing permissions and limitations
  70327. * under the License.
  70328. */
  70329. var PiecewiseModel = VisualMapModel.extend({
  70330. type: 'visualMap.piecewise',
  70331. /**
  70332. * Order Rule:
  70333. *
  70334. * option.categories / option.pieces / option.text / option.selected:
  70335. * If !option.inverse,
  70336. * Order when vertical: ['top', ..., 'bottom'].
  70337. * Order when horizontal: ['left', ..., 'right'].
  70338. * If option.inverse, the meaning of
  70339. * the order should be reversed.
  70340. *
  70341. * this._pieceList:
  70342. * The order is always [low, ..., high].
  70343. *
  70344. * Mapping from location to low-high:
  70345. * If !option.inverse
  70346. * When vertical, top is high.
  70347. * When horizontal, right is high.
  70348. * If option.inverse, reverse.
  70349. */
  70350. /**
  70351. * @protected
  70352. */
  70353. defaultOption: {
  70354. selected: null, // Object. If not specified, means selected.
  70355. // When pieces and splitNumber: {'0': true, '5': true}
  70356. // When categories: {'cate1': false, 'cate3': true}
  70357. // When selected === false, means all unselected.
  70358. minOpen: false, // Whether include values that smaller than `min`.
  70359. maxOpen: false, // Whether include values that bigger than `max`.
  70360. align: 'auto', // 'auto', 'left', 'right'
  70361. itemWidth: 20, // When put the controller vertically, it is the length of
  70362. // horizontal side of each item. Otherwise, vertical side.
  70363. itemHeight: 14, // When put the controller vertically, it is the length of
  70364. // vertical side of each item. Otherwise, horizontal side.
  70365. itemSymbol: 'roundRect',
  70366. pieceList: null, // Each item is Object, with some of those attrs:
  70367. // {min, max, lt, gt, lte, gte, value,
  70368. // color, colorSaturation, colorAlpha, opacity,
  70369. // symbol, symbolSize}, which customize the range or visual
  70370. // coding of the certain piece. Besides, see "Order Rule".
  70371. categories: null, // category names, like: ['some1', 'some2', 'some3'].
  70372. // Attr min/max are ignored when categories set. See "Order Rule"
  70373. splitNumber: 5, // If set to 5, auto split five pieces equally.
  70374. // If set to 0 and component type not set, component type will be
  70375. // determined as "continuous". (It is less reasonable but for ec2
  70376. // compatibility, see echarts/component/visualMap/typeDefaulter)
  70377. selectedMode: 'multiple', // Can be 'multiple' or 'single'.
  70378. itemGap: 10, // The gap between two items, in px.
  70379. hoverLink: true, // Enable hover highlight.
  70380. showLabel: null // By default, when text is used, label will hide (the logic
  70381. // is remained for compatibility reason)
  70382. },
  70383. /**
  70384. * @override
  70385. */
  70386. optionUpdated: function (newOption, isInit) {
  70387. PiecewiseModel.superApply(this, 'optionUpdated', arguments);
  70388. /**
  70389. * The order is always [low, ..., high].
  70390. * [{text: string, interval: Array.<number>}, ...]
  70391. * @private
  70392. * @type {Array.<Object>}
  70393. */
  70394. this._pieceList = [];
  70395. this.resetExtent();
  70396. /**
  70397. * 'pieces', 'categories', 'splitNumber'
  70398. * @type {string}
  70399. */
  70400. var mode = this._mode = this._determineMode();
  70401. resetMethods[this._mode].call(this);
  70402. this._resetSelected(newOption, isInit);
  70403. var categories = this.option.categories;
  70404. this.resetVisual(function (mappingOption, state) {
  70405. if (mode === 'categories') {
  70406. mappingOption.mappingMethod = 'category';
  70407. mappingOption.categories = clone(categories);
  70408. }
  70409. else {
  70410. mappingOption.dataExtent = this.getExtent();
  70411. mappingOption.mappingMethod = 'piecewise';
  70412. mappingOption.pieceList = map(this._pieceList, function (piece) {
  70413. var piece = clone(piece);
  70414. if (state !== 'inRange') {
  70415. // FIXME
  70416. // outOfRange do not support special visual in pieces.
  70417. piece.visual = null;
  70418. }
  70419. return piece;
  70420. });
  70421. }
  70422. });
  70423. },
  70424. /**
  70425. * @protected
  70426. * @override
  70427. */
  70428. completeVisualOption: function () {
  70429. // Consider this case:
  70430. // visualMap: {
  70431. // pieces: [{symbol: 'circle', lt: 0}, {symbol: 'rect', gte: 0}]
  70432. // }
  70433. // where no inRange/outOfRange set but only pieces. So we should make
  70434. // default inRange/outOfRange for this case, otherwise visuals that only
  70435. // appear in `pieces` will not be taken into account in visual encoding.
  70436. var option = this.option;
  70437. var visualTypesInPieces = {};
  70438. var visualTypes = VisualMapping.listVisualTypes();
  70439. var isCategory = this.isCategory();
  70440. each$1(option.pieces, function (piece) {
  70441. each$1(visualTypes, function (visualType) {
  70442. if (piece.hasOwnProperty(visualType)) {
  70443. visualTypesInPieces[visualType] = 1;
  70444. }
  70445. });
  70446. });
  70447. each$1(visualTypesInPieces, function (v, visualType) {
  70448. var exists = 0;
  70449. each$1(this.stateList, function (state) {
  70450. exists |= has(option, state, visualType)
  70451. || has(option.target, state, visualType);
  70452. }, this);
  70453. !exists && each$1(this.stateList, function (state) {
  70454. (option[state] || (option[state] = {}))[visualType] = visualDefault.get(
  70455. visualType, state === 'inRange' ? 'active' : 'inactive', isCategory
  70456. );
  70457. });
  70458. }, this);
  70459. function has(obj, state, visualType) {
  70460. return obj && obj[state] && (
  70461. isObject$1(obj[state])
  70462. ? obj[state].hasOwnProperty(visualType)
  70463. : obj[state] === visualType // e.g., inRange: 'symbol'
  70464. );
  70465. }
  70466. VisualMapModel.prototype.completeVisualOption.apply(this, arguments);
  70467. },
  70468. _resetSelected: function (newOption, isInit) {
  70469. var thisOption = this.option;
  70470. var pieceList = this._pieceList;
  70471. // Selected do not merge but all override.
  70472. var selected = (isInit ? thisOption : newOption).selected || {};
  70473. thisOption.selected = selected;
  70474. // Consider 'not specified' means true.
  70475. each$1(pieceList, function (piece, index) {
  70476. var key = this.getSelectedMapKey(piece);
  70477. if (!selected.hasOwnProperty(key)) {
  70478. selected[key] = true;
  70479. }
  70480. }, this);
  70481. if (thisOption.selectedMode === 'single') {
  70482. // Ensure there is only one selected.
  70483. var hasSel = false;
  70484. each$1(pieceList, function (piece, index) {
  70485. var key = this.getSelectedMapKey(piece);
  70486. if (selected[key]) {
  70487. hasSel
  70488. ? (selected[key] = false)
  70489. : (hasSel = true);
  70490. }
  70491. }, this);
  70492. }
  70493. // thisOption.selectedMode === 'multiple', default: all selected.
  70494. },
  70495. /**
  70496. * @public
  70497. */
  70498. getSelectedMapKey: function (piece) {
  70499. return this._mode === 'categories'
  70500. ? piece.value + '' : piece.index + '';
  70501. },
  70502. /**
  70503. * @public
  70504. */
  70505. getPieceList: function () {
  70506. return this._pieceList;
  70507. },
  70508. /**
  70509. * @private
  70510. * @return {string}
  70511. */
  70512. _determineMode: function () {
  70513. var option = this.option;
  70514. return option.pieces && option.pieces.length > 0
  70515. ? 'pieces'
  70516. : this.option.categories
  70517. ? 'categories'
  70518. : 'splitNumber';
  70519. },
  70520. /**
  70521. * @public
  70522. * @override
  70523. */
  70524. setSelected: function (selected) {
  70525. this.option.selected = clone(selected);
  70526. },
  70527. /**
  70528. * @public
  70529. * @override
  70530. */
  70531. getValueState: function (value) {
  70532. var index = VisualMapping.findPieceIndex(value, this._pieceList);
  70533. return index != null
  70534. ? (this.option.selected[this.getSelectedMapKey(this._pieceList[index])]
  70535. ? 'inRange' : 'outOfRange'
  70536. )
  70537. : 'outOfRange';
  70538. },
  70539. /**
  70540. * @public
  70541. * @params {number} pieceIndex piece index in visualMapModel.getPieceList()
  70542. * @return {Array.<Object>} [{seriesId, dataIndices: <Array.<number>>}, ...]
  70543. */
  70544. findTargetDataIndices: function (pieceIndex) {
  70545. var result = [];
  70546. this.eachTargetSeries(function (seriesModel) {
  70547. var dataIndices = [];
  70548. var data = seriesModel.getData();
  70549. data.each(this.getDataDimension(data), function (value, dataIndex) {
  70550. // Should always base on model pieceList, because it is order sensitive.
  70551. var pIdx = VisualMapping.findPieceIndex(value, this._pieceList);
  70552. pIdx === pieceIndex && dataIndices.push(dataIndex);
  70553. }, this);
  70554. result.push({seriesId: seriesModel.id, dataIndex: dataIndices});
  70555. }, this);
  70556. return result;
  70557. },
  70558. /**
  70559. * @private
  70560. * @param {Object} piece piece.value or piece.interval is required.
  70561. * @return {number} Can be Infinity or -Infinity
  70562. */
  70563. getRepresentValue: function (piece) {
  70564. var representValue;
  70565. if (this.isCategory()) {
  70566. representValue = piece.value;
  70567. }
  70568. else {
  70569. if (piece.value != null) {
  70570. representValue = piece.value;
  70571. }
  70572. else {
  70573. var pieceInterval = piece.interval || [];
  70574. representValue = (pieceInterval[0] === -Infinity && pieceInterval[1] === Infinity)
  70575. ? 0
  70576. : (pieceInterval[0] + pieceInterval[1]) / 2;
  70577. }
  70578. }
  70579. return representValue;
  70580. },
  70581. getVisualMeta: function (getColorVisual) {
  70582. // Do not support category. (category axis is ordinal, numerical)
  70583. if (this.isCategory()) {
  70584. return;
  70585. }
  70586. var stops = [];
  70587. var outerColors = [];
  70588. var visualMapModel = this;
  70589. function setStop(interval, valueState) {
  70590. var representValue = visualMapModel.getRepresentValue({interval: interval});
  70591. if (!valueState) {
  70592. valueState = visualMapModel.getValueState(representValue);
  70593. }
  70594. var color = getColorVisual(representValue, valueState);
  70595. if (interval[0] === -Infinity) {
  70596. outerColors[0] = color;
  70597. }
  70598. else if (interval[1] === Infinity) {
  70599. outerColors[1] = color;
  70600. }
  70601. else {
  70602. stops.push(
  70603. {value: interval[0], color: color},
  70604. {value: interval[1], color: color}
  70605. );
  70606. }
  70607. }
  70608. // Suplement
  70609. var pieceList = this._pieceList.slice();
  70610. if (!pieceList.length) {
  70611. pieceList.push({interval: [-Infinity, Infinity]});
  70612. }
  70613. else {
  70614. var edge = pieceList[0].interval[0];
  70615. edge !== -Infinity && pieceList.unshift({interval: [-Infinity, edge]});
  70616. edge = pieceList[pieceList.length - 1].interval[1];
  70617. edge !== Infinity && pieceList.push({interval: [edge, Infinity]});
  70618. }
  70619. var curr = -Infinity;
  70620. each$1(pieceList, function (piece) {
  70621. var interval = piece.interval;
  70622. if (interval) {
  70623. // Fulfill gap.
  70624. interval[0] > curr && setStop([curr, interval[0]], 'outOfRange');
  70625. setStop(interval.slice());
  70626. curr = interval[1];
  70627. }
  70628. }, this);
  70629. return {stops: stops, outerColors: outerColors};
  70630. }
  70631. });
  70632. /**
  70633. * Key is this._mode
  70634. * @type {Object}
  70635. * @this {module:echarts/component/viusalMap/PiecewiseMode}
  70636. */
  70637. var resetMethods = {
  70638. splitNumber: function () {
  70639. var thisOption = this.option;
  70640. var pieceList = this._pieceList;
  70641. var precision = Math.min(thisOption.precision, 20);
  70642. var dataExtent = this.getExtent();
  70643. var splitNumber = thisOption.splitNumber;
  70644. splitNumber = Math.max(parseInt(splitNumber, 10), 1);
  70645. thisOption.splitNumber = splitNumber;
  70646. var splitStep = (dataExtent[1] - dataExtent[0]) / splitNumber;
  70647. // Precision auto-adaption
  70648. while (+splitStep.toFixed(precision) !== splitStep && precision < 5) {
  70649. precision++;
  70650. }
  70651. thisOption.precision = precision;
  70652. splitStep = +splitStep.toFixed(precision);
  70653. var index = 0;
  70654. if (thisOption.minOpen) {
  70655. pieceList.push({
  70656. index: index++,
  70657. interval: [-Infinity, dataExtent[0]],
  70658. close: [0, 0]
  70659. });
  70660. }
  70661. for (
  70662. var curr = dataExtent[0], len = index + splitNumber;
  70663. index < len;
  70664. curr += splitStep
  70665. ) {
  70666. var max = index === splitNumber - 1 ? dataExtent[1] : (curr + splitStep);
  70667. pieceList.push({
  70668. index: index++,
  70669. interval: [curr, max],
  70670. close: [1, 1]
  70671. });
  70672. }
  70673. if (thisOption.maxOpen) {
  70674. pieceList.push({
  70675. index: index++,
  70676. interval: [dataExtent[1], Infinity],
  70677. close: [0, 0]
  70678. });
  70679. }
  70680. reformIntervals(pieceList);
  70681. each$1(pieceList, function (piece) {
  70682. piece.text = this.formatValueText(piece.interval);
  70683. }, this);
  70684. },
  70685. categories: function () {
  70686. var thisOption = this.option;
  70687. each$1(thisOption.categories, function (cate) {
  70688. // FIXME category模式也使用pieceList,但在visualMapping中不是使用pieceList。
  70689. // 是否改一致。
  70690. this._pieceList.push({
  70691. text: this.formatValueText(cate, true),
  70692. value: cate
  70693. });
  70694. }, this);
  70695. // See "Order Rule".
  70696. normalizeReverse(thisOption, this._pieceList);
  70697. },
  70698. pieces: function () {
  70699. var thisOption = this.option;
  70700. var pieceList = this._pieceList;
  70701. each$1(thisOption.pieces, function (pieceListItem, index) {
  70702. if (!isObject$1(pieceListItem)) {
  70703. pieceListItem = {value: pieceListItem};
  70704. }
  70705. var item = {text: '', index: index};
  70706. if (pieceListItem.label != null) {
  70707. item.text = pieceListItem.label;
  70708. }
  70709. if (pieceListItem.hasOwnProperty('value')) {
  70710. var value = item.value = pieceListItem.value;
  70711. item.interval = [value, value];
  70712. item.close = [1, 1];
  70713. }
  70714. else {
  70715. // `min` `max` is legacy option.
  70716. // `lt` `gt` `lte` `gte` is recommanded.
  70717. var interval = item.interval = [];
  70718. var close = item.close = [0, 0];
  70719. var closeList = [1, 0, 1];
  70720. var infinityList = [-Infinity, Infinity];
  70721. var useMinMax = [];
  70722. for (var lg = 0; lg < 2; lg++) {
  70723. var names = [['gte', 'gt', 'min'], ['lte', 'lt', 'max']][lg];
  70724. for (var i = 0; i < 3 && interval[lg] == null; i++) {
  70725. interval[lg] = pieceListItem[names[i]];
  70726. close[lg] = closeList[i];
  70727. useMinMax[lg] = i === 2;
  70728. }
  70729. interval[lg] == null && (interval[lg] = infinityList[lg]);
  70730. }
  70731. useMinMax[0] && interval[1] === Infinity && (close[0] = 0);
  70732. useMinMax[1] && interval[0] === -Infinity && (close[1] = 0);
  70733. if (__DEV__) {
  70734. if (interval[0] > interval[1]) {
  70735. console.warn(
  70736. 'Piece ' + index + 'is illegal: ' + interval
  70737. + ' lower bound should not greater then uppper bound.'
  70738. );
  70739. }
  70740. }
  70741. if (interval[0] === interval[1] && close[0] && close[1]) {
  70742. // Consider: [{min: 5, max: 5, visual: {...}}, {min: 0, max: 5}],
  70743. // we use value to lift the priority when min === max
  70744. item.value = interval[0];
  70745. }
  70746. }
  70747. item.visual = VisualMapping.retrieveVisuals(pieceListItem);
  70748. pieceList.push(item);
  70749. }, this);
  70750. // See "Order Rule".
  70751. normalizeReverse(thisOption, pieceList);
  70752. // Only pieces
  70753. reformIntervals(pieceList);
  70754. each$1(pieceList, function (piece) {
  70755. var close = piece.close;
  70756. var edgeSymbols = [['<', '≤'][close[1]], ['>', '≥'][close[0]]];
  70757. piece.text = piece.text || this.formatValueText(
  70758. piece.value != null ? piece.value : piece.interval,
  70759. false,
  70760. edgeSymbols
  70761. );
  70762. }, this);
  70763. }
  70764. };
  70765. function normalizeReverse(thisOption, pieceList) {
  70766. var inverse = thisOption.inverse;
  70767. if (thisOption.orient === 'vertical' ? !inverse : inverse) {
  70768. pieceList.reverse();
  70769. }
  70770. }
  70771. /*
  70772. * Licensed to the Apache Software Foundation (ASF) under one
  70773. * or more contributor license agreements. See the NOTICE file
  70774. * distributed with this work for additional information
  70775. * regarding copyright ownership. The ASF licenses this file
  70776. * to you under the Apache License, Version 2.0 (the
  70777. * "License"); you may not use this file except in compliance
  70778. * with the License. You may obtain a copy of the License at
  70779. *
  70780. * http://www.apache.org/licenses/LICENSE-2.0
  70781. *
  70782. * Unless required by applicable law or agreed to in writing,
  70783. * software distributed under the License is distributed on an
  70784. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  70785. * KIND, either express or implied. See the License for the
  70786. * specific language governing permissions and limitations
  70787. * under the License.
  70788. */
  70789. var PiecewiseVisualMapView = VisualMapView.extend({
  70790. type: 'visualMap.piecewise',
  70791. /**
  70792. * @protected
  70793. * @override
  70794. */
  70795. doRender: function () {
  70796. var thisGroup = this.group;
  70797. thisGroup.removeAll();
  70798. var visualMapModel = this.visualMapModel;
  70799. var textGap = visualMapModel.get('textGap');
  70800. var textStyleModel = visualMapModel.textStyleModel;
  70801. var textFont = textStyleModel.getFont();
  70802. var textFill = textStyleModel.getTextColor();
  70803. var itemAlign = this._getItemAlign();
  70804. var itemSize = visualMapModel.itemSize;
  70805. var viewData = this._getViewData();
  70806. var endsText = viewData.endsText;
  70807. var showLabel = retrieve(visualMapModel.get('showLabel', true), !endsText);
  70808. endsText && this._renderEndsText(
  70809. thisGroup, endsText[0], itemSize, showLabel, itemAlign
  70810. );
  70811. each$1(viewData.viewPieceList, renderItem, this);
  70812. endsText && this._renderEndsText(
  70813. thisGroup, endsText[1], itemSize, showLabel, itemAlign
  70814. );
  70815. box(
  70816. visualMapModel.get('orient'), thisGroup, visualMapModel.get('itemGap')
  70817. );
  70818. this.renderBackground(thisGroup);
  70819. this.positionGroup(thisGroup);
  70820. function renderItem(item) {
  70821. var piece = item.piece;
  70822. var itemGroup = new Group();
  70823. itemGroup.onclick = bind(this._onItemClick, this, piece);
  70824. this._enableHoverLink(itemGroup, item.indexInModelPieceList);
  70825. var representValue = visualMapModel.getRepresentValue(piece);
  70826. this._createItemSymbol(
  70827. itemGroup, representValue, [0, 0, itemSize[0], itemSize[1]]
  70828. );
  70829. if (showLabel) {
  70830. var visualState = this.visualMapModel.getValueState(representValue);
  70831. itemGroup.add(new Text({
  70832. style: {
  70833. x: itemAlign === 'right' ? -textGap : itemSize[0] + textGap,
  70834. y: itemSize[1] / 2,
  70835. text: piece.text,
  70836. textVerticalAlign: 'middle',
  70837. textAlign: itemAlign,
  70838. textFont: textFont,
  70839. textFill: textFill,
  70840. opacity: visualState === 'outOfRange' ? 0.5 : 1
  70841. }
  70842. }));
  70843. }
  70844. thisGroup.add(itemGroup);
  70845. }
  70846. },
  70847. /**
  70848. * @private
  70849. */
  70850. _enableHoverLink: function (itemGroup, pieceIndex) {
  70851. itemGroup
  70852. .on('mouseover', bind(onHoverLink, this, 'highlight'))
  70853. .on('mouseout', bind(onHoverLink, this, 'downplay'));
  70854. function onHoverLink(method) {
  70855. var visualMapModel = this.visualMapModel;
  70856. visualMapModel.option.hoverLink && this.api.dispatchAction({
  70857. type: method,
  70858. batch: convertDataIndex(
  70859. visualMapModel.findTargetDataIndices(pieceIndex)
  70860. )
  70861. });
  70862. }
  70863. },
  70864. /**
  70865. * @private
  70866. */
  70867. _getItemAlign: function () {
  70868. var visualMapModel = this.visualMapModel;
  70869. var modelOption = visualMapModel.option;
  70870. if (modelOption.orient === 'vertical') {
  70871. return getItemAlign(
  70872. visualMapModel, this.api, visualMapModel.itemSize
  70873. );
  70874. }
  70875. else { // horizontal, most case left unless specifying right.
  70876. var align = modelOption.align;
  70877. if (!align || align === 'auto') {
  70878. align = 'left';
  70879. }
  70880. return align;
  70881. }
  70882. },
  70883. /**
  70884. * @private
  70885. */
  70886. _renderEndsText: function (group, text, itemSize, showLabel, itemAlign) {
  70887. if (!text) {
  70888. return;
  70889. }
  70890. var itemGroup = new Group();
  70891. var textStyleModel = this.visualMapModel.textStyleModel;
  70892. itemGroup.add(new Text({
  70893. style: {
  70894. x: showLabel ? (itemAlign === 'right' ? itemSize[0] : 0) : itemSize[0] / 2,
  70895. y: itemSize[1] / 2,
  70896. textVerticalAlign: 'middle',
  70897. textAlign: showLabel ? itemAlign : 'center',
  70898. text: text,
  70899. textFont: textStyleModel.getFont(),
  70900. textFill: textStyleModel.getTextColor()
  70901. }
  70902. }));
  70903. group.add(itemGroup);
  70904. },
  70905. /**
  70906. * @private
  70907. * @return {Object} {peiceList, endsText} The order is the same as screen pixel order.
  70908. */
  70909. _getViewData: function () {
  70910. var visualMapModel = this.visualMapModel;
  70911. var viewPieceList = map(visualMapModel.getPieceList(), function (piece, index) {
  70912. return {piece: piece, indexInModelPieceList: index};
  70913. });
  70914. var endsText = visualMapModel.get('text');
  70915. // Consider orient and inverse.
  70916. var orient = visualMapModel.get('orient');
  70917. var inverse = visualMapModel.get('inverse');
  70918. // Order of model pieceList is always [low, ..., high]
  70919. if (orient === 'horizontal' ? inverse : !inverse) {
  70920. viewPieceList.reverse();
  70921. }
  70922. // Origin order of endsText is [high, low]
  70923. else if (endsText) {
  70924. endsText = endsText.slice().reverse();
  70925. }
  70926. return {viewPieceList: viewPieceList, endsText: endsText};
  70927. },
  70928. /**
  70929. * @private
  70930. */
  70931. _createItemSymbol: function (group, representValue, shapeParam) {
  70932. group.add(createSymbol(
  70933. this.getControllerVisual(representValue, 'symbol'),
  70934. shapeParam[0], shapeParam[1], shapeParam[2], shapeParam[3],
  70935. this.getControllerVisual(representValue, 'color')
  70936. ));
  70937. },
  70938. /**
  70939. * @private
  70940. */
  70941. _onItemClick: function (piece) {
  70942. var visualMapModel = this.visualMapModel;
  70943. var option = visualMapModel.option;
  70944. var selected = clone(option.selected);
  70945. var newKey = visualMapModel.getSelectedMapKey(piece);
  70946. if (option.selectedMode === 'single') {
  70947. selected[newKey] = true;
  70948. each$1(selected, function (o, key) {
  70949. selected[key] = key === newKey;
  70950. });
  70951. }
  70952. else {
  70953. selected[newKey] = !selected[newKey];
  70954. }
  70955. this.api.dispatchAction({
  70956. type: 'selectDataRange',
  70957. from: this.uid,
  70958. visualMapId: this.visualMapModel.id,
  70959. selected: selected
  70960. });
  70961. }
  70962. });
  70963. /*
  70964. * Licensed to the Apache Software Foundation (ASF) under one
  70965. * or more contributor license agreements. See the NOTICE file
  70966. * distributed with this work for additional information
  70967. * regarding copyright ownership. The ASF licenses this file
  70968. * to you under the Apache License, Version 2.0 (the
  70969. * "License"); you may not use this file except in compliance
  70970. * with the License. You may obtain a copy of the License at
  70971. *
  70972. * http://www.apache.org/licenses/LICENSE-2.0
  70973. *
  70974. * Unless required by applicable law or agreed to in writing,
  70975. * software distributed under the License is distributed on an
  70976. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  70977. * KIND, either express or implied. See the License for the
  70978. * specific language governing permissions and limitations
  70979. * under the License.
  70980. */
  70981. /**
  70982. * DataZoom component entry
  70983. */
  70984. registerPreprocessor(preprocessor$2);
  70985. /*
  70986. * Licensed to the Apache Software Foundation (ASF) under one
  70987. * or more contributor license agreements. See the NOTICE file
  70988. * distributed with this work for additional information
  70989. * regarding copyright ownership. The ASF licenses this file
  70990. * to you under the Apache License, Version 2.0 (the
  70991. * "License"); you may not use this file except in compliance
  70992. * with the License. You may obtain a copy of the License at
  70993. *
  70994. * http://www.apache.org/licenses/LICENSE-2.0
  70995. *
  70996. * Unless required by applicable law or agreed to in writing,
  70997. * software distributed under the License is distributed on an
  70998. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  70999. * KIND, either express or implied. See the License for the
  71000. * specific language governing permissions and limitations
  71001. * under the License.
  71002. */
  71003. /**
  71004. * visualMap component entry
  71005. */
  71006. /*
  71007. * Licensed to the Apache Software Foundation (ASF) under one
  71008. * or more contributor license agreements. See the NOTICE file
  71009. * distributed with this work for additional information
  71010. * regarding copyright ownership. The ASF licenses this file
  71011. * to you under the Apache License, Version 2.0 (the
  71012. * "License"); you may not use this file except in compliance
  71013. * with the License. You may obtain a copy of the License at
  71014. *
  71015. * http://www.apache.org/licenses/LICENSE-2.0
  71016. *
  71017. * Unless required by applicable law or agreed to in writing,
  71018. * software distributed under the License is distributed on an
  71019. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71020. * KIND, either express or implied. See the License for the
  71021. * specific language governing permissions and limitations
  71022. * under the License.
  71023. */
  71024. var addCommas$1 = addCommas;
  71025. var encodeHTML$1 = encodeHTML;
  71026. function fillLabel(opt) {
  71027. defaultEmphasis(opt, 'label', ['show']);
  71028. }
  71029. var MarkerModel = extendComponentModel({
  71030. type: 'marker',
  71031. dependencies: ['series', 'grid', 'polar', 'geo'],
  71032. /**
  71033. * @overrite
  71034. */
  71035. init: function (option, parentModel, ecModel, extraOpt) {
  71036. if (__DEV__) {
  71037. if (this.type === 'marker') {
  71038. throw new Error('Marker component is abstract component. Use markLine, markPoint, markArea instead.');
  71039. }
  71040. }
  71041. this.mergeDefaultAndTheme(option, ecModel);
  71042. this.mergeOption(option, ecModel, extraOpt.createdBySelf, true);
  71043. },
  71044. /**
  71045. * @return {boolean}
  71046. */
  71047. isAnimationEnabled: function () {
  71048. if (env$1.node) {
  71049. return false;
  71050. }
  71051. var hostSeries = this.__hostSeries;
  71052. return this.getShallow('animation') && hostSeries && hostSeries.isAnimationEnabled();
  71053. },
  71054. mergeOption: function (newOpt, ecModel, createdBySelf, isInit) {
  71055. var MarkerModel = this.constructor;
  71056. var modelPropName = this.mainType + 'Model';
  71057. if (!createdBySelf) {
  71058. ecModel.eachSeries(function (seriesModel) {
  71059. var markerOpt = seriesModel.get(this.mainType, true);
  71060. var markerModel = seriesModel[modelPropName];
  71061. if (!markerOpt || !markerOpt.data) {
  71062. seriesModel[modelPropName] = null;
  71063. return;
  71064. }
  71065. if (!markerModel) {
  71066. if (isInit) {
  71067. // Default label emphasis `position` and `show`
  71068. fillLabel(markerOpt);
  71069. }
  71070. each$1(markerOpt.data, function (item) {
  71071. // FIXME Overwrite fillLabel method ?
  71072. if (item instanceof Array) {
  71073. fillLabel(item[0]);
  71074. fillLabel(item[1]);
  71075. }
  71076. else {
  71077. fillLabel(item);
  71078. }
  71079. });
  71080. markerModel = new MarkerModel(
  71081. markerOpt, this, ecModel
  71082. );
  71083. extend(markerModel, {
  71084. mainType: this.mainType,
  71085. // Use the same series index and name
  71086. seriesIndex: seriesModel.seriesIndex,
  71087. name: seriesModel.name,
  71088. createdBySelf: true
  71089. });
  71090. markerModel.__hostSeries = seriesModel;
  71091. }
  71092. else {
  71093. markerModel.mergeOption(markerOpt, ecModel, true);
  71094. }
  71095. seriesModel[modelPropName] = markerModel;
  71096. }, this);
  71097. }
  71098. },
  71099. formatTooltip: function (dataIndex) {
  71100. var data = this.getData();
  71101. var value = this.getRawValue(dataIndex);
  71102. var formattedValue = isArray(value)
  71103. ? map(value, addCommas$1).join(', ') : addCommas$1(value);
  71104. var name = data.getName(dataIndex);
  71105. var html = encodeHTML$1(this.name);
  71106. if (value != null || name) {
  71107. html += '<br />';
  71108. }
  71109. if (name) {
  71110. html += encodeHTML$1(name);
  71111. if (value != null) {
  71112. html += ' : ';
  71113. }
  71114. }
  71115. if (value != null) {
  71116. html += encodeHTML$1(formattedValue);
  71117. }
  71118. return html;
  71119. },
  71120. getData: function () {
  71121. return this._data;
  71122. },
  71123. setData: function (data) {
  71124. this._data = data;
  71125. }
  71126. });
  71127. mixin(MarkerModel, dataFormatMixin);
  71128. /*
  71129. * Licensed to the Apache Software Foundation (ASF) under one
  71130. * or more contributor license agreements. See the NOTICE file
  71131. * distributed with this work for additional information
  71132. * regarding copyright ownership. The ASF licenses this file
  71133. * to you under the Apache License, Version 2.0 (the
  71134. * "License"); you may not use this file except in compliance
  71135. * with the License. You may obtain a copy of the License at
  71136. *
  71137. * http://www.apache.org/licenses/LICENSE-2.0
  71138. *
  71139. * Unless required by applicable law or agreed to in writing,
  71140. * software distributed under the License is distributed on an
  71141. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71142. * KIND, either express or implied. See the License for the
  71143. * specific language governing permissions and limitations
  71144. * under the License.
  71145. */
  71146. MarkerModel.extend({
  71147. type: 'markPoint',
  71148. defaultOption: {
  71149. zlevel: 0,
  71150. z: 5,
  71151. symbol: 'pin',
  71152. symbolSize: 50,
  71153. //symbolRotate: 0,
  71154. //symbolOffset: [0, 0]
  71155. tooltip: {
  71156. trigger: 'item'
  71157. },
  71158. label: {
  71159. show: true,
  71160. position: 'inside'
  71161. },
  71162. itemStyle: {
  71163. borderWidth: 2
  71164. },
  71165. emphasis: {
  71166. label: {
  71167. show: true
  71168. }
  71169. }
  71170. }
  71171. });
  71172. /*
  71173. * Licensed to the Apache Software Foundation (ASF) under one
  71174. * or more contributor license agreements. See the NOTICE file
  71175. * distributed with this work for additional information
  71176. * regarding copyright ownership. The ASF licenses this file
  71177. * to you under the Apache License, Version 2.0 (the
  71178. * "License"); you may not use this file except in compliance
  71179. * with the License. You may obtain a copy of the License at
  71180. *
  71181. * http://www.apache.org/licenses/LICENSE-2.0
  71182. *
  71183. * Unless required by applicable law or agreed to in writing,
  71184. * software distributed under the License is distributed on an
  71185. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71186. * KIND, either express or implied. See the License for the
  71187. * specific language governing permissions and limitations
  71188. * under the License.
  71189. */
  71190. var indexOf$2 = indexOf;
  71191. function hasXOrY(item) {
  71192. return !(isNaN(parseFloat(item.x)) && isNaN(parseFloat(item.y)));
  71193. }
  71194. function hasXAndY(item) {
  71195. return !isNaN(parseFloat(item.x)) && !isNaN(parseFloat(item.y));
  71196. }
  71197. // Make it simple, do not visit all stacked value to count precision.
  71198. // function getPrecision(data, valueAxisDim, dataIndex) {
  71199. // var precision = -1;
  71200. // var stackedDim = data.mapDimension(valueAxisDim);
  71201. // do {
  71202. // precision = Math.max(
  71203. // numberUtil.getPrecision(data.get(stackedDim, dataIndex)),
  71204. // precision
  71205. // );
  71206. // var stackedOnSeries = data.getCalculationInfo('stackedOnSeries');
  71207. // if (stackedOnSeries) {
  71208. // var byValue = data.get(data.getCalculationInfo('stackedByDimension'), dataIndex);
  71209. // data = stackedOnSeries.getData();
  71210. // dataIndex = data.indexOf(data.getCalculationInfo('stackedByDimension'), byValue);
  71211. // stackedDim = data.getCalculationInfo('stackedDimension');
  71212. // }
  71213. // else {
  71214. // data = null;
  71215. // }
  71216. // } while (data);
  71217. // return precision;
  71218. // }
  71219. function markerTypeCalculatorWithExtent(
  71220. mlType, data, otherDataDim, targetDataDim, otherCoordIndex, targetCoordIndex
  71221. ) {
  71222. var coordArr = [];
  71223. var stacked = isDimensionStacked(data, targetDataDim, otherDataDim);
  71224. var calcDataDim = stacked
  71225. ? data.getCalculationInfo('stackResultDimension')
  71226. : targetDataDim;
  71227. var value = numCalculate(data, calcDataDim, mlType);
  71228. var dataIndex = data.indicesOfNearest(calcDataDim, value)[0];
  71229. coordArr[otherCoordIndex] = data.get(otherDataDim, dataIndex);
  71230. coordArr[targetCoordIndex] = data.get(targetDataDim, dataIndex);
  71231. // Make it simple, do not visit all stacked value to count precision.
  71232. var precision = getPrecision(data.get(targetDataDim, dataIndex));
  71233. precision = Math.min(precision, 20);
  71234. if (precision >= 0) {
  71235. coordArr[targetCoordIndex] = +coordArr[targetCoordIndex].toFixed(precision);
  71236. }
  71237. return coordArr;
  71238. }
  71239. var curry$7 = curry;
  71240. // TODO Specified percent
  71241. var markerTypeCalculator = {
  71242. /**
  71243. * @method
  71244. * @param {module:echarts/data/List} data
  71245. * @param {string} baseAxisDim
  71246. * @param {string} valueAxisDim
  71247. */
  71248. min: curry$7(markerTypeCalculatorWithExtent, 'min'),
  71249. /**
  71250. * @method
  71251. * @param {module:echarts/data/List} data
  71252. * @param {string} baseAxisDim
  71253. * @param {string} valueAxisDim
  71254. */
  71255. max: curry$7(markerTypeCalculatorWithExtent, 'max'),
  71256. /**
  71257. * @method
  71258. * @param {module:echarts/data/List} data
  71259. * @param {string} baseAxisDim
  71260. * @param {string} valueAxisDim
  71261. */
  71262. average: curry$7(markerTypeCalculatorWithExtent, 'average')
  71263. };
  71264. /**
  71265. * Transform markPoint data item to format used in List by do the following
  71266. * 1. Calculate statistic like `max`, `min`, `average`
  71267. * 2. Convert `item.xAxis`, `item.yAxis` to `item.coord` array
  71268. * @param {module:echarts/model/Series} seriesModel
  71269. * @param {module:echarts/coord/*} [coordSys]
  71270. * @param {Object} item
  71271. * @return {Object}
  71272. */
  71273. function dataTransform(seriesModel, item) {
  71274. var data = seriesModel.getData();
  71275. var coordSys = seriesModel.coordinateSystem;
  71276. // 1. If not specify the position with pixel directly
  71277. // 2. If `coord` is not a data array. Which uses `xAxis`,
  71278. // `yAxis` to specify the coord on each dimension
  71279. // parseFloat first because item.x and item.y can be percent string like '20%'
  71280. if (item && !hasXAndY(item) && !isArray(item.coord) && coordSys) {
  71281. var dims = coordSys.dimensions;
  71282. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel);
  71283. // Clone the option
  71284. // Transform the properties xAxis, yAxis, radiusAxis, angleAxis, geoCoord to value
  71285. item = clone(item);
  71286. if (item.type
  71287. && markerTypeCalculator[item.type]
  71288. && axisInfo.baseAxis && axisInfo.valueAxis
  71289. ) {
  71290. var otherCoordIndex = indexOf$2(dims, axisInfo.baseAxis.dim);
  71291. var targetCoordIndex = indexOf$2(dims, axisInfo.valueAxis.dim);
  71292. item.coord = markerTypeCalculator[item.type](
  71293. data, axisInfo.baseDataDim, axisInfo.valueDataDim,
  71294. otherCoordIndex, targetCoordIndex
  71295. );
  71296. // Force to use the value of calculated value.
  71297. item.value = item.coord[targetCoordIndex];
  71298. }
  71299. else {
  71300. // FIXME Only has one of xAxis and yAxis.
  71301. var coord = [
  71302. item.xAxis != null ? item.xAxis : item.radiusAxis,
  71303. item.yAxis != null ? item.yAxis : item.angleAxis
  71304. ];
  71305. // Each coord support max, min, average
  71306. for (var i = 0; i < 2; i++) {
  71307. if (markerTypeCalculator[coord[i]]) {
  71308. coord[i] = numCalculate(data, data.mapDimension(dims[i]), coord[i]);
  71309. }
  71310. }
  71311. item.coord = coord;
  71312. }
  71313. }
  71314. return item;
  71315. }
  71316. function getAxisInfo$1(item, data, coordSys, seriesModel) {
  71317. var ret = {};
  71318. if (item.valueIndex != null || item.valueDim != null) {
  71319. ret.valueDataDim = item.valueIndex != null
  71320. ? data.getDimension(item.valueIndex) : item.valueDim;
  71321. ret.valueAxis = coordSys.getAxis(dataDimToCoordDim(seriesModel, ret.valueDataDim));
  71322. ret.baseAxis = coordSys.getOtherAxis(ret.valueAxis);
  71323. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  71324. }
  71325. else {
  71326. ret.baseAxis = seriesModel.getBaseAxis();
  71327. ret.valueAxis = coordSys.getOtherAxis(ret.baseAxis);
  71328. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  71329. ret.valueDataDim = data.mapDimension(ret.valueAxis.dim);
  71330. }
  71331. return ret;
  71332. }
  71333. function dataDimToCoordDim(seriesModel, dataDim) {
  71334. var data = seriesModel.getData();
  71335. var dimensions = data.dimensions;
  71336. dataDim = data.getDimension(dataDim);
  71337. for (var i = 0; i < dimensions.length; i++) {
  71338. var dimItem = data.getDimensionInfo(dimensions[i]);
  71339. if (dimItem.name === dataDim) {
  71340. return dimItem.coordDim;
  71341. }
  71342. }
  71343. }
  71344. /**
  71345. * Filter data which is out of coordinateSystem range
  71346. * [dataFilter description]
  71347. * @param {module:echarts/coord/*} [coordSys]
  71348. * @param {Object} item
  71349. * @return {boolean}
  71350. */
  71351. function dataFilter$1(coordSys, item) {
  71352. // Alwalys return true if there is no coordSys
  71353. return (coordSys && coordSys.containData && item.coord && !hasXOrY(item))
  71354. ? coordSys.containData(item.coord) : true;
  71355. }
  71356. function dimValueGetter(item, dimName, dataIndex, dimIndex) {
  71357. // x, y, radius, angle
  71358. if (dimIndex < 2) {
  71359. return item.coord && item.coord[dimIndex];
  71360. }
  71361. return item.value;
  71362. }
  71363. function numCalculate(data, valueDataDim, type) {
  71364. if (type === 'average') {
  71365. var sum = 0;
  71366. var count = 0;
  71367. data.each(valueDataDim, function (val, idx) {
  71368. if (!isNaN(val)) {
  71369. sum += val;
  71370. count++;
  71371. }
  71372. });
  71373. return sum / count;
  71374. }
  71375. else if (type === 'median') {
  71376. return data.getMedian(valueDataDim);
  71377. }
  71378. else {
  71379. // max & min
  71380. return data.getDataExtent(valueDataDim, true)[type === 'max' ? 1 : 0];
  71381. }
  71382. }
  71383. /*
  71384. * Licensed to the Apache Software Foundation (ASF) under one
  71385. * or more contributor license agreements. See the NOTICE file
  71386. * distributed with this work for additional information
  71387. * regarding copyright ownership. The ASF licenses this file
  71388. * to you under the Apache License, Version 2.0 (the
  71389. * "License"); you may not use this file except in compliance
  71390. * with the License. You may obtain a copy of the License at
  71391. *
  71392. * http://www.apache.org/licenses/LICENSE-2.0
  71393. *
  71394. * Unless required by applicable law or agreed to in writing,
  71395. * software distributed under the License is distributed on an
  71396. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71397. * KIND, either express or implied. See the License for the
  71398. * specific language governing permissions and limitations
  71399. * under the License.
  71400. */
  71401. var MarkerView = extendComponentView({
  71402. type: 'marker',
  71403. init: function () {
  71404. /**
  71405. * Markline grouped by series
  71406. * @private
  71407. * @type {module:zrender/core/util.HashMap}
  71408. */
  71409. this.markerGroupMap = createHashMap();
  71410. },
  71411. render: function (markerModel, ecModel, api) {
  71412. var markerGroupMap = this.markerGroupMap;
  71413. markerGroupMap.each(function (item) {
  71414. item.__keep = false;
  71415. });
  71416. var markerModelKey = this.type + 'Model';
  71417. ecModel.eachSeries(function (seriesModel) {
  71418. var markerModel = seriesModel[markerModelKey];
  71419. markerModel && this.renderSeries(seriesModel, markerModel, ecModel, api);
  71420. }, this);
  71421. markerGroupMap.each(function (item) {
  71422. !item.__keep && this.group.remove(item.group);
  71423. }, this);
  71424. },
  71425. renderSeries: function () {}
  71426. });
  71427. /*
  71428. * Licensed to the Apache Software Foundation (ASF) under one
  71429. * or more contributor license agreements. See the NOTICE file
  71430. * distributed with this work for additional information
  71431. * regarding copyright ownership. The ASF licenses this file
  71432. * to you under the Apache License, Version 2.0 (the
  71433. * "License"); you may not use this file except in compliance
  71434. * with the License. You may obtain a copy of the License at
  71435. *
  71436. * http://www.apache.org/licenses/LICENSE-2.0
  71437. *
  71438. * Unless required by applicable law or agreed to in writing,
  71439. * software distributed under the License is distributed on an
  71440. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71441. * KIND, either express or implied. See the License for the
  71442. * specific language governing permissions and limitations
  71443. * under the License.
  71444. */
  71445. function updateMarkerLayout(mpData, seriesModel, api) {
  71446. var coordSys = seriesModel.coordinateSystem;
  71447. mpData.each(function (idx) {
  71448. var itemModel = mpData.getItemModel(idx);
  71449. var point;
  71450. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  71451. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  71452. if (!isNaN(xPx) && !isNaN(yPx)) {
  71453. point = [xPx, yPx];
  71454. }
  71455. // Chart like bar may have there own marker positioning logic
  71456. else if (seriesModel.getMarkerPosition) {
  71457. // Use the getMarkerPoisition
  71458. point = seriesModel.getMarkerPosition(
  71459. mpData.getValues(mpData.dimensions, idx)
  71460. );
  71461. }
  71462. else if (coordSys) {
  71463. var x = mpData.get(coordSys.dimensions[0], idx);
  71464. var y = mpData.get(coordSys.dimensions[1], idx);
  71465. point = coordSys.dataToPoint([x, y]);
  71466. }
  71467. // Use x, y if has any
  71468. if (!isNaN(xPx)) {
  71469. point[0] = xPx;
  71470. }
  71471. if (!isNaN(yPx)) {
  71472. point[1] = yPx;
  71473. }
  71474. mpData.setItemLayout(idx, point);
  71475. });
  71476. }
  71477. MarkerView.extend({
  71478. type: 'markPoint',
  71479. // updateLayout: function (markPointModel, ecModel, api) {
  71480. // ecModel.eachSeries(function (seriesModel) {
  71481. // var mpModel = seriesModel.markPointModel;
  71482. // if (mpModel) {
  71483. // updateMarkerLayout(mpModel.getData(), seriesModel, api);
  71484. // this.markerGroupMap.get(seriesModel.id).updateLayout(mpModel);
  71485. // }
  71486. // }, this);
  71487. // },
  71488. updateTransform: function (markPointModel, ecModel, api) {
  71489. ecModel.eachSeries(function (seriesModel) {
  71490. var mpModel = seriesModel.markPointModel;
  71491. if (mpModel) {
  71492. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  71493. this.markerGroupMap.get(seriesModel.id).updateLayout(mpModel);
  71494. }
  71495. }, this);
  71496. },
  71497. renderSeries: function (seriesModel, mpModel, ecModel, api) {
  71498. var coordSys = seriesModel.coordinateSystem;
  71499. var seriesId = seriesModel.id;
  71500. var seriesData = seriesModel.getData();
  71501. var symbolDrawMap = this.markerGroupMap;
  71502. var symbolDraw = symbolDrawMap.get(seriesId)
  71503. || symbolDrawMap.set(seriesId, new SymbolDraw());
  71504. var mpData = createList$1(coordSys, seriesModel, mpModel);
  71505. // FIXME
  71506. mpModel.setData(mpData);
  71507. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  71508. mpData.each(function (idx) {
  71509. var itemModel = mpData.getItemModel(idx);
  71510. var symbolSize = itemModel.getShallow('symbolSize');
  71511. if (typeof symbolSize === 'function') {
  71512. // FIXME 这里不兼容 ECharts 2.x,2.x 貌似参数是整个数据?
  71513. symbolSize = symbolSize(
  71514. mpModel.getRawValue(idx), mpModel.getDataParams(idx)
  71515. );
  71516. }
  71517. mpData.setItemVisual(idx, {
  71518. symbolSize: symbolSize,
  71519. color: itemModel.get('itemStyle.color')
  71520. || seriesData.getVisual('color'),
  71521. symbol: itemModel.getShallow('symbol')
  71522. });
  71523. });
  71524. // TODO Text are wrong
  71525. symbolDraw.updateData(mpData);
  71526. this.group.add(symbolDraw.group);
  71527. // Set host model for tooltip
  71528. // FIXME
  71529. mpData.eachItemGraphicEl(function (el) {
  71530. el.traverse(function (child) {
  71531. child.dataModel = mpModel;
  71532. });
  71533. });
  71534. symbolDraw.__keep = true;
  71535. symbolDraw.group.silent = mpModel.get('silent') || seriesModel.get('silent');
  71536. }
  71537. });
  71538. /**
  71539. * @inner
  71540. * @param {module:echarts/coord/*} [coordSys]
  71541. * @param {module:echarts/model/Series} seriesModel
  71542. * @param {module:echarts/model/Model} mpModel
  71543. */
  71544. function createList$1(coordSys, seriesModel, mpModel) {
  71545. var coordDimsInfos;
  71546. if (coordSys) {
  71547. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  71548. var info = seriesModel.getData().getDimensionInfo(
  71549. seriesModel.getData().mapDimension(coordDim)
  71550. ) || {};
  71551. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  71552. return defaults({name: coordDim}, info);
  71553. });
  71554. }
  71555. else {
  71556. coordDimsInfos =[{
  71557. name: 'value',
  71558. type: 'float'
  71559. }];
  71560. }
  71561. var mpData = new List(coordDimsInfos, mpModel);
  71562. var dataOpt = map(mpModel.get('data'), curry(
  71563. dataTransform, seriesModel
  71564. ));
  71565. if (coordSys) {
  71566. dataOpt = filter(
  71567. dataOpt, curry(dataFilter$1, coordSys)
  71568. );
  71569. }
  71570. mpData.initData(dataOpt, null,
  71571. coordSys ? dimValueGetter : function (item) {
  71572. return item.value;
  71573. }
  71574. );
  71575. return mpData;
  71576. }
  71577. /*
  71578. * Licensed to the Apache Software Foundation (ASF) under one
  71579. * or more contributor license agreements. See the NOTICE file
  71580. * distributed with this work for additional information
  71581. * regarding copyright ownership. The ASF licenses this file
  71582. * to you under the Apache License, Version 2.0 (the
  71583. * "License"); you may not use this file except in compliance
  71584. * with the License. You may obtain a copy of the License at
  71585. *
  71586. * http://www.apache.org/licenses/LICENSE-2.0
  71587. *
  71588. * Unless required by applicable law or agreed to in writing,
  71589. * software distributed under the License is distributed on an
  71590. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71591. * KIND, either express or implied. See the License for the
  71592. * specific language governing permissions and limitations
  71593. * under the License.
  71594. */
  71595. // HINT Markpoint can't be used too much
  71596. registerPreprocessor(function (opt) {
  71597. // Make sure markPoint component is enabled
  71598. opt.markPoint = opt.markPoint || {};
  71599. });
  71600. /*
  71601. * Licensed to the Apache Software Foundation (ASF) under one
  71602. * or more contributor license agreements. See the NOTICE file
  71603. * distributed with this work for additional information
  71604. * regarding copyright ownership. The ASF licenses this file
  71605. * to you under the Apache License, Version 2.0 (the
  71606. * "License"); you may not use this file except in compliance
  71607. * with the License. You may obtain a copy of the License at
  71608. *
  71609. * http://www.apache.org/licenses/LICENSE-2.0
  71610. *
  71611. * Unless required by applicable law or agreed to in writing,
  71612. * software distributed under the License is distributed on an
  71613. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71614. * KIND, either express or implied. See the License for the
  71615. * specific language governing permissions and limitations
  71616. * under the License.
  71617. */
  71618. MarkerModel.extend({
  71619. type: 'markLine',
  71620. defaultOption: {
  71621. zlevel: 0,
  71622. z: 5,
  71623. symbol: ['circle', 'arrow'],
  71624. symbolSize: [8, 16],
  71625. //symbolRotate: 0,
  71626. precision: 2,
  71627. tooltip: {
  71628. trigger: 'item'
  71629. },
  71630. label: {
  71631. show: true,
  71632. position: 'end'
  71633. },
  71634. lineStyle: {
  71635. type: 'dashed'
  71636. },
  71637. emphasis: {
  71638. label: {
  71639. show: true
  71640. },
  71641. lineStyle: {
  71642. width: 3
  71643. }
  71644. },
  71645. animationEasing: 'linear'
  71646. }
  71647. });
  71648. /*
  71649. * Licensed to the Apache Software Foundation (ASF) under one
  71650. * or more contributor license agreements. See the NOTICE file
  71651. * distributed with this work for additional information
  71652. * regarding copyright ownership. The ASF licenses this file
  71653. * to you under the Apache License, Version 2.0 (the
  71654. * "License"); you may not use this file except in compliance
  71655. * with the License. You may obtain a copy of the License at
  71656. *
  71657. * http://www.apache.org/licenses/LICENSE-2.0
  71658. *
  71659. * Unless required by applicable law or agreed to in writing,
  71660. * software distributed under the License is distributed on an
  71661. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71662. * KIND, either express or implied. See the License for the
  71663. * specific language governing permissions and limitations
  71664. * under the License.
  71665. */
  71666. var markLineTransform = function (seriesModel, coordSys, mlModel, item) {
  71667. var data = seriesModel.getData();
  71668. // Special type markLine like 'min', 'max', 'average', 'median'
  71669. var mlType = item.type;
  71670. if (!isArray(item)
  71671. && (
  71672. mlType === 'min' || mlType === 'max' || mlType === 'average' || mlType === 'median'
  71673. // In case
  71674. // data: [{
  71675. // yAxis: 10
  71676. // }]
  71677. || (item.xAxis != null || item.yAxis != null)
  71678. )
  71679. ) {
  71680. var valueAxis;
  71681. var valueDataDim;
  71682. var value;
  71683. if (item.yAxis != null || item.xAxis != null) {
  71684. valueDataDim = item.yAxis != null ? 'y' : 'x';
  71685. valueAxis = coordSys.getAxis(valueDataDim);
  71686. value = retrieve(item.yAxis, item.xAxis);
  71687. }
  71688. else {
  71689. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel);
  71690. valueDataDim = axisInfo.valueDataDim;
  71691. valueAxis = axisInfo.valueAxis;
  71692. value = numCalculate(data, valueDataDim, mlType);
  71693. }
  71694. var valueIndex = valueDataDim === 'x' ? 0 : 1;
  71695. var baseIndex = 1 - valueIndex;
  71696. var mlFrom = clone(item);
  71697. var mlTo = {};
  71698. mlFrom.type = null;
  71699. mlFrom.coord = [];
  71700. mlTo.coord = [];
  71701. mlFrom.coord[baseIndex] = -Infinity;
  71702. mlTo.coord[baseIndex] = Infinity;
  71703. var precision = mlModel.get('precision');
  71704. if (precision >= 0 && typeof value === 'number') {
  71705. value = +value.toFixed(Math.min(precision, 20));
  71706. }
  71707. mlFrom.coord[valueIndex] = mlTo.coord[valueIndex] = value;
  71708. item = [mlFrom, mlTo, { // Extra option for tooltip and label
  71709. type: mlType,
  71710. valueIndex: item.valueIndex,
  71711. // Force to use the value of calculated value.
  71712. value: value
  71713. }];
  71714. }
  71715. item = [
  71716. dataTransform(seriesModel, item[0]),
  71717. dataTransform(seriesModel, item[1]),
  71718. extend({}, item[2])
  71719. ];
  71720. // Avoid line data type is extended by from(to) data type
  71721. item[2].type = item[2].type || '';
  71722. // Merge from option and to option into line option
  71723. merge(item[2], item[0]);
  71724. merge(item[2], item[1]);
  71725. return item;
  71726. };
  71727. function isInifinity(val) {
  71728. return !isNaN(val) && !isFinite(val);
  71729. }
  71730. // If a markLine has one dim
  71731. function ifMarkLineHasOnlyDim(dimIndex, fromCoord, toCoord, coordSys) {
  71732. var otherDimIndex = 1 - dimIndex;
  71733. var dimName = coordSys.dimensions[dimIndex];
  71734. return isInifinity(fromCoord[otherDimIndex]) && isInifinity(toCoord[otherDimIndex])
  71735. && fromCoord[dimIndex] === toCoord[dimIndex] && coordSys.getAxis(dimName).containData(fromCoord[dimIndex]);
  71736. }
  71737. function markLineFilter(coordSys, item) {
  71738. if (coordSys.type === 'cartesian2d') {
  71739. var fromCoord = item[0].coord;
  71740. var toCoord = item[1].coord;
  71741. // In case
  71742. // {
  71743. // markLine: {
  71744. // data: [{ yAxis: 2 }]
  71745. // }
  71746. // }
  71747. if (
  71748. fromCoord && toCoord &&
  71749. (ifMarkLineHasOnlyDim(1, fromCoord, toCoord, coordSys)
  71750. || ifMarkLineHasOnlyDim(0, fromCoord, toCoord, coordSys))
  71751. ) {
  71752. return true;
  71753. }
  71754. }
  71755. return dataFilter$1(coordSys, item[0])
  71756. && dataFilter$1(coordSys, item[1]);
  71757. }
  71758. function updateSingleMarkerEndLayout(
  71759. data, idx, isFrom, seriesModel, api
  71760. ) {
  71761. var coordSys = seriesModel.coordinateSystem;
  71762. var itemModel = data.getItemModel(idx);
  71763. var point;
  71764. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  71765. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  71766. if (!isNaN(xPx) && !isNaN(yPx)) {
  71767. point = [xPx, yPx];
  71768. }
  71769. else {
  71770. // Chart like bar may have there own marker positioning logic
  71771. if (seriesModel.getMarkerPosition) {
  71772. // Use the getMarkerPoisition
  71773. point = seriesModel.getMarkerPosition(
  71774. data.getValues(data.dimensions, idx)
  71775. );
  71776. }
  71777. else {
  71778. var dims = coordSys.dimensions;
  71779. var x = data.get(dims[0], idx);
  71780. var y = data.get(dims[1], idx);
  71781. point = coordSys.dataToPoint([x, y]);
  71782. }
  71783. // Expand line to the edge of grid if value on one axis is Inifnity
  71784. // In case
  71785. // markLine: {
  71786. // data: [{
  71787. // yAxis: 2
  71788. // // or
  71789. // type: 'average'
  71790. // }]
  71791. // }
  71792. if (coordSys.type === 'cartesian2d') {
  71793. var xAxis = coordSys.getAxis('x');
  71794. var yAxis = coordSys.getAxis('y');
  71795. var dims = coordSys.dimensions;
  71796. if (isInifinity(data.get(dims[0], idx))) {
  71797. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[isFrom ? 0 : 1]);
  71798. }
  71799. else if (isInifinity(data.get(dims[1], idx))) {
  71800. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[isFrom ? 0 : 1]);
  71801. }
  71802. }
  71803. // Use x, y if has any
  71804. if (!isNaN(xPx)) {
  71805. point[0] = xPx;
  71806. }
  71807. if (!isNaN(yPx)) {
  71808. point[1] = yPx;
  71809. }
  71810. }
  71811. data.setItemLayout(idx, point);
  71812. }
  71813. MarkerView.extend({
  71814. type: 'markLine',
  71815. // updateLayout: function (markLineModel, ecModel, api) {
  71816. // ecModel.eachSeries(function (seriesModel) {
  71817. // var mlModel = seriesModel.markLineModel;
  71818. // if (mlModel) {
  71819. // var mlData = mlModel.getData();
  71820. // var fromData = mlModel.__from;
  71821. // var toData = mlModel.__to;
  71822. // // Update visual and layout of from symbol and to symbol
  71823. // fromData.each(function (idx) {
  71824. // updateSingleMarkerEndLayout(fromData, idx, true, seriesModel, api);
  71825. // updateSingleMarkerEndLayout(toData, idx, false, seriesModel, api);
  71826. // });
  71827. // // Update layout of line
  71828. // mlData.each(function (idx) {
  71829. // mlData.setItemLayout(idx, [
  71830. // fromData.getItemLayout(idx),
  71831. // toData.getItemLayout(idx)
  71832. // ]);
  71833. // });
  71834. // this.markerGroupMap.get(seriesModel.id).updateLayout();
  71835. // }
  71836. // }, this);
  71837. // },
  71838. updateTransform: function (markLineModel, ecModel, api) {
  71839. ecModel.eachSeries(function (seriesModel) {
  71840. var mlModel = seriesModel.markLineModel;
  71841. if (mlModel) {
  71842. var mlData = mlModel.getData();
  71843. var fromData = mlModel.__from;
  71844. var toData = mlModel.__to;
  71845. // Update visual and layout of from symbol and to symbol
  71846. fromData.each(function (idx) {
  71847. updateSingleMarkerEndLayout(fromData, idx, true, seriesModel, api);
  71848. updateSingleMarkerEndLayout(toData, idx, false, seriesModel, api);
  71849. });
  71850. // Update layout of line
  71851. mlData.each(function (idx) {
  71852. mlData.setItemLayout(idx, [
  71853. fromData.getItemLayout(idx),
  71854. toData.getItemLayout(idx)
  71855. ]);
  71856. });
  71857. this.markerGroupMap.get(seriesModel.id).updateLayout();
  71858. }
  71859. }, this);
  71860. },
  71861. renderSeries: function (seriesModel, mlModel, ecModel, api) {
  71862. var coordSys = seriesModel.coordinateSystem;
  71863. var seriesId = seriesModel.id;
  71864. var seriesData = seriesModel.getData();
  71865. var lineDrawMap = this.markerGroupMap;
  71866. var lineDraw = lineDrawMap.get(seriesId)
  71867. || lineDrawMap.set(seriesId, new LineDraw());
  71868. this.group.add(lineDraw.group);
  71869. var mlData = createList$2(coordSys, seriesModel, mlModel);
  71870. var fromData = mlData.from;
  71871. var toData = mlData.to;
  71872. var lineData = mlData.line;
  71873. mlModel.__from = fromData;
  71874. mlModel.__to = toData;
  71875. // Line data for tooltip and formatter
  71876. mlModel.setData(lineData);
  71877. var symbolType = mlModel.get('symbol');
  71878. var symbolSize = mlModel.get('symbolSize');
  71879. if (!isArray(symbolType)) {
  71880. symbolType = [symbolType, symbolType];
  71881. }
  71882. if (typeof symbolSize === 'number') {
  71883. symbolSize = [symbolSize, symbolSize];
  71884. }
  71885. // Update visual and layout of from symbol and to symbol
  71886. mlData.from.each(function (idx) {
  71887. updateDataVisualAndLayout(fromData, idx, true);
  71888. updateDataVisualAndLayout(toData, idx, false);
  71889. });
  71890. // Update visual and layout of line
  71891. lineData.each(function (idx) {
  71892. var lineColor = lineData.getItemModel(idx).get('lineStyle.color');
  71893. lineData.setItemVisual(idx, {
  71894. color: lineColor || fromData.getItemVisual(idx, 'color')
  71895. });
  71896. lineData.setItemLayout(idx, [
  71897. fromData.getItemLayout(idx),
  71898. toData.getItemLayout(idx)
  71899. ]);
  71900. lineData.setItemVisual(idx, {
  71901. 'fromSymbolSize': fromData.getItemVisual(idx, 'symbolSize'),
  71902. 'fromSymbol': fromData.getItemVisual(idx, 'symbol'),
  71903. 'toSymbolSize': toData.getItemVisual(idx, 'symbolSize'),
  71904. 'toSymbol': toData.getItemVisual(idx, 'symbol')
  71905. });
  71906. });
  71907. lineDraw.updateData(lineData);
  71908. // Set host model for tooltip
  71909. // FIXME
  71910. mlData.line.eachItemGraphicEl(function (el, idx) {
  71911. el.traverse(function (child) {
  71912. child.dataModel = mlModel;
  71913. });
  71914. });
  71915. function updateDataVisualAndLayout(data, idx, isFrom) {
  71916. var itemModel = data.getItemModel(idx);
  71917. updateSingleMarkerEndLayout(
  71918. data, idx, isFrom, seriesModel, api
  71919. );
  71920. data.setItemVisual(idx, {
  71921. symbolSize: itemModel.get('symbolSize') || symbolSize[isFrom ? 0 : 1],
  71922. symbol: itemModel.get('symbol', true) || symbolType[isFrom ? 0 : 1],
  71923. color: itemModel.get('itemStyle.color') || seriesData.getVisual('color')
  71924. });
  71925. }
  71926. lineDraw.__keep = true;
  71927. lineDraw.group.silent = mlModel.get('silent') || seriesModel.get('silent');
  71928. }
  71929. });
  71930. /**
  71931. * @inner
  71932. * @param {module:echarts/coord/*} coordSys
  71933. * @param {module:echarts/model/Series} seriesModel
  71934. * @param {module:echarts/model/Model} mpModel
  71935. */
  71936. function createList$2(coordSys, seriesModel, mlModel) {
  71937. var coordDimsInfos;
  71938. if (coordSys) {
  71939. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  71940. var info = seriesModel.getData().getDimensionInfo(
  71941. seriesModel.getData().mapDimension(coordDim)
  71942. ) || {};
  71943. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  71944. return defaults({name: coordDim}, info);
  71945. });
  71946. }
  71947. else {
  71948. coordDimsInfos =[{
  71949. name: 'value',
  71950. type: 'float'
  71951. }];
  71952. }
  71953. var fromData = new List(coordDimsInfos, mlModel);
  71954. var toData = new List(coordDimsInfos, mlModel);
  71955. // No dimensions
  71956. var lineData = new List([], mlModel);
  71957. var optData = map(mlModel.get('data'), curry(
  71958. markLineTransform, seriesModel, coordSys, mlModel
  71959. ));
  71960. if (coordSys) {
  71961. optData = filter(
  71962. optData, curry(markLineFilter, coordSys)
  71963. );
  71964. }
  71965. var dimValueGetter$$1 = coordSys ? dimValueGetter : function (item) {
  71966. return item.value;
  71967. };
  71968. fromData.initData(
  71969. map(optData, function (item) { return item[0]; }),
  71970. null, dimValueGetter$$1
  71971. );
  71972. toData.initData(
  71973. map(optData, function (item) { return item[1]; }),
  71974. null, dimValueGetter$$1
  71975. );
  71976. lineData.initData(
  71977. map(optData, function (item) { return item[2]; })
  71978. );
  71979. lineData.hasItemOption = true;
  71980. return {
  71981. from: fromData,
  71982. to: toData,
  71983. line: lineData
  71984. };
  71985. }
  71986. /*
  71987. * Licensed to the Apache Software Foundation (ASF) under one
  71988. * or more contributor license agreements. See the NOTICE file
  71989. * distributed with this work for additional information
  71990. * regarding copyright ownership. The ASF licenses this file
  71991. * to you under the Apache License, Version 2.0 (the
  71992. * "License"); you may not use this file except in compliance
  71993. * with the License. You may obtain a copy of the License at
  71994. *
  71995. * http://www.apache.org/licenses/LICENSE-2.0
  71996. *
  71997. * Unless required by applicable law or agreed to in writing,
  71998. * software distributed under the License is distributed on an
  71999. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72000. * KIND, either express or implied. See the License for the
  72001. * specific language governing permissions and limitations
  72002. * under the License.
  72003. */
  72004. registerPreprocessor(function (opt) {
  72005. // Make sure markLine component is enabled
  72006. opt.markLine = opt.markLine || {};
  72007. });
  72008. /*
  72009. * Licensed to the Apache Software Foundation (ASF) under one
  72010. * or more contributor license agreements. See the NOTICE file
  72011. * distributed with this work for additional information
  72012. * regarding copyright ownership. The ASF licenses this file
  72013. * to you under the Apache License, Version 2.0 (the
  72014. * "License"); you may not use this file except in compliance
  72015. * with the License. You may obtain a copy of the License at
  72016. *
  72017. * http://www.apache.org/licenses/LICENSE-2.0
  72018. *
  72019. * Unless required by applicable law or agreed to in writing,
  72020. * software distributed under the License is distributed on an
  72021. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72022. * KIND, either express or implied. See the License for the
  72023. * specific language governing permissions and limitations
  72024. * under the License.
  72025. */
  72026. MarkerModel.extend({
  72027. type: 'markArea',
  72028. defaultOption: {
  72029. zlevel: 0,
  72030. // PENDING
  72031. z: 1,
  72032. tooltip: {
  72033. trigger: 'item'
  72034. },
  72035. // markArea should fixed on the coordinate system
  72036. animation: false,
  72037. label: {
  72038. show: true,
  72039. position: 'top'
  72040. },
  72041. itemStyle: {
  72042. // color and borderColor default to use color from series
  72043. // color: 'auto'
  72044. // borderColor: 'auto'
  72045. borderWidth: 0
  72046. },
  72047. emphasis: {
  72048. label: {
  72049. show: true,
  72050. position: 'top'
  72051. }
  72052. }
  72053. }
  72054. });
  72055. /*
  72056. * Licensed to the Apache Software Foundation (ASF) under one
  72057. * or more contributor license agreements. See the NOTICE file
  72058. * distributed with this work for additional information
  72059. * regarding copyright ownership. The ASF licenses this file
  72060. * to you under the Apache License, Version 2.0 (the
  72061. * "License"); you may not use this file except in compliance
  72062. * with the License. You may obtain a copy of the License at
  72063. *
  72064. * http://www.apache.org/licenses/LICENSE-2.0
  72065. *
  72066. * Unless required by applicable law or agreed to in writing,
  72067. * software distributed under the License is distributed on an
  72068. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72069. * KIND, either express or implied. See the License for the
  72070. * specific language governing permissions and limitations
  72071. * under the License.
  72072. */
  72073. // TODO Better on polar
  72074. var markAreaTransform = function (seriesModel, coordSys, maModel, item) {
  72075. var lt = dataTransform(seriesModel, item[0]);
  72076. var rb = dataTransform(seriesModel, item[1]);
  72077. var retrieve$$1 = retrieve;
  72078. // FIXME make sure lt is less than rb
  72079. var ltCoord = lt.coord;
  72080. var rbCoord = rb.coord;
  72081. ltCoord[0] = retrieve$$1(ltCoord[0], -Infinity);
  72082. ltCoord[1] = retrieve$$1(ltCoord[1], -Infinity);
  72083. rbCoord[0] = retrieve$$1(rbCoord[0], Infinity);
  72084. rbCoord[1] = retrieve$$1(rbCoord[1], Infinity);
  72085. // Merge option into one
  72086. var result = mergeAll([{}, lt, rb]);
  72087. result.coord = [
  72088. lt.coord, rb.coord
  72089. ];
  72090. result.x0 = lt.x;
  72091. result.y0 = lt.y;
  72092. result.x1 = rb.x;
  72093. result.y1 = rb.y;
  72094. return result;
  72095. };
  72096. function isInifinity$1(val) {
  72097. return !isNaN(val) && !isFinite(val);
  72098. }
  72099. // If a markArea has one dim
  72100. function ifMarkLineHasOnlyDim$1(dimIndex, fromCoord, toCoord, coordSys) {
  72101. var otherDimIndex = 1 - dimIndex;
  72102. return isInifinity$1(fromCoord[otherDimIndex]) && isInifinity$1(toCoord[otherDimIndex]);
  72103. }
  72104. function markAreaFilter(coordSys, item) {
  72105. var fromCoord = item.coord[0];
  72106. var toCoord = item.coord[1];
  72107. if (coordSys.type === 'cartesian2d') {
  72108. // In case
  72109. // {
  72110. // markArea: {
  72111. // data: [{ yAxis: 2 }]
  72112. // }
  72113. // }
  72114. if (
  72115. fromCoord && toCoord &&
  72116. (ifMarkLineHasOnlyDim$1(1, fromCoord, toCoord, coordSys)
  72117. || ifMarkLineHasOnlyDim$1(0, fromCoord, toCoord, coordSys))
  72118. ) {
  72119. return true;
  72120. }
  72121. }
  72122. return dataFilter$1(coordSys, {
  72123. coord: fromCoord,
  72124. x: item.x0,
  72125. y: item.y0
  72126. })
  72127. || dataFilter$1(coordSys, {
  72128. coord: toCoord,
  72129. x: item.x1,
  72130. y: item.y1
  72131. });
  72132. }
  72133. // dims can be ['x0', 'y0'], ['x1', 'y1'], ['x0', 'y1'], ['x1', 'y0']
  72134. function getSingleMarkerEndPoint(data, idx, dims, seriesModel, api) {
  72135. var coordSys = seriesModel.coordinateSystem;
  72136. var itemModel = data.getItemModel(idx);
  72137. var point;
  72138. var xPx = parsePercent$1(itemModel.get(dims[0]), api.getWidth());
  72139. var yPx = parsePercent$1(itemModel.get(dims[1]), api.getHeight());
  72140. if (!isNaN(xPx) && !isNaN(yPx)) {
  72141. point = [xPx, yPx];
  72142. }
  72143. else {
  72144. // Chart like bar may have there own marker positioning logic
  72145. if (seriesModel.getMarkerPosition) {
  72146. // Use the getMarkerPoisition
  72147. point = seriesModel.getMarkerPosition(
  72148. data.getValues(dims, idx)
  72149. );
  72150. }
  72151. else {
  72152. var x = data.get(dims[0], idx);
  72153. var y = data.get(dims[1], idx);
  72154. var pt = [x, y];
  72155. coordSys.clampData && coordSys.clampData(pt, pt);
  72156. point = coordSys.dataToPoint(pt, true);
  72157. }
  72158. if (coordSys.type === 'cartesian2d') {
  72159. var xAxis = coordSys.getAxis('x');
  72160. var yAxis = coordSys.getAxis('y');
  72161. var x = data.get(dims[0], idx);
  72162. var y = data.get(dims[1], idx);
  72163. if (isInifinity$1(x)) {
  72164. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[dims[0] === 'x0' ? 0 : 1]);
  72165. }
  72166. else if (isInifinity$1(y)) {
  72167. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[dims[1] === 'y0' ? 0 : 1]);
  72168. }
  72169. }
  72170. // Use x, y if has any
  72171. if (!isNaN(xPx)) {
  72172. point[0] = xPx;
  72173. }
  72174. if (!isNaN(yPx)) {
  72175. point[1] = yPx;
  72176. }
  72177. }
  72178. return point;
  72179. }
  72180. var dimPermutations = [['x0', 'y0'], ['x1', 'y0'], ['x1', 'y1'], ['x0', 'y1']];
  72181. MarkerView.extend({
  72182. type: 'markArea',
  72183. // updateLayout: function (markAreaModel, ecModel, api) {
  72184. // ecModel.eachSeries(function (seriesModel) {
  72185. // var maModel = seriesModel.markAreaModel;
  72186. // if (maModel) {
  72187. // var areaData = maModel.getData();
  72188. // areaData.each(function (idx) {
  72189. // var points = zrUtil.map(dimPermutations, function (dim) {
  72190. // return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  72191. // });
  72192. // // Layout
  72193. // areaData.setItemLayout(idx, points);
  72194. // var el = areaData.getItemGraphicEl(idx);
  72195. // el.setShape('points', points);
  72196. // });
  72197. // }
  72198. // }, this);
  72199. // },
  72200. updateTransform: function (markAreaModel, ecModel, api) {
  72201. ecModel.eachSeries(function (seriesModel) {
  72202. var maModel = seriesModel.markAreaModel;
  72203. if (maModel) {
  72204. var areaData = maModel.getData();
  72205. areaData.each(function (idx) {
  72206. var points = map(dimPermutations, function (dim) {
  72207. return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  72208. });
  72209. // Layout
  72210. areaData.setItemLayout(idx, points);
  72211. var el = areaData.getItemGraphicEl(idx);
  72212. el.setShape('points', points);
  72213. });
  72214. }
  72215. }, this);
  72216. },
  72217. renderSeries: function (seriesModel, maModel, ecModel, api) {
  72218. var coordSys = seriesModel.coordinateSystem;
  72219. var seriesId = seriesModel.id;
  72220. var seriesData = seriesModel.getData();
  72221. var areaGroupMap = this.markerGroupMap;
  72222. var polygonGroup = areaGroupMap.get(seriesId)
  72223. || areaGroupMap.set(seriesId, {group: new Group()});
  72224. this.group.add(polygonGroup.group);
  72225. polygonGroup.__keep = true;
  72226. var areaData = createList$3(coordSys, seriesModel, maModel);
  72227. // Line data for tooltip and formatter
  72228. maModel.setData(areaData);
  72229. // Update visual and layout of line
  72230. areaData.each(function (idx) {
  72231. // Layout
  72232. areaData.setItemLayout(idx, map(dimPermutations, function (dim) {
  72233. return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  72234. }));
  72235. // Visual
  72236. areaData.setItemVisual(idx, {
  72237. color: seriesData.getVisual('color')
  72238. });
  72239. });
  72240. areaData.diff(polygonGroup.__data)
  72241. .add(function (idx) {
  72242. var polygon = new Polygon({
  72243. shape: {
  72244. points: areaData.getItemLayout(idx)
  72245. }
  72246. });
  72247. areaData.setItemGraphicEl(idx, polygon);
  72248. polygonGroup.group.add(polygon);
  72249. })
  72250. .update(function (newIdx, oldIdx) {
  72251. var polygon = polygonGroup.__data.getItemGraphicEl(oldIdx);
  72252. updateProps(polygon, {
  72253. shape: {
  72254. points: areaData.getItemLayout(newIdx)
  72255. }
  72256. }, maModel, newIdx);
  72257. polygonGroup.group.add(polygon);
  72258. areaData.setItemGraphicEl(newIdx, polygon);
  72259. })
  72260. .remove(function (idx) {
  72261. var polygon = polygonGroup.__data.getItemGraphicEl(idx);
  72262. polygonGroup.group.remove(polygon);
  72263. })
  72264. .execute();
  72265. areaData.eachItemGraphicEl(function (polygon, idx) {
  72266. var itemModel = areaData.getItemModel(idx);
  72267. var labelModel = itemModel.getModel('label');
  72268. var labelHoverModel = itemModel.getModel('emphasis.label');
  72269. var color = areaData.getItemVisual(idx, 'color');
  72270. polygon.useStyle(
  72271. defaults(
  72272. itemModel.getModel('itemStyle').getItemStyle(),
  72273. {
  72274. fill: modifyAlpha(color, 0.4),
  72275. stroke: color
  72276. }
  72277. )
  72278. );
  72279. polygon.hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  72280. setLabelStyle(
  72281. polygon.style, polygon.hoverStyle, labelModel, labelHoverModel,
  72282. {
  72283. labelFetcher: maModel,
  72284. labelDataIndex: idx,
  72285. defaultText: areaData.getName(idx) || '',
  72286. isRectText: true,
  72287. autoColor: color
  72288. }
  72289. );
  72290. setHoverStyle(polygon, {});
  72291. polygon.dataModel = maModel;
  72292. });
  72293. polygonGroup.__data = areaData;
  72294. polygonGroup.group.silent = maModel.get('silent') || seriesModel.get('silent');
  72295. }
  72296. });
  72297. /**
  72298. * @inner
  72299. * @param {module:echarts/coord/*} coordSys
  72300. * @param {module:echarts/model/Series} seriesModel
  72301. * @param {module:echarts/model/Model} mpModel
  72302. */
  72303. function createList$3(coordSys, seriesModel, maModel) {
  72304. var coordDimsInfos;
  72305. var areaData;
  72306. var dims = ['x0', 'y0', 'x1', 'y1'];
  72307. if (coordSys) {
  72308. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  72309. var data = seriesModel.getData();
  72310. var info = data.getDimensionInfo(
  72311. data.mapDimension(coordDim)
  72312. ) || {};
  72313. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  72314. return defaults({name: coordDim}, info);
  72315. });
  72316. areaData = new List(map(dims, function (dim, idx) {
  72317. return {
  72318. name: dim,
  72319. type: coordDimsInfos[idx % 2].type
  72320. };
  72321. }), maModel);
  72322. }
  72323. else {
  72324. coordDimsInfos =[{
  72325. name: 'value',
  72326. type: 'float'
  72327. }];
  72328. areaData = new List(coordDimsInfos, maModel);
  72329. }
  72330. var optData = map(maModel.get('data'), curry(
  72331. markAreaTransform, seriesModel, coordSys, maModel
  72332. ));
  72333. if (coordSys) {
  72334. optData = filter(
  72335. optData, curry(markAreaFilter, coordSys)
  72336. );
  72337. }
  72338. var dimValueGetter$$1 = coordSys ? function (item, dimName, dataIndex, dimIndex) {
  72339. return item.coord[Math.floor(dimIndex / 2)][dimIndex % 2];
  72340. } : function (item) {
  72341. return item.value;
  72342. };
  72343. areaData.initData(optData, null, dimValueGetter$$1);
  72344. areaData.hasItemOption = true;
  72345. return areaData;
  72346. }
  72347. /*
  72348. * Licensed to the Apache Software Foundation (ASF) under one
  72349. * or more contributor license agreements. See the NOTICE file
  72350. * distributed with this work for additional information
  72351. * regarding copyright ownership. The ASF licenses this file
  72352. * to you under the Apache License, Version 2.0 (the
  72353. * "License"); you may not use this file except in compliance
  72354. * with the License. You may obtain a copy of the License at
  72355. *
  72356. * http://www.apache.org/licenses/LICENSE-2.0
  72357. *
  72358. * Unless required by applicable law or agreed to in writing,
  72359. * software distributed under the License is distributed on an
  72360. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72361. * KIND, either express or implied. See the License for the
  72362. * specific language governing permissions and limitations
  72363. * under the License.
  72364. */
  72365. registerPreprocessor(function (opt) {
  72366. // Make sure markArea component is enabled
  72367. opt.markArea = opt.markArea || {};
  72368. });
  72369. /*
  72370. * Licensed to the Apache Software Foundation (ASF) under one
  72371. * or more contributor license agreements. See the NOTICE file
  72372. * distributed with this work for additional information
  72373. * regarding copyright ownership. The ASF licenses this file
  72374. * to you under the Apache License, Version 2.0 (the
  72375. * "License"); you may not use this file except in compliance
  72376. * with the License. You may obtain a copy of the License at
  72377. *
  72378. * http://www.apache.org/licenses/LICENSE-2.0
  72379. *
  72380. * Unless required by applicable law or agreed to in writing,
  72381. * software distributed under the License is distributed on an
  72382. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72383. * KIND, either express or implied. See the License for the
  72384. * specific language governing permissions and limitations
  72385. * under the License.
  72386. */
  72387. var preprocessor$3 = function (option) {
  72388. var timelineOpt = option && option.timeline;
  72389. if (!isArray(timelineOpt)) {
  72390. timelineOpt = timelineOpt ? [timelineOpt] : [];
  72391. }
  72392. each$1(timelineOpt, function (opt) {
  72393. if (!opt) {
  72394. return;
  72395. }
  72396. compatibleEC2(opt);
  72397. });
  72398. };
  72399. function compatibleEC2(opt) {
  72400. var type = opt.type;
  72401. var ec2Types = {'number': 'value', 'time': 'time'};
  72402. // Compatible with ec2
  72403. if (ec2Types[type]) {
  72404. opt.axisType = ec2Types[type];
  72405. delete opt.type;
  72406. }
  72407. transferItem(opt);
  72408. if (has$2(opt, 'controlPosition')) {
  72409. var controlStyle = opt.controlStyle || (opt.controlStyle = {});
  72410. if (!has$2(controlStyle, 'position')) {
  72411. controlStyle.position = opt.controlPosition;
  72412. }
  72413. if (controlStyle.position === 'none' && !has$2(controlStyle, 'show')) {
  72414. controlStyle.show = false;
  72415. delete controlStyle.position;
  72416. }
  72417. delete opt.controlPosition;
  72418. }
  72419. each$1(opt.data || [], function (dataItem) {
  72420. if (isObject$1(dataItem) && !isArray(dataItem)) {
  72421. if (!has$2(dataItem, 'value') && has$2(dataItem, 'name')) {
  72422. // In ec2, using name as value.
  72423. dataItem.value = dataItem.name;
  72424. }
  72425. transferItem(dataItem);
  72426. }
  72427. });
  72428. }
  72429. function transferItem(opt) {
  72430. var itemStyle = opt.itemStyle || (opt.itemStyle = {});
  72431. var itemStyleEmphasis = itemStyle.emphasis || (itemStyle.emphasis = {});
  72432. // Transfer label out
  72433. var label = opt.label || (opt.label || {});
  72434. var labelNormal = label.normal || (label.normal = {});
  72435. var excludeLabelAttr = {normal: 1, emphasis: 1};
  72436. each$1(label, function (value, name) {
  72437. if (!excludeLabelAttr[name] && !has$2(labelNormal, name)) {
  72438. labelNormal[name] = value;
  72439. }
  72440. });
  72441. if (itemStyleEmphasis.label && !has$2(label, 'emphasis')) {
  72442. label.emphasis = itemStyleEmphasis.label;
  72443. delete itemStyleEmphasis.label;
  72444. }
  72445. }
  72446. function has$2(obj, attr) {
  72447. return obj.hasOwnProperty(attr);
  72448. }
  72449. /*
  72450. * Licensed to the Apache Software Foundation (ASF) under one
  72451. * or more contributor license agreements. See the NOTICE file
  72452. * distributed with this work for additional information
  72453. * regarding copyright ownership. The ASF licenses this file
  72454. * to you under the Apache License, Version 2.0 (the
  72455. * "License"); you may not use this file except in compliance
  72456. * with the License. You may obtain a copy of the License at
  72457. *
  72458. * http://www.apache.org/licenses/LICENSE-2.0
  72459. *
  72460. * Unless required by applicable law or agreed to in writing,
  72461. * software distributed under the License is distributed on an
  72462. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72463. * KIND, either express or implied. See the License for the
  72464. * specific language governing permissions and limitations
  72465. * under the License.
  72466. */
  72467. ComponentModel.registerSubTypeDefaulter('timeline', function () {
  72468. // Only slider now.
  72469. return 'slider';
  72470. });
  72471. /*
  72472. * Licensed to the Apache Software Foundation (ASF) under one
  72473. * or more contributor license agreements. See the NOTICE file
  72474. * distributed with this work for additional information
  72475. * regarding copyright ownership. The ASF licenses this file
  72476. * to you under the Apache License, Version 2.0 (the
  72477. * "License"); you may not use this file except in compliance
  72478. * with the License. You may obtain a copy of the License at
  72479. *
  72480. * http://www.apache.org/licenses/LICENSE-2.0
  72481. *
  72482. * Unless required by applicable law or agreed to in writing,
  72483. * software distributed under the License is distributed on an
  72484. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72485. * KIND, either express or implied. See the License for the
  72486. * specific language governing permissions and limitations
  72487. * under the License.
  72488. */
  72489. registerAction(
  72490. {type: 'timelineChange', event: 'timelineChanged', update: 'prepareAndUpdate'},
  72491. function (payload, ecModel) {
  72492. var timelineModel = ecModel.getComponent('timeline');
  72493. if (timelineModel && payload.currentIndex != null) {
  72494. timelineModel.setCurrentIndex(payload.currentIndex);
  72495. if (!timelineModel.get('loop', true) && timelineModel.isIndexMax()) {
  72496. timelineModel.setPlayState(false);
  72497. }
  72498. }
  72499. // Set normalized currentIndex to payload.
  72500. ecModel.resetOption('timeline');
  72501. return defaults({
  72502. currentIndex: timelineModel.option.currentIndex
  72503. }, payload);
  72504. }
  72505. );
  72506. registerAction(
  72507. {type: 'timelinePlayChange', event: 'timelinePlayChanged', update: 'update'},
  72508. function (payload, ecModel) {
  72509. var timelineModel = ecModel.getComponent('timeline');
  72510. if (timelineModel && payload.playState != null) {
  72511. timelineModel.setPlayState(payload.playState);
  72512. }
  72513. }
  72514. );
  72515. /*
  72516. * Licensed to the Apache Software Foundation (ASF) under one
  72517. * or more contributor license agreements. See the NOTICE file
  72518. * distributed with this work for additional information
  72519. * regarding copyright ownership. The ASF licenses this file
  72520. * to you under the Apache License, Version 2.0 (the
  72521. * "License"); you may not use this file except in compliance
  72522. * with the License. You may obtain a copy of the License at
  72523. *
  72524. * http://www.apache.org/licenses/LICENSE-2.0
  72525. *
  72526. * Unless required by applicable law or agreed to in writing,
  72527. * software distributed under the License is distributed on an
  72528. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72529. * KIND, either express or implied. See the License for the
  72530. * specific language governing permissions and limitations
  72531. * under the License.
  72532. */
  72533. var TimelineModel = ComponentModel.extend({
  72534. type: 'timeline',
  72535. layoutMode: 'box',
  72536. /**
  72537. * @protected
  72538. */
  72539. defaultOption: {
  72540. zlevel: 0, // 一级层叠
  72541. z: 4, // 二级层叠
  72542. show: true,
  72543. axisType: 'time', // 模式是时间类型,支持 value, category
  72544. realtime: true,
  72545. left: '20%',
  72546. top: null,
  72547. right: '20%',
  72548. bottom: 0,
  72549. width: null,
  72550. height: 40,
  72551. padding: 5,
  72552. controlPosition: 'left', // 'left' 'right' 'top' 'bottom' 'none'
  72553. autoPlay: false,
  72554. rewind: false, // 反向播放
  72555. loop: true,
  72556. playInterval: 2000, // 播放时间间隔,单位ms
  72557. currentIndex: 0,
  72558. itemStyle: {},
  72559. label: {
  72560. color: '#000'
  72561. },
  72562. data: []
  72563. },
  72564. /**
  72565. * @override
  72566. */
  72567. init: function (option, parentModel, ecModel) {
  72568. /**
  72569. * @private
  72570. * @type {module:echarts/data/List}
  72571. */
  72572. this._data;
  72573. /**
  72574. * @private
  72575. * @type {Array.<string>}
  72576. */
  72577. this._names;
  72578. this.mergeDefaultAndTheme(option, ecModel);
  72579. this._initData();
  72580. },
  72581. /**
  72582. * @override
  72583. */
  72584. mergeOption: function (option) {
  72585. TimelineModel.superApply(this, 'mergeOption', arguments);
  72586. this._initData();
  72587. },
  72588. /**
  72589. * @param {number} [currentIndex]
  72590. */
  72591. setCurrentIndex: function (currentIndex) {
  72592. if (currentIndex == null) {
  72593. currentIndex = this.option.currentIndex;
  72594. }
  72595. var count = this._data.count();
  72596. if (this.option.loop) {
  72597. currentIndex = (currentIndex % count + count) % count;
  72598. }
  72599. else {
  72600. currentIndex >= count && (currentIndex = count - 1);
  72601. currentIndex < 0 && (currentIndex = 0);
  72602. }
  72603. this.option.currentIndex = currentIndex;
  72604. },
  72605. /**
  72606. * @return {number} currentIndex
  72607. */
  72608. getCurrentIndex: function () {
  72609. return this.option.currentIndex;
  72610. },
  72611. /**
  72612. * @return {boolean}
  72613. */
  72614. isIndexMax: function () {
  72615. return this.getCurrentIndex() >= this._data.count() - 1;
  72616. },
  72617. /**
  72618. * @param {boolean} state true: play, false: stop
  72619. */
  72620. setPlayState: function (state) {
  72621. this.option.autoPlay = !!state;
  72622. },
  72623. /**
  72624. * @return {boolean} true: play, false: stop
  72625. */
  72626. getPlayState: function () {
  72627. return !!this.option.autoPlay;
  72628. },
  72629. /**
  72630. * @private
  72631. */
  72632. _initData: function () {
  72633. var thisOption = this.option;
  72634. var dataArr = thisOption.data || [];
  72635. var axisType = thisOption.axisType;
  72636. var names = this._names = [];
  72637. if (axisType === 'category') {
  72638. var idxArr = [];
  72639. each$1(dataArr, function (item, index) {
  72640. var value = getDataItemValue(item);
  72641. var newItem;
  72642. if (isObject$1(item)) {
  72643. newItem = clone(item);
  72644. newItem.value = index;
  72645. }
  72646. else {
  72647. newItem = index;
  72648. }
  72649. idxArr.push(newItem);
  72650. if (!isString(value) && (value == null || isNaN(value))) {
  72651. value = '';
  72652. }
  72653. names.push(value + '');
  72654. });
  72655. dataArr = idxArr;
  72656. }
  72657. var dimType = ({category: 'ordinal', time: 'time'})[axisType] || 'number';
  72658. var data = this._data = new List([{name: 'value', type: dimType}], this);
  72659. data.initData(dataArr, names);
  72660. },
  72661. getData: function () {
  72662. return this._data;
  72663. },
  72664. /**
  72665. * @public
  72666. * @return {Array.<string>} categoreis
  72667. */
  72668. getCategories: function () {
  72669. if (this.get('axisType') === 'category') {
  72670. return this._names.slice();
  72671. }
  72672. }
  72673. });
  72674. /*
  72675. * Licensed to the Apache Software Foundation (ASF) under one
  72676. * or more contributor license agreements. See the NOTICE file
  72677. * distributed with this work for additional information
  72678. * regarding copyright ownership. The ASF licenses this file
  72679. * to you under the Apache License, Version 2.0 (the
  72680. * "License"); you may not use this file except in compliance
  72681. * with the License. You may obtain a copy of the License at
  72682. *
  72683. * http://www.apache.org/licenses/LICENSE-2.0
  72684. *
  72685. * Unless required by applicable law or agreed to in writing,
  72686. * software distributed under the License is distributed on an
  72687. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72688. * KIND, either express or implied. See the License for the
  72689. * specific language governing permissions and limitations
  72690. * under the License.
  72691. */
  72692. var SliderTimelineModel = TimelineModel.extend({
  72693. type: 'timeline.slider',
  72694. /**
  72695. * @protected
  72696. */
  72697. defaultOption: {
  72698. backgroundColor: 'rgba(0,0,0,0)', // 时间轴背景颜色
  72699. borderColor: '#ccc', // 时间轴边框颜色
  72700. borderWidth: 0, // 时间轴边框线宽,单位px,默认为0(无边框)
  72701. orient: 'horizontal', // 'vertical'
  72702. inverse: false,
  72703. tooltip: { // boolean or Object
  72704. trigger: 'item' // data item may also have tootip attr.
  72705. },
  72706. symbol: 'emptyCircle',
  72707. symbolSize: 10,
  72708. lineStyle: {
  72709. show: true,
  72710. width: 2,
  72711. color: '#304654'
  72712. },
  72713. label: { // 文本标签
  72714. position: 'auto', // auto left right top bottom
  72715. // When using number, label position is not
  72716. // restricted by viewRect.
  72717. // positive: right/bottom, negative: left/top
  72718. show: true,
  72719. interval: 'auto',
  72720. rotate: 0,
  72721. // formatter: null,
  72722. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  72723. color: '#304654'
  72724. },
  72725. itemStyle: {
  72726. color: '#304654',
  72727. borderWidth: 1
  72728. },
  72729. checkpointStyle: {
  72730. symbol: 'circle',
  72731. symbolSize: 13,
  72732. color: '#c23531',
  72733. borderWidth: 5,
  72734. borderColor: 'rgba(194,53,49, 0.5)',
  72735. animation: true,
  72736. animationDuration: 300,
  72737. animationEasing: 'quinticInOut'
  72738. },
  72739. controlStyle: {
  72740. show: true,
  72741. showPlayBtn: true,
  72742. showPrevBtn: true,
  72743. showNextBtn: true,
  72744. itemSize: 22,
  72745. itemGap: 12,
  72746. position: 'left', // 'left' 'right' 'top' 'bottom'
  72747. 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
  72748. 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
  72749. 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
  72750. 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
  72751. color: '#304654',
  72752. borderColor: '#304654',
  72753. borderWidth: 1
  72754. },
  72755. emphasis: {
  72756. label: {
  72757. show: true,
  72758. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  72759. color: '#c23531'
  72760. },
  72761. itemStyle: {
  72762. color: '#c23531'
  72763. },
  72764. controlStyle: {
  72765. color: '#c23531',
  72766. borderColor: '#c23531',
  72767. borderWidth: 2
  72768. }
  72769. },
  72770. data: []
  72771. }
  72772. });
  72773. mixin(SliderTimelineModel, dataFormatMixin);
  72774. /*
  72775. * Licensed to the Apache Software Foundation (ASF) under one
  72776. * or more contributor license agreements. See the NOTICE file
  72777. * distributed with this work for additional information
  72778. * regarding copyright ownership. The ASF licenses this file
  72779. * to you under the Apache License, Version 2.0 (the
  72780. * "License"); you may not use this file except in compliance
  72781. * with the License. You may obtain a copy of the License at
  72782. *
  72783. * http://www.apache.org/licenses/LICENSE-2.0
  72784. *
  72785. * Unless required by applicable law or agreed to in writing,
  72786. * software distributed under the License is distributed on an
  72787. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72788. * KIND, either express or implied. See the License for the
  72789. * specific language governing permissions and limitations
  72790. * under the License.
  72791. */
  72792. var TimelineView = Component.extend({
  72793. type: 'timeline'
  72794. });
  72795. /*
  72796. * Licensed to the Apache Software Foundation (ASF) under one
  72797. * or more contributor license agreements. See the NOTICE file
  72798. * distributed with this work for additional information
  72799. * regarding copyright ownership. The ASF licenses this file
  72800. * to you under the Apache License, Version 2.0 (the
  72801. * "License"); you may not use this file except in compliance
  72802. * with the License. You may obtain a copy of the License at
  72803. *
  72804. * http://www.apache.org/licenses/LICENSE-2.0
  72805. *
  72806. * Unless required by applicable law or agreed to in writing,
  72807. * software distributed under the License is distributed on an
  72808. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72809. * KIND, either express or implied. See the License for the
  72810. * specific language governing permissions and limitations
  72811. * under the License.
  72812. */
  72813. /**
  72814. * Extend axis 2d
  72815. * @constructor module:echarts/coord/cartesian/Axis2D
  72816. * @extends {module:echarts/coord/cartesian/Axis}
  72817. * @param {string} dim
  72818. * @param {*} scale
  72819. * @param {Array.<number>} coordExtent
  72820. * @param {string} axisType
  72821. * @param {string} position
  72822. */
  72823. var TimelineAxis = function (dim, scale, coordExtent, axisType) {
  72824. Axis.call(this, dim, scale, coordExtent);
  72825. /**
  72826. * Axis type
  72827. * - 'category'
  72828. * - 'value'
  72829. * - 'time'
  72830. * - 'log'
  72831. * @type {string}
  72832. */
  72833. this.type = axisType || 'value';
  72834. /**
  72835. * Axis model
  72836. * @param {module:echarts/component/TimelineModel}
  72837. */
  72838. this.model = null;
  72839. };
  72840. TimelineAxis.prototype = {
  72841. constructor: TimelineAxis,
  72842. /**
  72843. * @override
  72844. */
  72845. getLabelModel: function () {
  72846. return this.model.getModel('label');
  72847. },
  72848. /**
  72849. * @override
  72850. */
  72851. isHorizontal: function () {
  72852. return this.model.get('orient') === 'horizontal';
  72853. }
  72854. };
  72855. inherits(TimelineAxis, Axis);
  72856. /*
  72857. * Licensed to the Apache Software Foundation (ASF) under one
  72858. * or more contributor license agreements. See the NOTICE file
  72859. * distributed with this work for additional information
  72860. * regarding copyright ownership. The ASF licenses this file
  72861. * to you under the Apache License, Version 2.0 (the
  72862. * "License"); you may not use this file except in compliance
  72863. * with the License. You may obtain a copy of the License at
  72864. *
  72865. * http://www.apache.org/licenses/LICENSE-2.0
  72866. *
  72867. * Unless required by applicable law or agreed to in writing,
  72868. * software distributed under the License is distributed on an
  72869. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72870. * KIND, either express or implied. See the License for the
  72871. * specific language governing permissions and limitations
  72872. * under the License.
  72873. */
  72874. var bind$6 = bind;
  72875. var each$27 = each$1;
  72876. var PI$4 = Math.PI;
  72877. TimelineView.extend({
  72878. type: 'timeline.slider',
  72879. init: function (ecModel, api) {
  72880. this.api = api;
  72881. /**
  72882. * @private
  72883. * @type {module:echarts/component/timeline/TimelineAxis}
  72884. */
  72885. this._axis;
  72886. /**
  72887. * @private
  72888. * @type {module:zrender/core/BoundingRect}
  72889. */
  72890. this._viewRect;
  72891. /**
  72892. * @type {number}
  72893. */
  72894. this._timer;
  72895. /**
  72896. * @type {module:zrender/Element}
  72897. */
  72898. this._currentPointer;
  72899. /**
  72900. * @type {module:zrender/container/Group}
  72901. */
  72902. this._mainGroup;
  72903. /**
  72904. * @type {module:zrender/container/Group}
  72905. */
  72906. this._labelGroup;
  72907. },
  72908. /**
  72909. * @override
  72910. */
  72911. render: function (timelineModel, ecModel, api, payload) {
  72912. this.model = timelineModel;
  72913. this.api = api;
  72914. this.ecModel = ecModel;
  72915. this.group.removeAll();
  72916. if (timelineModel.get('show', true)) {
  72917. var layoutInfo = this._layout(timelineModel, api);
  72918. var mainGroup = this._createGroup('mainGroup');
  72919. var labelGroup = this._createGroup('labelGroup');
  72920. /**
  72921. * @private
  72922. * @type {module:echarts/component/timeline/TimelineAxis}
  72923. */
  72924. var axis = this._axis = this._createAxis(layoutInfo, timelineModel);
  72925. timelineModel.formatTooltip = function (dataIndex) {
  72926. return encodeHTML(axis.scale.getLabel(dataIndex));
  72927. };
  72928. each$27(
  72929. ['AxisLine', 'AxisTick', 'Control', 'CurrentPointer'],
  72930. function (name) {
  72931. this['_render' + name](layoutInfo, mainGroup, axis, timelineModel);
  72932. },
  72933. this
  72934. );
  72935. this._renderAxisLabel(layoutInfo, labelGroup, axis, timelineModel);
  72936. this._position(layoutInfo, timelineModel);
  72937. }
  72938. this._doPlayStop();
  72939. },
  72940. /**
  72941. * @override
  72942. */
  72943. remove: function () {
  72944. this._clearTimer();
  72945. this.group.removeAll();
  72946. },
  72947. /**
  72948. * @override
  72949. */
  72950. dispose: function () {
  72951. this._clearTimer();
  72952. },
  72953. _layout: function (timelineModel, api) {
  72954. var labelPosOpt = timelineModel.get('label.position');
  72955. var orient = timelineModel.get('orient');
  72956. var viewRect = getViewRect$4(timelineModel, api);
  72957. // Auto label offset.
  72958. if (labelPosOpt == null || labelPosOpt === 'auto') {
  72959. labelPosOpt = orient === 'horizontal'
  72960. ? ((viewRect.y + viewRect.height / 2) < api.getHeight() / 2 ? '-' : '+')
  72961. : ((viewRect.x + viewRect.width / 2) < api.getWidth() / 2 ? '+' : '-');
  72962. }
  72963. else if (isNaN(labelPosOpt)) {
  72964. labelPosOpt = ({
  72965. horizontal: {top: '-', bottom: '+'},
  72966. vertical: {left: '-', right: '+'}
  72967. })[orient][labelPosOpt];
  72968. }
  72969. var labelAlignMap = {
  72970. horizontal: 'center',
  72971. vertical: (labelPosOpt >= 0 || labelPosOpt === '+') ? 'left' : 'right'
  72972. };
  72973. var labelBaselineMap = {
  72974. horizontal: (labelPosOpt >= 0 || labelPosOpt === '+') ? 'top' : 'bottom',
  72975. vertical: 'middle'
  72976. };
  72977. var rotationMap = {
  72978. horizontal: 0,
  72979. vertical: PI$4 / 2
  72980. };
  72981. // Position
  72982. var mainLength = orient === 'vertical' ? viewRect.height : viewRect.width;
  72983. var controlModel = timelineModel.getModel('controlStyle');
  72984. var showControl = controlModel.get('show', true);
  72985. var controlSize = showControl ? controlModel.get('itemSize') : 0;
  72986. var controlGap = showControl ? controlModel.get('itemGap') : 0;
  72987. var sizePlusGap = controlSize + controlGap;
  72988. // Special label rotate.
  72989. var labelRotation = timelineModel.get('label.rotate') || 0;
  72990. labelRotation = labelRotation * PI$4 / 180; // To radian.
  72991. var playPosition;
  72992. var prevBtnPosition;
  72993. var nextBtnPosition;
  72994. var axisExtent;
  72995. var controlPosition = controlModel.get('position', true);
  72996. var showPlayBtn = showControl && controlModel.get('showPlayBtn', true);
  72997. var showPrevBtn = showControl && controlModel.get('showPrevBtn', true);
  72998. var showNextBtn = showControl && controlModel.get('showNextBtn', true);
  72999. var xLeft = 0;
  73000. var xRight = mainLength;
  73001. // position[0] means left, position[1] means middle.
  73002. if (controlPosition === 'left' || controlPosition === 'bottom') {
  73003. showPlayBtn && (playPosition = [0, 0], xLeft += sizePlusGap);
  73004. showPrevBtn && (prevBtnPosition = [xLeft, 0], xLeft += sizePlusGap);
  73005. showNextBtn && (nextBtnPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
  73006. }
  73007. else { // 'top' 'right'
  73008. showPlayBtn && (playPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
  73009. showPrevBtn && (prevBtnPosition = [0, 0], xLeft += sizePlusGap);
  73010. showNextBtn && (nextBtnPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
  73011. }
  73012. axisExtent = [xLeft, xRight];
  73013. if (timelineModel.get('inverse')) {
  73014. axisExtent.reverse();
  73015. }
  73016. return {
  73017. viewRect: viewRect,
  73018. mainLength: mainLength,
  73019. orient: orient,
  73020. rotation: rotationMap[orient],
  73021. labelRotation: labelRotation,
  73022. labelPosOpt: labelPosOpt,
  73023. labelAlign: timelineModel.get('label.align') || labelAlignMap[orient],
  73024. labelBaseline: timelineModel.get('label.verticalAlign')
  73025. || timelineModel.get('label.baseline')
  73026. || labelBaselineMap[orient],
  73027. // Based on mainGroup.
  73028. playPosition: playPosition,
  73029. prevBtnPosition: prevBtnPosition,
  73030. nextBtnPosition: nextBtnPosition,
  73031. axisExtent: axisExtent,
  73032. controlSize: controlSize,
  73033. controlGap: controlGap
  73034. };
  73035. },
  73036. _position: function (layoutInfo, timelineModel) {
  73037. // Position is be called finally, because bounding rect is needed for
  73038. // adapt content to fill viewRect (auto adapt offset).
  73039. // Timeline may be not all in the viewRect when 'offset' is specified
  73040. // as a number, because it is more appropriate that label aligns at
  73041. // 'offset' but not the other edge defined by viewRect.
  73042. var mainGroup = this._mainGroup;
  73043. var labelGroup = this._labelGroup;
  73044. var viewRect = layoutInfo.viewRect;
  73045. if (layoutInfo.orient === 'vertical') {
  73046. // transform to horizontal, inverse rotate by left-top point.
  73047. var m = create$1();
  73048. var rotateOriginX = viewRect.x;
  73049. var rotateOriginY = viewRect.y + viewRect.height;
  73050. translate(m, m, [-rotateOriginX, -rotateOriginY]);
  73051. rotate(m, m, -PI$4 / 2);
  73052. translate(m, m, [rotateOriginX, rotateOriginY]);
  73053. viewRect = viewRect.clone();
  73054. viewRect.applyTransform(m);
  73055. }
  73056. var viewBound = getBound(viewRect);
  73057. var mainBound = getBound(mainGroup.getBoundingRect());
  73058. var labelBound = getBound(labelGroup.getBoundingRect());
  73059. var mainPosition = mainGroup.position;
  73060. var labelsPosition = labelGroup.position;
  73061. labelsPosition[0] = mainPosition[0] = viewBound[0][0];
  73062. var labelPosOpt = layoutInfo.labelPosOpt;
  73063. if (isNaN(labelPosOpt)) { // '+' or '-'
  73064. var mainBoundIdx = labelPosOpt === '+' ? 0 : 1;
  73065. toBound(mainPosition, mainBound, viewBound, 1, mainBoundIdx);
  73066. toBound(labelsPosition, labelBound, viewBound, 1, 1 - mainBoundIdx);
  73067. }
  73068. else {
  73069. var mainBoundIdx = labelPosOpt >= 0 ? 0 : 1;
  73070. toBound(mainPosition, mainBound, viewBound, 1, mainBoundIdx);
  73071. labelsPosition[1] = mainPosition[1] + labelPosOpt;
  73072. }
  73073. mainGroup.attr('position', mainPosition);
  73074. labelGroup.attr('position', labelsPosition);
  73075. mainGroup.rotation = labelGroup.rotation = layoutInfo.rotation;
  73076. setOrigin(mainGroup);
  73077. setOrigin(labelGroup);
  73078. function setOrigin(targetGroup) {
  73079. var pos = targetGroup.position;
  73080. targetGroup.origin = [
  73081. viewBound[0][0] - pos[0],
  73082. viewBound[1][0] - pos[1]
  73083. ];
  73084. }
  73085. function getBound(rect) {
  73086. // [[xmin, xmax], [ymin, ymax]]
  73087. return [
  73088. [rect.x, rect.x + rect.width],
  73089. [rect.y, rect.y + rect.height]
  73090. ];
  73091. }
  73092. function toBound(fromPos, from, to, dimIdx, boundIdx) {
  73093. fromPos[dimIdx] += to[dimIdx][boundIdx] - from[dimIdx][boundIdx];
  73094. }
  73095. },
  73096. _createAxis: function (layoutInfo, timelineModel) {
  73097. var data = timelineModel.getData();
  73098. var axisType = timelineModel.get('axisType');
  73099. var scale = createScaleByModel(timelineModel, axisType);
  73100. // Customize scale. The `tickValue` is `dataIndex`.
  73101. scale.getTicks = function () {
  73102. return data.mapArray(['value'], function (value) {
  73103. return value;
  73104. });
  73105. };
  73106. var dataExtent = data.getDataExtent('value');
  73107. scale.setExtent(dataExtent[0], dataExtent[1]);
  73108. scale.niceTicks();
  73109. var axis = new TimelineAxis('value', scale, layoutInfo.axisExtent, axisType);
  73110. axis.model = timelineModel;
  73111. return axis;
  73112. },
  73113. _createGroup: function (name) {
  73114. var newGroup = this['_' + name] = new Group();
  73115. this.group.add(newGroup);
  73116. return newGroup;
  73117. },
  73118. _renderAxisLine: function (layoutInfo, group, axis, timelineModel) {
  73119. var axisExtent = axis.getExtent();
  73120. if (!timelineModel.get('lineStyle.show')) {
  73121. return;
  73122. }
  73123. group.add(new Line({
  73124. shape: {
  73125. x1: axisExtent[0], y1: 0,
  73126. x2: axisExtent[1], y2: 0
  73127. },
  73128. style: extend(
  73129. {lineCap: 'round'},
  73130. timelineModel.getModel('lineStyle').getLineStyle()
  73131. ),
  73132. silent: true,
  73133. z2: 1
  73134. }));
  73135. },
  73136. /**
  73137. * @private
  73138. */
  73139. _renderAxisTick: function (layoutInfo, group, axis, timelineModel) {
  73140. var data = timelineModel.getData();
  73141. // Show all ticks, despite ignoring strategy.
  73142. var ticks = axis.scale.getTicks();
  73143. // The value is dataIndex, see the costomized scale.
  73144. each$27(ticks, function (value) {
  73145. var tickCoord = axis.dataToCoord(value);
  73146. var itemModel = data.getItemModel(value);
  73147. var itemStyleModel = itemModel.getModel('itemStyle');
  73148. var hoverStyleModel = itemModel.getModel('emphasis.itemStyle');
  73149. var symbolOpt = {
  73150. position: [tickCoord, 0],
  73151. onclick: bind$6(this._changeTimeline, this, value)
  73152. };
  73153. var el = giveSymbol(itemModel, itemStyleModel, group, symbolOpt);
  73154. setHoverStyle(el, hoverStyleModel.getItemStyle());
  73155. if (itemModel.get('tooltip')) {
  73156. el.dataIndex = value;
  73157. el.dataModel = timelineModel;
  73158. }
  73159. else {
  73160. el.dataIndex = el.dataModel = null;
  73161. }
  73162. }, this);
  73163. },
  73164. /**
  73165. * @private
  73166. */
  73167. _renderAxisLabel: function (layoutInfo, group, axis, timelineModel) {
  73168. var labelModel = axis.getLabelModel();
  73169. if (!labelModel.get('show')) {
  73170. return;
  73171. }
  73172. var data = timelineModel.getData();
  73173. var labels = axis.getViewLabels();
  73174. each$27(labels, function (labelItem) {
  73175. // The tickValue is dataIndex, see the costomized scale.
  73176. var dataIndex = labelItem.tickValue;
  73177. var itemModel = data.getItemModel(dataIndex);
  73178. var normalLabelModel = itemModel.getModel('label');
  73179. var hoverLabelModel = itemModel.getModel('emphasis.label');
  73180. var tickCoord = axis.dataToCoord(labelItem.tickValue);
  73181. var textEl = new Text({
  73182. position: [tickCoord, 0],
  73183. rotation: layoutInfo.labelRotation - layoutInfo.rotation,
  73184. onclick: bind$6(this._changeTimeline, this, dataIndex),
  73185. silent: false
  73186. });
  73187. setTextStyle(textEl.style, normalLabelModel, {
  73188. text: labelItem.formattedLabel,
  73189. textAlign: layoutInfo.labelAlign,
  73190. textVerticalAlign: layoutInfo.labelBaseline
  73191. });
  73192. group.add(textEl);
  73193. setHoverStyle(
  73194. textEl, setTextStyle({}, hoverLabelModel)
  73195. );
  73196. }, this);
  73197. },
  73198. /**
  73199. * @private
  73200. */
  73201. _renderControl: function (layoutInfo, group, axis, timelineModel) {
  73202. var controlSize = layoutInfo.controlSize;
  73203. var rotation = layoutInfo.rotation;
  73204. var itemStyle = timelineModel.getModel('controlStyle').getItemStyle();
  73205. var hoverStyle = timelineModel.getModel('emphasis.controlStyle').getItemStyle();
  73206. var rect = [0, -controlSize / 2, controlSize, controlSize];
  73207. var playState = timelineModel.getPlayState();
  73208. var inverse = timelineModel.get('inverse', true);
  73209. makeBtn(
  73210. layoutInfo.nextBtnPosition,
  73211. 'controlStyle.nextIcon',
  73212. bind$6(this._changeTimeline, this, inverse ? '-' : '+')
  73213. );
  73214. makeBtn(
  73215. layoutInfo.prevBtnPosition,
  73216. 'controlStyle.prevIcon',
  73217. bind$6(this._changeTimeline, this, inverse ? '+' : '-')
  73218. );
  73219. makeBtn(
  73220. layoutInfo.playPosition,
  73221. 'controlStyle.' + (playState ? 'stopIcon' : 'playIcon'),
  73222. bind$6(this._handlePlayClick, this, !playState),
  73223. true
  73224. );
  73225. function makeBtn(position, iconPath, onclick, willRotate) {
  73226. if (!position) {
  73227. return;
  73228. }
  73229. var opt = {
  73230. position: position,
  73231. origin: [controlSize / 2, 0],
  73232. rotation: willRotate ? -rotation : 0,
  73233. rectHover: true,
  73234. style: itemStyle,
  73235. onclick: onclick
  73236. };
  73237. var btn = makeIcon(timelineModel, iconPath, rect, opt);
  73238. group.add(btn);
  73239. setHoverStyle(btn, hoverStyle);
  73240. }
  73241. },
  73242. _renderCurrentPointer: function (layoutInfo, group, axis, timelineModel) {
  73243. var data = timelineModel.getData();
  73244. var currentIndex = timelineModel.getCurrentIndex();
  73245. var pointerModel = data.getItemModel(currentIndex).getModel('checkpointStyle');
  73246. var me = this;
  73247. var callback = {
  73248. onCreate: function (pointer) {
  73249. pointer.draggable = true;
  73250. pointer.drift = bind$6(me._handlePointerDrag, me);
  73251. pointer.ondragend = bind$6(me._handlePointerDragend, me);
  73252. pointerMoveTo(pointer, currentIndex, axis, timelineModel, true);
  73253. },
  73254. onUpdate: function (pointer) {
  73255. pointerMoveTo(pointer, currentIndex, axis, timelineModel);
  73256. }
  73257. };
  73258. // Reuse when exists, for animation and drag.
  73259. this._currentPointer = giveSymbol(
  73260. pointerModel, pointerModel, this._mainGroup, {}, this._currentPointer, callback
  73261. );
  73262. },
  73263. _handlePlayClick: function (nextState) {
  73264. this._clearTimer();
  73265. this.api.dispatchAction({
  73266. type: 'timelinePlayChange',
  73267. playState: nextState,
  73268. from: this.uid
  73269. });
  73270. },
  73271. _handlePointerDrag: function (dx, dy, e) {
  73272. this._clearTimer();
  73273. this._pointerChangeTimeline([e.offsetX, e.offsetY]);
  73274. },
  73275. _handlePointerDragend: function (e) {
  73276. this._pointerChangeTimeline([e.offsetX, e.offsetY], true);
  73277. },
  73278. _pointerChangeTimeline: function (mousePos, trigger) {
  73279. var toCoord = this._toAxisCoord(mousePos)[0];
  73280. var axis = this._axis;
  73281. var axisExtent = asc(axis.getExtent().slice());
  73282. toCoord > axisExtent[1] && (toCoord = axisExtent[1]);
  73283. toCoord < axisExtent[0] && (toCoord = axisExtent[0]);
  73284. this._currentPointer.position[0] = toCoord;
  73285. this._currentPointer.dirty();
  73286. var targetDataIndex = this._findNearestTick(toCoord);
  73287. var timelineModel = this.model;
  73288. if (trigger || (
  73289. targetDataIndex !== timelineModel.getCurrentIndex()
  73290. && timelineModel.get('realtime')
  73291. )) {
  73292. this._changeTimeline(targetDataIndex);
  73293. }
  73294. },
  73295. _doPlayStop: function () {
  73296. this._clearTimer();
  73297. if (this.model.getPlayState()) {
  73298. this._timer = setTimeout(
  73299. bind$6(handleFrame, this),
  73300. this.model.get('playInterval')
  73301. );
  73302. }
  73303. function handleFrame() {
  73304. // Do not cache
  73305. var timelineModel = this.model;
  73306. this._changeTimeline(
  73307. timelineModel.getCurrentIndex()
  73308. + (timelineModel.get('rewind', true) ? -1 : 1)
  73309. );
  73310. }
  73311. },
  73312. _toAxisCoord: function (vertex) {
  73313. var trans = this._mainGroup.getLocalTransform();
  73314. return applyTransform$1(vertex, trans, true);
  73315. },
  73316. _findNearestTick: function (axisCoord) {
  73317. var data = this.model.getData();
  73318. var dist = Infinity;
  73319. var targetDataIndex;
  73320. var axis = this._axis;
  73321. data.each(['value'], function (value, dataIndex) {
  73322. var coord = axis.dataToCoord(value);
  73323. var d = Math.abs(coord - axisCoord);
  73324. if (d < dist) {
  73325. dist = d;
  73326. targetDataIndex = dataIndex;
  73327. }
  73328. });
  73329. return targetDataIndex;
  73330. },
  73331. _clearTimer: function () {
  73332. if (this._timer) {
  73333. clearTimeout(this._timer);
  73334. this._timer = null;
  73335. }
  73336. },
  73337. _changeTimeline: function (nextIndex) {
  73338. var currentIndex = this.model.getCurrentIndex();
  73339. if (nextIndex === '+') {
  73340. nextIndex = currentIndex + 1;
  73341. }
  73342. else if (nextIndex === '-') {
  73343. nextIndex = currentIndex - 1;
  73344. }
  73345. this.api.dispatchAction({
  73346. type: 'timelineChange',
  73347. currentIndex: nextIndex,
  73348. from: this.uid
  73349. });
  73350. }
  73351. });
  73352. function getViewRect$4(model, api) {
  73353. return getLayoutRect(
  73354. model.getBoxLayoutParams(),
  73355. {
  73356. width: api.getWidth(),
  73357. height: api.getHeight()
  73358. },
  73359. model.get('padding')
  73360. );
  73361. }
  73362. function makeIcon(timelineModel, objPath, rect, opts) {
  73363. var icon = makePath(
  73364. timelineModel.get(objPath).replace(/^path:\/\//, ''),
  73365. clone(opts || {}),
  73366. new BoundingRect(rect[0], rect[1], rect[2], rect[3]),
  73367. 'center'
  73368. );
  73369. return icon;
  73370. }
  73371. /**
  73372. * Create symbol or update symbol
  73373. * opt: basic position and event handlers
  73374. */
  73375. function giveSymbol(hostModel, itemStyleModel, group, opt, symbol, callback) {
  73376. var color = itemStyleModel.get('color');
  73377. if (!symbol) {
  73378. var symbolType = hostModel.get('symbol');
  73379. symbol = createSymbol(symbolType, -1, -1, 2, 2, color);
  73380. symbol.setStyle('strokeNoScale', true);
  73381. group.add(symbol);
  73382. callback && callback.onCreate(symbol);
  73383. }
  73384. else {
  73385. symbol.setColor(color);
  73386. group.add(symbol); // Group may be new, also need to add.
  73387. callback && callback.onUpdate(symbol);
  73388. }
  73389. // Style
  73390. var itemStyle = itemStyleModel.getItemStyle(['color', 'symbol', 'symbolSize']);
  73391. symbol.setStyle(itemStyle);
  73392. // Transform and events.
  73393. opt = merge({
  73394. rectHover: true,
  73395. z2: 100
  73396. }, opt, true);
  73397. var symbolSize = hostModel.get('symbolSize');
  73398. symbolSize = symbolSize instanceof Array
  73399. ? symbolSize.slice()
  73400. : [+symbolSize, +symbolSize];
  73401. symbolSize[0] /= 2;
  73402. symbolSize[1] /= 2;
  73403. opt.scale = symbolSize;
  73404. var symbolOffset = hostModel.get('symbolOffset');
  73405. if (symbolOffset) {
  73406. var pos = opt.position = opt.position || [0, 0];
  73407. pos[0] += parsePercent$1(symbolOffset[0], symbolSize[0]);
  73408. pos[1] += parsePercent$1(symbolOffset[1], symbolSize[1]);
  73409. }
  73410. var symbolRotate = hostModel.get('symbolRotate');
  73411. opt.rotation = (symbolRotate || 0) * Math.PI / 180 || 0;
  73412. symbol.attr(opt);
  73413. // FIXME
  73414. // (1) When symbol.style.strokeNoScale is true and updateTransform is not performed,
  73415. // getBoundingRect will return wrong result.
  73416. // (This is supposed to be resolved in zrender, but it is a little difficult to
  73417. // leverage performance and auto updateTransform)
  73418. // (2) All of ancesters of symbol do not scale, so we can just updateTransform symbol.
  73419. symbol.updateTransform();
  73420. return symbol;
  73421. }
  73422. function pointerMoveTo(pointer, dataIndex, axis, timelineModel, noAnimation) {
  73423. if (pointer.dragging) {
  73424. return;
  73425. }
  73426. var pointerModel = timelineModel.getModel('checkpointStyle');
  73427. var toCoord = axis.dataToCoord(timelineModel.getData().get(['value'], dataIndex));
  73428. if (noAnimation || !pointerModel.get('animation', true)) {
  73429. pointer.attr({position: [toCoord, 0]});
  73430. }
  73431. else {
  73432. pointer.stopAnimation(true);
  73433. pointer.animateTo(
  73434. {position: [toCoord, 0]},
  73435. pointerModel.get('animationDuration', true),
  73436. pointerModel.get('animationEasing', true)
  73437. );
  73438. }
  73439. }
  73440. /*
  73441. * Licensed to the Apache Software Foundation (ASF) under one
  73442. * or more contributor license agreements. See the NOTICE file
  73443. * distributed with this work for additional information
  73444. * regarding copyright ownership. The ASF licenses this file
  73445. * to you under the Apache License, Version 2.0 (the
  73446. * "License"); you may not use this file except in compliance
  73447. * with the License. You may obtain a copy of the License at
  73448. *
  73449. * http://www.apache.org/licenses/LICENSE-2.0
  73450. *
  73451. * Unless required by applicable law or agreed to in writing,
  73452. * software distributed under the License is distributed on an
  73453. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73454. * KIND, either express or implied. See the License for the
  73455. * specific language governing permissions and limitations
  73456. * under the License.
  73457. */
  73458. /**
  73459. * DataZoom component entry
  73460. */
  73461. registerPreprocessor(preprocessor$3);
  73462. /*
  73463. * Licensed to the Apache Software Foundation (ASF) under one
  73464. * or more contributor license agreements. See the NOTICE file
  73465. * distributed with this work for additional information
  73466. * regarding copyright ownership. The ASF licenses this file
  73467. * to you under the Apache License, Version 2.0 (the
  73468. * "License"); you may not use this file except in compliance
  73469. * with the License. You may obtain a copy of the License at
  73470. *
  73471. * http://www.apache.org/licenses/LICENSE-2.0
  73472. *
  73473. * Unless required by applicable law or agreed to in writing,
  73474. * software distributed under the License is distributed on an
  73475. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73476. * KIND, either express or implied. See the License for the
  73477. * specific language governing permissions and limitations
  73478. * under the License.
  73479. */
  73480. var ToolboxModel = extendComponentModel({
  73481. type: 'toolbox',
  73482. layoutMode: {
  73483. type: 'box',
  73484. ignoreSize: true
  73485. },
  73486. optionUpdated: function () {
  73487. ToolboxModel.superApply(this, 'optionUpdated', arguments);
  73488. each$1(this.option.feature, function (featureOpt, featureName) {
  73489. var Feature = get$1(featureName);
  73490. Feature && merge(featureOpt, Feature.defaultOption);
  73491. });
  73492. },
  73493. defaultOption: {
  73494. show: true,
  73495. z: 6,
  73496. zlevel: 0,
  73497. orient: 'horizontal',
  73498. left: 'right',
  73499. top: 'top',
  73500. // right
  73501. // bottom
  73502. backgroundColor: 'transparent',
  73503. borderColor: '#ccc',
  73504. borderRadius: 0,
  73505. borderWidth: 0,
  73506. padding: 5,
  73507. itemSize: 15,
  73508. itemGap: 8,
  73509. showTitle: true,
  73510. iconStyle: {
  73511. borderColor: '#666',
  73512. color: 'none'
  73513. },
  73514. emphasis: {
  73515. iconStyle: {
  73516. borderColor: '#3E98C5'
  73517. }
  73518. }
  73519. // textStyle: {},
  73520. // feature
  73521. }
  73522. });
  73523. /*
  73524. * Licensed to the Apache Software Foundation (ASF) under one
  73525. * or more contributor license agreements. See the NOTICE file
  73526. * distributed with this work for additional information
  73527. * regarding copyright ownership. The ASF licenses this file
  73528. * to you under the Apache License, Version 2.0 (the
  73529. * "License"); you may not use this file except in compliance
  73530. * with the License. You may obtain a copy of the License at
  73531. *
  73532. * http://www.apache.org/licenses/LICENSE-2.0
  73533. *
  73534. * Unless required by applicable law or agreed to in writing,
  73535. * software distributed under the License is distributed on an
  73536. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73537. * KIND, either express or implied. See the License for the
  73538. * specific language governing permissions and limitations
  73539. * under the License.
  73540. */
  73541. extendComponentView({
  73542. type: 'toolbox',
  73543. render: function (toolboxModel, ecModel, api, payload) {
  73544. var group = this.group;
  73545. group.removeAll();
  73546. if (!toolboxModel.get('show')) {
  73547. return;
  73548. }
  73549. var itemSize = +toolboxModel.get('itemSize');
  73550. var featureOpts = toolboxModel.get('feature') || {};
  73551. var features = this._features || (this._features = {});
  73552. var featureNames = [];
  73553. each$1(featureOpts, function (opt, name) {
  73554. featureNames.push(name);
  73555. });
  73556. (new DataDiffer(this._featureNames || [], featureNames))
  73557. .add(processFeature)
  73558. .update(processFeature)
  73559. .remove(curry(processFeature, null))
  73560. .execute();
  73561. // Keep for diff.
  73562. this._featureNames = featureNames;
  73563. function processFeature(newIndex, oldIndex) {
  73564. var featureName = featureNames[newIndex];
  73565. var oldName = featureNames[oldIndex];
  73566. var featureOpt = featureOpts[featureName];
  73567. var featureModel = new Model(featureOpt, toolboxModel, toolboxModel.ecModel);
  73568. var feature;
  73569. if (featureName && !oldName) { // Create
  73570. if (isUserFeatureName(featureName)) {
  73571. feature = {
  73572. model: featureModel,
  73573. onclick: featureModel.option.onclick,
  73574. featureName: featureName
  73575. };
  73576. }
  73577. else {
  73578. var Feature = get$1(featureName);
  73579. if (!Feature) {
  73580. return;
  73581. }
  73582. feature = new Feature(featureModel, ecModel, api);
  73583. }
  73584. features[featureName] = feature;
  73585. }
  73586. else {
  73587. feature = features[oldName];
  73588. // If feature does not exsit.
  73589. if (!feature) {
  73590. return;
  73591. }
  73592. feature.model = featureModel;
  73593. feature.ecModel = ecModel;
  73594. feature.api = api;
  73595. }
  73596. if (!featureName && oldName) {
  73597. feature.dispose && feature.dispose(ecModel, api);
  73598. return;
  73599. }
  73600. if (!featureModel.get('show') || feature.unusable) {
  73601. feature.remove && feature.remove(ecModel, api);
  73602. return;
  73603. }
  73604. createIconPaths(featureModel, feature, featureName);
  73605. featureModel.setIconStatus = function (iconName, status) {
  73606. var option = this.option;
  73607. var iconPaths = this.iconPaths;
  73608. option.iconStatus = option.iconStatus || {};
  73609. option.iconStatus[iconName] = status;
  73610. // FIXME
  73611. iconPaths[iconName] && iconPaths[iconName].trigger(status);
  73612. };
  73613. if (feature.render) {
  73614. feature.render(featureModel, ecModel, api, payload);
  73615. }
  73616. }
  73617. function createIconPaths(featureModel, feature, featureName) {
  73618. var iconStyleModel = featureModel.getModel('iconStyle');
  73619. var iconStyleEmphasisModel = featureModel.getModel('emphasis.iconStyle');
  73620. // If one feature has mutiple icon. they are orginaized as
  73621. // {
  73622. // icon: {
  73623. // foo: '',
  73624. // bar: ''
  73625. // },
  73626. // title: {
  73627. // foo: '',
  73628. // bar: ''
  73629. // }
  73630. // }
  73631. var icons = feature.getIcons ? feature.getIcons() : featureModel.get('icon');
  73632. var titles = featureModel.get('title') || {};
  73633. if (typeof icons === 'string') {
  73634. var icon = icons;
  73635. var title = titles;
  73636. icons = {};
  73637. titles = {};
  73638. icons[featureName] = icon;
  73639. titles[featureName] = title;
  73640. }
  73641. var iconPaths = featureModel.iconPaths = {};
  73642. each$1(icons, function (iconStr, iconName) {
  73643. var path = createIcon(
  73644. iconStr,
  73645. {},
  73646. {
  73647. x: -itemSize / 2,
  73648. y: -itemSize / 2,
  73649. width: itemSize,
  73650. height: itemSize
  73651. }
  73652. );
  73653. path.setStyle(iconStyleModel.getItemStyle());
  73654. path.hoverStyle = iconStyleEmphasisModel.getItemStyle();
  73655. setHoverStyle(path);
  73656. if (toolboxModel.get('showTitle')) {
  73657. path.__title = titles[iconName];
  73658. path.on('mouseover', function () {
  73659. // Should not reuse above hoverStyle, which might be modified.
  73660. var hoverStyle = iconStyleEmphasisModel.getItemStyle();
  73661. path.setStyle({
  73662. text: titles[iconName],
  73663. textPosition: hoverStyle.textPosition || 'bottom',
  73664. textFill: hoverStyle.fill || hoverStyle.stroke || '#000',
  73665. textAlign: hoverStyle.textAlign || 'center'
  73666. });
  73667. })
  73668. .on('mouseout', function () {
  73669. path.setStyle({
  73670. textFill: null
  73671. });
  73672. });
  73673. }
  73674. path.trigger(featureModel.get('iconStatus.' + iconName) || 'normal');
  73675. group.add(path);
  73676. path.on('click', bind(
  73677. feature.onclick, feature, ecModel, api, iconName
  73678. ));
  73679. iconPaths[iconName] = path;
  73680. });
  73681. }
  73682. layout$3(group, toolboxModel, api);
  73683. // Render background after group is layout
  73684. // FIXME
  73685. group.add(makeBackground(group.getBoundingRect(), toolboxModel));
  73686. // Adjust icon title positions to avoid them out of screen
  73687. group.eachChild(function (icon) {
  73688. var titleText = icon.__title;
  73689. var hoverStyle = icon.hoverStyle;
  73690. // May be background element
  73691. if (hoverStyle && titleText) {
  73692. var rect = getBoundingRect(
  73693. titleText, makeFont(hoverStyle)
  73694. );
  73695. var offsetX = icon.position[0] + group.position[0];
  73696. var offsetY = icon.position[1] + group.position[1] + itemSize;
  73697. var needPutOnTop = false;
  73698. if (offsetY + rect.height > api.getHeight()) {
  73699. hoverStyle.textPosition = 'top';
  73700. needPutOnTop = true;
  73701. }
  73702. var topOffset = needPutOnTop ? (-5 - rect.height) : (itemSize + 8);
  73703. if (offsetX + rect.width / 2 > api.getWidth()) {
  73704. hoverStyle.textPosition = ['100%', topOffset];
  73705. hoverStyle.textAlign = 'right';
  73706. }
  73707. else if (offsetX - rect.width / 2 < 0) {
  73708. hoverStyle.textPosition = [0, topOffset];
  73709. hoverStyle.textAlign = 'left';
  73710. }
  73711. }
  73712. });
  73713. },
  73714. updateView: function (toolboxModel, ecModel, api, payload) {
  73715. each$1(this._features, function (feature) {
  73716. feature.updateView && feature.updateView(feature.model, ecModel, api, payload);
  73717. });
  73718. },
  73719. // updateLayout: function (toolboxModel, ecModel, api, payload) {
  73720. // zrUtil.each(this._features, function (feature) {
  73721. // feature.updateLayout && feature.updateLayout(feature.model, ecModel, api, payload);
  73722. // });
  73723. // },
  73724. remove: function (ecModel, api) {
  73725. each$1(this._features, function (feature) {
  73726. feature.remove && feature.remove(ecModel, api);
  73727. });
  73728. this.group.removeAll();
  73729. },
  73730. dispose: function (ecModel, api) {
  73731. each$1(this._features, function (feature) {
  73732. feature.dispose && feature.dispose(ecModel, api);
  73733. });
  73734. }
  73735. });
  73736. function isUserFeatureName(featureName) {
  73737. return featureName.indexOf('my') === 0;
  73738. }
  73739. /*
  73740. * Licensed to the Apache Software Foundation (ASF) under one
  73741. * or more contributor license agreements. See the NOTICE file
  73742. * distributed with this work for additional information
  73743. * regarding copyright ownership. The ASF licenses this file
  73744. * to you under the Apache License, Version 2.0 (the
  73745. * "License"); you may not use this file except in compliance
  73746. * with the License. You may obtain a copy of the License at
  73747. *
  73748. * http://www.apache.org/licenses/LICENSE-2.0
  73749. *
  73750. * Unless required by applicable law or agreed to in writing,
  73751. * software distributed under the License is distributed on an
  73752. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73753. * KIND, either express or implied. See the License for the
  73754. * specific language governing permissions and limitations
  73755. * under the License.
  73756. */
  73757. var saveAsImageLang = lang.toolbox.saveAsImage;
  73758. function SaveAsImage(model) {
  73759. this.model = model;
  73760. }
  73761. SaveAsImage.defaultOption = {
  73762. show: true,
  73763. 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',
  73764. title: saveAsImageLang.title,
  73765. type: 'png',
  73766. // Default use option.backgroundColor
  73767. // backgroundColor: '#fff',
  73768. name: '',
  73769. excludeComponents: ['toolbox'],
  73770. pixelRatio: 1,
  73771. lang: saveAsImageLang.lang.slice()
  73772. };
  73773. SaveAsImage.prototype.unusable = !env$1.canvasSupported;
  73774. var proto$4 = SaveAsImage.prototype;
  73775. proto$4.onclick = function (ecModel, api) {
  73776. var model = this.model;
  73777. var title = model.get('name') || ecModel.get('title.0.text') || 'echarts';
  73778. var $a = document.createElement('a');
  73779. var type = model.get('type', true) || 'png';
  73780. $a.download = title + '.' + type;
  73781. $a.target = '_blank';
  73782. var url = api.getConnectedDataURL({
  73783. type: type,
  73784. backgroundColor: model.get('backgroundColor', true)
  73785. || ecModel.get('backgroundColor') || '#fff',
  73786. excludeComponents: model.get('excludeComponents'),
  73787. pixelRatio: model.get('pixelRatio')
  73788. });
  73789. $a.href = url;
  73790. // Chrome and Firefox
  73791. if (typeof MouseEvent === 'function' && !env$1.browser.ie && !env$1.browser.edge) {
  73792. var evt = new MouseEvent('click', {
  73793. view: window,
  73794. bubbles: true,
  73795. cancelable: false
  73796. });
  73797. $a.dispatchEvent(evt);
  73798. }
  73799. // IE
  73800. else {
  73801. if (window.navigator.msSaveOrOpenBlob) {
  73802. var bstr = atob(url.split(',')[1]);
  73803. var n = bstr.length;
  73804. var u8arr = new Uint8Array(n);
  73805. while(n--) {
  73806. u8arr[n] = bstr.charCodeAt(n);
  73807. }
  73808. var blob = new Blob([u8arr]);
  73809. window.navigator.msSaveOrOpenBlob(blob, title + '.' + type);
  73810. }
  73811. else {
  73812. var lang$$1 = model.get('lang');
  73813. var html = '' +
  73814. '<body style="margin:0;">' +
  73815. '<img src="' + url + '" style="max-width:100%;" title="' + ((lang$$1 && lang$$1[0]) || '') + '" />' +
  73816. '</body>';
  73817. var tab = window.open();
  73818. tab.document.write(html);
  73819. }
  73820. }
  73821. };
  73822. register$1(
  73823. 'saveAsImage', SaveAsImage
  73824. );
  73825. /*
  73826. * Licensed to the Apache Software Foundation (ASF) under one
  73827. * or more contributor license agreements. See the NOTICE file
  73828. * distributed with this work for additional information
  73829. * regarding copyright ownership. The ASF licenses this file
  73830. * to you under the Apache License, Version 2.0 (the
  73831. * "License"); you may not use this file except in compliance
  73832. * with the License. You may obtain a copy of the License at
  73833. *
  73834. * http://www.apache.org/licenses/LICENSE-2.0
  73835. *
  73836. * Unless required by applicable law or agreed to in writing,
  73837. * software distributed under the License is distributed on an
  73838. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73839. * KIND, either express or implied. See the License for the
  73840. * specific language governing permissions and limitations
  73841. * under the License.
  73842. */
  73843. var magicTypeLang = lang.toolbox.magicType;
  73844. function MagicType(model) {
  73845. this.model = model;
  73846. }
  73847. MagicType.defaultOption = {
  73848. show: true,
  73849. type: [],
  73850. // Icon group
  73851. icon: {
  73852. line: 'M4.1,28.9h7.1l9.3-22l7.4,38l9.7-19.7l3,12.8h14.9M4.1,58h51.4',
  73853. bar: 'M6.7,22.9h10V48h-10V22.9zM24.9,13h10v35h-10V13zM43.2,2h10v46h-10V2zM3.1,58h53.7',
  73854. 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
  73855. tiled: 'M2.3,2.2h22.8V25H2.3V2.2z M35,2.2h22.8V25H35V2.2zM2.3,35h22.8v22.8H2.3V35z M35,35h22.8v22.8H35V35z'
  73856. },
  73857. // `line`, `bar`, `stack`, `tiled`
  73858. title: clone(magicTypeLang.title),
  73859. option: {},
  73860. seriesIndex: {}
  73861. };
  73862. var proto$5 = MagicType.prototype;
  73863. proto$5.getIcons = function () {
  73864. var model = this.model;
  73865. var availableIcons = model.get('icon');
  73866. var icons = {};
  73867. each$1(model.get('type'), function (type) {
  73868. if (availableIcons[type]) {
  73869. icons[type] = availableIcons[type];
  73870. }
  73871. });
  73872. return icons;
  73873. };
  73874. var seriesOptGenreator = {
  73875. 'line': function (seriesType, seriesId, seriesModel, model) {
  73876. if (seriesType === 'bar') {
  73877. return merge({
  73878. id: seriesId,
  73879. type: 'line',
  73880. // Preserve data related option
  73881. data: seriesModel.get('data'),
  73882. stack: seriesModel.get('stack'),
  73883. markPoint: seriesModel.get('markPoint'),
  73884. markLine: seriesModel.get('markLine')
  73885. }, model.get('option.line') || {}, true);
  73886. }
  73887. },
  73888. 'bar': function (seriesType, seriesId, seriesModel, model) {
  73889. if (seriesType === 'line') {
  73890. return merge({
  73891. id: seriesId,
  73892. type: 'bar',
  73893. // Preserve data related option
  73894. data: seriesModel.get('data'),
  73895. stack: seriesModel.get('stack'),
  73896. markPoint: seriesModel.get('markPoint'),
  73897. markLine: seriesModel.get('markLine')
  73898. }, model.get('option.bar') || {}, true);
  73899. }
  73900. },
  73901. 'stack': function (seriesType, seriesId, seriesModel, model) {
  73902. if (seriesType === 'line' || seriesType === 'bar') {
  73903. return merge({
  73904. id: seriesId,
  73905. stack: '__ec_magicType_stack__'
  73906. }, model.get('option.stack') || {}, true);
  73907. }
  73908. },
  73909. 'tiled': function (seriesType, seriesId, seriesModel, model) {
  73910. if (seriesType === 'line' || seriesType === 'bar') {
  73911. return merge({
  73912. id: seriesId,
  73913. stack: ''
  73914. }, model.get('option.tiled') || {}, true);
  73915. }
  73916. }
  73917. };
  73918. var radioTypes = [
  73919. ['line', 'bar'],
  73920. ['stack', 'tiled']
  73921. ];
  73922. proto$5.onclick = function (ecModel, api, type) {
  73923. var model = this.model;
  73924. var seriesIndex = model.get('seriesIndex.' + type);
  73925. // Not supported magicType
  73926. if (!seriesOptGenreator[type]) {
  73927. return;
  73928. }
  73929. var newOption = {
  73930. series: []
  73931. };
  73932. var generateNewSeriesTypes = function (seriesModel) {
  73933. var seriesType = seriesModel.subType;
  73934. var seriesId = seriesModel.id;
  73935. var newSeriesOpt = seriesOptGenreator[type](
  73936. seriesType, seriesId, seriesModel, model
  73937. );
  73938. if (newSeriesOpt) {
  73939. // PENDING If merge original option?
  73940. defaults(newSeriesOpt, seriesModel.option);
  73941. newOption.series.push(newSeriesOpt);
  73942. }
  73943. // Modify boundaryGap
  73944. var coordSys = seriesModel.coordinateSystem;
  73945. if (coordSys && coordSys.type === 'cartesian2d' && (type === 'line' || type === 'bar')) {
  73946. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  73947. if (categoryAxis) {
  73948. var axisDim = categoryAxis.dim;
  73949. var axisType = axisDim + 'Axis';
  73950. var axisModel = ecModel.queryComponents({
  73951. mainType: axisType,
  73952. index: seriesModel.get(name + 'Index'),
  73953. id: seriesModel.get(name + 'Id')
  73954. })[0];
  73955. var axisIndex = axisModel.componentIndex;
  73956. newOption[axisType] = newOption[axisType] || [];
  73957. for (var i = 0; i <= axisIndex; i++) {
  73958. newOption[axisType][axisIndex] = newOption[axisType][axisIndex] || {};
  73959. }
  73960. newOption[axisType][axisIndex].boundaryGap = type === 'bar' ? true : false;
  73961. }
  73962. }
  73963. };
  73964. each$1(radioTypes, function (radio) {
  73965. if (indexOf(radio, type) >= 0) {
  73966. each$1(radio, function (item) {
  73967. model.setIconStatus(item, 'normal');
  73968. });
  73969. }
  73970. });
  73971. model.setIconStatus(type, 'emphasis');
  73972. ecModel.eachComponent(
  73973. {
  73974. mainType: 'series',
  73975. query: seriesIndex == null ? null : {
  73976. seriesIndex: seriesIndex
  73977. }
  73978. }, generateNewSeriesTypes
  73979. );
  73980. api.dispatchAction({
  73981. type: 'changeMagicType',
  73982. currentType: type,
  73983. newOption: newOption
  73984. });
  73985. };
  73986. registerAction({
  73987. type: 'changeMagicType',
  73988. event: 'magicTypeChanged',
  73989. update: 'prepareAndUpdate'
  73990. }, function (payload, ecModel) {
  73991. ecModel.mergeOption(payload.newOption);
  73992. });
  73993. register$1('magicType', MagicType);
  73994. /*
  73995. * Licensed to the Apache Software Foundation (ASF) under one
  73996. * or more contributor license agreements. See the NOTICE file
  73997. * distributed with this work for additional information
  73998. * regarding copyright ownership. The ASF licenses this file
  73999. * to you under the Apache License, Version 2.0 (the
  74000. * "License"); you may not use this file except in compliance
  74001. * with the License. You may obtain a copy of the License at
  74002. *
  74003. * http://www.apache.org/licenses/LICENSE-2.0
  74004. *
  74005. * Unless required by applicable law or agreed to in writing,
  74006. * software distributed under the License is distributed on an
  74007. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74008. * KIND, either express or implied. See the License for the
  74009. * specific language governing permissions and limitations
  74010. * under the License.
  74011. */
  74012. var dataViewLang = lang.toolbox.dataView;
  74013. var BLOCK_SPLITER = new Array(60).join('-');
  74014. var ITEM_SPLITER = '\t';
  74015. /**
  74016. * Group series into two types
  74017. * 1. on category axis, like line, bar
  74018. * 2. others, like scatter, pie
  74019. * @param {module:echarts/model/Global} ecModel
  74020. * @return {Object}
  74021. * @inner
  74022. */
  74023. function groupSeries(ecModel) {
  74024. var seriesGroupByCategoryAxis = {};
  74025. var otherSeries = [];
  74026. var meta = [];
  74027. ecModel.eachRawSeries(function (seriesModel) {
  74028. var coordSys = seriesModel.coordinateSystem;
  74029. if (coordSys && (coordSys.type === 'cartesian2d' || coordSys.type === 'polar')) {
  74030. var baseAxis = coordSys.getBaseAxis();
  74031. if (baseAxis.type === 'category') {
  74032. var key = baseAxis.dim + '_' + baseAxis.index;
  74033. if (!seriesGroupByCategoryAxis[key]) {
  74034. seriesGroupByCategoryAxis[key] = {
  74035. categoryAxis: baseAxis,
  74036. valueAxis: coordSys.getOtherAxis(baseAxis),
  74037. series: []
  74038. };
  74039. meta.push({
  74040. axisDim: baseAxis.dim,
  74041. axisIndex: baseAxis.index
  74042. });
  74043. }
  74044. seriesGroupByCategoryAxis[key].series.push(seriesModel);
  74045. }
  74046. else {
  74047. otherSeries.push(seriesModel);
  74048. }
  74049. }
  74050. else {
  74051. otherSeries.push(seriesModel);
  74052. }
  74053. });
  74054. return {
  74055. seriesGroupByCategoryAxis: seriesGroupByCategoryAxis,
  74056. other: otherSeries,
  74057. meta: meta
  74058. };
  74059. }
  74060. /**
  74061. * Assemble content of series on cateogory axis
  74062. * @param {Array.<module:echarts/model/Series>} series
  74063. * @return {string}
  74064. * @inner
  74065. */
  74066. function assembleSeriesWithCategoryAxis(series) {
  74067. var tables = [];
  74068. each$1(series, function (group, key) {
  74069. var categoryAxis = group.categoryAxis;
  74070. var valueAxis = group.valueAxis;
  74071. var valueAxisDim = valueAxis.dim;
  74072. var headers = [' '].concat(map(group.series, function (series) {
  74073. return series.name;
  74074. }));
  74075. var columns = [categoryAxis.model.getCategories()];
  74076. each$1(group.series, function (series) {
  74077. columns.push(series.getRawData().mapArray(valueAxisDim, function (val) {
  74078. return val;
  74079. }));
  74080. });
  74081. // Assemble table content
  74082. var lines = [headers.join(ITEM_SPLITER)];
  74083. for (var i = 0; i < columns[0].length; i++) {
  74084. var items = [];
  74085. for (var j = 0; j < columns.length; j++) {
  74086. items.push(columns[j][i]);
  74087. }
  74088. lines.push(items.join(ITEM_SPLITER));
  74089. }
  74090. tables.push(lines.join('\n'));
  74091. });
  74092. return tables.join('\n\n' + BLOCK_SPLITER + '\n\n');
  74093. }
  74094. /**
  74095. * Assemble content of other series
  74096. * @param {Array.<module:echarts/model/Series>} series
  74097. * @return {string}
  74098. * @inner
  74099. */
  74100. function assembleOtherSeries(series) {
  74101. return map(series, function (series) {
  74102. var data = series.getRawData();
  74103. var lines = [series.name];
  74104. var vals = [];
  74105. data.each(data.dimensions, function () {
  74106. var argLen = arguments.length;
  74107. var dataIndex = arguments[argLen - 1];
  74108. var name = data.getName(dataIndex);
  74109. for (var i = 0; i < argLen - 1; i++) {
  74110. vals[i] = arguments[i];
  74111. }
  74112. lines.push((name ? (name + ITEM_SPLITER) : '') + vals.join(ITEM_SPLITER));
  74113. });
  74114. return lines.join('\n');
  74115. }).join('\n\n' + BLOCK_SPLITER + '\n\n');
  74116. }
  74117. /**
  74118. * @param {module:echarts/model/Global}
  74119. * @return {Object}
  74120. * @inner
  74121. */
  74122. function getContentFromModel(ecModel) {
  74123. var result = groupSeries(ecModel);
  74124. return {
  74125. value: filter([
  74126. assembleSeriesWithCategoryAxis(result.seriesGroupByCategoryAxis),
  74127. assembleOtherSeries(result.other)
  74128. ], function (str) {
  74129. return str.replace(/[\n\t\s]/g, '');
  74130. }).join('\n\n' + BLOCK_SPLITER + '\n\n'),
  74131. meta: result.meta
  74132. };
  74133. }
  74134. function trim$1(str) {
  74135. return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  74136. }
  74137. /**
  74138. * If a block is tsv format
  74139. */
  74140. function isTSVFormat(block) {
  74141. // Simple method to find out if a block is tsv format
  74142. var firstLine = block.slice(0, block.indexOf('\n'));
  74143. if (firstLine.indexOf(ITEM_SPLITER) >= 0) {
  74144. return true;
  74145. }
  74146. }
  74147. var itemSplitRegex = new RegExp('[' + ITEM_SPLITER + ']+', 'g');
  74148. /**
  74149. * @param {string} tsv
  74150. * @return {Object}
  74151. */
  74152. function parseTSVContents(tsv) {
  74153. var tsvLines = tsv.split(/\n+/g);
  74154. var headers = trim$1(tsvLines.shift()).split(itemSplitRegex);
  74155. var categories = [];
  74156. var series = map(headers, function (header) {
  74157. return {
  74158. name: header,
  74159. data: []
  74160. };
  74161. });
  74162. for (var i = 0; i < tsvLines.length; i++) {
  74163. var items = trim$1(tsvLines[i]).split(itemSplitRegex);
  74164. categories.push(items.shift());
  74165. for (var j = 0; j < items.length; j++) {
  74166. series[j] && (series[j].data[i] = items[j]);
  74167. }
  74168. }
  74169. return {
  74170. series: series,
  74171. categories: categories
  74172. };
  74173. }
  74174. /**
  74175. * @param {string} str
  74176. * @return {Array.<Object>}
  74177. * @inner
  74178. */
  74179. function parseListContents(str) {
  74180. var lines = str.split(/\n+/g);
  74181. var seriesName = trim$1(lines.shift());
  74182. var data = [];
  74183. for (var i = 0; i < lines.length; i++) {
  74184. var items = trim$1(lines[i]).split(itemSplitRegex);
  74185. var name = '';
  74186. var value;
  74187. var hasName = false;
  74188. if (isNaN(items[0])) { // First item is name
  74189. hasName = true;
  74190. name = items[0];
  74191. items = items.slice(1);
  74192. data[i] = {
  74193. name: name,
  74194. value: []
  74195. };
  74196. value = data[i].value;
  74197. }
  74198. else {
  74199. value = data[i] = [];
  74200. }
  74201. for (var j = 0; j < items.length; j++) {
  74202. value.push(+items[j]);
  74203. }
  74204. if (value.length === 1) {
  74205. hasName ? (data[i].value = value[0]) : (data[i] = value[0]);
  74206. }
  74207. }
  74208. return {
  74209. name: seriesName,
  74210. data: data
  74211. };
  74212. }
  74213. /**
  74214. * @param {string} str
  74215. * @param {Array.<Object>} blockMetaList
  74216. * @return {Object}
  74217. * @inner
  74218. */
  74219. function parseContents(str, blockMetaList) {
  74220. var blocks = str.split(new RegExp('\n*' + BLOCK_SPLITER + '\n*', 'g'));
  74221. var newOption = {
  74222. series: []
  74223. };
  74224. each$1(blocks, function (block, idx) {
  74225. if (isTSVFormat(block)) {
  74226. var result = parseTSVContents(block);
  74227. var blockMeta = blockMetaList[idx];
  74228. var axisKey = blockMeta.axisDim + 'Axis';
  74229. if (blockMeta) {
  74230. newOption[axisKey] = newOption[axisKey] || [];
  74231. newOption[axisKey][blockMeta.axisIndex] = {
  74232. data: result.categories
  74233. };
  74234. newOption.series = newOption.series.concat(result.series);
  74235. }
  74236. }
  74237. else {
  74238. var result = parseListContents(block);
  74239. newOption.series.push(result);
  74240. }
  74241. });
  74242. return newOption;
  74243. }
  74244. /**
  74245. * @alias {module:echarts/component/toolbox/feature/DataView}
  74246. * @constructor
  74247. * @param {module:echarts/model/Model} model
  74248. */
  74249. function DataView(model) {
  74250. this._dom = null;
  74251. this.model = model;
  74252. }
  74253. DataView.defaultOption = {
  74254. show: true,
  74255. readOnly: false,
  74256. optionToContent: null,
  74257. contentToOption: null,
  74258. 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',
  74259. title: clone(dataViewLang.title),
  74260. lang: clone(dataViewLang.lang),
  74261. backgroundColor: '#fff',
  74262. textColor: '#000',
  74263. textareaColor: '#fff',
  74264. textareaBorderColor: '#333',
  74265. buttonColor: '#c23531',
  74266. buttonTextColor: '#fff'
  74267. };
  74268. DataView.prototype.onclick = function (ecModel, api) {
  74269. var container = api.getDom();
  74270. var model = this.model;
  74271. if (this._dom) {
  74272. container.removeChild(this._dom);
  74273. }
  74274. var root = document.createElement('div');
  74275. root.style.cssText = 'position:absolute;left:5px;top:5px;bottom:5px;right:5px;';
  74276. root.style.backgroundColor = model.get('backgroundColor') || '#fff';
  74277. // Create elements
  74278. var header = document.createElement('h4');
  74279. var lang$$1 = model.get('lang') || [];
  74280. header.innerHTML = lang$$1[0] || model.get('title');
  74281. header.style.cssText = 'margin: 10px 20px;';
  74282. header.style.color = model.get('textColor');
  74283. var viewMain = document.createElement('div');
  74284. var textarea = document.createElement('textarea');
  74285. viewMain.style.cssText = 'display:block;width:100%;overflow:auto;';
  74286. var optionToContent = model.get('optionToContent');
  74287. var contentToOption = model.get('contentToOption');
  74288. var result = getContentFromModel(ecModel);
  74289. if (typeof optionToContent === 'function') {
  74290. var htmlOrDom = optionToContent(api.getOption());
  74291. if (typeof htmlOrDom === 'string') {
  74292. viewMain.innerHTML = htmlOrDom;
  74293. }
  74294. else if (isDom(htmlOrDom)) {
  74295. viewMain.appendChild(htmlOrDom);
  74296. }
  74297. }
  74298. else {
  74299. // Use default textarea
  74300. viewMain.appendChild(textarea);
  74301. textarea.readOnly = model.get('readOnly');
  74302. textarea.style.cssText = 'width:100%;height:100%;font-family:monospace;font-size:14px;line-height:1.6rem;';
  74303. textarea.style.color = model.get('textColor');
  74304. textarea.style.borderColor = model.get('textareaBorderColor');
  74305. textarea.style.backgroundColor = model.get('textareaColor');
  74306. textarea.value = result.value;
  74307. }
  74308. var blockMetaList = result.meta;
  74309. var buttonContainer = document.createElement('div');
  74310. buttonContainer.style.cssText = 'position:absolute;bottom:0;left:0;right:0;';
  74311. var buttonStyle = 'float:right;margin-right:20px;border:none;'
  74312. + 'cursor:pointer;padding:2px 5px;font-size:12px;border-radius:3px';
  74313. var closeButton = document.createElement('div');
  74314. var refreshButton = document.createElement('div');
  74315. buttonStyle += ';background-color:' + model.get('buttonColor');
  74316. buttonStyle += ';color:' + model.get('buttonTextColor');
  74317. var self = this;
  74318. function close() {
  74319. container.removeChild(root);
  74320. self._dom = null;
  74321. }
  74322. addEventListener(closeButton, 'click', close);
  74323. addEventListener(refreshButton, 'click', function () {
  74324. var newOption;
  74325. try {
  74326. if (typeof contentToOption === 'function') {
  74327. newOption = contentToOption(viewMain, api.getOption());
  74328. }
  74329. else {
  74330. newOption = parseContents(textarea.value, blockMetaList);
  74331. }
  74332. }
  74333. catch (e) {
  74334. close();
  74335. throw new Error('Data view format error ' + e);
  74336. }
  74337. if (newOption) {
  74338. api.dispatchAction({
  74339. type: 'changeDataView',
  74340. newOption: newOption
  74341. });
  74342. }
  74343. close();
  74344. });
  74345. closeButton.innerHTML = lang$$1[1];
  74346. refreshButton.innerHTML = lang$$1[2];
  74347. refreshButton.style.cssText = buttonStyle;
  74348. closeButton.style.cssText = buttonStyle;
  74349. !model.get('readOnly') && buttonContainer.appendChild(refreshButton);
  74350. buttonContainer.appendChild(closeButton);
  74351. // http://stackoverflow.com/questions/6637341/use-tab-to-indent-in-textarea
  74352. addEventListener(textarea, 'keydown', function (e) {
  74353. if ((e.keyCode || e.which) === 9) {
  74354. // get caret position/selection
  74355. var val = this.value;
  74356. var start = this.selectionStart;
  74357. var end = this.selectionEnd;
  74358. // set textarea value to: text before caret + tab + text after caret
  74359. this.value = val.substring(0, start) + ITEM_SPLITER + val.substring(end);
  74360. // put caret at right position again
  74361. this.selectionStart = this.selectionEnd = start + 1;
  74362. // prevent the focus lose
  74363. stop(e);
  74364. }
  74365. });
  74366. root.appendChild(header);
  74367. root.appendChild(viewMain);
  74368. root.appendChild(buttonContainer);
  74369. viewMain.style.height = (container.clientHeight - 80) + 'px';
  74370. container.appendChild(root);
  74371. this._dom = root;
  74372. };
  74373. DataView.prototype.remove = function (ecModel, api) {
  74374. this._dom && api.getDom().removeChild(this._dom);
  74375. };
  74376. DataView.prototype.dispose = function (ecModel, api) {
  74377. this.remove(ecModel, api);
  74378. };
  74379. /**
  74380. * @inner
  74381. */
  74382. function tryMergeDataOption(newData, originalData) {
  74383. return map(newData, function (newVal, idx) {
  74384. var original = originalData && originalData[idx];
  74385. if (isObject$1(original) && !isArray(original)) {
  74386. if (isObject$1(newVal) && !isArray(newVal)) {
  74387. newVal = newVal.value;
  74388. }
  74389. // Original data has option
  74390. return defaults({
  74391. value: newVal
  74392. }, original);
  74393. }
  74394. else {
  74395. return newVal;
  74396. }
  74397. });
  74398. }
  74399. register$1('dataView', DataView);
  74400. registerAction({
  74401. type: 'changeDataView',
  74402. event: 'dataViewChanged',
  74403. update: 'prepareAndUpdate'
  74404. }, function (payload, ecModel) {
  74405. var newSeriesOptList = [];
  74406. each$1(payload.newOption.series, function (seriesOpt) {
  74407. var seriesModel = ecModel.getSeriesByName(seriesOpt.name)[0];
  74408. if (!seriesModel) {
  74409. // New created series
  74410. // Geuss the series type
  74411. newSeriesOptList.push(extend({
  74412. // Default is scatter
  74413. type: 'scatter'
  74414. }, seriesOpt));
  74415. }
  74416. else {
  74417. var originalData = seriesModel.get('data');
  74418. newSeriesOptList.push({
  74419. name: seriesOpt.name,
  74420. data: tryMergeDataOption(seriesOpt.data, originalData)
  74421. });
  74422. }
  74423. });
  74424. ecModel.mergeOption(defaults({
  74425. series: newSeriesOptList
  74426. }, payload.newOption));
  74427. });
  74428. /*
  74429. * Licensed to the Apache Software Foundation (ASF) under one
  74430. * or more contributor license agreements. See the NOTICE file
  74431. * distributed with this work for additional information
  74432. * regarding copyright ownership. The ASF licenses this file
  74433. * to you under the Apache License, Version 2.0 (the
  74434. * "License"); you may not use this file except in compliance
  74435. * with the License. You may obtain a copy of the License at
  74436. *
  74437. * http://www.apache.org/licenses/LICENSE-2.0
  74438. *
  74439. * Unless required by applicable law or agreed to in writing,
  74440. * software distributed under the License is distributed on an
  74441. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74442. * KIND, either express or implied. See the License for the
  74443. * specific language governing permissions and limitations
  74444. * under the License.
  74445. */
  74446. var each$29 = each$1;
  74447. var ATTR$2 = '\0_ec_hist_store';
  74448. /**
  74449. * @param {module:echarts/model/Global} ecModel
  74450. * @param {Object} newSnapshot {dataZoomId, batch: [payloadInfo, ...]}
  74451. */
  74452. function push(ecModel, newSnapshot) {
  74453. var store = giveStore$1(ecModel);
  74454. // If previous dataZoom can not be found,
  74455. // complete an range with current range.
  74456. each$29(newSnapshot, function (batchItem, dataZoomId) {
  74457. var i = store.length - 1;
  74458. for (; i >= 0; i--) {
  74459. var snapshot = store[i];
  74460. if (snapshot[dataZoomId]) {
  74461. break;
  74462. }
  74463. }
  74464. if (i < 0) {
  74465. // No origin range set, create one by current range.
  74466. var dataZoomModel = ecModel.queryComponents(
  74467. {mainType: 'dataZoom', subType: 'select', id: dataZoomId}
  74468. )[0];
  74469. if (dataZoomModel) {
  74470. var percentRange = dataZoomModel.getPercentRange();
  74471. store[0][dataZoomId] = {
  74472. dataZoomId: dataZoomId,
  74473. start: percentRange[0],
  74474. end: percentRange[1]
  74475. };
  74476. }
  74477. }
  74478. });
  74479. store.push(newSnapshot);
  74480. }
  74481. /**
  74482. * @param {module:echarts/model/Global} ecModel
  74483. * @return {Object} snapshot
  74484. */
  74485. function pop(ecModel) {
  74486. var store = giveStore$1(ecModel);
  74487. var head = store[store.length - 1];
  74488. store.length > 1 && store.pop();
  74489. // Find top for all dataZoom.
  74490. var snapshot = {};
  74491. each$29(head, function (batchItem, dataZoomId) {
  74492. for (var i = store.length - 1; i >= 0; i--) {
  74493. var batchItem = store[i][dataZoomId];
  74494. if (batchItem) {
  74495. snapshot[dataZoomId] = batchItem;
  74496. break;
  74497. }
  74498. }
  74499. });
  74500. return snapshot;
  74501. }
  74502. /**
  74503. * @param {module:echarts/model/Global} ecModel
  74504. */
  74505. function clear$1(ecModel) {
  74506. ecModel[ATTR$2] = null;
  74507. }
  74508. /**
  74509. * @param {module:echarts/model/Global} ecModel
  74510. * @return {number} records. always >= 1.
  74511. */
  74512. function count(ecModel) {
  74513. return giveStore$1(ecModel).length;
  74514. }
  74515. /**
  74516. * [{key: dataZoomId, value: {dataZoomId, range}}, ...]
  74517. * History length of each dataZoom may be different.
  74518. * this._history[0] is used to store origin range.
  74519. * @type {Array.<Object>}
  74520. */
  74521. function giveStore$1(ecModel) {
  74522. var store = ecModel[ATTR$2];
  74523. if (!store) {
  74524. store = ecModel[ATTR$2] = [{}];
  74525. }
  74526. return store;
  74527. }
  74528. /*
  74529. * Licensed to the Apache Software Foundation (ASF) under one
  74530. * or more contributor license agreements. See the NOTICE file
  74531. * distributed with this work for additional information
  74532. * regarding copyright ownership. The ASF licenses this file
  74533. * to you under the Apache License, Version 2.0 (the
  74534. * "License"); you may not use this file except in compliance
  74535. * with the License. You may obtain a copy of the License at
  74536. *
  74537. * http://www.apache.org/licenses/LICENSE-2.0
  74538. *
  74539. * Unless required by applicable law or agreed to in writing,
  74540. * software distributed under the License is distributed on an
  74541. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74542. * KIND, either express or implied. See the License for the
  74543. * specific language governing permissions and limitations
  74544. * under the License.
  74545. */
  74546. DataZoomModel.extend({
  74547. type: 'dataZoom.select'
  74548. });
  74549. /*
  74550. * Licensed to the Apache Software Foundation (ASF) under one
  74551. * or more contributor license agreements. See the NOTICE file
  74552. * distributed with this work for additional information
  74553. * regarding copyright ownership. The ASF licenses this file
  74554. * to you under the Apache License, Version 2.0 (the
  74555. * "License"); you may not use this file except in compliance
  74556. * with the License. You may obtain a copy of the License at
  74557. *
  74558. * http://www.apache.org/licenses/LICENSE-2.0
  74559. *
  74560. * Unless required by applicable law or agreed to in writing,
  74561. * software distributed under the License is distributed on an
  74562. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74563. * KIND, either express or implied. See the License for the
  74564. * specific language governing permissions and limitations
  74565. * under the License.
  74566. */
  74567. DataZoomView.extend({
  74568. type: 'dataZoom.select'
  74569. });
  74570. /*
  74571. * Licensed to the Apache Software Foundation (ASF) under one
  74572. * or more contributor license agreements. See the NOTICE file
  74573. * distributed with this work for additional information
  74574. * regarding copyright ownership. The ASF licenses this file
  74575. * to you under the Apache License, Version 2.0 (the
  74576. * "License"); you may not use this file except in compliance
  74577. * with the License. You may obtain a copy of the License at
  74578. *
  74579. * http://www.apache.org/licenses/LICENSE-2.0
  74580. *
  74581. * Unless required by applicable law or agreed to in writing,
  74582. * software distributed under the License is distributed on an
  74583. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74584. * KIND, either express or implied. See the License for the
  74585. * specific language governing permissions and limitations
  74586. * under the License.
  74587. */
  74588. /**
  74589. * DataZoom component entry
  74590. */
  74591. /*
  74592. * Licensed to the Apache Software Foundation (ASF) under one
  74593. * or more contributor license agreements. See the NOTICE file
  74594. * distributed with this work for additional information
  74595. * regarding copyright ownership. The ASF licenses this file
  74596. * to you under the Apache License, Version 2.0 (the
  74597. * "License"); you may not use this file except in compliance
  74598. * with the License. You may obtain a copy of the License at
  74599. *
  74600. * http://www.apache.org/licenses/LICENSE-2.0
  74601. *
  74602. * Unless required by applicable law or agreed to in writing,
  74603. * software distributed under the License is distributed on an
  74604. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74605. * KIND, either express or implied. See the License for the
  74606. * specific language governing permissions and limitations
  74607. * under the License.
  74608. */
  74609. // Use dataZoomSelect
  74610. var dataZoomLang = lang.toolbox.dataZoom;
  74611. var each$28 = each$1;
  74612. // Spectial component id start with \0ec\0, see echarts/model/Global.js~hasInnerId
  74613. var DATA_ZOOM_ID_BASE = '\0_ec_\0toolbox-dataZoom_';
  74614. function DataZoom(model, ecModel, api) {
  74615. /**
  74616. * @private
  74617. * @type {module:echarts/component/helper/BrushController}
  74618. */
  74619. (this._brushController = new BrushController(api.getZr()))
  74620. .on('brush', bind(this._onBrush, this))
  74621. .mount();
  74622. /**
  74623. * @private
  74624. * @type {boolean}
  74625. */
  74626. this._isZoomActive;
  74627. }
  74628. DataZoom.defaultOption = {
  74629. show: true,
  74630. // Icon group
  74631. icon: {
  74632. zoom: 'M0,13.5h26.9 M13.5,26.9V0 M32.1,13.5H58V58H13.5 V32.1',
  74633. back: 'M22,1.4L9.9,13.5l12.3,12.3 M10.3,13.5H54.9v44.6 H10.3v-26'
  74634. },
  74635. // `zoom`, `back`
  74636. title: clone(dataZoomLang.title)
  74637. };
  74638. var proto$6 = DataZoom.prototype;
  74639. proto$6.render = function (featureModel, ecModel, api, payload) {
  74640. this.model = featureModel;
  74641. this.ecModel = ecModel;
  74642. this.api = api;
  74643. updateZoomBtnStatus(featureModel, ecModel, this, payload, api);
  74644. updateBackBtnStatus(featureModel, ecModel);
  74645. };
  74646. proto$6.onclick = function (ecModel, api, type) {
  74647. handlers$1[type].call(this);
  74648. };
  74649. proto$6.remove = function (ecModel, api) {
  74650. this._brushController.unmount();
  74651. };
  74652. proto$6.dispose = function (ecModel, api) {
  74653. this._brushController.dispose();
  74654. };
  74655. /**
  74656. * @private
  74657. */
  74658. var handlers$1 = {
  74659. zoom: function () {
  74660. var nextActive = !this._isZoomActive;
  74661. this.api.dispatchAction({
  74662. type: 'takeGlobalCursor',
  74663. key: 'dataZoomSelect',
  74664. dataZoomSelectActive: nextActive
  74665. });
  74666. },
  74667. back: function () {
  74668. this._dispatchZoomAction(pop(this.ecModel));
  74669. }
  74670. };
  74671. /**
  74672. * @private
  74673. */
  74674. proto$6._onBrush = function (areas, opt) {
  74675. if (!opt.isEnd || !areas.length) {
  74676. return;
  74677. }
  74678. var snapshot = {};
  74679. var ecModel = this.ecModel;
  74680. this._brushController.updateCovers([]); // remove cover
  74681. var brushTargetManager = new BrushTargetManager(
  74682. retrieveAxisSetting(this.model.option), ecModel, {include: ['grid']}
  74683. );
  74684. brushTargetManager.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  74685. if (coordSys.type !== 'cartesian2d') {
  74686. return;
  74687. }
  74688. var brushType = area.brushType;
  74689. if (brushType === 'rect') {
  74690. setBatch('x', coordSys, coordRange[0]);
  74691. setBatch('y', coordSys, coordRange[1]);
  74692. }
  74693. else {
  74694. setBatch(({lineX: 'x', lineY: 'y'})[brushType], coordSys, coordRange);
  74695. }
  74696. });
  74697. push(ecModel, snapshot);
  74698. this._dispatchZoomAction(snapshot);
  74699. function setBatch(dimName, coordSys, minMax) {
  74700. var axis = coordSys.getAxis(dimName);
  74701. var axisModel = axis.model;
  74702. var dataZoomModel = findDataZoom(dimName, axisModel, ecModel);
  74703. // Restrict range.
  74704. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy(axisModel).getMinMaxSpan();
  74705. if (minMaxSpan.minValueSpan != null || minMaxSpan.maxValueSpan != null) {
  74706. minMax = sliderMove(
  74707. 0, minMax.slice(), axis.scale.getExtent(), 0,
  74708. minMaxSpan.minValueSpan, minMaxSpan.maxValueSpan
  74709. );
  74710. }
  74711. dataZoomModel && (snapshot[dataZoomModel.id] = {
  74712. dataZoomId: dataZoomModel.id,
  74713. startValue: minMax[0],
  74714. endValue: minMax[1]
  74715. });
  74716. }
  74717. function findDataZoom(dimName, axisModel, ecModel) {
  74718. var found;
  74719. ecModel.eachComponent({mainType: 'dataZoom', subType: 'select'}, function (dzModel) {
  74720. var has = dzModel.getAxisModel(dimName, axisModel.componentIndex);
  74721. has && (found = dzModel);
  74722. });
  74723. return found;
  74724. }
  74725. };
  74726. /**
  74727. * @private
  74728. */
  74729. proto$6._dispatchZoomAction = function (snapshot) {
  74730. var batch = [];
  74731. // Convert from hash map to array.
  74732. each$28(snapshot, function (batchItem, dataZoomId) {
  74733. batch.push(clone(batchItem));
  74734. });
  74735. batch.length && this.api.dispatchAction({
  74736. type: 'dataZoom',
  74737. from: this.uid,
  74738. batch: batch
  74739. });
  74740. };
  74741. function retrieveAxisSetting(option) {
  74742. var setting = {};
  74743. // Compatible with previous setting: null => all axis, false => no axis.
  74744. each$1(['xAxisIndex', 'yAxisIndex'], function (name) {
  74745. setting[name] = option[name];
  74746. setting[name] == null && (setting[name] = 'all');
  74747. (setting[name] === false || setting[name] === 'none') && (setting[name] = []);
  74748. });
  74749. return setting;
  74750. }
  74751. function updateBackBtnStatus(featureModel, ecModel) {
  74752. featureModel.setIconStatus(
  74753. 'back',
  74754. count(ecModel) > 1 ? 'emphasis' : 'normal'
  74755. );
  74756. }
  74757. function updateZoomBtnStatus(featureModel, ecModel, view, payload, api) {
  74758. var zoomActive = view._isZoomActive;
  74759. if (payload && payload.type === 'takeGlobalCursor') {
  74760. zoomActive = payload.key === 'dataZoomSelect'
  74761. ? payload.dataZoomSelectActive : false;
  74762. }
  74763. view._isZoomActive = zoomActive;
  74764. featureModel.setIconStatus('zoom', zoomActive ? 'emphasis' : 'normal');
  74765. var brushTargetManager = new BrushTargetManager(
  74766. retrieveAxisSetting(featureModel.option), ecModel, {include: ['grid']}
  74767. );
  74768. view._brushController
  74769. .setPanels(brushTargetManager.makePanelOpts(api, function (targetInfo) {
  74770. return (targetInfo.xAxisDeclared && !targetInfo.yAxisDeclared)
  74771. ? 'lineX'
  74772. : (!targetInfo.xAxisDeclared && targetInfo.yAxisDeclared)
  74773. ? 'lineY'
  74774. : 'rect';
  74775. }))
  74776. .enableBrush(
  74777. zoomActive
  74778. ? {
  74779. brushType: 'auto',
  74780. brushStyle: {
  74781. // FIXME user customized?
  74782. lineWidth: 0,
  74783. fill: 'rgba(0,0,0,0.2)'
  74784. }
  74785. }
  74786. : false
  74787. );
  74788. }
  74789. register$1('dataZoom', DataZoom);
  74790. // Create special dataZoom option for select
  74791. // FIXME consider the case of merge option, where axes options are not exists.
  74792. registerPreprocessor(function (option) {
  74793. if (!option) {
  74794. return;
  74795. }
  74796. var dataZoomOpts = option.dataZoom || (option.dataZoom = []);
  74797. if (!isArray(dataZoomOpts)) {
  74798. option.dataZoom = dataZoomOpts = [dataZoomOpts];
  74799. }
  74800. var toolboxOpt = option.toolbox;
  74801. if (toolboxOpt) {
  74802. // Assume there is only one toolbox
  74803. if (isArray(toolboxOpt)) {
  74804. toolboxOpt = toolboxOpt[0];
  74805. }
  74806. if (toolboxOpt && toolboxOpt.feature) {
  74807. var dataZoomOpt = toolboxOpt.feature.dataZoom;
  74808. // FIXME: If add dataZoom when setOption in merge mode,
  74809. // no axis info to be added. See `test/dataZoom-extreme.html`
  74810. addForAxis('xAxis', dataZoomOpt);
  74811. addForAxis('yAxis', dataZoomOpt);
  74812. }
  74813. }
  74814. function addForAxis(axisName, dataZoomOpt) {
  74815. if (!dataZoomOpt) {
  74816. return;
  74817. }
  74818. // Try not to modify model, because it is not merged yet.
  74819. var axisIndicesName = axisName + 'Index';
  74820. var givenAxisIndices = dataZoomOpt[axisIndicesName];
  74821. if (givenAxisIndices != null
  74822. && givenAxisIndices != 'all'
  74823. && !isArray(givenAxisIndices)
  74824. ) {
  74825. givenAxisIndices = (givenAxisIndices === false || givenAxisIndices === 'none') ? [] : [givenAxisIndices];
  74826. }
  74827. forEachComponent(axisName, function (axisOpt, axisIndex) {
  74828. if (givenAxisIndices != null
  74829. && givenAxisIndices != 'all'
  74830. && indexOf(givenAxisIndices, axisIndex) === -1
  74831. ) {
  74832. return;
  74833. }
  74834. var newOpt = {
  74835. type: 'select',
  74836. $fromToolbox: true,
  74837. // Id for merge mapping.
  74838. id: DATA_ZOOM_ID_BASE + axisName + axisIndex
  74839. };
  74840. // FIXME
  74841. // Only support one axis now.
  74842. newOpt[axisIndicesName] = axisIndex;
  74843. dataZoomOpts.push(newOpt);
  74844. });
  74845. }
  74846. function forEachComponent(mainType, cb) {
  74847. var opts = option[mainType];
  74848. if (!isArray(opts)) {
  74849. opts = opts ? [opts] : [];
  74850. }
  74851. each$28(opts, cb);
  74852. }
  74853. });
  74854. /*
  74855. * Licensed to the Apache Software Foundation (ASF) under one
  74856. * or more contributor license agreements. See the NOTICE file
  74857. * distributed with this work for additional information
  74858. * regarding copyright ownership. The ASF licenses this file
  74859. * to you under the Apache License, Version 2.0 (the
  74860. * "License"); you may not use this file except in compliance
  74861. * with the License. You may obtain a copy of the License at
  74862. *
  74863. * http://www.apache.org/licenses/LICENSE-2.0
  74864. *
  74865. * Unless required by applicable law or agreed to in writing,
  74866. * software distributed under the License is distributed on an
  74867. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74868. * KIND, either express or implied. See the License for the
  74869. * specific language governing permissions and limitations
  74870. * under the License.
  74871. */
  74872. var restoreLang = lang.toolbox.restore;
  74873. function Restore(model) {
  74874. this.model = model;
  74875. }
  74876. Restore.defaultOption = {
  74877. show: true,
  74878. 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',
  74879. title: restoreLang.title
  74880. };
  74881. var proto$7 = Restore.prototype;
  74882. proto$7.onclick = function (ecModel, api, type) {
  74883. clear$1(ecModel);
  74884. api.dispatchAction({
  74885. type: 'restore',
  74886. from: this.uid
  74887. });
  74888. };
  74889. register$1('restore', Restore);
  74890. registerAction(
  74891. {type: 'restore', event: 'restore', update: 'prepareAndUpdate'},
  74892. function (payload, ecModel) {
  74893. ecModel.resetOption('recreate');
  74894. }
  74895. );
  74896. /*
  74897. * Licensed to the Apache Software Foundation (ASF) under one
  74898. * or more contributor license agreements. See the NOTICE file
  74899. * distributed with this work for additional information
  74900. * regarding copyright ownership. The ASF licenses this file
  74901. * to you under the Apache License, Version 2.0 (the
  74902. * "License"); you may not use this file except in compliance
  74903. * with the License. You may obtain a copy of the License at
  74904. *
  74905. * http://www.apache.org/licenses/LICENSE-2.0
  74906. *
  74907. * Unless required by applicable law or agreed to in writing,
  74908. * software distributed under the License is distributed on an
  74909. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74910. * KIND, either express or implied. See the License for the
  74911. * specific language governing permissions and limitations
  74912. * under the License.
  74913. */
  74914. var urn = 'urn:schemas-microsoft-com:vml';
  74915. var win = typeof window === 'undefined' ? null : window;
  74916. var vmlInited = false;
  74917. var doc = win && win.document;
  74918. function createNode(tagName) {
  74919. return doCreateNode(tagName);
  74920. }
  74921. // Avoid assign to an exported variable, for transforming to cjs.
  74922. var doCreateNode;
  74923. if (doc && !env$1.canvasSupported) {
  74924. try {
  74925. !doc.namespaces.zrvml && doc.namespaces.add('zrvml', urn);
  74926. doCreateNode = function (tagName) {
  74927. return doc.createElement('<zrvml:' + tagName + ' class="zrvml">');
  74928. };
  74929. }
  74930. catch (e) {
  74931. doCreateNode = function (tagName) {
  74932. return doc.createElement('<' + tagName + ' xmlns="' + urn + '" class="zrvml">');
  74933. };
  74934. }
  74935. }
  74936. // From raphael
  74937. function initVML() {
  74938. if (vmlInited || !doc) {
  74939. return;
  74940. }
  74941. vmlInited = true;
  74942. var styleSheets = doc.styleSheets;
  74943. if (styleSheets.length < 31) {
  74944. doc.createStyleSheet().addRule('.zrvml', 'behavior:url(#default#VML)');
  74945. }
  74946. else {
  74947. // http://msdn.microsoft.com/en-us/library/ms531194%28VS.85%29.aspx
  74948. styleSheets[0].addRule('.zrvml', 'behavior:url(#default#VML)');
  74949. }
  74950. }
  74951. // http://www.w3.org/TR/NOTE-VML
  74952. // TODO Use proxy like svg instead of overwrite brush methods
  74953. var CMD$3 = PathProxy.CMD;
  74954. var round$3 = Math.round;
  74955. var sqrt = Math.sqrt;
  74956. var abs$1 = Math.abs;
  74957. var cos = Math.cos;
  74958. var sin = Math.sin;
  74959. var mathMax$8 = Math.max;
  74960. if (!env$1.canvasSupported) {
  74961. var comma = ',';
  74962. var imageTransformPrefix = 'progid:DXImageTransform.Microsoft';
  74963. var Z = 21600;
  74964. var Z2 = Z / 2;
  74965. var ZLEVEL_BASE = 100000;
  74966. var Z_BASE$1 = 1000;
  74967. var initRootElStyle = function (el) {
  74968. el.style.cssText = 'position:absolute;left:0;top:0;width:1px;height:1px;';
  74969. el.coordsize = Z + ',' + Z;
  74970. el.coordorigin = '0,0';
  74971. };
  74972. var encodeHtmlAttribute = function (s) {
  74973. return String(s).replace(/&/g, '&amp;').replace(/"/g, '&quot;');
  74974. };
  74975. var rgb2Str = function (r, g, b) {
  74976. return 'rgb(' + [r, g, b].join(',') + ')';
  74977. };
  74978. var append = function (parent, child) {
  74979. if (child && parent && child.parentNode !== parent) {
  74980. parent.appendChild(child);
  74981. }
  74982. };
  74983. var remove = function (parent, child) {
  74984. if (child && parent && child.parentNode === parent) {
  74985. parent.removeChild(child);
  74986. }
  74987. };
  74988. var getZIndex = function (zlevel, z, z2) {
  74989. // z 的取值范围为 [0, 1000]
  74990. return (parseFloat(zlevel) || 0) * ZLEVEL_BASE + (parseFloat(z) || 0) * Z_BASE$1 + z2;
  74991. };
  74992. var parsePercent$3 = function (value, maxValue) {
  74993. if (typeof value === 'string') {
  74994. if (value.lastIndexOf('%') >= 0) {
  74995. return parseFloat(value) / 100 * maxValue;
  74996. }
  74997. return parseFloat(value);
  74998. }
  74999. return value;
  75000. };
  75001. /***************************************************
  75002. * PATH
  75003. **************************************************/
  75004. var setColorAndOpacity = function (el, color, opacity) {
  75005. var colorArr = parse(color);
  75006. opacity = +opacity;
  75007. if (isNaN(opacity)) {
  75008. opacity = 1;
  75009. }
  75010. if (colorArr) {
  75011. el.color = rgb2Str(colorArr[0], colorArr[1], colorArr[2]);
  75012. el.opacity = opacity * colorArr[3];
  75013. }
  75014. };
  75015. var getColorAndAlpha = function (color) {
  75016. var colorArr = parse(color);
  75017. return [
  75018. rgb2Str(colorArr[0], colorArr[1], colorArr[2]),
  75019. colorArr[3]
  75020. ];
  75021. };
  75022. var updateFillNode = function (el, style, zrEl) {
  75023. // TODO pattern
  75024. var fill = style.fill;
  75025. if (fill != null) {
  75026. // Modified from excanvas
  75027. if (fill instanceof Gradient) {
  75028. var gradientType;
  75029. var angle = 0;
  75030. var focus = [0, 0];
  75031. // additional offset
  75032. var shift = 0;
  75033. // scale factor for offset
  75034. var expansion = 1;
  75035. var rect = zrEl.getBoundingRect();
  75036. var rectWidth = rect.width;
  75037. var rectHeight = rect.height;
  75038. if (fill.type === 'linear') {
  75039. gradientType = 'gradient';
  75040. var transform = zrEl.transform;
  75041. var p0 = [fill.x * rectWidth, fill.y * rectHeight];
  75042. var p1 = [fill.x2 * rectWidth, fill.y2 * rectHeight];
  75043. if (transform) {
  75044. applyTransform(p0, p0, transform);
  75045. applyTransform(p1, p1, transform);
  75046. }
  75047. var dx = p1[0] - p0[0];
  75048. var dy = p1[1] - p0[1];
  75049. angle = Math.atan2(dx, dy) * 180 / Math.PI;
  75050. // The angle should be a non-negative number.
  75051. if (angle < 0) {
  75052. angle += 360;
  75053. }
  75054. // Very small angles produce an unexpected result because they are
  75055. // converted to a scientific notation string.
  75056. if (angle < 1e-6) {
  75057. angle = 0;
  75058. }
  75059. }
  75060. else {
  75061. gradientType = 'gradientradial';
  75062. var p0 = [fill.x * rectWidth, fill.y * rectHeight];
  75063. var transform = zrEl.transform;
  75064. var scale$$1 = zrEl.scale;
  75065. var width = rectWidth;
  75066. var height = rectHeight;
  75067. focus = [
  75068. // Percent in bounding rect
  75069. (p0[0] - rect.x) / width,
  75070. (p0[1] - rect.y) / height
  75071. ];
  75072. if (transform) {
  75073. applyTransform(p0, p0, transform);
  75074. }
  75075. width /= scale$$1[0] * Z;
  75076. height /= scale$$1[1] * Z;
  75077. var dimension = mathMax$8(width, height);
  75078. shift = 2 * 0 / dimension;
  75079. expansion = 2 * fill.r / dimension - shift;
  75080. }
  75081. // We need to sort the color stops in ascending order by offset,
  75082. // otherwise IE won't interpret it correctly.
  75083. var stops = fill.colorStops.slice();
  75084. stops.sort(function(cs1, cs2) {
  75085. return cs1.offset - cs2.offset;
  75086. });
  75087. var length$$1 = stops.length;
  75088. // Color and alpha list of first and last stop
  75089. var colorAndAlphaList = [];
  75090. var colors = [];
  75091. for (var i = 0; i < length$$1; i++) {
  75092. var stop = stops[i];
  75093. var colorAndAlpha = getColorAndAlpha(stop.color);
  75094. colors.push(stop.offset * expansion + shift + ' ' + colorAndAlpha[0]);
  75095. if (i === 0 || i === length$$1 - 1) {
  75096. colorAndAlphaList.push(colorAndAlpha);
  75097. }
  75098. }
  75099. if (length$$1 >= 2) {
  75100. var color1 = colorAndAlphaList[0][0];
  75101. var color2 = colorAndAlphaList[1][0];
  75102. var opacity1 = colorAndAlphaList[0][1] * style.opacity;
  75103. var opacity2 = colorAndAlphaList[1][1] * style.opacity;
  75104. el.type = gradientType;
  75105. el.method = 'none';
  75106. el.focus = '100%';
  75107. el.angle = angle;
  75108. el.color = color1;
  75109. el.color2 = color2;
  75110. el.colors = colors.join(',');
  75111. // When colors attribute is used, the meanings of opacity and o:opacity2
  75112. // are reversed.
  75113. el.opacity = opacity2;
  75114. // FIXME g_o_:opacity ?
  75115. el.opacity2 = opacity1;
  75116. }
  75117. if (gradientType === 'radial') {
  75118. el.focusposition = focus.join(',');
  75119. }
  75120. }
  75121. else {
  75122. // FIXME Change from Gradient fill to color fill
  75123. setColorAndOpacity(el, fill, style.opacity);
  75124. }
  75125. }
  75126. };
  75127. var updateStrokeNode = function (el, style) {
  75128. // if (style.lineJoin != null) {
  75129. // el.joinstyle = style.lineJoin;
  75130. // }
  75131. // if (style.miterLimit != null) {
  75132. // el.miterlimit = style.miterLimit * Z;
  75133. // }
  75134. // if (style.lineCap != null) {
  75135. // el.endcap = style.lineCap;
  75136. // }
  75137. if (style.lineDash != null) {
  75138. el.dashstyle = style.lineDash.join(' ');
  75139. }
  75140. if (style.stroke != null && !(style.stroke instanceof Gradient)) {
  75141. setColorAndOpacity(el, style.stroke, style.opacity);
  75142. }
  75143. };
  75144. var updateFillAndStroke = function (vmlEl, type, style, zrEl) {
  75145. var isFill = type == 'fill';
  75146. var el = vmlEl.getElementsByTagName(type)[0];
  75147. // Stroke must have lineWidth
  75148. if (style[type] != null && style[type] !== 'none' && (isFill || (!isFill && style.lineWidth))) {
  75149. vmlEl[isFill ? 'filled' : 'stroked'] = 'true';
  75150. // FIXME Remove before updating, or set `colors` will throw error
  75151. if (style[type] instanceof Gradient) {
  75152. remove(vmlEl, el);
  75153. }
  75154. if (!el) {
  75155. el = createNode(type);
  75156. }
  75157. isFill ? updateFillNode(el, style, zrEl) : updateStrokeNode(el, style);
  75158. append(vmlEl, el);
  75159. }
  75160. else {
  75161. vmlEl[isFill ? 'filled' : 'stroked'] = 'false';
  75162. remove(vmlEl, el);
  75163. }
  75164. };
  75165. var points$3 = [[], [], []];
  75166. var pathDataToString = function (path, m) {
  75167. var M = CMD$3.M;
  75168. var C = CMD$3.C;
  75169. var L = CMD$3.L;
  75170. var A = CMD$3.A;
  75171. var Q = CMD$3.Q;
  75172. var str = [];
  75173. var nPoint;
  75174. var cmdStr;
  75175. var cmd;
  75176. var i;
  75177. var xi;
  75178. var yi;
  75179. var data = path.data;
  75180. var dataLength = path.len();
  75181. for (i = 0; i < dataLength;) {
  75182. cmd = data[i++];
  75183. cmdStr = '';
  75184. nPoint = 0;
  75185. switch (cmd) {
  75186. case M:
  75187. cmdStr = ' m ';
  75188. nPoint = 1;
  75189. xi = data[i++];
  75190. yi = data[i++];
  75191. points$3[0][0] = xi;
  75192. points$3[0][1] = yi;
  75193. break;
  75194. case L:
  75195. cmdStr = ' l ';
  75196. nPoint = 1;
  75197. xi = data[i++];
  75198. yi = data[i++];
  75199. points$3[0][0] = xi;
  75200. points$3[0][1] = yi;
  75201. break;
  75202. case Q:
  75203. case C:
  75204. cmdStr = ' c ';
  75205. nPoint = 3;
  75206. var x1 = data[i++];
  75207. var y1 = data[i++];
  75208. var x2 = data[i++];
  75209. var y2 = data[i++];
  75210. var x3;
  75211. var y3;
  75212. if (cmd === Q) {
  75213. // Convert quadratic to cubic using degree elevation
  75214. x3 = x2;
  75215. y3 = y2;
  75216. x2 = (x2 + 2 * x1) / 3;
  75217. y2 = (y2 + 2 * y1) / 3;
  75218. x1 = (xi + 2 * x1) / 3;
  75219. y1 = (yi + 2 * y1) / 3;
  75220. }
  75221. else {
  75222. x3 = data[i++];
  75223. y3 = data[i++];
  75224. }
  75225. points$3[0][0] = x1;
  75226. points$3[0][1] = y1;
  75227. points$3[1][0] = x2;
  75228. points$3[1][1] = y2;
  75229. points$3[2][0] = x3;
  75230. points$3[2][1] = y3;
  75231. xi = x3;
  75232. yi = y3;
  75233. break;
  75234. case A:
  75235. var x = 0;
  75236. var y = 0;
  75237. var sx = 1;
  75238. var sy = 1;
  75239. var angle = 0;
  75240. if (m) {
  75241. // Extract SRT from matrix
  75242. x = m[4];
  75243. y = m[5];
  75244. sx = sqrt(m[0] * m[0] + m[1] * m[1]);
  75245. sy = sqrt(m[2] * m[2] + m[3] * m[3]);
  75246. angle = Math.atan2(-m[1] / sy, m[0] / sx);
  75247. }
  75248. var cx = data[i++];
  75249. var cy = data[i++];
  75250. var rx = data[i++];
  75251. var ry = data[i++];
  75252. var startAngle = data[i++] + angle;
  75253. var endAngle = data[i++] + startAngle + angle;
  75254. // FIXME
  75255. // var psi = data[i++];
  75256. i++;
  75257. var clockwise = data[i++];
  75258. var x0 = cx + cos(startAngle) * rx;
  75259. var y0 = cy + sin(startAngle) * ry;
  75260. var x1 = cx + cos(endAngle) * rx;
  75261. var y1 = cy + sin(endAngle) * ry;
  75262. var type = clockwise ? ' wa ' : ' at ';
  75263. if (Math.abs(x0 - x1) < 1e-4) {
  75264. // IE won't render arches drawn counter clockwise if x0 == x1.
  75265. if (Math.abs(endAngle - startAngle) > 1e-2) {
  75266. // Offset x0 by 1/80 of a pixel. Use something
  75267. // that can be represented in binary
  75268. if (clockwise) {
  75269. x0 += 270 / Z;
  75270. }
  75271. }
  75272. else {
  75273. // Avoid case draw full circle
  75274. if (Math.abs(y0 - cy) < 1e-4) {
  75275. if ((clockwise && x0 < cx) || (!clockwise && x0 > cx)) {
  75276. y1 -= 270 / Z;
  75277. }
  75278. else {
  75279. y1 += 270 / Z;
  75280. }
  75281. }
  75282. else if ((clockwise && y0 < cy) || (!clockwise && y0 > cy)) {
  75283. x1 += 270 / Z;
  75284. }
  75285. else {
  75286. x1 -= 270 / Z;
  75287. }
  75288. }
  75289. }
  75290. str.push(
  75291. type,
  75292. round$3(((cx - rx) * sx + x) * Z - Z2), comma,
  75293. round$3(((cy - ry) * sy + y) * Z - Z2), comma,
  75294. round$3(((cx + rx) * sx + x) * Z - Z2), comma,
  75295. round$3(((cy + ry) * sy + y) * Z - Z2), comma,
  75296. round$3((x0 * sx + x) * Z - Z2), comma,
  75297. round$3((y0 * sy + y) * Z - Z2), comma,
  75298. round$3((x1 * sx + x) * Z - Z2), comma,
  75299. round$3((y1 * sy + y) * Z - Z2)
  75300. );
  75301. xi = x1;
  75302. yi = y1;
  75303. break;
  75304. case CMD$3.R:
  75305. var p0 = points$3[0];
  75306. var p1 = points$3[1];
  75307. // x0, y0
  75308. p0[0] = data[i++];
  75309. p0[1] = data[i++];
  75310. // x1, y1
  75311. p1[0] = p0[0] + data[i++];
  75312. p1[1] = p0[1] + data[i++];
  75313. if (m) {
  75314. applyTransform(p0, p0, m);
  75315. applyTransform(p1, p1, m);
  75316. }
  75317. p0[0] = round$3(p0[0] * Z - Z2);
  75318. p1[0] = round$3(p1[0] * Z - Z2);
  75319. p0[1] = round$3(p0[1] * Z - Z2);
  75320. p1[1] = round$3(p1[1] * Z - Z2);
  75321. str.push(
  75322. // x0, y0
  75323. ' m ', p0[0], comma, p0[1],
  75324. // x1, y0
  75325. ' l ', p1[0], comma, p0[1],
  75326. // x1, y1
  75327. ' l ', p1[0], comma, p1[1],
  75328. // x0, y1
  75329. ' l ', p0[0], comma, p1[1]
  75330. );
  75331. break;
  75332. case CMD$3.Z:
  75333. // FIXME Update xi, yi
  75334. str.push(' x ');
  75335. }
  75336. if (nPoint > 0) {
  75337. str.push(cmdStr);
  75338. for (var k = 0; k < nPoint; k++) {
  75339. var p = points$3[k];
  75340. m && applyTransform(p, p, m);
  75341. // 不 round 会非常慢
  75342. str.push(
  75343. round$3(p[0] * Z - Z2), comma, round$3(p[1] * Z - Z2),
  75344. k < nPoint - 1 ? comma : ''
  75345. );
  75346. }
  75347. }
  75348. }
  75349. return str.join('');
  75350. };
  75351. // Rewrite the original path method
  75352. Path.prototype.brushVML = function (vmlRoot) {
  75353. var style = this.style;
  75354. var vmlEl = this._vmlEl;
  75355. if (!vmlEl) {
  75356. vmlEl = createNode('shape');
  75357. initRootElStyle(vmlEl);
  75358. this._vmlEl = vmlEl;
  75359. }
  75360. updateFillAndStroke(vmlEl, 'fill', style, this);
  75361. updateFillAndStroke(vmlEl, 'stroke', style, this);
  75362. var m = this.transform;
  75363. var needTransform = m != null;
  75364. var strokeEl = vmlEl.getElementsByTagName('stroke')[0];
  75365. if (strokeEl) {
  75366. var lineWidth = style.lineWidth;
  75367. // Get the line scale.
  75368. // Determinant of this.m_ means how much the area is enlarged by the
  75369. // transformation. So its square root can be used as a scale factor
  75370. // for width.
  75371. if (needTransform && !style.strokeNoScale) {
  75372. var det = m[0] * m[3] - m[1] * m[2];
  75373. lineWidth *= sqrt(abs$1(det));
  75374. }
  75375. strokeEl.weight = lineWidth + 'px';
  75376. }
  75377. var path = this.path || (this.path = new PathProxy());
  75378. if (this.__dirtyPath) {
  75379. path.beginPath();
  75380. this.buildPath(path, this.shape);
  75381. path.toStatic();
  75382. this.__dirtyPath = false;
  75383. }
  75384. vmlEl.path = pathDataToString(path, this.transform);
  75385. vmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  75386. // Append to root
  75387. append(vmlRoot, vmlEl);
  75388. // Text
  75389. if (style.text != null) {
  75390. this.drawRectText(vmlRoot, this.getBoundingRect());
  75391. }
  75392. else {
  75393. this.removeRectText(vmlRoot);
  75394. }
  75395. };
  75396. Path.prototype.onRemove = function (vmlRoot) {
  75397. remove(vmlRoot, this._vmlEl);
  75398. this.removeRectText(vmlRoot);
  75399. };
  75400. Path.prototype.onAdd = function (vmlRoot) {
  75401. append(vmlRoot, this._vmlEl);
  75402. this.appendRectText(vmlRoot);
  75403. };
  75404. /***************************************************
  75405. * IMAGE
  75406. **************************************************/
  75407. var isImage = function (img) {
  75408. // FIXME img instanceof Image 如果 img 是一个字符串的时候,IE8 下会报错
  75409. return (typeof img === 'object') && img.tagName && img.tagName.toUpperCase() === 'IMG';
  75410. // return img instanceof Image;
  75411. };
  75412. // Rewrite the original path method
  75413. ZImage.prototype.brushVML = function (vmlRoot) {
  75414. var style = this.style;
  75415. var image = style.image;
  75416. // Image original width, height
  75417. var ow;
  75418. var oh;
  75419. if (isImage(image)) {
  75420. var src = image.src;
  75421. if (src === this._imageSrc) {
  75422. ow = this._imageWidth;
  75423. oh = this._imageHeight;
  75424. }
  75425. else {
  75426. var imageRuntimeStyle = image.runtimeStyle;
  75427. var oldRuntimeWidth = imageRuntimeStyle.width;
  75428. var oldRuntimeHeight = imageRuntimeStyle.height;
  75429. imageRuntimeStyle.width = 'auto';
  75430. imageRuntimeStyle.height = 'auto';
  75431. // get the original size
  75432. ow = image.width;
  75433. oh = image.height;
  75434. // and remove overides
  75435. imageRuntimeStyle.width = oldRuntimeWidth;
  75436. imageRuntimeStyle.height = oldRuntimeHeight;
  75437. // Caching image original width, height and src
  75438. this._imageSrc = src;
  75439. this._imageWidth = ow;
  75440. this._imageHeight = oh;
  75441. }
  75442. image = src;
  75443. }
  75444. else {
  75445. if (image === this._imageSrc) {
  75446. ow = this._imageWidth;
  75447. oh = this._imageHeight;
  75448. }
  75449. }
  75450. if (!image) {
  75451. return;
  75452. }
  75453. var x = style.x || 0;
  75454. var y = style.y || 0;
  75455. var dw = style.width;
  75456. var dh = style.height;
  75457. var sw = style.sWidth;
  75458. var sh = style.sHeight;
  75459. var sx = style.sx || 0;
  75460. var sy = style.sy || 0;
  75461. var hasCrop = sw && sh;
  75462. var vmlEl = this._vmlEl;
  75463. if (!vmlEl) {
  75464. // FIXME 使用 group 在 left, top 都不是 0 的时候就无法显示了。
  75465. // vmlEl = vmlCore.createNode('group');
  75466. vmlEl = doc.createElement('div');
  75467. initRootElStyle(vmlEl);
  75468. this._vmlEl = vmlEl;
  75469. }
  75470. var vmlElStyle = vmlEl.style;
  75471. var hasRotation = false;
  75472. var m;
  75473. var scaleX = 1;
  75474. var scaleY = 1;
  75475. if (this.transform) {
  75476. m = this.transform;
  75477. scaleX = sqrt(m[0] * m[0] + m[1] * m[1]);
  75478. scaleY = sqrt(m[2] * m[2] + m[3] * m[3]);
  75479. hasRotation = m[1] || m[2];
  75480. }
  75481. if (hasRotation) {
  75482. // If filters are necessary (rotation exists), create them
  75483. // filters are bog-slow, so only create them if abbsolutely necessary
  75484. // The following check doesn't account for skews (which don't exist
  75485. // in the canvas spec (yet) anyway.
  75486. // From excanvas
  75487. var p0 = [x, y];
  75488. var p1 = [x + dw, y];
  75489. var p2 = [x, y + dh];
  75490. var p3 = [x + dw, y + dh];
  75491. applyTransform(p0, p0, m);
  75492. applyTransform(p1, p1, m);
  75493. applyTransform(p2, p2, m);
  75494. applyTransform(p3, p3, m);
  75495. var maxX = mathMax$8(p0[0], p1[0], p2[0], p3[0]);
  75496. var maxY = mathMax$8(p0[1], p1[1], p2[1], p3[1]);
  75497. var transformFilter = [];
  75498. transformFilter.push('M11=', m[0] / scaleX, comma,
  75499. 'M12=', m[2] / scaleY, comma,
  75500. 'M21=', m[1] / scaleX, comma,
  75501. 'M22=', m[3] / scaleY, comma,
  75502. 'Dx=', round$3(x * scaleX + m[4]), comma,
  75503. 'Dy=', round$3(y * scaleY + m[5]));
  75504. vmlElStyle.padding = '0 ' + round$3(maxX) + 'px ' + round$3(maxY) + 'px 0';
  75505. // FIXME DXImageTransform 在 IE11 的兼容模式下不起作用
  75506. vmlElStyle.filter = imageTransformPrefix + '.Matrix('
  75507. + transformFilter.join('') + ', SizingMethod=clip)';
  75508. }
  75509. else {
  75510. if (m) {
  75511. x = x * scaleX + m[4];
  75512. y = y * scaleY + m[5];
  75513. }
  75514. vmlElStyle.filter = '';
  75515. vmlElStyle.left = round$3(x) + 'px';
  75516. vmlElStyle.top = round$3(y) + 'px';
  75517. }
  75518. var imageEl = this._imageEl;
  75519. var cropEl = this._cropEl;
  75520. if (!imageEl) {
  75521. imageEl = doc.createElement('div');
  75522. this._imageEl = imageEl;
  75523. }
  75524. var imageELStyle = imageEl.style;
  75525. if (hasCrop) {
  75526. // Needs know image original width and height
  75527. if (! (ow && oh)) {
  75528. var tmpImage = new Image();
  75529. var self = this;
  75530. tmpImage.onload = function () {
  75531. tmpImage.onload = null;
  75532. ow = tmpImage.width;
  75533. oh = tmpImage.height;
  75534. // Adjust image width and height to fit the ratio destinationSize / sourceSize
  75535. imageELStyle.width = round$3(scaleX * ow * dw / sw) + 'px';
  75536. imageELStyle.height = round$3(scaleY * oh * dh / sh) + 'px';
  75537. // Caching image original width, height and src
  75538. self._imageWidth = ow;
  75539. self._imageHeight = oh;
  75540. self._imageSrc = image;
  75541. };
  75542. tmpImage.src = image;
  75543. }
  75544. else {
  75545. imageELStyle.width = round$3(scaleX * ow * dw / sw) + 'px';
  75546. imageELStyle.height = round$3(scaleY * oh * dh / sh) + 'px';
  75547. }
  75548. if (! cropEl) {
  75549. cropEl = doc.createElement('div');
  75550. cropEl.style.overflow = 'hidden';
  75551. this._cropEl = cropEl;
  75552. }
  75553. var cropElStyle = cropEl.style;
  75554. cropElStyle.width = round$3((dw + sx * dw / sw) * scaleX);
  75555. cropElStyle.height = round$3((dh + sy * dh / sh) * scaleY);
  75556. cropElStyle.filter = imageTransformPrefix + '.Matrix(Dx='
  75557. + (-sx * dw / sw * scaleX) + ',Dy=' + (-sy * dh / sh * scaleY) + ')';
  75558. if (! cropEl.parentNode) {
  75559. vmlEl.appendChild(cropEl);
  75560. }
  75561. if (imageEl.parentNode != cropEl) {
  75562. cropEl.appendChild(imageEl);
  75563. }
  75564. }
  75565. else {
  75566. imageELStyle.width = round$3(scaleX * dw) + 'px';
  75567. imageELStyle.height = round$3(scaleY * dh) + 'px';
  75568. vmlEl.appendChild(imageEl);
  75569. if (cropEl && cropEl.parentNode) {
  75570. vmlEl.removeChild(cropEl);
  75571. this._cropEl = null;
  75572. }
  75573. }
  75574. var filterStr = '';
  75575. var alpha = style.opacity;
  75576. if (alpha < 1) {
  75577. filterStr += '.Alpha(opacity=' + round$3(alpha * 100) + ') ';
  75578. }
  75579. filterStr += imageTransformPrefix + '.AlphaImageLoader(src=' + image + ', SizingMethod=scale)';
  75580. imageELStyle.filter = filterStr;
  75581. vmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  75582. // Append to root
  75583. append(vmlRoot, vmlEl);
  75584. // Text
  75585. if (style.text != null) {
  75586. this.drawRectText(vmlRoot, this.getBoundingRect());
  75587. }
  75588. };
  75589. ZImage.prototype.onRemove = function (vmlRoot) {
  75590. remove(vmlRoot, this._vmlEl);
  75591. this._vmlEl = null;
  75592. this._cropEl = null;
  75593. this._imageEl = null;
  75594. this.removeRectText(vmlRoot);
  75595. };
  75596. ZImage.prototype.onAdd = function (vmlRoot) {
  75597. append(vmlRoot, this._vmlEl);
  75598. this.appendRectText(vmlRoot);
  75599. };
  75600. /***************************************************
  75601. * TEXT
  75602. **************************************************/
  75603. var DEFAULT_STYLE_NORMAL = 'normal';
  75604. var fontStyleCache = {};
  75605. var fontStyleCacheCount = 0;
  75606. var MAX_FONT_CACHE_SIZE = 100;
  75607. var fontEl = document.createElement('div');
  75608. var getFontStyle = function (fontString) {
  75609. var fontStyle = fontStyleCache[fontString];
  75610. if (!fontStyle) {
  75611. // Clear cache
  75612. if (fontStyleCacheCount > MAX_FONT_CACHE_SIZE) {
  75613. fontStyleCacheCount = 0;
  75614. fontStyleCache = {};
  75615. }
  75616. var style = fontEl.style;
  75617. var fontFamily;
  75618. try {
  75619. style.font = fontString;
  75620. fontFamily = style.fontFamily.split(',')[0];
  75621. }
  75622. catch (e) {
  75623. }
  75624. fontStyle = {
  75625. style: style.fontStyle || DEFAULT_STYLE_NORMAL,
  75626. variant: style.fontVariant || DEFAULT_STYLE_NORMAL,
  75627. weight: style.fontWeight || DEFAULT_STYLE_NORMAL,
  75628. size: parseFloat(style.fontSize || 12) | 0,
  75629. family: fontFamily || 'Microsoft YaHei'
  75630. };
  75631. fontStyleCache[fontString] = fontStyle;
  75632. fontStyleCacheCount++;
  75633. }
  75634. return fontStyle;
  75635. };
  75636. var textMeasureEl;
  75637. // Overwrite measure text method
  75638. $override$1('measureText', function (text, textFont) {
  75639. var doc$$1 = doc;
  75640. if (!textMeasureEl) {
  75641. textMeasureEl = doc$$1.createElement('div');
  75642. textMeasureEl.style.cssText = 'position:absolute;top:-20000px;left:0;'
  75643. + 'padding:0;margin:0;border:none;white-space:pre;';
  75644. doc.body.appendChild(textMeasureEl);
  75645. }
  75646. try {
  75647. textMeasureEl.style.font = textFont;
  75648. } catch (ex) {
  75649. // Ignore failures to set to invalid font.
  75650. }
  75651. textMeasureEl.innerHTML = '';
  75652. // Don't use innerHTML or innerText because they allow markup/whitespace.
  75653. textMeasureEl.appendChild(doc$$1.createTextNode(text));
  75654. return {
  75655. width: textMeasureEl.offsetWidth
  75656. };
  75657. });
  75658. var tmpRect$2 = new BoundingRect();
  75659. var drawRectText = function (vmlRoot, rect, textRect, fromTextEl) {
  75660. var style = this.style;
  75661. // Optimize, avoid normalize every time.
  75662. this.__dirty && normalizeTextStyle(style, true);
  75663. var text = style.text;
  75664. // Convert to string
  75665. text != null && (text += '');
  75666. if (!text) {
  75667. return;
  75668. }
  75669. // Convert rich text to plain text. Rich text is not supported in
  75670. // IE8-, but tags in rich text template will be removed.
  75671. if (style.rich) {
  75672. var contentBlock = parseRichText(text, style);
  75673. text = [];
  75674. for (var i = 0; i < contentBlock.lines.length; i++) {
  75675. var tokens = contentBlock.lines[i].tokens;
  75676. var textLine = [];
  75677. for (var j = 0; j < tokens.length; j++) {
  75678. textLine.push(tokens[j].text);
  75679. }
  75680. text.push(textLine.join(''));
  75681. }
  75682. text = text.join('\n');
  75683. }
  75684. var x;
  75685. var y;
  75686. var align = style.textAlign;
  75687. var verticalAlign = style.textVerticalAlign;
  75688. var fontStyle = getFontStyle(style.font);
  75689. // FIXME encodeHtmlAttribute ?
  75690. var font = fontStyle.style + ' ' + fontStyle.variant + ' ' + fontStyle.weight + ' '
  75691. + fontStyle.size + 'px "' + fontStyle.family + '"';
  75692. textRect = textRect || getBoundingRect(text, font, align, verticalAlign);
  75693. // Transform rect to view space
  75694. var m = this.transform;
  75695. // Ignore transform for text in other element
  75696. if (m && !fromTextEl) {
  75697. tmpRect$2.copy(rect);
  75698. tmpRect$2.applyTransform(m);
  75699. rect = tmpRect$2;
  75700. }
  75701. if (!fromTextEl) {
  75702. var textPosition = style.textPosition;
  75703. var distance$$1 = style.textDistance;
  75704. // Text position represented by coord
  75705. if (textPosition instanceof Array) {
  75706. x = rect.x + parsePercent$3(textPosition[0], rect.width);
  75707. y = rect.y + parsePercent$3(textPosition[1], rect.height);
  75708. align = align || 'left';
  75709. }
  75710. else {
  75711. var res = adjustTextPositionOnRect(
  75712. textPosition, rect, distance$$1
  75713. );
  75714. x = res.x;
  75715. y = res.y;
  75716. // Default align and baseline when has textPosition
  75717. align = align || res.textAlign;
  75718. verticalAlign = verticalAlign || res.textVerticalAlign;
  75719. }
  75720. }
  75721. else {
  75722. x = rect.x;
  75723. y = rect.y;
  75724. }
  75725. x = adjustTextX(x, textRect.width, align);
  75726. y = adjustTextY(y, textRect.height, verticalAlign);
  75727. // Force baseline 'middle'
  75728. y += textRect.height / 2;
  75729. // var fontSize = fontStyle.size;
  75730. // 1.75 is an arbitrary number, as there is no info about the text baseline
  75731. // switch (baseline) {
  75732. // case 'hanging':
  75733. // case 'top':
  75734. // y += fontSize / 1.75;
  75735. // break;
  75736. // case 'middle':
  75737. // break;
  75738. // default:
  75739. // // case null:
  75740. // // case 'alphabetic':
  75741. // // case 'ideographic':
  75742. // // case 'bottom':
  75743. // y -= fontSize / 2.25;
  75744. // break;
  75745. // }
  75746. // switch (align) {
  75747. // case 'left':
  75748. // break;
  75749. // case 'center':
  75750. // x -= textRect.width / 2;
  75751. // break;
  75752. // case 'right':
  75753. // x -= textRect.width;
  75754. // break;
  75755. // case 'end':
  75756. // align = elementStyle.direction == 'ltr' ? 'right' : 'left';
  75757. // break;
  75758. // case 'start':
  75759. // align = elementStyle.direction == 'rtl' ? 'right' : 'left';
  75760. // break;
  75761. // default:
  75762. // align = 'left';
  75763. // }
  75764. var createNode$$1 = createNode;
  75765. var textVmlEl = this._textVmlEl;
  75766. var pathEl;
  75767. var textPathEl;
  75768. var skewEl;
  75769. if (!textVmlEl) {
  75770. textVmlEl = createNode$$1('line');
  75771. pathEl = createNode$$1('path');
  75772. textPathEl = createNode$$1('textpath');
  75773. skewEl = createNode$$1('skew');
  75774. // FIXME Why here is not cammel case
  75775. // Align 'center' seems wrong
  75776. textPathEl.style['v-text-align'] = 'left';
  75777. initRootElStyle(textVmlEl);
  75778. pathEl.textpathok = true;
  75779. textPathEl.on = true;
  75780. textVmlEl.from = '0 0';
  75781. textVmlEl.to = '1000 0.05';
  75782. append(textVmlEl, skewEl);
  75783. append(textVmlEl, pathEl);
  75784. append(textVmlEl, textPathEl);
  75785. this._textVmlEl = textVmlEl;
  75786. }
  75787. else {
  75788. // 这里是在前面 appendChild 保证顺序的前提下
  75789. skewEl = textVmlEl.firstChild;
  75790. pathEl = skewEl.nextSibling;
  75791. textPathEl = pathEl.nextSibling;
  75792. }
  75793. var coords = [x, y];
  75794. var textVmlElStyle = textVmlEl.style;
  75795. // Ignore transform for text in other element
  75796. if (m && fromTextEl) {
  75797. applyTransform(coords, coords, m);
  75798. skewEl.on = true;
  75799. skewEl.matrix = m[0].toFixed(3) + comma + m[2].toFixed(3) + comma +
  75800. m[1].toFixed(3) + comma + m[3].toFixed(3) + ',0,0';
  75801. // Text position
  75802. skewEl.offset = (round$3(coords[0]) || 0) + ',' + (round$3(coords[1]) || 0);
  75803. // Left top point as origin
  75804. skewEl.origin = '0 0';
  75805. textVmlElStyle.left = '0px';
  75806. textVmlElStyle.top = '0px';
  75807. }
  75808. else {
  75809. skewEl.on = false;
  75810. textVmlElStyle.left = round$3(x) + 'px';
  75811. textVmlElStyle.top = round$3(y) + 'px';
  75812. }
  75813. textPathEl.string = encodeHtmlAttribute(text);
  75814. // TODO
  75815. try {
  75816. textPathEl.style.font = font;
  75817. }
  75818. // Error font format
  75819. catch (e) {}
  75820. updateFillAndStroke(textVmlEl, 'fill', {
  75821. fill: style.textFill,
  75822. opacity: style.opacity
  75823. }, this);
  75824. updateFillAndStroke(textVmlEl, 'stroke', {
  75825. stroke: style.textStroke,
  75826. opacity: style.opacity,
  75827. lineDash: style.lineDash
  75828. }, this);
  75829. textVmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  75830. // Attached to root
  75831. append(vmlRoot, textVmlEl);
  75832. };
  75833. var removeRectText = function (vmlRoot) {
  75834. remove(vmlRoot, this._textVmlEl);
  75835. this._textVmlEl = null;
  75836. };
  75837. var appendRectText = function (vmlRoot) {
  75838. append(vmlRoot, this._textVmlEl);
  75839. };
  75840. var list = [RectText, Displayable, ZImage, Path, Text];
  75841. // In case Displayable has been mixed in RectText
  75842. for (var i$3 = 0; i$3 < list.length; i$3++) {
  75843. var proto$8 = list[i$3].prototype;
  75844. proto$8.drawRectText = drawRectText;
  75845. proto$8.removeRectText = removeRectText;
  75846. proto$8.appendRectText = appendRectText;
  75847. }
  75848. Text.prototype.brushVML = function (vmlRoot) {
  75849. var style = this.style;
  75850. if (style.text != null) {
  75851. this.drawRectText(vmlRoot, {
  75852. x: style.x || 0, y: style.y || 0,
  75853. width: 0, height: 0
  75854. }, this.getBoundingRect(), true);
  75855. }
  75856. else {
  75857. this.removeRectText(vmlRoot);
  75858. }
  75859. };
  75860. Text.prototype.onRemove = function (vmlRoot) {
  75861. this.removeRectText(vmlRoot);
  75862. };
  75863. Text.prototype.onAdd = function (vmlRoot) {
  75864. this.appendRectText(vmlRoot);
  75865. };
  75866. }
  75867. /**
  75868. * VML Painter.
  75869. *
  75870. * @module zrender/vml/Painter
  75871. */
  75872. function parseInt10$1(val) {
  75873. return parseInt(val, 10);
  75874. }
  75875. /**
  75876. * @alias module:zrender/vml/Painter
  75877. */
  75878. function VMLPainter(root, storage) {
  75879. initVML();
  75880. this.root = root;
  75881. this.storage = storage;
  75882. var vmlViewport = document.createElement('div');
  75883. var vmlRoot = document.createElement('div');
  75884. vmlViewport.style.cssText = 'display:inline-block;overflow:hidden;position:relative;width:300px;height:150px;';
  75885. vmlRoot.style.cssText = 'position:absolute;left:0;top:0;';
  75886. root.appendChild(vmlViewport);
  75887. this._vmlRoot = vmlRoot;
  75888. this._vmlViewport = vmlViewport;
  75889. this.resize();
  75890. // Modify storage
  75891. var oldDelFromStorage = storage.delFromStorage;
  75892. var oldAddToStorage = storage.addToStorage;
  75893. storage.delFromStorage = function (el) {
  75894. oldDelFromStorage.call(storage, el);
  75895. if (el) {
  75896. el.onRemove && el.onRemove(vmlRoot);
  75897. }
  75898. };
  75899. storage.addToStorage = function (el) {
  75900. // Displayable already has a vml node
  75901. el.onAdd && el.onAdd(vmlRoot);
  75902. oldAddToStorage.call(storage, el);
  75903. };
  75904. this._firstPaint = true;
  75905. }
  75906. VMLPainter.prototype = {
  75907. constructor: VMLPainter,
  75908. getType: function () {
  75909. return 'vml';
  75910. },
  75911. /**
  75912. * @return {HTMLDivElement}
  75913. */
  75914. getViewportRoot: function () {
  75915. return this._vmlViewport;
  75916. },
  75917. getViewportRootOffset: function () {
  75918. var viewportRoot = this.getViewportRoot();
  75919. if (viewportRoot) {
  75920. return {
  75921. offsetLeft: viewportRoot.offsetLeft || 0,
  75922. offsetTop: viewportRoot.offsetTop || 0
  75923. };
  75924. }
  75925. },
  75926. /**
  75927. * 刷新
  75928. */
  75929. refresh: function () {
  75930. var list = this.storage.getDisplayList(true, true);
  75931. this._paintList(list);
  75932. },
  75933. _paintList: function (list) {
  75934. var vmlRoot = this._vmlRoot;
  75935. for (var i = 0; i < list.length; i++) {
  75936. var el = list[i];
  75937. if (el.invisible || el.ignore) {
  75938. if (!el.__alreadyNotVisible) {
  75939. el.onRemove(vmlRoot);
  75940. }
  75941. // Set as already invisible
  75942. el.__alreadyNotVisible = true;
  75943. }
  75944. else {
  75945. if (el.__alreadyNotVisible) {
  75946. el.onAdd(vmlRoot);
  75947. }
  75948. el.__alreadyNotVisible = false;
  75949. if (el.__dirty) {
  75950. el.beforeBrush && el.beforeBrush();
  75951. (el.brushVML || el.brush).call(el, vmlRoot);
  75952. el.afterBrush && el.afterBrush();
  75953. }
  75954. }
  75955. el.__dirty = false;
  75956. }
  75957. if (this._firstPaint) {
  75958. // Detached from document at first time
  75959. // to avoid page refreshing too many times
  75960. // FIXME 如果每次都先 removeChild 可能会导致一些填充和描边的效果改变
  75961. this._vmlViewport.appendChild(vmlRoot);
  75962. this._firstPaint = false;
  75963. }
  75964. },
  75965. resize: function (width, height) {
  75966. var width = width == null ? this._getWidth() : width;
  75967. var height = height == null ? this._getHeight() : height;
  75968. if (this._width != width || this._height != height) {
  75969. this._width = width;
  75970. this._height = height;
  75971. var vmlViewportStyle = this._vmlViewport.style;
  75972. vmlViewportStyle.width = width + 'px';
  75973. vmlViewportStyle.height = height + 'px';
  75974. }
  75975. },
  75976. dispose: function () {
  75977. this.root.innerHTML = '';
  75978. this._vmlRoot =
  75979. this._vmlViewport =
  75980. this.storage = null;
  75981. },
  75982. getWidth: function () {
  75983. return this._width;
  75984. },
  75985. getHeight: function () {
  75986. return this._height;
  75987. },
  75988. clear: function () {
  75989. if (this._vmlViewport) {
  75990. this.root.removeChild(this._vmlViewport);
  75991. }
  75992. },
  75993. _getWidth: function () {
  75994. var root = this.root;
  75995. var stl = root.currentStyle;
  75996. return ((root.clientWidth || parseInt10$1(stl.width))
  75997. - parseInt10$1(stl.paddingLeft)
  75998. - parseInt10$1(stl.paddingRight)) | 0;
  75999. },
  76000. _getHeight: function () {
  76001. var root = this.root;
  76002. var stl = root.currentStyle;
  76003. return ((root.clientHeight || parseInt10$1(stl.height))
  76004. - parseInt10$1(stl.paddingTop)
  76005. - parseInt10$1(stl.paddingBottom)) | 0;
  76006. }
  76007. };
  76008. // Not supported methods
  76009. function createMethodNotSupport(method) {
  76010. return function () {
  76011. zrLog('In IE8.0 VML mode painter not support method "' + method + '"');
  76012. };
  76013. }
  76014. // Unsupported methods
  76015. each$1([
  76016. 'getLayer', 'insertLayer', 'eachLayer', 'eachBuiltinLayer', 'eachOtherLayer', 'getLayers',
  76017. 'modLayer', 'delLayer', 'clearLayer', 'toDataURL', 'pathToImage'
  76018. ], function (name) {
  76019. VMLPainter.prototype[name] = createMethodNotSupport(name);
  76020. });
  76021. registerPainter('vml', VMLPainter);
  76022. var svgURI = 'http://www.w3.org/2000/svg';
  76023. function createElement(name) {
  76024. return document.createElementNS(svgURI, name);
  76025. }
  76026. // TODO
  76027. // 1. shadow
  76028. // 2. Image: sx, sy, sw, sh
  76029. var CMD$4 = PathProxy.CMD;
  76030. var arrayJoin = Array.prototype.join;
  76031. var NONE = 'none';
  76032. var mathRound = Math.round;
  76033. var mathSin$3 = Math.sin;
  76034. var mathCos$3 = Math.cos;
  76035. var PI$5 = Math.PI;
  76036. var PI2$7 = Math.PI * 2;
  76037. var degree = 180 / PI$5;
  76038. var EPSILON$4 = 1e-4;
  76039. function round4(val) {
  76040. return mathRound(val * 1e4) / 1e4;
  76041. }
  76042. function isAroundZero$1(val) {
  76043. return val < EPSILON$4 && val > -EPSILON$4;
  76044. }
  76045. function pathHasFill(style, isText) {
  76046. var fill = isText ? style.textFill : style.fill;
  76047. return fill != null && fill !== NONE;
  76048. }
  76049. function pathHasStroke(style, isText) {
  76050. var stroke = isText ? style.textStroke : style.stroke;
  76051. return stroke != null && stroke !== NONE;
  76052. }
  76053. function setTransform(svgEl, m) {
  76054. if (m) {
  76055. attr(svgEl, 'transform', 'matrix(' + arrayJoin.call(m, ',') + ')');
  76056. }
  76057. }
  76058. function attr(el, key, val) {
  76059. if (!val || val.type !== 'linear' && val.type !== 'radial') {
  76060. // Don't set attribute for gradient, since it need new dom nodes
  76061. if (typeof val === 'string' && val.indexOf('NaN') > -1) {
  76062. console.log(val);
  76063. }
  76064. el.setAttribute(key, val);
  76065. }
  76066. }
  76067. function attrXLink(el, key, val) {
  76068. el.setAttributeNS('http://www.w3.org/1999/xlink', key, val);
  76069. }
  76070. function bindStyle(svgEl, style, isText) {
  76071. if (pathHasFill(style, isText)) {
  76072. var fill = isText ? style.textFill : style.fill;
  76073. fill = fill === 'transparent' ? NONE : fill;
  76074. /**
  76075. * FIXME:
  76076. * This is a temporary fix for Chrome's clipping bug
  76077. * that happens when a clip-path is referring another one.
  76078. * This fix should be used before Chrome's bug is fixed.
  76079. * For an element that has clip-path, and fill is none,
  76080. * set it to be "rgba(0, 0, 0, 0.002)" will hide the element.
  76081. * Otherwise, it will show black fill color.
  76082. * 0.002 is used because this won't work for alpha values smaller
  76083. * than 0.002.
  76084. *
  76085. * See
  76086. * https://bugs.chromium.org/p/chromium/issues/detail?id=659790
  76087. * for more information.
  76088. */
  76089. if (svgEl.getAttribute('clip-path') !== 'none' && fill === NONE) {
  76090. fill = 'rgba(0, 0, 0, 0.002)';
  76091. }
  76092. attr(svgEl, 'fill', fill);
  76093. attr(svgEl, 'fill-opacity', style.opacity);
  76094. }
  76095. else {
  76096. attr(svgEl, 'fill', NONE);
  76097. }
  76098. if (pathHasStroke(style, isText)) {
  76099. var stroke = isText ? style.textStroke : style.stroke;
  76100. stroke = stroke === 'transparent' ? NONE : stroke;
  76101. attr(svgEl, 'stroke', stroke);
  76102. var strokeWidth = isText
  76103. ? style.textStrokeWidth
  76104. : style.lineWidth;
  76105. var strokeScale = !isText && style.strokeNoScale
  76106. ? style.host.getLineScale()
  76107. : 1;
  76108. attr(svgEl, 'stroke-width', strokeWidth / strokeScale);
  76109. // stroke then fill for text; fill then stroke for others
  76110. attr(svgEl, 'paint-order', isText ? 'stroke' : 'fill');
  76111. attr(svgEl, 'stroke-opacity', style.opacity);
  76112. var lineDash = style.lineDash;
  76113. if (lineDash) {
  76114. attr(svgEl, 'stroke-dasharray', style.lineDash.join(','));
  76115. attr(svgEl, 'stroke-dashoffset', mathRound(style.lineDashOffset || 0));
  76116. }
  76117. else {
  76118. attr(svgEl, 'stroke-dasharray', '');
  76119. }
  76120. // PENDING
  76121. style.lineCap && attr(svgEl, 'stroke-linecap', style.lineCap);
  76122. style.lineJoin && attr(svgEl, 'stroke-linejoin', style.lineJoin);
  76123. style.miterLimit && attr(svgEl, 'stroke-miterlimit', style.miterLimit);
  76124. }
  76125. else {
  76126. attr(svgEl, 'stroke', NONE);
  76127. }
  76128. }
  76129. /***************************************************
  76130. * PATH
  76131. **************************************************/
  76132. function pathDataToString$1(path) {
  76133. var str = [];
  76134. var data = path.data;
  76135. var dataLength = path.len();
  76136. for (var i = 0; i < dataLength;) {
  76137. var cmd = data[i++];
  76138. var cmdStr = '';
  76139. var nData = 0;
  76140. switch (cmd) {
  76141. case CMD$4.M:
  76142. cmdStr = 'M';
  76143. nData = 2;
  76144. break;
  76145. case CMD$4.L:
  76146. cmdStr = 'L';
  76147. nData = 2;
  76148. break;
  76149. case CMD$4.Q:
  76150. cmdStr = 'Q';
  76151. nData = 4;
  76152. break;
  76153. case CMD$4.C:
  76154. cmdStr = 'C';
  76155. nData = 6;
  76156. break;
  76157. case CMD$4.A:
  76158. var cx = data[i++];
  76159. var cy = data[i++];
  76160. var rx = data[i++];
  76161. var ry = data[i++];
  76162. var theta = data[i++];
  76163. var dTheta = data[i++];
  76164. var psi = data[i++];
  76165. var clockwise = data[i++];
  76166. var dThetaPositive = Math.abs(dTheta);
  76167. var isCircle = isAroundZero$1(dThetaPositive - PI2$7)
  76168. && !isAroundZero$1(dThetaPositive);
  76169. var large = false;
  76170. if (dThetaPositive >= PI2$7) {
  76171. large = true;
  76172. }
  76173. else if (isAroundZero$1(dThetaPositive)) {
  76174. large = false;
  76175. }
  76176. else {
  76177. large = (dTheta > -PI$5 && dTheta < 0 || dTheta > PI$5)
  76178. === !!clockwise;
  76179. }
  76180. var x0 = round4(cx + rx * mathCos$3(theta));
  76181. var y0 = round4(cy + ry * mathSin$3(theta));
  76182. // It will not draw if start point and end point are exactly the same
  76183. // We need to shift the end point with a small value
  76184. // FIXME A better way to draw circle ?
  76185. if (isCircle) {
  76186. if (clockwise) {
  76187. dTheta = PI2$7 - 1e-4;
  76188. }
  76189. else {
  76190. dTheta = -PI2$7 + 1e-4;
  76191. }
  76192. large = true;
  76193. if (i === 9) {
  76194. // Move to (x0, y0) only when CMD.A comes at the
  76195. // first position of a shape.
  76196. // For instance, when drawing a ring, CMD.A comes
  76197. // after CMD.M, so it's unnecessary to move to
  76198. // (x0, y0).
  76199. str.push('M', x0, y0);
  76200. }
  76201. }
  76202. var x = round4(cx + rx * mathCos$3(theta + dTheta));
  76203. var y = round4(cy + ry * mathSin$3(theta + dTheta));
  76204. // FIXME Ellipse
  76205. str.push('A', round4(rx), round4(ry),
  76206. mathRound(psi * degree), +large, +clockwise, x, y);
  76207. break;
  76208. case CMD$4.Z:
  76209. cmdStr = 'Z';
  76210. break;
  76211. case CMD$4.R:
  76212. var x = round4(data[i++]);
  76213. var y = round4(data[i++]);
  76214. var w = round4(data[i++]);
  76215. var h = round4(data[i++]);
  76216. str.push(
  76217. 'M', x, y,
  76218. 'L', x + w, y,
  76219. 'L', x + w, y + h,
  76220. 'L', x, y + h,
  76221. 'L', x, y
  76222. );
  76223. break;
  76224. }
  76225. cmdStr && str.push(cmdStr);
  76226. for (var j = 0; j < nData; j++) {
  76227. // PENDING With scale
  76228. str.push(round4(data[i++]));
  76229. }
  76230. }
  76231. return str.join(' ');
  76232. }
  76233. var svgPath = {};
  76234. svgPath.brush = function (el) {
  76235. var style = el.style;
  76236. var svgEl = el.__svgEl;
  76237. if (!svgEl) {
  76238. svgEl = createElement('path');
  76239. el.__svgEl = svgEl;
  76240. }
  76241. if (!el.path) {
  76242. el.createPathProxy();
  76243. }
  76244. var path = el.path;
  76245. if (el.__dirtyPath) {
  76246. path.beginPath();
  76247. el.buildPath(path, el.shape);
  76248. el.__dirtyPath = false;
  76249. var pathStr = pathDataToString$1(path);
  76250. if (pathStr.indexOf('NaN') < 0) {
  76251. // Ignore illegal path, which may happen such in out-of-range
  76252. // data in Calendar series.
  76253. attr(svgEl, 'd', pathStr);
  76254. }
  76255. }
  76256. bindStyle(svgEl, style);
  76257. setTransform(svgEl, el.transform);
  76258. if (style.text != null) {
  76259. svgTextDrawRectText(el, el.getBoundingRect());
  76260. }
  76261. };
  76262. /***************************************************
  76263. * IMAGE
  76264. **************************************************/
  76265. var svgImage = {};
  76266. svgImage.brush = function (el) {
  76267. var style = el.style;
  76268. var image = style.image;
  76269. if (image instanceof HTMLImageElement) {
  76270. var src = image.src;
  76271. image = src;
  76272. }
  76273. if (! image) {
  76274. return;
  76275. }
  76276. var x = style.x || 0;
  76277. var y = style.y || 0;
  76278. var dw = style.width;
  76279. var dh = style.height;
  76280. var svgEl = el.__svgEl;
  76281. if (! svgEl) {
  76282. svgEl = createElement('image');
  76283. el.__svgEl = svgEl;
  76284. }
  76285. if (image !== el.__imageSrc) {
  76286. attrXLink(svgEl, 'href', image);
  76287. // Caching image src
  76288. el.__imageSrc = image;
  76289. }
  76290. attr(svgEl, 'width', dw);
  76291. attr(svgEl, 'height', dh);
  76292. attr(svgEl, 'x', x);
  76293. attr(svgEl, 'y', y);
  76294. setTransform(svgEl, el.transform);
  76295. if (style.text != null) {
  76296. svgTextDrawRectText(el, el.getBoundingRect());
  76297. }
  76298. };
  76299. /***************************************************
  76300. * TEXT
  76301. **************************************************/
  76302. var svgText = {};
  76303. var tmpRect$3 = new BoundingRect();
  76304. var svgTextDrawRectText = function (el, rect, textRect) {
  76305. var style = el.style;
  76306. el.__dirty && normalizeTextStyle(style, true);
  76307. var text = style.text;
  76308. // Convert to string
  76309. if (text == null) {
  76310. // Draw no text only when text is set to null, but not ''
  76311. return;
  76312. }
  76313. else {
  76314. text += '';
  76315. }
  76316. var textSvgEl = el.__textSvgEl;
  76317. if (! textSvgEl) {
  76318. textSvgEl = createElement('text');
  76319. el.__textSvgEl = textSvgEl;
  76320. }
  76321. var x;
  76322. var y;
  76323. var textPosition = style.textPosition;
  76324. var distance = style.textDistance;
  76325. var align = style.textAlign || 'left';
  76326. if (typeof style.fontSize === 'number') {
  76327. style.fontSize += 'px';
  76328. }
  76329. var font = style.font
  76330. || [
  76331. style.fontStyle || '',
  76332. style.fontWeight || '',
  76333. style.fontSize || '',
  76334. style.fontFamily || ''
  76335. ].join(' ')
  76336. || DEFAULT_FONT;
  76337. var verticalAlign = getVerticalAlignForSvg(style.textVerticalAlign);
  76338. textRect = getBoundingRect(text, font, align,
  76339. verticalAlign);
  76340. var lineHeight = textRect.lineHeight;
  76341. // Text position represented by coord
  76342. if (textPosition instanceof Array) {
  76343. x = rect.x + textPosition[0];
  76344. y = rect.y + textPosition[1];
  76345. }
  76346. else {
  76347. var newPos = adjustTextPositionOnRect(
  76348. textPosition, rect, distance
  76349. );
  76350. x = newPos.x;
  76351. y = newPos.y;
  76352. verticalAlign = getVerticalAlignForSvg(newPos.textVerticalAlign);
  76353. align = newPos.textAlign;
  76354. }
  76355. attr(textSvgEl, 'alignment-baseline', verticalAlign);
  76356. if (font) {
  76357. textSvgEl.style.font = font;
  76358. }
  76359. var textPadding = style.textPadding;
  76360. // Make baseline top
  76361. attr(textSvgEl, 'x', x);
  76362. attr(textSvgEl, 'y', y);
  76363. bindStyle(textSvgEl, style, true);
  76364. if (el instanceof Text || el.style.transformText) {
  76365. // Transform text with element
  76366. setTransform(textSvgEl, el.transform);
  76367. }
  76368. else {
  76369. if (el.transform) {
  76370. tmpRect$3.copy(rect);
  76371. tmpRect$3.applyTransform(el.transform);
  76372. rect = tmpRect$3;
  76373. }
  76374. else {
  76375. var pos = el.transformCoordToGlobal(rect.x, rect.y);
  76376. rect.x = pos[0];
  76377. rect.y = pos[1];
  76378. }
  76379. // Text rotation, but no element transform
  76380. var origin = style.textOrigin;
  76381. if (origin === 'center') {
  76382. x = textRect.width / 2 + x;
  76383. y = textRect.height / 2 + y;
  76384. }
  76385. else if (origin) {
  76386. x = origin[0] + x;
  76387. y = origin[1] + y;
  76388. }
  76389. var rotate$$1 = -style.textRotation || 0;
  76390. var transform = create$1();
  76391. // Apply textRotate to element matrix
  76392. rotate(transform, el.transform, rotate$$1);
  76393. setTransform(textSvgEl, transform);
  76394. }
  76395. var textLines = text.split('\n');
  76396. var nTextLines = textLines.length;
  76397. var textAnchor = align;
  76398. // PENDING
  76399. if (textAnchor === 'left') {
  76400. textAnchor = 'start';
  76401. textPadding && (x += textPadding[3]);
  76402. }
  76403. else if (textAnchor === 'right') {
  76404. textAnchor = 'end';
  76405. textPadding && (x -= textPadding[1]);
  76406. }
  76407. else if (textAnchor === 'center') {
  76408. textAnchor = 'middle';
  76409. textPadding && (x += (textPadding[3] - textPadding[1]) / 2);
  76410. }
  76411. var dy = 0;
  76412. if (verticalAlign === 'baseline') {
  76413. dy = -textRect.height + lineHeight;
  76414. textPadding && (dy -= textPadding[2]);
  76415. }
  76416. else if (verticalAlign === 'middle') {
  76417. dy = (-textRect.height + lineHeight) / 2;
  76418. textPadding && (y += (textPadding[0] - textPadding[2]) / 2);
  76419. }
  76420. else {
  76421. textPadding && (dy += textPadding[0]);
  76422. }
  76423. // Font may affect position of each tspan elements
  76424. if (el.__text !== text || el.__textFont !== font) {
  76425. var tspanList = el.__tspanList || [];
  76426. el.__tspanList = tspanList;
  76427. for (var i = 0; i < nTextLines; i++) {
  76428. // Using cached tspan elements
  76429. var tspan = tspanList[i];
  76430. if (! tspan) {
  76431. tspan = tspanList[i] = createElement('tspan');
  76432. textSvgEl.appendChild(tspan);
  76433. attr(tspan, 'alignment-baseline', verticalAlign);
  76434. attr(tspan, 'text-anchor', textAnchor);
  76435. }
  76436. else {
  76437. tspan.innerHTML = '';
  76438. }
  76439. attr(tspan, 'x', x);
  76440. attr(tspan, 'y', y + i * lineHeight + dy);
  76441. tspan.appendChild(document.createTextNode(textLines[i]));
  76442. }
  76443. // Remove unsed tspan elements
  76444. for (; i < tspanList.length; i++) {
  76445. textSvgEl.removeChild(tspanList[i]);
  76446. }
  76447. tspanList.length = nTextLines;
  76448. el.__text = text;
  76449. el.__textFont = font;
  76450. }
  76451. else if (el.__tspanList.length) {
  76452. // Update span x and y
  76453. var len = el.__tspanList.length;
  76454. for (var i = 0; i < len; ++i) {
  76455. var tspan = el.__tspanList[i];
  76456. if (tspan) {
  76457. attr(tspan, 'x', x);
  76458. attr(tspan, 'y', y + i * lineHeight + dy);
  76459. }
  76460. }
  76461. }
  76462. };
  76463. function getVerticalAlignForSvg(verticalAlign) {
  76464. if (verticalAlign === 'middle') {
  76465. return 'middle';
  76466. }
  76467. else if (verticalAlign === 'bottom') {
  76468. return 'baseline';
  76469. }
  76470. else {
  76471. return 'hanging';
  76472. }
  76473. }
  76474. svgText.drawRectText = svgTextDrawRectText;
  76475. svgText.brush = function (el) {
  76476. var style = el.style;
  76477. if (style.text != null) {
  76478. // 强制设置 textPosition
  76479. style.textPosition = [0, 0];
  76480. svgTextDrawRectText(el, {
  76481. x: style.x || 0, y: style.y || 0,
  76482. width: 0, height: 0
  76483. }, el.getBoundingRect());
  76484. }
  76485. };
  76486. // Myers' Diff Algorithm
  76487. // Modified from https://github.com/kpdecker/jsdiff/blob/master/src/diff/base.js
  76488. function Diff() {}
  76489. Diff.prototype = {
  76490. diff: function (oldArr, newArr, equals) {
  76491. if (!equals) {
  76492. equals = function (a, b) {
  76493. return a === b;
  76494. };
  76495. }
  76496. this.equals = equals;
  76497. var self = this;
  76498. oldArr = oldArr.slice();
  76499. newArr = newArr.slice();
  76500. // Allow subclasses to massage the input prior to running
  76501. var newLen = newArr.length;
  76502. var oldLen = oldArr.length;
  76503. var editLength = 1;
  76504. var maxEditLength = newLen + oldLen;
  76505. var bestPath = [{ newPos: -1, components: [] }];
  76506. // Seed editLength = 0, i.e. the content starts with the same values
  76507. var oldPos = this.extractCommon(bestPath[0], newArr, oldArr, 0);
  76508. if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
  76509. var indices = [];
  76510. for (var i = 0; i < newArr.length; i++) {
  76511. indices.push(i);
  76512. }
  76513. // Identity per the equality and tokenizer
  76514. return [{
  76515. indices: indices, count: newArr.length
  76516. }];
  76517. }
  76518. // Main worker method. checks all permutations of a given edit length for acceptance.
  76519. function execEditLength() {
  76520. for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
  76521. var basePath;
  76522. var addPath = bestPath[diagonalPath - 1];
  76523. var removePath = bestPath[diagonalPath + 1];
  76524. var oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
  76525. if (addPath) {
  76526. // No one else is going to attempt to use this value, clear it
  76527. bestPath[diagonalPath - 1] = undefined;
  76528. }
  76529. var canAdd = addPath && addPath.newPos + 1 < newLen;
  76530. var canRemove = removePath && 0 <= oldPos && oldPos < oldLen;
  76531. if (!canAdd && !canRemove) {
  76532. // If this path is a terminal then prune
  76533. bestPath[diagonalPath] = undefined;
  76534. continue;
  76535. }
  76536. // Select the diagonal that we want to branch from. We select the prior
  76537. // path whose position in the new string is the farthest from the origin
  76538. // and does not pass the bounds of the diff graph
  76539. if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) {
  76540. basePath = clonePath(removePath);
  76541. self.pushComponent(basePath.components, undefined, true);
  76542. }
  76543. else {
  76544. basePath = addPath; // No need to clone, we've pulled it from the list
  76545. basePath.newPos++;
  76546. self.pushComponent(basePath.components, true, undefined);
  76547. }
  76548. oldPos = self.extractCommon(basePath, newArr, oldArr, diagonalPath);
  76549. // If we have hit the end of both strings, then we are done
  76550. if (basePath.newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
  76551. return buildValues(self, basePath.components, newArr, oldArr);
  76552. }
  76553. else {
  76554. // Otherwise track this path as a potential candidate and continue.
  76555. bestPath[diagonalPath] = basePath;
  76556. }
  76557. }
  76558. editLength++;
  76559. }
  76560. while (editLength <= maxEditLength) {
  76561. var ret = execEditLength();
  76562. if (ret) {
  76563. return ret;
  76564. }
  76565. }
  76566. },
  76567. pushComponent: function (components, added, removed) {
  76568. var last = components[components.length - 1];
  76569. if (last && last.added === added && last.removed === removed) {
  76570. // We need to clone here as the component clone operation is just
  76571. // as shallow array clone
  76572. components[components.length - 1] = {count: last.count + 1, added: added, removed: removed };
  76573. }
  76574. else {
  76575. components.push({count: 1, added: added, removed: removed });
  76576. }
  76577. },
  76578. extractCommon: function (basePath, newArr, oldArr, diagonalPath) {
  76579. var newLen = newArr.length;
  76580. var oldLen = oldArr.length;
  76581. var newPos = basePath.newPos;
  76582. var oldPos = newPos - diagonalPath;
  76583. var commonCount = 0;
  76584. while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newArr[newPos + 1], oldArr[oldPos + 1])) {
  76585. newPos++;
  76586. oldPos++;
  76587. commonCount++;
  76588. }
  76589. if (commonCount) {
  76590. basePath.components.push({count: commonCount});
  76591. }
  76592. basePath.newPos = newPos;
  76593. return oldPos;
  76594. },
  76595. tokenize: function (value) {
  76596. return value.slice();
  76597. },
  76598. join: function (value) {
  76599. return value.slice();
  76600. }
  76601. };
  76602. function buildValues(diff, components, newArr, oldArr) {
  76603. var componentPos = 0;
  76604. var componentLen = components.length;
  76605. var newPos = 0;
  76606. var oldPos = 0;
  76607. for (; componentPos < componentLen; componentPos++) {
  76608. var component = components[componentPos];
  76609. if (!component.removed) {
  76610. var indices = [];
  76611. for (var i = newPos; i < newPos + component.count; i++) {
  76612. indices.push(i);
  76613. }
  76614. component.indices = indices;
  76615. newPos += component.count;
  76616. // Common case
  76617. if (!component.added) {
  76618. oldPos += component.count;
  76619. }
  76620. }
  76621. else {
  76622. var indices = [];
  76623. for (var i = oldPos; i < oldPos + component.count; i++) {
  76624. indices.push(i);
  76625. }
  76626. component.indices = indices;
  76627. oldPos += component.count;
  76628. }
  76629. }
  76630. return components;
  76631. }
  76632. function clonePath(path) {
  76633. return { newPos: path.newPos, components: path.components.slice(0) };
  76634. }
  76635. var arrayDiff = new Diff();
  76636. var arrayDiff$1 = function (oldArr, newArr, callback) {
  76637. return arrayDiff.diff(oldArr, newArr, callback);
  76638. };
  76639. /**
  76640. * @file Manages elements that can be defined in <defs> in SVG,
  76641. * e.g., gradients, clip path, etc.
  76642. * @author Zhang Wenli
  76643. */
  76644. var MARK_UNUSED = '0';
  76645. var MARK_USED = '1';
  76646. /**
  76647. * Manages elements that can be defined in <defs> in SVG,
  76648. * e.g., gradients, clip path, etc.
  76649. *
  76650. * @class
  76651. * @param {number} zrId zrender instance id
  76652. * @param {SVGElement} svgRoot root of SVG document
  76653. * @param {string|string[]} tagNames possible tag names
  76654. * @param {string} markLabel label name to make if the element
  76655. * is used
  76656. */
  76657. function Definable(
  76658. zrId,
  76659. svgRoot,
  76660. tagNames,
  76661. markLabel,
  76662. domName
  76663. ) {
  76664. this._zrId = zrId;
  76665. this._svgRoot = svgRoot;
  76666. this._tagNames = typeof tagNames === 'string' ? [tagNames] : tagNames;
  76667. this._markLabel = markLabel;
  76668. this._domName = domName || '_dom';
  76669. this.nextId = 0;
  76670. }
  76671. Definable.prototype.createElement = createElement;
  76672. /**
  76673. * Get the <defs> tag for svgRoot; optionally creates one if not exists.
  76674. *
  76675. * @param {boolean} isForceCreating if need to create when not exists
  76676. * @return {SVGDefsElement} SVG <defs> element, null if it doesn't
  76677. * exist and isForceCreating is false
  76678. */
  76679. Definable.prototype.getDefs = function (isForceCreating) {
  76680. var svgRoot = this._svgRoot;
  76681. var defs = this._svgRoot.getElementsByTagName('defs');
  76682. if (defs.length === 0) {
  76683. // Not exist
  76684. if (isForceCreating) {
  76685. defs = svgRoot.insertBefore(
  76686. this.createElement('defs'), // Create new tag
  76687. svgRoot.firstChild // Insert in the front of svg
  76688. );
  76689. if (!defs.contains) {
  76690. // IE doesn't support contains method
  76691. defs.contains = function (el) {
  76692. var children = defs.children;
  76693. if (!children) {
  76694. return false;
  76695. }
  76696. for (var i = children.length - 1; i >= 0; --i) {
  76697. if (children[i] === el) {
  76698. return true;
  76699. }
  76700. }
  76701. return false;
  76702. };
  76703. }
  76704. return defs;
  76705. }
  76706. else {
  76707. return null;
  76708. }
  76709. }
  76710. else {
  76711. return defs[0];
  76712. }
  76713. };
  76714. /**
  76715. * Update DOM element if necessary.
  76716. *
  76717. * @param {Object|string} element style element. e.g., for gradient,
  76718. * it may be '#ccc' or {type: 'linear', ...}
  76719. * @param {Function|undefined} onUpdate update callback
  76720. */
  76721. Definable.prototype.update = function (element, onUpdate) {
  76722. if (!element) {
  76723. return;
  76724. }
  76725. var defs = this.getDefs(false);
  76726. if (element[this._domName] && defs.contains(element[this._domName])) {
  76727. // Update DOM
  76728. if (typeof onUpdate === 'function') {
  76729. onUpdate(element);
  76730. }
  76731. }
  76732. else {
  76733. // No previous dom, create new
  76734. var dom = this.add(element);
  76735. if (dom) {
  76736. element[this._domName] = dom;
  76737. }
  76738. }
  76739. };
  76740. /**
  76741. * Add gradient dom to defs
  76742. *
  76743. * @param {SVGElement} dom DOM to be added to <defs>
  76744. */
  76745. Definable.prototype.addDom = function (dom) {
  76746. var defs = this.getDefs(true);
  76747. defs.appendChild(dom);
  76748. };
  76749. /**
  76750. * Remove DOM of a given element.
  76751. *
  76752. * @param {SVGElement} element element to remove dom
  76753. */
  76754. Definable.prototype.removeDom = function (element) {
  76755. var defs = this.getDefs(false);
  76756. if (defs && element[this._domName]) {
  76757. defs.removeChild(element[this._domName]);
  76758. element[this._domName] = null;
  76759. }
  76760. };
  76761. /**
  76762. * Get DOMs of this element.
  76763. *
  76764. * @return {HTMLDomElement} doms of this defineable elements in <defs>
  76765. */
  76766. Definable.prototype.getDoms = function () {
  76767. var defs = this.getDefs(false);
  76768. if (!defs) {
  76769. // No dom when defs is not defined
  76770. return [];
  76771. }
  76772. var doms = [];
  76773. each$1(this._tagNames, function (tagName) {
  76774. var tags = defs.getElementsByTagName(tagName);
  76775. // Note that tags is HTMLCollection, which is array-like
  76776. // rather than real array.
  76777. // So `doms.concat(tags)` add tags as one object.
  76778. doms = doms.concat([].slice.call(tags));
  76779. });
  76780. return doms;
  76781. };
  76782. /**
  76783. * Mark DOMs to be unused before painting, and clear unused ones at the end
  76784. * of the painting.
  76785. */
  76786. Definable.prototype.markAllUnused = function () {
  76787. var doms = this.getDoms();
  76788. var that = this;
  76789. each$1(doms, function (dom) {
  76790. dom[that._markLabel] = MARK_UNUSED;
  76791. });
  76792. };
  76793. /**
  76794. * Mark a single DOM to be used.
  76795. *
  76796. * @param {SVGElement} dom DOM to mark
  76797. */
  76798. Definable.prototype.markUsed = function (dom) {
  76799. if (dom) {
  76800. dom[this._markLabel] = MARK_USED;
  76801. }
  76802. };
  76803. /**
  76804. * Remove unused DOMs defined in <defs>
  76805. */
  76806. Definable.prototype.removeUnused = function () {
  76807. var defs = this.getDefs(false);
  76808. if (!defs) {
  76809. // Nothing to remove
  76810. return;
  76811. }
  76812. var doms = this.getDoms();
  76813. var that = this;
  76814. each$1(doms, function (dom) {
  76815. if (dom[that._markLabel] !== MARK_USED) {
  76816. // Remove gradient
  76817. defs.removeChild(dom);
  76818. }
  76819. });
  76820. };
  76821. /**
  76822. * Get SVG proxy.
  76823. *
  76824. * @param {Displayable} displayable displayable element
  76825. * @return {Path|Image|Text} svg proxy of given element
  76826. */
  76827. Definable.prototype.getSvgProxy = function (displayable) {
  76828. if (displayable instanceof Path) {
  76829. return svgPath;
  76830. }
  76831. else if (displayable instanceof ZImage) {
  76832. return svgImage;
  76833. }
  76834. else if (displayable instanceof Text) {
  76835. return svgText;
  76836. }
  76837. else {
  76838. return svgPath;
  76839. }
  76840. };
  76841. /**
  76842. * Get text SVG element.
  76843. *
  76844. * @param {Displayable} displayable displayable element
  76845. * @return {SVGElement} SVG element of text
  76846. */
  76847. Definable.prototype.getTextSvgElement = function (displayable) {
  76848. return displayable.__textSvgEl;
  76849. };
  76850. /**
  76851. * Get SVG element.
  76852. *
  76853. * @param {Displayable} displayable displayable element
  76854. * @return {SVGElement} SVG element
  76855. */
  76856. Definable.prototype.getSvgElement = function (displayable) {
  76857. return displayable.__svgEl;
  76858. };
  76859. /**
  76860. * @file Manages SVG gradient elements.
  76861. * @author Zhang Wenli
  76862. */
  76863. /**
  76864. * Manages SVG gradient elements.
  76865. *
  76866. * @class
  76867. * @extends Definable
  76868. * @param {number} zrId zrender instance id
  76869. * @param {SVGElement} svgRoot root of SVG document
  76870. */
  76871. function GradientManager(zrId, svgRoot) {
  76872. Definable.call(
  76873. this,
  76874. zrId,
  76875. svgRoot,
  76876. ['linearGradient', 'radialGradient'],
  76877. '__gradient_in_use__'
  76878. );
  76879. }
  76880. inherits(GradientManager, Definable);
  76881. /**
  76882. * Create new gradient DOM for fill or stroke if not exist,
  76883. * but will not update gradient if exists.
  76884. *
  76885. * @param {SvgElement} svgElement SVG element to paint
  76886. * @param {Displayable} displayable zrender displayable element
  76887. */
  76888. GradientManager.prototype.addWithoutUpdate = function (
  76889. svgElement,
  76890. displayable
  76891. ) {
  76892. if (displayable && displayable.style) {
  76893. var that = this;
  76894. each$1(['fill', 'stroke'], function (fillOrStroke) {
  76895. if (displayable.style[fillOrStroke]
  76896. && (displayable.style[fillOrStroke].type === 'linear'
  76897. || displayable.style[fillOrStroke].type === 'radial')
  76898. ) {
  76899. var gradient = displayable.style[fillOrStroke];
  76900. var defs = that.getDefs(true);
  76901. // Create dom in <defs> if not exists
  76902. var dom;
  76903. if (gradient._dom) {
  76904. // Gradient exists
  76905. dom = gradient._dom;
  76906. if (!defs.contains(gradient._dom)) {
  76907. // _dom is no longer in defs, recreate
  76908. that.addDom(dom);
  76909. }
  76910. }
  76911. else {
  76912. // New dom
  76913. dom = that.add(gradient);
  76914. }
  76915. that.markUsed(displayable);
  76916. var id = dom.getAttribute('id');
  76917. svgElement.setAttribute(fillOrStroke, 'url(#' + id + ')');
  76918. }
  76919. });
  76920. }
  76921. };
  76922. /**
  76923. * Add a new gradient tag in <defs>
  76924. *
  76925. * @param {Gradient} gradient zr gradient instance
  76926. * @return {SVGLinearGradientElement | SVGRadialGradientElement}
  76927. * created DOM
  76928. */
  76929. GradientManager.prototype.add = function (gradient) {
  76930. var dom;
  76931. if (gradient.type === 'linear') {
  76932. dom = this.createElement('linearGradient');
  76933. }
  76934. else if (gradient.type === 'radial') {
  76935. dom = this.createElement('radialGradient');
  76936. }
  76937. else {
  76938. zrLog('Illegal gradient type.');
  76939. return null;
  76940. }
  76941. // Set dom id with gradient id, since each gradient instance
  76942. // will have no more than one dom element.
  76943. // id may exists before for those dirty elements, in which case
  76944. // id should remain the same, and other attributes should be
  76945. // updated.
  76946. gradient.id = gradient.id || this.nextId++;
  76947. dom.setAttribute('id', 'zr' + this._zrId
  76948. + '-gradient-' + gradient.id);
  76949. this.updateDom(gradient, dom);
  76950. this.addDom(dom);
  76951. return dom;
  76952. };
  76953. /**
  76954. * Update gradient.
  76955. *
  76956. * @param {Gradient} gradient zr gradient instance
  76957. */
  76958. GradientManager.prototype.update = function (gradient) {
  76959. var that = this;
  76960. Definable.prototype.update.call(this, gradient, function () {
  76961. var type = gradient.type;
  76962. var tagName = gradient._dom.tagName;
  76963. if (type === 'linear' && tagName === 'linearGradient'
  76964. || type === 'radial' && tagName === 'radialGradient'
  76965. ) {
  76966. // Gradient type is not changed, update gradient
  76967. that.updateDom(gradient, gradient._dom);
  76968. }
  76969. else {
  76970. // Remove and re-create if type is changed
  76971. that.removeDom(gradient);
  76972. that.add(gradient);
  76973. }
  76974. });
  76975. };
  76976. /**
  76977. * Update gradient dom
  76978. *
  76979. * @param {Gradient} gradient zr gradient instance
  76980. * @param {SVGLinearGradientElement | SVGRadialGradientElement} dom
  76981. * DOM to update
  76982. */
  76983. GradientManager.prototype.updateDom = function (gradient, dom) {
  76984. if (gradient.type === 'linear') {
  76985. dom.setAttribute('x1', gradient.x);
  76986. dom.setAttribute('y1', gradient.y);
  76987. dom.setAttribute('x2', gradient.x2);
  76988. dom.setAttribute('y2', gradient.y2);
  76989. }
  76990. else if (gradient.type === 'radial') {
  76991. dom.setAttribute('cx', gradient.x);
  76992. dom.setAttribute('cy', gradient.y);
  76993. dom.setAttribute('r', gradient.r);
  76994. }
  76995. else {
  76996. zrLog('Illegal gradient type.');
  76997. return;
  76998. }
  76999. if (gradient.global) {
  77000. // x1, x2, y1, y2 in range of 0 to canvas width or height
  77001. dom.setAttribute('gradientUnits', 'userSpaceOnUse');
  77002. }
  77003. else {
  77004. // x1, x2, y1, y2 in range of 0 to 1
  77005. dom.setAttribute('gradientUnits', 'objectBoundingBox');
  77006. }
  77007. // Remove color stops if exists
  77008. dom.innerHTML = '';
  77009. // Add color stops
  77010. var colors = gradient.colorStops;
  77011. for (var i = 0, len = colors.length; i < len; ++i) {
  77012. var stop = this.createElement('stop');
  77013. stop.setAttribute('offset', colors[i].offset * 100 + '%');
  77014. stop.setAttribute('stop-color', colors[i].color);
  77015. dom.appendChild(stop);
  77016. }
  77017. // Store dom element in gradient, to avoid creating multiple
  77018. // dom instances for the same gradient element
  77019. gradient._dom = dom;
  77020. };
  77021. /**
  77022. * Mark a single gradient to be used
  77023. *
  77024. * @param {Displayable} displayable displayable element
  77025. */
  77026. GradientManager.prototype.markUsed = function (displayable) {
  77027. if (displayable.style) {
  77028. var gradient = displayable.style.fill;
  77029. if (gradient && gradient._dom) {
  77030. Definable.prototype.markUsed.call(this, gradient._dom);
  77031. }
  77032. gradient = displayable.style.stroke;
  77033. if (gradient && gradient._dom) {
  77034. Definable.prototype.markUsed.call(this, gradient._dom);
  77035. }
  77036. }
  77037. };
  77038. /**
  77039. * @file Manages SVG clipPath elements.
  77040. * @author Zhang Wenli
  77041. */
  77042. /**
  77043. * Manages SVG clipPath elements.
  77044. *
  77045. * @class
  77046. * @extends Definable
  77047. * @param {number} zrId zrender instance id
  77048. * @param {SVGElement} svgRoot root of SVG document
  77049. */
  77050. function ClippathManager(zrId, svgRoot) {
  77051. Definable.call(this, zrId, svgRoot, 'clipPath', '__clippath_in_use__');
  77052. }
  77053. inherits(ClippathManager, Definable);
  77054. /**
  77055. * Update clipPath.
  77056. *
  77057. * @param {Displayable} displayable displayable element
  77058. */
  77059. ClippathManager.prototype.update = function (displayable) {
  77060. var svgEl = this.getSvgElement(displayable);
  77061. if (svgEl) {
  77062. this.updateDom(svgEl, displayable.__clipPaths, false);
  77063. }
  77064. var textEl = this.getTextSvgElement(displayable);
  77065. if (textEl) {
  77066. // Make another clipPath for text, since it's transform
  77067. // matrix is not the same with svgElement
  77068. this.updateDom(textEl, displayable.__clipPaths, true);
  77069. }
  77070. this.markUsed(displayable);
  77071. };
  77072. /**
  77073. * Create an SVGElement of displayable and create a <clipPath> of its
  77074. * clipPath
  77075. *
  77076. * @param {Displayable} parentEl parent element
  77077. * @param {ClipPath[]} clipPaths clipPaths of parent element
  77078. * @param {boolean} isText if parent element is Text
  77079. */
  77080. ClippathManager.prototype.updateDom = function (
  77081. parentEl,
  77082. clipPaths,
  77083. isText
  77084. ) {
  77085. if (clipPaths && clipPaths.length > 0) {
  77086. // Has clipPath, create <clipPath> with the first clipPath
  77087. var defs = this.getDefs(true);
  77088. var clipPath = clipPaths[0];
  77089. var clipPathEl;
  77090. var id;
  77091. var dom = isText ? '_textDom' : '_dom';
  77092. if (clipPath[dom]) {
  77093. // Use a dom that is already in <defs>
  77094. id = clipPath[dom].getAttribute('id');
  77095. clipPathEl = clipPath[dom];
  77096. // Use a dom that is already in <defs>
  77097. if (!defs.contains(clipPathEl)) {
  77098. // This happens when set old clipPath that has
  77099. // been previously removed
  77100. defs.appendChild(clipPathEl);
  77101. }
  77102. }
  77103. else {
  77104. // New <clipPath>
  77105. id = 'zr' + this._zrId + '-clip-' + this.nextId;
  77106. ++this.nextId;
  77107. clipPathEl = this.createElement('clipPath');
  77108. clipPathEl.setAttribute('id', id);
  77109. defs.appendChild(clipPathEl);
  77110. clipPath[dom] = clipPathEl;
  77111. }
  77112. // Build path and add to <clipPath>
  77113. var svgProxy = this.getSvgProxy(clipPath);
  77114. if (clipPath.transform
  77115. && clipPath.parent.invTransform
  77116. && !isText
  77117. ) {
  77118. /**
  77119. * If a clipPath has a parent with transform, the transform
  77120. * of parent should not be considered when setting transform
  77121. * of clipPath. So we need to transform back from parent's
  77122. * transform, which is done by multiplying parent's inverse
  77123. * transform.
  77124. */
  77125. // Store old transform
  77126. var transform = Array.prototype.slice.call(
  77127. clipPath.transform
  77128. );
  77129. // Transform back from parent, and brush path
  77130. mul$1(
  77131. clipPath.transform,
  77132. clipPath.parent.invTransform,
  77133. clipPath.transform
  77134. );
  77135. svgProxy.brush(clipPath);
  77136. // Set back transform of clipPath
  77137. clipPath.transform = transform;
  77138. }
  77139. else {
  77140. svgProxy.brush(clipPath);
  77141. }
  77142. var pathEl = this.getSvgElement(clipPath);
  77143. clipPathEl.innerHTML = '';
  77144. /**
  77145. * Use `cloneNode()` here to appendChild to multiple parents,
  77146. * which may happend when Text and other shapes are using the same
  77147. * clipPath. Since Text will create an extra clipPath DOM due to
  77148. * different transform rules.
  77149. */
  77150. clipPathEl.appendChild(pathEl.cloneNode());
  77151. parentEl.setAttribute('clip-path', 'url(#' + id + ')');
  77152. if (clipPaths.length > 1) {
  77153. // Make the other clipPaths recursively
  77154. this.updateDom(clipPathEl, clipPaths.slice(1), isText);
  77155. }
  77156. }
  77157. else {
  77158. // No clipPath
  77159. if (parentEl) {
  77160. parentEl.setAttribute('clip-path', 'none');
  77161. }
  77162. }
  77163. };
  77164. /**
  77165. * Mark a single clipPath to be used
  77166. *
  77167. * @param {Displayable} displayable displayable element
  77168. */
  77169. ClippathManager.prototype.markUsed = function (displayable) {
  77170. var that = this;
  77171. if (displayable.__clipPaths && displayable.__clipPaths.length > 0) {
  77172. each$1(displayable.__clipPaths, function (clipPath) {
  77173. if (clipPath._dom) {
  77174. Definable.prototype.markUsed.call(that, clipPath._dom);
  77175. }
  77176. if (clipPath._textDom) {
  77177. Definable.prototype.markUsed.call(that, clipPath._textDom);
  77178. }
  77179. });
  77180. }
  77181. };
  77182. /**
  77183. * @file Manages SVG shadow elements.
  77184. * @author Zhang Wenli
  77185. */
  77186. /**
  77187. * Manages SVG shadow elements.
  77188. *
  77189. * @class
  77190. * @extends Definable
  77191. * @param {number} zrId zrender instance id
  77192. * @param {SVGElement} svgRoot root of SVG document
  77193. */
  77194. function ShadowManager(zrId, svgRoot) {
  77195. Definable.call(
  77196. this,
  77197. zrId,
  77198. svgRoot,
  77199. ['filter'],
  77200. '__filter_in_use__',
  77201. '_shadowDom'
  77202. );
  77203. }
  77204. inherits(ShadowManager, Definable);
  77205. /**
  77206. * Create new shadow DOM for fill or stroke if not exist,
  77207. * but will not update shadow if exists.
  77208. *
  77209. * @param {SvgElement} svgElement SVG element to paint
  77210. * @param {Displayable} displayable zrender displayable element
  77211. */
  77212. ShadowManager.prototype.addWithoutUpdate = function (
  77213. svgElement,
  77214. displayable
  77215. ) {
  77216. if (displayable && hasShadow(displayable.style)) {
  77217. var style = displayable.style;
  77218. // Create dom in <defs> if not exists
  77219. var dom;
  77220. if (style._shadowDom) {
  77221. // Gradient exists
  77222. dom = style._shadowDom;
  77223. var defs = this.getDefs(true);
  77224. if (!defs.contains(style._shadowDom)) {
  77225. // _shadowDom is no longer in defs, recreate
  77226. this.addDom(dom);
  77227. }
  77228. }
  77229. else {
  77230. // New dom
  77231. dom = this.add(displayable);
  77232. }
  77233. this.markUsed(displayable);
  77234. var id = dom.getAttribute('id');
  77235. svgElement.style.filter = 'url(#' + id + ')';
  77236. }
  77237. };
  77238. /**
  77239. * Add a new shadow tag in <defs>
  77240. *
  77241. * @param {Displayable} displayable zrender displayable element
  77242. * @return {SVGFilterElement} created DOM
  77243. */
  77244. ShadowManager.prototype.add = function (displayable) {
  77245. var dom = this.createElement('filter');
  77246. var style = displayable.style;
  77247. // Set dom id with shadow id, since each shadow instance
  77248. // will have no more than one dom element.
  77249. // id may exists before for those dirty elements, in which case
  77250. // id should remain the same, and other attributes should be
  77251. // updated.
  77252. style._shadowDomId = style._shadowDomId || this.nextId++;
  77253. dom.setAttribute('id', 'zr' + this._zrId
  77254. + '-shadow-' + style._shadowDomId);
  77255. this.updateDom(displayable, dom);
  77256. this.addDom(dom);
  77257. return dom;
  77258. };
  77259. /**
  77260. * Update shadow.
  77261. *
  77262. * @param {Displayable} displayable zrender displayable element
  77263. */
  77264. ShadowManager.prototype.update = function (svgElement, displayable) {
  77265. var style = displayable.style;
  77266. if (hasShadow(style)) {
  77267. var that = this;
  77268. Definable.prototype.update.call(this, displayable, function (style) {
  77269. that.updateDom(displayable, style._shadowDom);
  77270. });
  77271. }
  77272. else {
  77273. // Remove shadow
  77274. this.remove(svgElement, style);
  77275. }
  77276. };
  77277. /**
  77278. * Remove DOM and clear parent filter
  77279. */
  77280. ShadowManager.prototype.remove = function (svgElement, style) {
  77281. if (style._shadowDomId != null) {
  77282. this.removeDom(style);
  77283. svgElement.style.filter = '';
  77284. }
  77285. };
  77286. /**
  77287. * Update shadow dom
  77288. *
  77289. * @param {Displayable} displayable zrender displayable element
  77290. * @param {SVGFilterElement} dom DOM to update
  77291. */
  77292. ShadowManager.prototype.updateDom = function (displayable, dom) {
  77293. var domChild = dom.getElementsByTagName('feDropShadow');
  77294. if (domChild.length === 0) {
  77295. domChild = this.createElement('feDropShadow');
  77296. }
  77297. else {
  77298. domChild = domChild[0];
  77299. }
  77300. var style = displayable.style;
  77301. var scaleX = displayable.scale ? (displayable.scale[0] || 1) : 1;
  77302. var scaleY = displayable.scale ? (displayable.scale[1] || 1) : 1;
  77303. // TODO: textBoxShadowBlur is not supported yet
  77304. var offsetX, offsetY, blur, color;
  77305. if (style.shadowBlur || style.shadowOffsetX || style.shadowOffsetY) {
  77306. offsetX = style.shadowOffsetX || 0;
  77307. offsetY = style.shadowOffsetY || 0;
  77308. blur = style.shadowBlur;
  77309. color = style.shadowColor;
  77310. }
  77311. else if (style.textShadowBlur) {
  77312. offsetX = style.textShadowOffsetX || 0;
  77313. offsetY = style.textShadowOffsetY || 0;
  77314. blur = style.textShadowBlur;
  77315. color = style.textShadowColor;
  77316. }
  77317. else {
  77318. // Remove shadow
  77319. this.removeDom(dom, style);
  77320. return;
  77321. }
  77322. domChild.setAttribute('dx', offsetX / scaleX);
  77323. domChild.setAttribute('dy', offsetY / scaleY);
  77324. domChild.setAttribute('flood-color', color);
  77325. // Divide by two here so that it looks the same as in canvas
  77326. // See: https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-shadowblur
  77327. var stdDx = blur / 2 / scaleX;
  77328. var stdDy = blur / 2 / scaleY;
  77329. var stdDeviation = stdDx + ' ' + stdDy;
  77330. domChild.setAttribute('stdDeviation', stdDeviation);
  77331. // Fix filter clipping problem
  77332. dom.setAttribute('x', '-100%');
  77333. dom.setAttribute('y', '-100%');
  77334. dom.setAttribute('width', Math.ceil(blur / 2 * 200) + '%');
  77335. dom.setAttribute('height', Math.ceil(blur / 2 * 200) + '%');
  77336. dom.appendChild(domChild);
  77337. // Store dom element in shadow, to avoid creating multiple
  77338. // dom instances for the same shadow element
  77339. style._shadowDom = dom;
  77340. };
  77341. /**
  77342. * Mark a single shadow to be used
  77343. *
  77344. * @param {Displayable} displayable displayable element
  77345. */
  77346. ShadowManager.prototype.markUsed = function (displayable) {
  77347. var style = displayable.style;
  77348. if (style && style._shadowDom) {
  77349. Definable.prototype.markUsed.call(this, style._shadowDom);
  77350. }
  77351. };
  77352. function hasShadow(style) {
  77353. // TODO: textBoxShadowBlur is not supported yet
  77354. return style
  77355. && (style.shadowBlur || style.shadowOffsetX || style.shadowOffsetY
  77356. || style.textShadowBlur || style.textShadowOffsetX
  77357. || style.textShadowOffsetY);
  77358. }
  77359. /**
  77360. * SVG Painter
  77361. * @module zrender/svg/Painter
  77362. */
  77363. function parseInt10$2(val) {
  77364. return parseInt(val, 10);
  77365. }
  77366. function getSvgProxy(el) {
  77367. if (el instanceof Path) {
  77368. return svgPath;
  77369. }
  77370. else if (el instanceof ZImage) {
  77371. return svgImage;
  77372. }
  77373. else if (el instanceof Text) {
  77374. return svgText;
  77375. }
  77376. else {
  77377. return svgPath;
  77378. }
  77379. }
  77380. function checkParentAvailable(parent, child) {
  77381. return child && parent && child.parentNode !== parent;
  77382. }
  77383. function insertAfter(parent, child, prevSibling) {
  77384. if (checkParentAvailable(parent, child) && prevSibling) {
  77385. var nextSibling = prevSibling.nextSibling;
  77386. nextSibling ? parent.insertBefore(child, nextSibling)
  77387. : parent.appendChild(child);
  77388. }
  77389. }
  77390. function prepend(parent, child) {
  77391. if (checkParentAvailable(parent, child)) {
  77392. var firstChild = parent.firstChild;
  77393. firstChild ? parent.insertBefore(child, firstChild)
  77394. : parent.appendChild(child);
  77395. }
  77396. }
  77397. function remove$1(parent, child) {
  77398. if (child && parent && child.parentNode === parent) {
  77399. parent.removeChild(child);
  77400. }
  77401. }
  77402. function getTextSvgElement(displayable) {
  77403. return displayable.__textSvgEl;
  77404. }
  77405. function getSvgElement(displayable) {
  77406. return displayable.__svgEl;
  77407. }
  77408. /**
  77409. * @alias module:zrender/svg/Painter
  77410. * @constructor
  77411. * @param {HTMLElement} root 绘图容器
  77412. * @param {module:zrender/Storage} storage
  77413. * @param {Object} opts
  77414. */
  77415. var SVGPainter = function (root, storage, opts, zrId) {
  77416. this.root = root;
  77417. this.storage = storage;
  77418. this._opts = opts = extend({}, opts || {});
  77419. var svgRoot = createElement('svg');
  77420. svgRoot.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
  77421. svgRoot.setAttribute('version', '1.1');
  77422. svgRoot.setAttribute('baseProfile', 'full');
  77423. svgRoot.style.cssText = 'user-select:none;position:absolute;left:0;top:0;';
  77424. this.gradientManager = new GradientManager(zrId, svgRoot);
  77425. this.clipPathManager = new ClippathManager(zrId, svgRoot);
  77426. this.shadowManager = new ShadowManager(zrId, svgRoot);
  77427. var viewport = document.createElement('div');
  77428. viewport.style.cssText = 'overflow:hidden;position:relative';
  77429. this._svgRoot = svgRoot;
  77430. this._viewport = viewport;
  77431. root.appendChild(viewport);
  77432. viewport.appendChild(svgRoot);
  77433. this.resize(opts.width, opts.height);
  77434. this._visibleList = [];
  77435. };
  77436. SVGPainter.prototype = {
  77437. constructor: SVGPainter,
  77438. getType: function () {
  77439. return 'svg';
  77440. },
  77441. getViewportRoot: function () {
  77442. return this._viewport;
  77443. },
  77444. getViewportRootOffset: function () {
  77445. var viewportRoot = this.getViewportRoot();
  77446. if (viewportRoot) {
  77447. return {
  77448. offsetLeft: viewportRoot.offsetLeft || 0,
  77449. offsetTop: viewportRoot.offsetTop || 0
  77450. };
  77451. }
  77452. },
  77453. refresh: function () {
  77454. var list = this.storage.getDisplayList(true);
  77455. this._paintList(list);
  77456. },
  77457. setBackgroundColor: function (backgroundColor) {
  77458. // TODO gradient
  77459. this._viewport.style.background = backgroundColor;
  77460. },
  77461. _paintList: function (list) {
  77462. this.gradientManager.markAllUnused();
  77463. this.clipPathManager.markAllUnused();
  77464. this.shadowManager.markAllUnused();
  77465. var svgRoot = this._svgRoot;
  77466. var visibleList = this._visibleList;
  77467. var listLen = list.length;
  77468. var newVisibleList = [];
  77469. var i;
  77470. for (i = 0; i < listLen; i++) {
  77471. var displayable = list[i];
  77472. var svgProxy = getSvgProxy(displayable);
  77473. var svgElement = getSvgElement(displayable)
  77474. || getTextSvgElement(displayable);
  77475. if (!displayable.invisible) {
  77476. if (displayable.__dirty) {
  77477. svgProxy && svgProxy.brush(displayable);
  77478. // Update clipPath
  77479. this.clipPathManager.update(displayable);
  77480. // Update gradient and shadow
  77481. if (displayable.style) {
  77482. this.gradientManager
  77483. .update(displayable.style.fill);
  77484. this.gradientManager
  77485. .update(displayable.style.stroke);
  77486. this.shadowManager
  77487. .update(svgElement, displayable);
  77488. }
  77489. displayable.__dirty = false;
  77490. }
  77491. newVisibleList.push(displayable);
  77492. }
  77493. }
  77494. var diff = arrayDiff$1(visibleList, newVisibleList);
  77495. var prevSvgElement;
  77496. // First do remove, in case element moved to the head and do remove
  77497. // after add
  77498. for (i = 0; i < diff.length; i++) {
  77499. var item = diff[i];
  77500. if (item.removed) {
  77501. for (var k = 0; k < item.count; k++) {
  77502. var displayable = visibleList[item.indices[k]];
  77503. var svgElement = getSvgElement(displayable);
  77504. var textSvgElement = getTextSvgElement(displayable);
  77505. remove$1(svgRoot, svgElement);
  77506. remove$1(svgRoot, textSvgElement);
  77507. }
  77508. }
  77509. }
  77510. for (i = 0; i < diff.length; i++) {
  77511. var item = diff[i];
  77512. if (item.added) {
  77513. for (var k = 0; k < item.count; k++) {
  77514. var displayable = newVisibleList[item.indices[k]];
  77515. var svgElement = getSvgElement(displayable);
  77516. var textSvgElement = getTextSvgElement(displayable);
  77517. prevSvgElement
  77518. ? insertAfter(svgRoot, svgElement, prevSvgElement)
  77519. : prepend(svgRoot, svgElement);
  77520. if (svgElement) {
  77521. insertAfter(svgRoot, textSvgElement, svgElement);
  77522. }
  77523. else if (prevSvgElement) {
  77524. insertAfter(
  77525. svgRoot, textSvgElement, prevSvgElement
  77526. );
  77527. }
  77528. else {
  77529. prepend(svgRoot, textSvgElement);
  77530. }
  77531. // Insert text
  77532. insertAfter(svgRoot, textSvgElement, svgElement);
  77533. prevSvgElement = textSvgElement || svgElement
  77534. || prevSvgElement;
  77535. this.gradientManager
  77536. .addWithoutUpdate(svgElement, displayable);
  77537. this.shadowManager
  77538. .addWithoutUpdate(prevSvgElement, displayable);
  77539. this.clipPathManager.markUsed(displayable);
  77540. }
  77541. }
  77542. else if (!item.removed) {
  77543. for (var k = 0; k < item.count; k++) {
  77544. var displayable = newVisibleList[item.indices[k]];
  77545. prevSvgElement
  77546. = svgElement
  77547. = getTextSvgElement(displayable)
  77548. || getSvgElement(displayable)
  77549. || prevSvgElement;
  77550. this.gradientManager.markUsed(displayable);
  77551. this.gradientManager
  77552. .addWithoutUpdate(svgElement, displayable);
  77553. this.shadowManager.markUsed(displayable);
  77554. this.shadowManager
  77555. .addWithoutUpdate(svgElement, displayable);
  77556. this.clipPathManager.markUsed(displayable);
  77557. }
  77558. }
  77559. }
  77560. this.gradientManager.removeUnused();
  77561. this.clipPathManager.removeUnused();
  77562. this.shadowManager.removeUnused();
  77563. this._visibleList = newVisibleList;
  77564. },
  77565. _getDefs: function (isForceCreating) {
  77566. var svgRoot = this._svgRoot;
  77567. var defs = this._svgRoot.getElementsByTagName('defs');
  77568. if (defs.length === 0) {
  77569. // Not exist
  77570. if (isForceCreating) {
  77571. var defs = svgRoot.insertBefore(
  77572. createElement('defs'), // Create new tag
  77573. svgRoot.firstChild // Insert in the front of svg
  77574. );
  77575. if (!defs.contains) {
  77576. // IE doesn't support contains method
  77577. defs.contains = function (el) {
  77578. var children = defs.children;
  77579. if (!children) {
  77580. return false;
  77581. }
  77582. for (var i = children.length - 1; i >= 0; --i) {
  77583. if (children[i] === el) {
  77584. return true;
  77585. }
  77586. }
  77587. return false;
  77588. };
  77589. }
  77590. return defs;
  77591. }
  77592. else {
  77593. return null;
  77594. }
  77595. }
  77596. else {
  77597. return defs[0];
  77598. }
  77599. },
  77600. resize: function (width, height) {
  77601. var viewport = this._viewport;
  77602. // FIXME Why ?
  77603. viewport.style.display = 'none';
  77604. // Save input w/h
  77605. var opts = this._opts;
  77606. width != null && (opts.width = width);
  77607. height != null && (opts.height = height);
  77608. width = this._getSize(0);
  77609. height = this._getSize(1);
  77610. viewport.style.display = '';
  77611. if (this._width !== width || this._height !== height) {
  77612. this._width = width;
  77613. this._height = height;
  77614. var viewportStyle = viewport.style;
  77615. viewportStyle.width = width + 'px';
  77616. viewportStyle.height = height + 'px';
  77617. var svgRoot = this._svgRoot;
  77618. // Set width by 'svgRoot.width = width' is invalid
  77619. svgRoot.setAttribute('width', width);
  77620. svgRoot.setAttribute('height', height);
  77621. }
  77622. },
  77623. /**
  77624. * 获取绘图区域宽度
  77625. */
  77626. getWidth: function () {
  77627. return this._width;
  77628. },
  77629. /**
  77630. * 获取绘图区域高度
  77631. */
  77632. getHeight: function () {
  77633. return this._height;
  77634. },
  77635. _getSize: function (whIdx) {
  77636. var opts = this._opts;
  77637. var wh = ['width', 'height'][whIdx];
  77638. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  77639. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  77640. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  77641. if (opts[wh] != null && opts[wh] !== 'auto') {
  77642. return parseFloat(opts[wh]);
  77643. }
  77644. var root = this.root;
  77645. // IE8 does not support getComputedStyle, but it use VML.
  77646. var stl = document.defaultView.getComputedStyle(root);
  77647. return (
  77648. (root[cwh] || parseInt10$2(stl[wh]) || parseInt10$2(root.style[wh]))
  77649. - (parseInt10$2(stl[plt]) || 0)
  77650. - (parseInt10$2(stl[prb]) || 0)
  77651. ) | 0;
  77652. },
  77653. dispose: function () {
  77654. this.root.innerHTML = '';
  77655. this._svgRoot
  77656. = this._viewport
  77657. = this.storage
  77658. = null;
  77659. },
  77660. clear: function () {
  77661. if (this._viewport) {
  77662. this.root.removeChild(this._viewport);
  77663. }
  77664. },
  77665. pathToDataUrl: function () {
  77666. this.refresh();
  77667. var html = this._svgRoot.outerHTML;
  77668. return 'data:image/svg+xml;charset=UTF-8,' + html;
  77669. }
  77670. };
  77671. // Not supported methods
  77672. function createMethodNotSupport$1(method) {
  77673. return function () {
  77674. zrLog('In SVG mode painter not support method "' + method + '"');
  77675. };
  77676. }
  77677. // Unsuppoted methods
  77678. each$1([
  77679. 'getLayer', 'insertLayer', 'eachLayer', 'eachBuiltinLayer',
  77680. 'eachOtherLayer', 'getLayers', 'modLayer', 'delLayer', 'clearLayer',
  77681. 'toDataURL', 'pathToImage'
  77682. ], function (name) {
  77683. SVGPainter.prototype[name] = createMethodNotSupport$1(name);
  77684. });
  77685. registerPainter('svg', SVGPainter);
  77686. /*
  77687. * Licensed to the Apache Software Foundation (ASF) under one
  77688. * or more contributor license agreements. See the NOTICE file
  77689. * distributed with this work for additional information
  77690. * regarding copyright ownership. The ASF licenses this file
  77691. * to you under the Apache License, Version 2.0 (the
  77692. * "License"); you may not use this file except in compliance
  77693. * with the License. You may obtain a copy of the License at
  77694. *
  77695. * http://www.apache.org/licenses/LICENSE-2.0
  77696. *
  77697. * Unless required by applicable law or agreed to in writing,
  77698. * software distributed under the License is distributed on an
  77699. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  77700. * KIND, either express or implied. See the License for the
  77701. * specific language governing permissions and limitations
  77702. * under the License.
  77703. */
  77704. // Import all charts and components
  77705. exports.version = version;
  77706. exports.dependencies = dependencies;
  77707. exports.PRIORITY = PRIORITY;
  77708. exports.init = init;
  77709. exports.connect = connect;
  77710. exports.disConnect = disConnect;
  77711. exports.disconnect = disconnect;
  77712. exports.dispose = dispose;
  77713. exports.getInstanceByDom = getInstanceByDom;
  77714. exports.getInstanceById = getInstanceById;
  77715. exports.registerTheme = registerTheme;
  77716. exports.registerPreprocessor = registerPreprocessor;
  77717. exports.registerProcessor = registerProcessor;
  77718. exports.registerPostUpdate = registerPostUpdate;
  77719. exports.registerAction = registerAction;
  77720. exports.registerCoordinateSystem = registerCoordinateSystem;
  77721. exports.getCoordinateSystemDimensions = getCoordinateSystemDimensions;
  77722. exports.registerLayout = registerLayout;
  77723. exports.registerVisual = registerVisual;
  77724. exports.registerLoading = registerLoading;
  77725. exports.extendComponentModel = extendComponentModel;
  77726. exports.extendComponentView = extendComponentView;
  77727. exports.extendSeriesModel = extendSeriesModel;
  77728. exports.extendChartView = extendChartView;
  77729. exports.setCanvasCreator = setCanvasCreator;
  77730. exports.registerMap = registerMap;
  77731. exports.getMap = getMap;
  77732. exports.dataTool = dataTool;
  77733. exports.zrender = zrender;
  77734. exports.graphic = graphic;
  77735. exports.number = number;
  77736. exports.format = format;
  77737. exports.throttle = throttle;
  77738. exports.helper = helper;
  77739. exports.matrix = matrix;
  77740. exports.vector = vector;
  77741. exports.color = color;
  77742. exports.parseGeoJSON = parseGeoJson$1;
  77743. exports.parseGeoJson = parseGeoJson;
  77744. exports.util = ecUtil;
  77745. exports.List = List;
  77746. exports.Model = Model;
  77747. exports.Axis = Axis;
  77748. exports.env = env$1;
  77749. })));
  77750. //# sourceMappingURL=echarts.js.map